babylon.viewer.max.js 6.0 MB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911139121391313914139151391613917139181391913920139211392213923139241392513926139271392813929139301393113932139331393413935139361393713938139391394013941139421394313944139451394613947139481394913950139511395213953139541395513956139571395813959139601396113962139631396413965139661396713968139691397013971139721397313974139751397613977139781397913980139811398213983139841398513986139871398813989139901399113992139931399413995139961399713998139991400014001140021400314004140051400614007140081400914010140111401214013140141401514016140171401814019140201402114022140231402414025140261402714028140291403014031140321403314034140351403614037140381403914040140411404214043140441404514046140471404814049140501405114052140531405414055140561405714058140591406014061140621406314064140651406614067140681406914070140711407214073140741407514076140771407814079140801408114082140831408414085140861408714088140891409014091140921409314094140951409614097140981409914100141011410214103141041410514106141071410814109141101411114112141131411414115141161411714118141191412014121141221412314124141251412614127141281412914130141311413214133141341413514136141371413814139141401414114142141431414414145141461414714148141491415014151141521415314154141551415614157141581415914160141611416214163141641416514166141671416814169141701417114172141731417414175141761417714178141791418014181141821418314184141851418614187141881418914190141911419214193141941419514196141971419814199142001420114202142031420414205142061420714208142091421014211142121421314214142151421614217142181421914220142211422214223142241422514226142271422814229142301423114232142331423414235142361423714238142391424014241142421424314244142451424614247142481424914250142511425214253142541425514256142571425814259142601426114262142631426414265142661426714268142691427014271142721427314274142751427614277142781427914280142811428214283142841428514286142871428814289142901429114292142931429414295142961429714298142991430014301143021430314304143051430614307143081430914310143111431214313143141431514316143171431814319143201432114322143231432414325143261432714328143291433014331143321433314334143351433614337143381433914340143411434214343143441434514346143471434814349143501435114352143531435414355143561435714358143591436014361143621436314364143651436614367143681436914370143711437214373143741437514376143771437814379143801438114382143831438414385143861438714388143891439014391143921439314394143951439614397143981439914400144011440214403144041440514406144071440814409144101441114412144131441414415144161441714418144191442014421144221442314424144251442614427144281442914430144311443214433144341443514436144371443814439144401444114442144431444414445144461444714448144491445014451144521445314454144551445614457144581445914460144611446214463144641446514466144671446814469144701447114472144731447414475144761447714478144791448014481144821448314484144851448614487144881448914490144911449214493144941449514496144971449814499145001450114502145031450414505145061450714508145091451014511145121451314514145151451614517145181451914520145211452214523145241452514526145271452814529145301453114532145331453414535145361453714538145391454014541145421454314544145451454614547145481454914550145511455214553145541455514556145571455814559145601456114562145631456414565145661456714568145691457014571145721457314574145751457614577145781457914580145811458214583145841458514586145871458814589145901459114592145931459414595145961459714598145991460014601146021460314604146051460614607146081460914610146111461214613146141461514616146171461814619146201462114622146231462414625146261462714628146291463014631146321463314634146351463614637146381463914640146411464214643146441464514646146471464814649146501465114652146531465414655146561465714658146591466014661146621466314664146651466614667146681466914670146711467214673146741467514676146771467814679146801468114682146831468414685146861468714688146891469014691146921469314694146951469614697146981469914700147011470214703147041470514706147071470814709147101471114712147131471414715147161471714718147191472014721147221472314724147251472614727147281472914730147311473214733147341473514736147371473814739147401474114742147431474414745147461474714748147491475014751147521475314754147551475614757147581475914760147611476214763147641476514766147671476814769147701477114772147731477414775147761477714778147791478014781147821478314784147851478614787147881478914790147911479214793147941479514796147971479814799148001480114802148031480414805148061480714808148091481014811148121481314814148151481614817148181481914820148211482214823148241482514826148271482814829148301483114832148331483414835148361483714838148391484014841148421484314844148451484614847148481484914850148511485214853148541485514856148571485814859148601486114862148631486414865148661486714868148691487014871148721487314874148751487614877148781487914880148811488214883148841488514886148871488814889148901489114892148931489414895148961489714898148991490014901149021490314904149051490614907149081490914910149111491214913149141491514916149171491814919149201492114922149231492414925149261492714928149291493014931149321493314934149351493614937149381493914940149411494214943149441494514946149471494814949149501495114952149531495414955149561495714958149591496014961149621496314964149651496614967149681496914970149711497214973149741497514976149771497814979149801498114982149831498414985149861498714988149891499014991149921499314994149951499614997149981499915000150011500215003150041500515006150071500815009150101501115012150131501415015150161501715018150191502015021150221502315024150251502615027150281502915030150311503215033150341503515036150371503815039150401504115042150431504415045150461504715048150491505015051150521505315054150551505615057150581505915060150611506215063150641506515066150671506815069150701507115072150731507415075150761507715078150791508015081150821508315084150851508615087150881508915090150911509215093150941509515096150971509815099151001510115102151031510415105151061510715108151091511015111151121511315114151151511615117151181511915120151211512215123151241512515126151271512815129151301513115132151331513415135151361513715138151391514015141151421514315144151451514615147151481514915150151511515215153151541515515156151571515815159151601516115162151631516415165151661516715168151691517015171151721517315174151751517615177151781517915180151811518215183151841518515186151871518815189151901519115192151931519415195151961519715198151991520015201152021520315204152051520615207152081520915210152111521215213152141521515216152171521815219152201522115222152231522415225152261522715228152291523015231152321523315234152351523615237152381523915240152411524215243152441524515246152471524815249152501525115252152531525415255152561525715258152591526015261152621526315264152651526615267152681526915270152711527215273152741527515276152771527815279152801528115282152831528415285152861528715288152891529015291152921529315294152951529615297152981529915300153011530215303153041530515306153071530815309153101531115312153131531415315153161531715318153191532015321153221532315324153251532615327153281532915330153311533215333153341533515336153371533815339153401534115342153431534415345153461534715348153491535015351153521535315354153551535615357153581535915360153611536215363153641536515366153671536815369153701537115372153731537415375153761537715378153791538015381153821538315384153851538615387153881538915390153911539215393153941539515396153971539815399154001540115402154031540415405154061540715408154091541015411154121541315414154151541615417154181541915420154211542215423154241542515426154271542815429154301543115432154331543415435154361543715438154391544015441154421544315444154451544615447154481544915450154511545215453154541545515456154571545815459154601546115462154631546415465154661546715468154691547015471154721547315474154751547615477154781547915480154811548215483154841548515486154871548815489154901549115492154931549415495154961549715498154991550015501155021550315504155051550615507155081550915510155111551215513155141551515516155171551815519155201552115522155231552415525155261552715528155291553015531155321553315534155351553615537155381553915540155411554215543155441554515546155471554815549155501555115552155531555415555155561555715558155591556015561155621556315564155651556615567155681556915570155711557215573155741557515576155771557815579155801558115582155831558415585155861558715588155891559015591155921559315594155951559615597155981559915600156011560215603156041560515606156071560815609156101561115612156131561415615156161561715618156191562015621156221562315624156251562615627156281562915630156311563215633156341563515636156371563815639156401564115642156431564415645156461564715648156491565015651156521565315654156551565615657156581565915660156611566215663156641566515666156671566815669156701567115672156731567415675156761567715678156791568015681156821568315684156851568615687156881568915690156911569215693156941569515696156971569815699157001570115702157031570415705157061570715708157091571015711157121571315714157151571615717157181571915720157211572215723157241572515726157271572815729157301573115732157331573415735157361573715738157391574015741157421574315744157451574615747157481574915750157511575215753157541575515756157571575815759157601576115762157631576415765157661576715768157691577015771157721577315774157751577615777157781577915780157811578215783157841578515786157871578815789157901579115792157931579415795157961579715798157991580015801158021580315804158051580615807158081580915810158111581215813158141581515816158171581815819158201582115822158231582415825158261582715828158291583015831158321583315834158351583615837158381583915840158411584215843158441584515846158471584815849158501585115852158531585415855158561585715858158591586015861158621586315864158651586615867158681586915870158711587215873158741587515876158771587815879158801588115882158831588415885158861588715888158891589015891158921589315894158951589615897158981589915900159011590215903159041590515906159071590815909159101591115912159131591415915159161591715918159191592015921159221592315924159251592615927159281592915930159311593215933159341593515936159371593815939159401594115942159431594415945159461594715948159491595015951159521595315954159551595615957159581595915960159611596215963159641596515966159671596815969159701597115972159731597415975159761597715978159791598015981159821598315984159851598615987159881598915990159911599215993159941599515996159971599815999160001600116002160031600416005160061600716008160091601016011160121601316014160151601616017160181601916020160211602216023160241602516026160271602816029160301603116032160331603416035160361603716038160391604016041160421604316044160451604616047160481604916050160511605216053160541605516056160571605816059160601606116062160631606416065160661606716068160691607016071160721607316074160751607616077160781607916080160811608216083160841608516086160871608816089160901609116092160931609416095160961609716098160991610016101161021610316104161051610616107161081610916110161111611216113161141611516116161171611816119161201612116122161231612416125161261612716128161291613016131161321613316134161351613616137161381613916140161411614216143161441614516146161471614816149161501615116152161531615416155161561615716158161591616016161161621616316164161651616616167161681616916170161711617216173161741617516176161771617816179161801618116182161831618416185161861618716188161891619016191161921619316194161951619616197161981619916200162011620216203162041620516206162071620816209162101621116212162131621416215162161621716218162191622016221162221622316224162251622616227162281622916230162311623216233162341623516236162371623816239162401624116242162431624416245162461624716248162491625016251162521625316254162551625616257162581625916260162611626216263162641626516266162671626816269162701627116272162731627416275162761627716278162791628016281162821628316284162851628616287162881628916290162911629216293162941629516296162971629816299163001630116302163031630416305163061630716308163091631016311163121631316314163151631616317163181631916320163211632216323163241632516326163271632816329163301633116332163331633416335163361633716338163391634016341163421634316344163451634616347163481634916350163511635216353163541635516356163571635816359163601636116362163631636416365163661636716368163691637016371163721637316374163751637616377163781637916380163811638216383163841638516386163871638816389163901639116392163931639416395163961639716398163991640016401164021640316404164051640616407164081640916410164111641216413164141641516416164171641816419164201642116422164231642416425164261642716428164291643016431164321643316434164351643616437164381643916440164411644216443164441644516446164471644816449164501645116452164531645416455164561645716458164591646016461164621646316464164651646616467164681646916470164711647216473164741647516476164771647816479164801648116482164831648416485164861648716488164891649016491164921649316494164951649616497164981649916500165011650216503165041650516506165071650816509165101651116512165131651416515165161651716518165191652016521165221652316524165251652616527165281652916530165311653216533165341653516536165371653816539165401654116542165431654416545165461654716548165491655016551165521655316554165551655616557165581655916560165611656216563165641656516566165671656816569165701657116572165731657416575165761657716578165791658016581165821658316584165851658616587165881658916590165911659216593165941659516596165971659816599166001660116602166031660416605166061660716608166091661016611166121661316614166151661616617166181661916620166211662216623166241662516626166271662816629166301663116632166331663416635166361663716638166391664016641166421664316644166451664616647166481664916650166511665216653166541665516656166571665816659166601666116662166631666416665166661666716668166691667016671166721667316674166751667616677166781667916680166811668216683166841668516686166871668816689166901669116692166931669416695166961669716698166991670016701167021670316704167051670616707167081670916710167111671216713167141671516716167171671816719167201672116722167231672416725167261672716728167291673016731167321673316734167351673616737167381673916740167411674216743167441674516746167471674816749167501675116752167531675416755167561675716758167591676016761167621676316764167651676616767167681676916770167711677216773167741677516776167771677816779167801678116782167831678416785167861678716788167891679016791167921679316794167951679616797167981679916800168011680216803168041680516806168071680816809168101681116812168131681416815168161681716818168191682016821168221682316824168251682616827168281682916830168311683216833168341683516836168371683816839168401684116842168431684416845168461684716848168491685016851168521685316854168551685616857168581685916860168611686216863168641686516866168671686816869168701687116872168731687416875168761687716878168791688016881168821688316884168851688616887168881688916890168911689216893168941689516896168971689816899169001690116902169031690416905169061690716908169091691016911169121691316914169151691616917169181691916920169211692216923169241692516926169271692816929169301693116932169331693416935169361693716938169391694016941169421694316944169451694616947169481694916950169511695216953169541695516956169571695816959169601696116962169631696416965169661696716968169691697016971169721697316974169751697616977169781697916980169811698216983169841698516986169871698816989169901699116992169931699416995169961699716998169991700017001170021700317004170051700617007170081700917010170111701217013170141701517016170171701817019170201702117022170231702417025170261702717028170291703017031170321703317034170351703617037170381703917040170411704217043170441704517046170471704817049170501705117052170531705417055170561705717058170591706017061170621706317064170651706617067170681706917070170711707217073170741707517076170771707817079170801708117082170831708417085170861708717088170891709017091170921709317094170951709617097170981709917100171011710217103171041710517106171071710817109171101711117112171131711417115171161711717118171191712017121171221712317124171251712617127171281712917130171311713217133171341713517136171371713817139171401714117142171431714417145171461714717148171491715017151171521715317154171551715617157171581715917160171611716217163171641716517166171671716817169171701717117172171731717417175171761717717178171791718017181171821718317184171851718617187171881718917190171911719217193171941719517196171971719817199172001720117202172031720417205172061720717208172091721017211172121721317214172151721617217172181721917220172211722217223172241722517226172271722817229172301723117232172331723417235172361723717238172391724017241172421724317244172451724617247172481724917250172511725217253172541725517256172571725817259172601726117262172631726417265172661726717268172691727017271172721727317274172751727617277172781727917280172811728217283172841728517286172871728817289172901729117292172931729417295172961729717298172991730017301173021730317304173051730617307173081730917310173111731217313173141731517316173171731817319173201732117322173231732417325173261732717328173291733017331173321733317334173351733617337173381733917340173411734217343173441734517346173471734817349173501735117352173531735417355173561735717358173591736017361173621736317364173651736617367173681736917370173711737217373173741737517376173771737817379173801738117382173831738417385173861738717388173891739017391173921739317394173951739617397173981739917400174011740217403174041740517406174071740817409174101741117412174131741417415174161741717418174191742017421174221742317424174251742617427174281742917430174311743217433174341743517436174371743817439174401744117442174431744417445174461744717448174491745017451174521745317454174551745617457174581745917460174611746217463174641746517466174671746817469174701747117472174731747417475174761747717478174791748017481174821748317484174851748617487174881748917490174911749217493174941749517496174971749817499175001750117502175031750417505175061750717508175091751017511175121751317514175151751617517175181751917520175211752217523175241752517526175271752817529175301753117532175331753417535175361753717538175391754017541175421754317544175451754617547175481754917550175511755217553175541755517556175571755817559175601756117562175631756417565175661756717568175691757017571175721757317574175751757617577175781757917580175811758217583175841758517586175871758817589175901759117592175931759417595175961759717598175991760017601176021760317604176051760617607176081760917610176111761217613176141761517616176171761817619176201762117622176231762417625176261762717628176291763017631176321763317634176351763617637176381763917640176411764217643176441764517646176471764817649176501765117652176531765417655176561765717658176591766017661176621766317664176651766617667176681766917670176711767217673176741767517676176771767817679176801768117682176831768417685176861768717688176891769017691176921769317694176951769617697176981769917700177011770217703177041770517706177071770817709177101771117712177131771417715177161771717718177191772017721177221772317724177251772617727177281772917730177311773217733177341773517736177371773817739177401774117742177431774417745177461774717748177491775017751177521775317754177551775617757177581775917760177611776217763177641776517766177671776817769177701777117772177731777417775177761777717778177791778017781177821778317784177851778617787177881778917790177911779217793177941779517796177971779817799178001780117802178031780417805178061780717808178091781017811178121781317814178151781617817178181781917820178211782217823178241782517826178271782817829178301783117832178331783417835178361783717838178391784017841178421784317844178451784617847178481784917850178511785217853178541785517856178571785817859178601786117862178631786417865178661786717868178691787017871178721787317874178751787617877178781787917880178811788217883178841788517886178871788817889178901789117892178931789417895178961789717898178991790017901179021790317904179051790617907179081790917910179111791217913179141791517916179171791817919179201792117922179231792417925179261792717928179291793017931179321793317934179351793617937179381793917940179411794217943179441794517946179471794817949179501795117952179531795417955179561795717958179591796017961179621796317964179651796617967179681796917970179711797217973179741797517976179771797817979179801798117982179831798417985179861798717988179891799017991179921799317994179951799617997179981799918000180011800218003180041800518006180071800818009180101801118012180131801418015180161801718018180191802018021180221802318024180251802618027180281802918030180311803218033180341803518036180371803818039180401804118042180431804418045180461804718048180491805018051180521805318054180551805618057180581805918060180611806218063180641806518066180671806818069180701807118072180731807418075180761807718078180791808018081180821808318084180851808618087180881808918090180911809218093180941809518096180971809818099181001810118102181031810418105181061810718108181091811018111181121811318114181151811618117181181811918120181211812218123181241812518126181271812818129181301813118132181331813418135181361813718138181391814018141181421814318144181451814618147181481814918150181511815218153181541815518156181571815818159181601816118162181631816418165181661816718168181691817018171181721817318174181751817618177181781817918180181811818218183181841818518186181871818818189181901819118192181931819418195181961819718198181991820018201182021820318204182051820618207182081820918210182111821218213182141821518216182171821818219182201822118222182231822418225182261822718228182291823018231182321823318234182351823618237182381823918240182411824218243182441824518246182471824818249182501825118252182531825418255182561825718258182591826018261182621826318264182651826618267182681826918270182711827218273182741827518276182771827818279182801828118282182831828418285182861828718288182891829018291182921829318294182951829618297182981829918300183011830218303183041830518306183071830818309183101831118312183131831418315183161831718318183191832018321183221832318324183251832618327183281832918330183311833218333183341833518336183371833818339183401834118342183431834418345183461834718348183491835018351183521835318354183551835618357183581835918360183611836218363183641836518366183671836818369183701837118372183731837418375183761837718378183791838018381183821838318384183851838618387183881838918390183911839218393183941839518396183971839818399184001840118402184031840418405184061840718408184091841018411184121841318414184151841618417184181841918420184211842218423184241842518426184271842818429184301843118432184331843418435184361843718438184391844018441184421844318444184451844618447184481844918450184511845218453184541845518456184571845818459184601846118462184631846418465184661846718468184691847018471184721847318474184751847618477184781847918480184811848218483184841848518486184871848818489184901849118492184931849418495184961849718498184991850018501185021850318504185051850618507185081850918510185111851218513185141851518516185171851818519185201852118522185231852418525185261852718528185291853018531185321853318534185351853618537185381853918540185411854218543185441854518546185471854818549185501855118552185531855418555185561855718558185591856018561185621856318564185651856618567185681856918570185711857218573185741857518576185771857818579185801858118582185831858418585185861858718588185891859018591185921859318594185951859618597185981859918600186011860218603186041860518606186071860818609186101861118612186131861418615186161861718618186191862018621186221862318624186251862618627186281862918630186311863218633186341863518636186371863818639186401864118642186431864418645186461864718648186491865018651186521865318654186551865618657186581865918660186611866218663186641866518666186671866818669186701867118672186731867418675186761867718678186791868018681186821868318684186851868618687186881868918690186911869218693186941869518696186971869818699187001870118702187031870418705187061870718708187091871018711187121871318714187151871618717187181871918720187211872218723187241872518726187271872818729187301873118732187331873418735187361873718738187391874018741187421874318744187451874618747187481874918750187511875218753187541875518756187571875818759187601876118762187631876418765187661876718768187691877018771187721877318774187751877618777187781877918780187811878218783187841878518786187871878818789187901879118792187931879418795187961879718798187991880018801188021880318804188051880618807188081880918810188111881218813188141881518816188171881818819188201882118822188231882418825188261882718828188291883018831188321883318834188351883618837188381883918840188411884218843188441884518846188471884818849188501885118852188531885418855188561885718858188591886018861188621886318864188651886618867188681886918870188711887218873188741887518876188771887818879188801888118882188831888418885188861888718888188891889018891188921889318894188951889618897188981889918900189011890218903189041890518906189071890818909189101891118912189131891418915189161891718918189191892018921189221892318924189251892618927189281892918930189311893218933189341893518936189371893818939189401894118942189431894418945189461894718948189491895018951189521895318954189551895618957189581895918960189611896218963189641896518966189671896818969189701897118972189731897418975189761897718978189791898018981189821898318984189851898618987189881898918990189911899218993189941899518996189971899818999190001900119002190031900419005190061900719008190091901019011190121901319014190151901619017190181901919020190211902219023190241902519026190271902819029190301903119032190331903419035190361903719038190391904019041190421904319044190451904619047190481904919050190511905219053190541905519056190571905819059190601906119062190631906419065190661906719068190691907019071190721907319074190751907619077190781907919080190811908219083190841908519086190871908819089190901909119092190931909419095190961909719098190991910019101191021910319104191051910619107191081910919110191111911219113191141911519116191171911819119191201912119122191231912419125191261912719128191291913019131191321913319134191351913619137191381913919140191411914219143191441914519146191471914819149191501915119152191531915419155191561915719158191591916019161191621916319164191651916619167191681916919170191711917219173191741917519176191771917819179191801918119182191831918419185191861918719188191891919019191191921919319194191951919619197191981919919200192011920219203192041920519206192071920819209192101921119212192131921419215192161921719218192191922019221192221922319224192251922619227192281922919230192311923219233192341923519236192371923819239192401924119242192431924419245192461924719248192491925019251192521925319254192551925619257192581925919260192611926219263192641926519266192671926819269192701927119272192731927419275192761927719278192791928019281192821928319284192851928619287192881928919290192911929219293192941929519296192971929819299193001930119302193031930419305193061930719308193091931019311193121931319314193151931619317193181931919320193211932219323193241932519326193271932819329193301933119332193331933419335193361933719338193391934019341193421934319344193451934619347193481934919350193511935219353193541935519356193571935819359193601936119362193631936419365193661936719368193691937019371193721937319374193751937619377193781937919380193811938219383193841938519386193871938819389193901939119392193931939419395193961939719398193991940019401194021940319404194051940619407194081940919410194111941219413194141941519416194171941819419194201942119422194231942419425194261942719428194291943019431194321943319434194351943619437194381943919440194411944219443194441944519446194471944819449194501945119452194531945419455194561945719458194591946019461194621946319464194651946619467194681946919470194711947219473194741947519476194771947819479194801948119482194831948419485194861948719488194891949019491194921949319494194951949619497194981949919500195011950219503195041950519506195071950819509195101951119512195131951419515195161951719518195191952019521195221952319524195251952619527195281952919530195311953219533195341953519536195371953819539195401954119542195431954419545195461954719548195491955019551195521955319554195551955619557195581955919560195611956219563195641956519566195671956819569195701957119572195731957419575195761957719578195791958019581195821958319584195851958619587195881958919590195911959219593195941959519596195971959819599196001960119602196031960419605196061960719608196091961019611196121961319614196151961619617196181961919620196211962219623196241962519626196271962819629196301963119632196331963419635196361963719638196391964019641196421964319644196451964619647196481964919650196511965219653196541965519656196571965819659196601966119662196631966419665196661966719668196691967019671196721967319674196751967619677196781967919680196811968219683196841968519686196871968819689196901969119692196931969419695196961969719698196991970019701197021970319704197051970619707197081970919710197111971219713197141971519716197171971819719197201972119722197231972419725197261972719728197291973019731197321973319734197351973619737197381973919740197411974219743197441974519746197471974819749197501975119752197531975419755197561975719758197591976019761197621976319764197651976619767197681976919770197711977219773197741977519776197771977819779197801978119782197831978419785197861978719788197891979019791197921979319794197951979619797197981979919800198011980219803198041980519806198071980819809198101981119812198131981419815198161981719818198191982019821198221982319824198251982619827198281982919830198311983219833198341983519836198371983819839198401984119842198431984419845198461984719848198491985019851198521985319854198551985619857198581985919860198611986219863198641986519866198671986819869198701987119872198731987419875198761987719878198791988019881198821988319884198851988619887198881988919890198911989219893198941989519896198971989819899199001990119902199031990419905199061990719908199091991019911199121991319914199151991619917199181991919920199211992219923199241992519926199271992819929199301993119932199331993419935199361993719938199391994019941199421994319944199451994619947199481994919950199511995219953199541995519956199571995819959199601996119962199631996419965199661996719968199691997019971199721997319974199751997619977199781997919980199811998219983199841998519986199871998819989199901999119992199931999419995199961999719998199992000020001200022000320004200052000620007200082000920010200112001220013200142001520016200172001820019200202002120022200232002420025200262002720028200292003020031200322003320034200352003620037200382003920040200412004220043200442004520046200472004820049200502005120052200532005420055200562005720058200592006020061200622006320064200652006620067200682006920070200712007220073200742007520076200772007820079200802008120082200832008420085200862008720088200892009020091200922009320094200952009620097200982009920100201012010220103201042010520106201072010820109201102011120112201132011420115201162011720118201192012020121201222012320124201252012620127201282012920130201312013220133201342013520136201372013820139201402014120142201432014420145201462014720148201492015020151201522015320154201552015620157201582015920160201612016220163201642016520166201672016820169201702017120172201732017420175201762017720178201792018020181201822018320184201852018620187201882018920190201912019220193201942019520196201972019820199202002020120202202032020420205202062020720208202092021020211202122021320214202152021620217202182021920220202212022220223202242022520226202272022820229202302023120232202332023420235202362023720238202392024020241202422024320244202452024620247202482024920250202512025220253202542025520256202572025820259202602026120262202632026420265202662026720268202692027020271202722027320274202752027620277202782027920280202812028220283202842028520286202872028820289202902029120292202932029420295202962029720298202992030020301203022030320304203052030620307203082030920310203112031220313203142031520316203172031820319203202032120322203232032420325203262032720328203292033020331203322033320334203352033620337203382033920340203412034220343203442034520346203472034820349203502035120352203532035420355203562035720358203592036020361203622036320364203652036620367203682036920370203712037220373203742037520376203772037820379203802038120382203832038420385203862038720388203892039020391203922039320394203952039620397203982039920400204012040220403204042040520406204072040820409204102041120412204132041420415204162041720418204192042020421204222042320424204252042620427204282042920430204312043220433204342043520436204372043820439204402044120442204432044420445204462044720448204492045020451204522045320454204552045620457204582045920460204612046220463204642046520466204672046820469204702047120472204732047420475204762047720478204792048020481204822048320484204852048620487204882048920490204912049220493204942049520496204972049820499205002050120502205032050420505205062050720508205092051020511205122051320514205152051620517205182051920520205212052220523205242052520526205272052820529205302053120532205332053420535205362053720538205392054020541205422054320544205452054620547205482054920550205512055220553205542055520556205572055820559205602056120562205632056420565205662056720568205692057020571205722057320574205752057620577205782057920580205812058220583205842058520586205872058820589205902059120592205932059420595205962059720598205992060020601206022060320604206052060620607206082060920610206112061220613206142061520616206172061820619206202062120622206232062420625206262062720628206292063020631206322063320634206352063620637206382063920640206412064220643206442064520646206472064820649206502065120652206532065420655206562065720658206592066020661206622066320664206652066620667206682066920670206712067220673206742067520676206772067820679206802068120682206832068420685206862068720688206892069020691206922069320694206952069620697206982069920700207012070220703207042070520706207072070820709207102071120712207132071420715207162071720718207192072020721207222072320724207252072620727207282072920730207312073220733207342073520736207372073820739207402074120742207432074420745207462074720748207492075020751207522075320754207552075620757207582075920760207612076220763207642076520766207672076820769207702077120772207732077420775207762077720778207792078020781207822078320784207852078620787207882078920790207912079220793207942079520796207972079820799208002080120802208032080420805208062080720808208092081020811208122081320814208152081620817208182081920820208212082220823208242082520826208272082820829208302083120832208332083420835208362083720838208392084020841208422084320844208452084620847208482084920850208512085220853208542085520856208572085820859208602086120862208632086420865208662086720868208692087020871208722087320874208752087620877208782087920880208812088220883208842088520886208872088820889208902089120892208932089420895208962089720898208992090020901209022090320904209052090620907209082090920910209112091220913209142091520916209172091820919209202092120922209232092420925209262092720928209292093020931209322093320934209352093620937209382093920940209412094220943209442094520946209472094820949209502095120952209532095420955209562095720958209592096020961209622096320964209652096620967209682096920970209712097220973209742097520976209772097820979209802098120982209832098420985209862098720988209892099020991209922099320994209952099620997209982099921000210012100221003210042100521006210072100821009210102101121012210132101421015210162101721018210192102021021210222102321024210252102621027210282102921030210312103221033210342103521036210372103821039210402104121042210432104421045210462104721048210492105021051210522105321054210552105621057210582105921060210612106221063210642106521066210672106821069210702107121072210732107421075210762107721078210792108021081210822108321084210852108621087210882108921090210912109221093210942109521096210972109821099211002110121102211032110421105211062110721108211092111021111211122111321114211152111621117211182111921120211212112221123211242112521126211272112821129211302113121132211332113421135211362113721138211392114021141211422114321144211452114621147211482114921150211512115221153211542115521156211572115821159211602116121162211632116421165211662116721168211692117021171211722117321174211752117621177211782117921180211812118221183211842118521186211872118821189211902119121192211932119421195211962119721198211992120021201212022120321204212052120621207212082120921210212112121221213212142121521216212172121821219212202122121222212232122421225212262122721228212292123021231212322123321234212352123621237212382123921240212412124221243212442124521246212472124821249212502125121252212532125421255212562125721258212592126021261212622126321264212652126621267212682126921270212712127221273212742127521276212772127821279212802128121282212832128421285212862128721288212892129021291212922129321294212952129621297212982129921300213012130221303213042130521306213072130821309213102131121312213132131421315213162131721318213192132021321213222132321324213252132621327213282132921330213312133221333213342133521336213372133821339213402134121342213432134421345213462134721348213492135021351213522135321354213552135621357213582135921360213612136221363213642136521366213672136821369213702137121372213732137421375213762137721378213792138021381213822138321384213852138621387213882138921390213912139221393213942139521396213972139821399214002140121402214032140421405214062140721408214092141021411214122141321414214152141621417214182141921420214212142221423214242142521426214272142821429214302143121432214332143421435214362143721438214392144021441214422144321444214452144621447214482144921450214512145221453214542145521456214572145821459214602146121462214632146421465214662146721468214692147021471214722147321474214752147621477214782147921480214812148221483214842148521486214872148821489214902149121492214932149421495214962149721498214992150021501215022150321504215052150621507215082150921510215112151221513215142151521516215172151821519215202152121522215232152421525215262152721528215292153021531215322153321534215352153621537215382153921540215412154221543215442154521546215472154821549215502155121552215532155421555215562155721558215592156021561215622156321564215652156621567215682156921570215712157221573215742157521576215772157821579215802158121582215832158421585215862158721588215892159021591215922159321594215952159621597215982159921600216012160221603216042160521606216072160821609216102161121612216132161421615216162161721618216192162021621216222162321624216252162621627216282162921630216312163221633216342163521636216372163821639216402164121642216432164421645216462164721648216492165021651216522165321654216552165621657216582165921660216612166221663216642166521666216672166821669216702167121672216732167421675216762167721678216792168021681216822168321684216852168621687216882168921690216912169221693216942169521696216972169821699217002170121702217032170421705217062170721708217092171021711217122171321714217152171621717217182171921720217212172221723217242172521726217272172821729217302173121732217332173421735217362173721738217392174021741217422174321744217452174621747217482174921750217512175221753217542175521756217572175821759217602176121762217632176421765217662176721768217692177021771217722177321774217752177621777217782177921780217812178221783217842178521786217872178821789217902179121792217932179421795217962179721798217992180021801218022180321804218052180621807218082180921810218112181221813218142181521816218172181821819218202182121822218232182421825218262182721828218292183021831218322183321834218352183621837218382183921840218412184221843218442184521846218472184821849218502185121852218532185421855218562185721858218592186021861218622186321864218652186621867218682186921870218712187221873218742187521876218772187821879218802188121882218832188421885218862188721888218892189021891218922189321894218952189621897218982189921900219012190221903219042190521906219072190821909219102191121912219132191421915219162191721918219192192021921219222192321924219252192621927219282192921930219312193221933219342193521936219372193821939219402194121942219432194421945219462194721948219492195021951219522195321954219552195621957219582195921960219612196221963219642196521966219672196821969219702197121972219732197421975219762197721978219792198021981219822198321984219852198621987219882198921990219912199221993219942199521996219972199821999220002200122002220032200422005220062200722008220092201022011220122201322014220152201622017220182201922020220212202222023220242202522026220272202822029220302203122032220332203422035220362203722038220392204022041220422204322044220452204622047220482204922050220512205222053220542205522056220572205822059220602206122062220632206422065220662206722068220692207022071220722207322074220752207622077220782207922080220812208222083220842208522086220872208822089220902209122092220932209422095220962209722098220992210022101221022210322104221052210622107221082210922110221112211222113221142211522116221172211822119221202212122122221232212422125221262212722128221292213022131221322213322134221352213622137221382213922140221412214222143221442214522146221472214822149221502215122152221532215422155221562215722158221592216022161221622216322164221652216622167221682216922170221712217222173221742217522176221772217822179221802218122182221832218422185221862218722188221892219022191221922219322194221952219622197221982219922200222012220222203222042220522206222072220822209222102221122212222132221422215222162221722218222192222022221222222222322224222252222622227222282222922230222312223222233222342223522236222372223822239222402224122242222432224422245222462224722248222492225022251222522225322254222552225622257222582225922260222612226222263222642226522266222672226822269222702227122272222732227422275222762227722278222792228022281222822228322284222852228622287222882228922290222912229222293222942229522296222972229822299223002230122302223032230422305223062230722308223092231022311223122231322314223152231622317223182231922320223212232222323223242232522326223272232822329223302233122332223332233422335223362233722338223392234022341223422234322344223452234622347223482234922350223512235222353223542235522356223572235822359223602236122362223632236422365223662236722368223692237022371223722237322374223752237622377223782237922380223812238222383223842238522386223872238822389223902239122392223932239422395223962239722398223992240022401224022240322404224052240622407224082240922410224112241222413224142241522416224172241822419224202242122422224232242422425224262242722428224292243022431224322243322434224352243622437224382243922440224412244222443224442244522446224472244822449224502245122452224532245422455224562245722458224592246022461224622246322464224652246622467224682246922470224712247222473224742247522476224772247822479224802248122482224832248422485224862248722488224892249022491224922249322494224952249622497224982249922500225012250222503225042250522506225072250822509225102251122512225132251422515225162251722518225192252022521225222252322524225252252622527225282252922530225312253222533225342253522536225372253822539225402254122542225432254422545225462254722548225492255022551225522255322554225552255622557225582255922560225612256222563225642256522566225672256822569225702257122572225732257422575225762257722578225792258022581225822258322584225852258622587225882258922590225912259222593225942259522596225972259822599226002260122602226032260422605226062260722608226092261022611226122261322614226152261622617226182261922620226212262222623226242262522626226272262822629226302263122632226332263422635226362263722638226392264022641226422264322644226452264622647226482264922650226512265222653226542265522656226572265822659226602266122662226632266422665226662266722668226692267022671226722267322674226752267622677226782267922680226812268222683226842268522686226872268822689226902269122692226932269422695226962269722698226992270022701227022270322704227052270622707227082270922710227112271222713227142271522716227172271822719227202272122722227232272422725227262272722728227292273022731227322273322734227352273622737227382273922740227412274222743227442274522746227472274822749227502275122752227532275422755227562275722758227592276022761227622276322764227652276622767227682276922770227712277222773227742277522776227772277822779227802278122782227832278422785227862278722788227892279022791227922279322794227952279622797227982279922800228012280222803228042280522806228072280822809228102281122812228132281422815228162281722818228192282022821228222282322824228252282622827228282282922830228312283222833228342283522836228372283822839228402284122842228432284422845228462284722848228492285022851228522285322854228552285622857228582285922860228612286222863228642286522866228672286822869228702287122872228732287422875228762287722878228792288022881228822288322884228852288622887228882288922890228912289222893228942289522896228972289822899229002290122902229032290422905229062290722908229092291022911229122291322914229152291622917229182291922920229212292222923229242292522926229272292822929229302293122932229332293422935229362293722938229392294022941229422294322944229452294622947229482294922950229512295222953229542295522956229572295822959229602296122962229632296422965229662296722968229692297022971229722297322974229752297622977229782297922980229812298222983229842298522986229872298822989229902299122992229932299422995229962299722998229992300023001230022300323004230052300623007230082300923010230112301223013230142301523016230172301823019230202302123022230232302423025230262302723028230292303023031230322303323034230352303623037230382303923040230412304223043230442304523046230472304823049230502305123052230532305423055230562305723058230592306023061230622306323064230652306623067230682306923070230712307223073230742307523076230772307823079230802308123082230832308423085230862308723088230892309023091230922309323094230952309623097230982309923100231012310223103231042310523106231072310823109231102311123112231132311423115231162311723118231192312023121231222312323124231252312623127231282312923130231312313223133231342313523136231372313823139231402314123142231432314423145231462314723148231492315023151231522315323154231552315623157231582315923160231612316223163231642316523166231672316823169231702317123172231732317423175231762317723178231792318023181231822318323184231852318623187231882318923190231912319223193231942319523196231972319823199232002320123202232032320423205232062320723208232092321023211232122321323214232152321623217232182321923220232212322223223232242322523226232272322823229232302323123232232332323423235232362323723238232392324023241232422324323244232452324623247232482324923250232512325223253232542325523256232572325823259232602326123262232632326423265232662326723268232692327023271232722327323274232752327623277232782327923280232812328223283232842328523286232872328823289232902329123292232932329423295232962329723298232992330023301233022330323304233052330623307233082330923310233112331223313233142331523316233172331823319233202332123322233232332423325233262332723328233292333023331233322333323334233352333623337233382333923340233412334223343233442334523346233472334823349233502335123352233532335423355233562335723358233592336023361233622336323364233652336623367233682336923370233712337223373233742337523376233772337823379233802338123382233832338423385233862338723388233892339023391233922339323394233952339623397233982339923400234012340223403234042340523406234072340823409234102341123412234132341423415234162341723418234192342023421234222342323424234252342623427234282342923430234312343223433234342343523436234372343823439234402344123442234432344423445234462344723448234492345023451234522345323454234552345623457234582345923460234612346223463234642346523466234672346823469234702347123472234732347423475234762347723478234792348023481234822348323484234852348623487234882348923490234912349223493234942349523496234972349823499235002350123502235032350423505235062350723508235092351023511235122351323514235152351623517235182351923520235212352223523235242352523526235272352823529235302353123532235332353423535235362353723538235392354023541235422354323544235452354623547235482354923550235512355223553235542355523556235572355823559235602356123562235632356423565235662356723568235692357023571235722357323574235752357623577235782357923580235812358223583235842358523586235872358823589235902359123592235932359423595235962359723598235992360023601236022360323604236052360623607236082360923610236112361223613236142361523616236172361823619236202362123622236232362423625236262362723628236292363023631236322363323634236352363623637236382363923640236412364223643236442364523646236472364823649236502365123652236532365423655236562365723658236592366023661236622366323664236652366623667236682366923670236712367223673236742367523676236772367823679236802368123682236832368423685236862368723688236892369023691236922369323694236952369623697236982369923700237012370223703237042370523706237072370823709237102371123712237132371423715237162371723718237192372023721237222372323724237252372623727237282372923730237312373223733237342373523736237372373823739237402374123742237432374423745237462374723748237492375023751237522375323754237552375623757237582375923760237612376223763237642376523766237672376823769237702377123772237732377423775237762377723778237792378023781237822378323784237852378623787237882378923790237912379223793237942379523796237972379823799238002380123802238032380423805238062380723808238092381023811238122381323814238152381623817238182381923820238212382223823238242382523826238272382823829238302383123832238332383423835238362383723838238392384023841238422384323844238452384623847238482384923850238512385223853238542385523856238572385823859238602386123862238632386423865238662386723868238692387023871238722387323874238752387623877238782387923880238812388223883238842388523886238872388823889238902389123892238932389423895238962389723898238992390023901239022390323904239052390623907239082390923910239112391223913239142391523916239172391823919239202392123922239232392423925239262392723928239292393023931239322393323934239352393623937239382393923940239412394223943239442394523946239472394823949239502395123952239532395423955239562395723958239592396023961239622396323964239652396623967239682396923970239712397223973239742397523976239772397823979239802398123982239832398423985239862398723988239892399023991239922399323994239952399623997239982399924000240012400224003240042400524006240072400824009240102401124012240132401424015240162401724018240192402024021240222402324024240252402624027240282402924030240312403224033240342403524036240372403824039240402404124042240432404424045240462404724048240492405024051240522405324054240552405624057240582405924060240612406224063240642406524066240672406824069240702407124072240732407424075240762407724078240792408024081240822408324084240852408624087240882408924090240912409224093240942409524096240972409824099241002410124102241032410424105241062410724108241092411024111241122411324114241152411624117241182411924120241212412224123241242412524126241272412824129241302413124132241332413424135241362413724138241392414024141241422414324144241452414624147241482414924150241512415224153241542415524156241572415824159241602416124162241632416424165241662416724168241692417024171241722417324174241752417624177241782417924180241812418224183241842418524186241872418824189241902419124192241932419424195241962419724198241992420024201242022420324204242052420624207242082420924210242112421224213242142421524216242172421824219242202422124222242232422424225242262422724228242292423024231242322423324234242352423624237242382423924240242412424224243242442424524246242472424824249242502425124252242532425424255242562425724258242592426024261242622426324264242652426624267242682426924270242712427224273242742427524276242772427824279242802428124282242832428424285242862428724288242892429024291242922429324294242952429624297242982429924300243012430224303243042430524306243072430824309243102431124312243132431424315243162431724318243192432024321243222432324324243252432624327243282432924330243312433224333243342433524336243372433824339243402434124342243432434424345243462434724348243492435024351243522435324354243552435624357243582435924360243612436224363243642436524366243672436824369243702437124372243732437424375243762437724378243792438024381243822438324384243852438624387243882438924390243912439224393243942439524396243972439824399244002440124402244032440424405244062440724408244092441024411244122441324414244152441624417244182441924420244212442224423244242442524426244272442824429244302443124432244332443424435244362443724438244392444024441244422444324444244452444624447244482444924450244512445224453244542445524456244572445824459244602446124462244632446424465244662446724468244692447024471244722447324474244752447624477244782447924480244812448224483244842448524486244872448824489244902449124492244932449424495244962449724498244992450024501245022450324504245052450624507245082450924510245112451224513245142451524516245172451824519245202452124522245232452424525245262452724528245292453024531245322453324534245352453624537245382453924540245412454224543245442454524546245472454824549245502455124552245532455424555245562455724558245592456024561245622456324564245652456624567245682456924570245712457224573245742457524576245772457824579245802458124582245832458424585245862458724588245892459024591245922459324594245952459624597245982459924600246012460224603246042460524606246072460824609246102461124612246132461424615246162461724618246192462024621246222462324624246252462624627246282462924630246312463224633246342463524636246372463824639246402464124642246432464424645246462464724648246492465024651246522465324654246552465624657246582465924660246612466224663246642466524666246672466824669246702467124672246732467424675246762467724678246792468024681246822468324684246852468624687246882468924690246912469224693246942469524696246972469824699247002470124702247032470424705247062470724708247092471024711247122471324714247152471624717247182471924720247212472224723247242472524726247272472824729247302473124732247332473424735247362473724738247392474024741247422474324744247452474624747247482474924750247512475224753247542475524756247572475824759247602476124762247632476424765247662476724768247692477024771247722477324774247752477624777247782477924780247812478224783247842478524786247872478824789247902479124792247932479424795247962479724798247992480024801248022480324804248052480624807248082480924810248112481224813248142481524816248172481824819248202482124822248232482424825248262482724828248292483024831248322483324834248352483624837248382483924840248412484224843248442484524846248472484824849248502485124852248532485424855248562485724858248592486024861248622486324864248652486624867248682486924870248712487224873248742487524876248772487824879248802488124882248832488424885248862488724888248892489024891248922489324894248952489624897248982489924900249012490224903249042490524906249072490824909249102491124912249132491424915249162491724918249192492024921249222492324924249252492624927249282492924930249312493224933249342493524936249372493824939249402494124942249432494424945249462494724948249492495024951249522495324954249552495624957249582495924960249612496224963249642496524966249672496824969249702497124972249732497424975249762497724978249792498024981249822498324984249852498624987249882498924990249912499224993249942499524996249972499824999250002500125002250032500425005250062500725008250092501025011250122501325014250152501625017250182501925020250212502225023250242502525026250272502825029250302503125032250332503425035250362503725038250392504025041250422504325044250452504625047250482504925050250512505225053250542505525056250572505825059250602506125062250632506425065250662506725068250692507025071250722507325074250752507625077250782507925080250812508225083250842508525086250872508825089250902509125092250932509425095250962509725098250992510025101251022510325104251052510625107251082510925110251112511225113251142511525116251172511825119251202512125122251232512425125251262512725128251292513025131251322513325134251352513625137251382513925140251412514225143251442514525146251472514825149251502515125152251532515425155251562515725158251592516025161251622516325164251652516625167251682516925170251712517225173251742517525176251772517825179251802518125182251832518425185251862518725188251892519025191251922519325194251952519625197251982519925200252012520225203252042520525206252072520825209252102521125212252132521425215252162521725218252192522025221252222522325224252252522625227252282522925230252312523225233252342523525236252372523825239252402524125242252432524425245252462524725248252492525025251252522525325254252552525625257252582525925260252612526225263252642526525266252672526825269252702527125272252732527425275252762527725278252792528025281252822528325284252852528625287252882528925290252912529225293252942529525296252972529825299253002530125302253032530425305253062530725308253092531025311253122531325314253152531625317253182531925320253212532225323253242532525326253272532825329253302533125332253332533425335253362533725338253392534025341253422534325344253452534625347253482534925350253512535225353253542535525356253572535825359253602536125362253632536425365253662536725368253692537025371253722537325374253752537625377253782537925380253812538225383253842538525386253872538825389253902539125392253932539425395253962539725398253992540025401254022540325404254052540625407254082540925410254112541225413254142541525416254172541825419254202542125422254232542425425254262542725428254292543025431254322543325434254352543625437254382543925440254412544225443254442544525446254472544825449254502545125452254532545425455254562545725458254592546025461254622546325464254652546625467254682546925470254712547225473254742547525476254772547825479254802548125482254832548425485254862548725488254892549025491254922549325494254952549625497254982549925500255012550225503255042550525506255072550825509255102551125512255132551425515255162551725518255192552025521255222552325524255252552625527255282552925530255312553225533255342553525536255372553825539255402554125542255432554425545255462554725548255492555025551255522555325554255552555625557255582555925560255612556225563255642556525566255672556825569255702557125572255732557425575255762557725578255792558025581255822558325584255852558625587255882558925590255912559225593255942559525596255972559825599256002560125602256032560425605256062560725608256092561025611256122561325614256152561625617256182561925620256212562225623256242562525626256272562825629256302563125632256332563425635256362563725638256392564025641256422564325644256452564625647256482564925650256512565225653256542565525656256572565825659256602566125662256632566425665256662566725668256692567025671256722567325674256752567625677256782567925680256812568225683256842568525686256872568825689256902569125692256932569425695256962569725698256992570025701257022570325704257052570625707257082570925710257112571225713257142571525716257172571825719257202572125722257232572425725257262572725728257292573025731257322573325734257352573625737257382573925740257412574225743257442574525746257472574825749257502575125752257532575425755257562575725758257592576025761257622576325764257652576625767257682576925770257712577225773257742577525776257772577825779257802578125782257832578425785257862578725788257892579025791257922579325794257952579625797257982579925800258012580225803258042580525806258072580825809258102581125812258132581425815258162581725818258192582025821258222582325824258252582625827258282582925830258312583225833258342583525836258372583825839258402584125842258432584425845258462584725848258492585025851258522585325854258552585625857258582585925860258612586225863258642586525866258672586825869258702587125872258732587425875258762587725878258792588025881258822588325884258852588625887258882588925890258912589225893258942589525896258972589825899259002590125902259032590425905259062590725908259092591025911259122591325914259152591625917259182591925920259212592225923259242592525926259272592825929259302593125932259332593425935259362593725938259392594025941259422594325944259452594625947259482594925950259512595225953259542595525956259572595825959259602596125962259632596425965259662596725968259692597025971259722597325974259752597625977259782597925980259812598225983259842598525986259872598825989259902599125992259932599425995259962599725998259992600026001260022600326004260052600626007260082600926010260112601226013260142601526016260172601826019260202602126022260232602426025260262602726028260292603026031260322603326034260352603626037260382603926040260412604226043260442604526046260472604826049260502605126052260532605426055260562605726058260592606026061260622606326064260652606626067260682606926070260712607226073260742607526076260772607826079260802608126082260832608426085260862608726088260892609026091260922609326094260952609626097260982609926100261012610226103261042610526106261072610826109261102611126112261132611426115261162611726118261192612026121261222612326124261252612626127261282612926130261312613226133261342613526136261372613826139261402614126142261432614426145261462614726148261492615026151261522615326154261552615626157261582615926160261612616226163261642616526166261672616826169261702617126172261732617426175261762617726178261792618026181261822618326184261852618626187261882618926190261912619226193261942619526196261972619826199262002620126202262032620426205262062620726208262092621026211262122621326214262152621626217262182621926220262212622226223262242622526226262272622826229262302623126232262332623426235262362623726238262392624026241262422624326244262452624626247262482624926250262512625226253262542625526256262572625826259262602626126262262632626426265262662626726268262692627026271262722627326274262752627626277262782627926280262812628226283262842628526286262872628826289262902629126292262932629426295262962629726298262992630026301263022630326304263052630626307263082630926310263112631226313263142631526316263172631826319263202632126322263232632426325263262632726328263292633026331263322633326334263352633626337263382633926340263412634226343263442634526346263472634826349263502635126352263532635426355263562635726358263592636026361263622636326364263652636626367263682636926370263712637226373263742637526376263772637826379263802638126382263832638426385263862638726388263892639026391263922639326394263952639626397263982639926400264012640226403264042640526406264072640826409264102641126412264132641426415264162641726418264192642026421264222642326424264252642626427264282642926430264312643226433264342643526436264372643826439264402644126442264432644426445264462644726448264492645026451264522645326454264552645626457264582645926460264612646226463264642646526466264672646826469264702647126472264732647426475264762647726478264792648026481264822648326484264852648626487264882648926490264912649226493264942649526496264972649826499265002650126502265032650426505265062650726508265092651026511265122651326514265152651626517265182651926520265212652226523265242652526526265272652826529265302653126532265332653426535265362653726538265392654026541265422654326544265452654626547265482654926550265512655226553265542655526556265572655826559265602656126562265632656426565265662656726568265692657026571265722657326574265752657626577265782657926580265812658226583265842658526586265872658826589265902659126592265932659426595265962659726598265992660026601266022660326604266052660626607266082660926610266112661226613266142661526616266172661826619266202662126622266232662426625266262662726628266292663026631266322663326634266352663626637266382663926640266412664226643266442664526646266472664826649266502665126652266532665426655266562665726658266592666026661266622666326664266652666626667266682666926670266712667226673266742667526676266772667826679266802668126682266832668426685266862668726688266892669026691266922669326694266952669626697266982669926700267012670226703267042670526706267072670826709267102671126712267132671426715267162671726718267192672026721267222672326724267252672626727267282672926730267312673226733267342673526736267372673826739267402674126742267432674426745267462674726748267492675026751267522675326754267552675626757267582675926760267612676226763267642676526766267672676826769267702677126772267732677426775267762677726778267792678026781267822678326784267852678626787267882678926790267912679226793267942679526796267972679826799268002680126802268032680426805268062680726808268092681026811268122681326814268152681626817268182681926820268212682226823268242682526826268272682826829268302683126832268332683426835268362683726838268392684026841268422684326844268452684626847268482684926850268512685226853268542685526856268572685826859268602686126862268632686426865268662686726868268692687026871268722687326874268752687626877268782687926880268812688226883268842688526886268872688826889268902689126892268932689426895268962689726898268992690026901269022690326904269052690626907269082690926910269112691226913269142691526916269172691826919269202692126922269232692426925269262692726928269292693026931269322693326934269352693626937269382693926940269412694226943269442694526946269472694826949269502695126952269532695426955269562695726958269592696026961269622696326964269652696626967269682696926970269712697226973269742697526976269772697826979269802698126982269832698426985269862698726988269892699026991269922699326994269952699626997269982699927000270012700227003270042700527006270072700827009270102701127012270132701427015270162701727018270192702027021270222702327024270252702627027270282702927030270312703227033270342703527036270372703827039270402704127042270432704427045270462704727048270492705027051270522705327054270552705627057270582705927060270612706227063270642706527066270672706827069270702707127072270732707427075270762707727078270792708027081270822708327084270852708627087270882708927090270912709227093270942709527096270972709827099271002710127102271032710427105271062710727108271092711027111271122711327114271152711627117271182711927120271212712227123271242712527126271272712827129271302713127132271332713427135271362713727138271392714027141271422714327144271452714627147271482714927150271512715227153271542715527156271572715827159271602716127162271632716427165271662716727168271692717027171271722717327174271752717627177271782717927180271812718227183271842718527186271872718827189271902719127192271932719427195271962719727198271992720027201272022720327204272052720627207272082720927210272112721227213272142721527216272172721827219272202722127222272232722427225272262722727228272292723027231272322723327234272352723627237272382723927240272412724227243272442724527246272472724827249272502725127252272532725427255272562725727258272592726027261272622726327264272652726627267272682726927270272712727227273272742727527276272772727827279272802728127282272832728427285272862728727288272892729027291272922729327294272952729627297272982729927300273012730227303273042730527306273072730827309273102731127312273132731427315273162731727318273192732027321273222732327324273252732627327273282732927330273312733227333273342733527336273372733827339273402734127342273432734427345273462734727348273492735027351273522735327354273552735627357273582735927360273612736227363273642736527366273672736827369273702737127372273732737427375273762737727378273792738027381273822738327384273852738627387273882738927390273912739227393273942739527396273972739827399274002740127402274032740427405274062740727408274092741027411274122741327414274152741627417274182741927420274212742227423274242742527426274272742827429274302743127432274332743427435274362743727438274392744027441274422744327444274452744627447274482744927450274512745227453274542745527456274572745827459274602746127462274632746427465274662746727468274692747027471274722747327474274752747627477274782747927480274812748227483274842748527486274872748827489274902749127492274932749427495274962749727498274992750027501275022750327504275052750627507275082750927510275112751227513275142751527516275172751827519275202752127522275232752427525275262752727528275292753027531275322753327534275352753627537275382753927540275412754227543275442754527546275472754827549275502755127552275532755427555275562755727558275592756027561275622756327564275652756627567275682756927570275712757227573275742757527576275772757827579275802758127582275832758427585275862758727588275892759027591275922759327594275952759627597275982759927600276012760227603276042760527606276072760827609276102761127612276132761427615276162761727618276192762027621276222762327624276252762627627276282762927630276312763227633276342763527636276372763827639276402764127642276432764427645276462764727648276492765027651276522765327654276552765627657276582765927660276612766227663276642766527666276672766827669276702767127672276732767427675276762767727678276792768027681276822768327684276852768627687276882768927690276912769227693276942769527696276972769827699277002770127702277032770427705277062770727708277092771027711277122771327714277152771627717277182771927720277212772227723277242772527726277272772827729277302773127732277332773427735277362773727738277392774027741277422774327744277452774627747277482774927750277512775227753277542775527756277572775827759277602776127762277632776427765277662776727768277692777027771277722777327774277752777627777277782777927780277812778227783277842778527786277872778827789277902779127792277932779427795277962779727798277992780027801278022780327804278052780627807278082780927810278112781227813278142781527816278172781827819278202782127822278232782427825278262782727828278292783027831278322783327834278352783627837278382783927840278412784227843278442784527846278472784827849278502785127852278532785427855278562785727858278592786027861278622786327864278652786627867278682786927870278712787227873278742787527876278772787827879278802788127882278832788427885278862788727888278892789027891278922789327894278952789627897278982789927900279012790227903279042790527906279072790827909279102791127912279132791427915279162791727918279192792027921279222792327924279252792627927279282792927930279312793227933279342793527936279372793827939279402794127942279432794427945279462794727948279492795027951279522795327954279552795627957279582795927960279612796227963279642796527966279672796827969279702797127972279732797427975279762797727978279792798027981279822798327984279852798627987279882798927990279912799227993279942799527996279972799827999280002800128002280032800428005280062800728008280092801028011280122801328014280152801628017280182801928020280212802228023280242802528026280272802828029280302803128032280332803428035280362803728038280392804028041280422804328044280452804628047280482804928050280512805228053280542805528056280572805828059280602806128062280632806428065280662806728068280692807028071280722807328074280752807628077280782807928080280812808228083280842808528086280872808828089280902809128092280932809428095280962809728098280992810028101281022810328104281052810628107281082810928110281112811228113281142811528116281172811828119281202812128122281232812428125281262812728128281292813028131281322813328134281352813628137281382813928140281412814228143281442814528146281472814828149281502815128152281532815428155281562815728158281592816028161281622816328164281652816628167281682816928170281712817228173281742817528176281772817828179281802818128182281832818428185281862818728188281892819028191281922819328194281952819628197281982819928200282012820228203282042820528206282072820828209282102821128212282132821428215282162821728218282192822028221282222822328224282252822628227282282822928230282312823228233282342823528236282372823828239282402824128242282432824428245282462824728248282492825028251282522825328254282552825628257282582825928260282612826228263282642826528266282672826828269282702827128272282732827428275282762827728278282792828028281282822828328284282852828628287282882828928290282912829228293282942829528296282972829828299283002830128302283032830428305283062830728308283092831028311283122831328314283152831628317283182831928320283212832228323283242832528326283272832828329283302833128332283332833428335283362833728338283392834028341283422834328344283452834628347283482834928350283512835228353283542835528356283572835828359283602836128362283632836428365283662836728368283692837028371283722837328374283752837628377283782837928380283812838228383283842838528386283872838828389283902839128392283932839428395283962839728398283992840028401284022840328404284052840628407284082840928410284112841228413284142841528416284172841828419284202842128422284232842428425284262842728428284292843028431284322843328434284352843628437284382843928440284412844228443284442844528446284472844828449284502845128452284532845428455284562845728458284592846028461284622846328464284652846628467284682846928470284712847228473284742847528476284772847828479284802848128482284832848428485284862848728488284892849028491284922849328494284952849628497284982849928500285012850228503285042850528506285072850828509285102851128512285132851428515285162851728518285192852028521285222852328524285252852628527285282852928530285312853228533285342853528536285372853828539285402854128542285432854428545285462854728548285492855028551285522855328554285552855628557285582855928560285612856228563285642856528566285672856828569285702857128572285732857428575285762857728578285792858028581285822858328584285852858628587285882858928590285912859228593285942859528596285972859828599286002860128602286032860428605286062860728608286092861028611286122861328614286152861628617286182861928620286212862228623286242862528626286272862828629286302863128632286332863428635286362863728638286392864028641286422864328644286452864628647286482864928650286512865228653286542865528656286572865828659286602866128662286632866428665286662866728668286692867028671286722867328674286752867628677286782867928680286812868228683286842868528686286872868828689286902869128692286932869428695286962869728698286992870028701287022870328704287052870628707287082870928710287112871228713287142871528716287172871828719287202872128722287232872428725287262872728728287292873028731287322873328734287352873628737287382873928740287412874228743287442874528746287472874828749287502875128752287532875428755287562875728758287592876028761287622876328764287652876628767287682876928770287712877228773287742877528776287772877828779287802878128782287832878428785287862878728788287892879028791287922879328794287952879628797287982879928800288012880228803288042880528806288072880828809288102881128812288132881428815288162881728818288192882028821288222882328824288252882628827288282882928830288312883228833288342883528836288372883828839288402884128842288432884428845288462884728848288492885028851288522885328854288552885628857288582885928860288612886228863288642886528866288672886828869288702887128872288732887428875288762887728878288792888028881288822888328884288852888628887288882888928890288912889228893288942889528896288972889828899289002890128902289032890428905289062890728908289092891028911289122891328914289152891628917289182891928920289212892228923289242892528926289272892828929289302893128932289332893428935289362893728938289392894028941289422894328944289452894628947289482894928950289512895228953289542895528956289572895828959289602896128962289632896428965289662896728968289692897028971289722897328974289752897628977289782897928980289812898228983289842898528986289872898828989289902899128992289932899428995289962899728998289992900029001290022900329004290052900629007290082900929010290112901229013290142901529016290172901829019290202902129022290232902429025290262902729028290292903029031290322903329034290352903629037290382903929040290412904229043290442904529046290472904829049290502905129052290532905429055290562905729058290592906029061290622906329064290652906629067290682906929070290712907229073290742907529076290772907829079290802908129082290832908429085290862908729088290892909029091290922909329094290952909629097290982909929100291012910229103291042910529106291072910829109291102911129112291132911429115291162911729118291192912029121291222912329124291252912629127291282912929130291312913229133291342913529136291372913829139291402914129142291432914429145291462914729148291492915029151291522915329154291552915629157291582915929160291612916229163291642916529166291672916829169291702917129172291732917429175291762917729178291792918029181291822918329184291852918629187291882918929190291912919229193291942919529196291972919829199292002920129202292032920429205292062920729208292092921029211292122921329214292152921629217292182921929220292212922229223292242922529226292272922829229292302923129232292332923429235292362923729238292392924029241292422924329244292452924629247292482924929250292512925229253292542925529256292572925829259292602926129262292632926429265292662926729268292692927029271292722927329274292752927629277292782927929280292812928229283292842928529286292872928829289292902929129292292932929429295292962929729298292992930029301293022930329304293052930629307293082930929310293112931229313293142931529316293172931829319293202932129322293232932429325293262932729328293292933029331293322933329334293352933629337293382933929340293412934229343293442934529346293472934829349293502935129352293532935429355293562935729358293592936029361293622936329364293652936629367293682936929370293712937229373293742937529376293772937829379293802938129382293832938429385293862938729388293892939029391293922939329394293952939629397293982939929400294012940229403294042940529406294072940829409294102941129412294132941429415294162941729418294192942029421294222942329424294252942629427294282942929430294312943229433294342943529436294372943829439294402944129442294432944429445294462944729448294492945029451294522945329454294552945629457294582945929460294612946229463294642946529466294672946829469294702947129472294732947429475294762947729478294792948029481294822948329484294852948629487294882948929490294912949229493294942949529496294972949829499295002950129502295032950429505295062950729508295092951029511295122951329514295152951629517295182951929520295212952229523295242952529526295272952829529295302953129532295332953429535295362953729538295392954029541295422954329544295452954629547295482954929550295512955229553295542955529556295572955829559295602956129562295632956429565295662956729568295692957029571295722957329574295752957629577295782957929580295812958229583295842958529586295872958829589295902959129592295932959429595295962959729598295992960029601296022960329604296052960629607296082960929610296112961229613296142961529616296172961829619296202962129622296232962429625296262962729628296292963029631296322963329634296352963629637296382963929640296412964229643296442964529646296472964829649296502965129652296532965429655296562965729658296592966029661296622966329664296652966629667296682966929670296712967229673296742967529676296772967829679296802968129682296832968429685296862968729688296892969029691296922969329694296952969629697296982969929700297012970229703297042970529706297072970829709297102971129712297132971429715297162971729718297192972029721297222972329724297252972629727297282972929730297312973229733297342973529736297372973829739297402974129742297432974429745297462974729748297492975029751297522975329754297552975629757297582975929760297612976229763297642976529766297672976829769297702977129772297732977429775297762977729778297792978029781297822978329784297852978629787297882978929790297912979229793297942979529796297972979829799298002980129802298032980429805298062980729808298092981029811298122981329814298152981629817298182981929820298212982229823298242982529826298272982829829298302983129832298332983429835298362983729838298392984029841298422984329844298452984629847298482984929850298512985229853298542985529856298572985829859298602986129862298632986429865298662986729868298692987029871298722987329874298752987629877298782987929880298812988229883298842988529886298872988829889298902989129892298932989429895298962989729898298992990029901299022990329904299052990629907299082990929910299112991229913299142991529916299172991829919299202992129922299232992429925299262992729928299292993029931299322993329934299352993629937299382993929940299412994229943299442994529946299472994829949299502995129952299532995429955299562995729958299592996029961299622996329964299652996629967299682996929970299712997229973299742997529976299772997829979299802998129982299832998429985299862998729988299892999029991299922999329994299952999629997299982999930000300013000230003300043000530006300073000830009300103001130012300133001430015300163001730018300193002030021300223002330024300253002630027300283002930030300313003230033300343003530036300373003830039300403004130042300433004430045300463004730048300493005030051300523005330054300553005630057300583005930060300613006230063300643006530066300673006830069300703007130072300733007430075300763007730078300793008030081300823008330084300853008630087300883008930090300913009230093300943009530096300973009830099301003010130102301033010430105301063010730108301093011030111301123011330114301153011630117301183011930120301213012230123301243012530126301273012830129301303013130132301333013430135301363013730138301393014030141301423014330144301453014630147301483014930150301513015230153301543015530156301573015830159301603016130162301633016430165301663016730168301693017030171301723017330174301753017630177301783017930180301813018230183301843018530186301873018830189301903019130192301933019430195301963019730198301993020030201302023020330204302053020630207302083020930210302113021230213302143021530216302173021830219302203022130222302233022430225302263022730228302293023030231302323023330234302353023630237302383023930240302413024230243302443024530246302473024830249302503025130252302533025430255302563025730258302593026030261302623026330264302653026630267302683026930270302713027230273302743027530276302773027830279302803028130282302833028430285302863028730288302893029030291302923029330294302953029630297302983029930300303013030230303303043030530306303073030830309303103031130312303133031430315303163031730318303193032030321303223032330324303253032630327303283032930330303313033230333303343033530336303373033830339303403034130342303433034430345303463034730348303493035030351303523035330354303553035630357303583035930360303613036230363303643036530366303673036830369303703037130372303733037430375303763037730378303793038030381303823038330384303853038630387303883038930390303913039230393303943039530396303973039830399304003040130402304033040430405304063040730408304093041030411304123041330414304153041630417304183041930420304213042230423304243042530426304273042830429304303043130432304333043430435304363043730438304393044030441304423044330444304453044630447304483044930450304513045230453304543045530456304573045830459304603046130462304633046430465304663046730468304693047030471304723047330474304753047630477304783047930480304813048230483304843048530486304873048830489304903049130492304933049430495304963049730498304993050030501305023050330504305053050630507305083050930510305113051230513305143051530516305173051830519305203052130522305233052430525305263052730528305293053030531305323053330534305353053630537305383053930540305413054230543305443054530546305473054830549305503055130552305533055430555305563055730558305593056030561305623056330564305653056630567305683056930570305713057230573305743057530576305773057830579305803058130582305833058430585305863058730588305893059030591305923059330594305953059630597305983059930600306013060230603306043060530606306073060830609306103061130612306133061430615306163061730618306193062030621306223062330624306253062630627306283062930630306313063230633306343063530636306373063830639306403064130642306433064430645306463064730648306493065030651306523065330654306553065630657306583065930660306613066230663306643066530666306673066830669306703067130672306733067430675306763067730678306793068030681306823068330684306853068630687306883068930690306913069230693306943069530696306973069830699307003070130702307033070430705307063070730708307093071030711307123071330714307153071630717307183071930720307213072230723307243072530726307273072830729307303073130732307333073430735307363073730738307393074030741307423074330744307453074630747307483074930750307513075230753307543075530756307573075830759307603076130762307633076430765307663076730768307693077030771307723077330774307753077630777307783077930780307813078230783307843078530786307873078830789307903079130792307933079430795307963079730798307993080030801308023080330804308053080630807308083080930810308113081230813308143081530816308173081830819308203082130822308233082430825308263082730828308293083030831308323083330834308353083630837308383083930840308413084230843308443084530846308473084830849308503085130852308533085430855308563085730858308593086030861308623086330864308653086630867308683086930870308713087230873308743087530876308773087830879308803088130882308833088430885308863088730888308893089030891308923089330894308953089630897308983089930900309013090230903309043090530906309073090830909309103091130912309133091430915309163091730918309193092030921309223092330924309253092630927309283092930930309313093230933309343093530936309373093830939309403094130942309433094430945309463094730948309493095030951309523095330954309553095630957309583095930960309613096230963309643096530966309673096830969309703097130972309733097430975309763097730978309793098030981309823098330984309853098630987309883098930990309913099230993309943099530996309973099830999310003100131002310033100431005310063100731008310093101031011310123101331014310153101631017310183101931020310213102231023310243102531026310273102831029310303103131032310333103431035310363103731038310393104031041310423104331044310453104631047310483104931050310513105231053310543105531056310573105831059310603106131062310633106431065310663106731068310693107031071310723107331074310753107631077310783107931080310813108231083310843108531086310873108831089310903109131092310933109431095310963109731098310993110031101311023110331104311053110631107311083110931110311113111231113311143111531116311173111831119311203112131122311233112431125311263112731128311293113031131311323113331134311353113631137311383113931140311413114231143311443114531146311473114831149311503115131152311533115431155311563115731158311593116031161311623116331164311653116631167311683116931170311713117231173311743117531176311773117831179311803118131182311833118431185311863118731188311893119031191311923119331194311953119631197311983119931200312013120231203312043120531206312073120831209312103121131212312133121431215312163121731218312193122031221312223122331224312253122631227312283122931230312313123231233312343123531236312373123831239312403124131242312433124431245312463124731248312493125031251312523125331254312553125631257312583125931260312613126231263312643126531266312673126831269312703127131272312733127431275312763127731278312793128031281312823128331284312853128631287312883128931290312913129231293312943129531296312973129831299313003130131302313033130431305313063130731308313093131031311313123131331314313153131631317313183131931320313213132231323313243132531326313273132831329313303133131332313333133431335313363133731338313393134031341313423134331344313453134631347313483134931350313513135231353313543135531356313573135831359313603136131362313633136431365313663136731368313693137031371313723137331374313753137631377313783137931380313813138231383313843138531386313873138831389313903139131392313933139431395313963139731398313993140031401314023140331404314053140631407314083140931410314113141231413314143141531416314173141831419314203142131422314233142431425314263142731428314293143031431314323143331434314353143631437314383143931440314413144231443314443144531446314473144831449314503145131452314533145431455314563145731458314593146031461314623146331464314653146631467314683146931470314713147231473314743147531476314773147831479314803148131482314833148431485314863148731488314893149031491314923149331494314953149631497314983149931500315013150231503315043150531506315073150831509315103151131512315133151431515315163151731518315193152031521315223152331524315253152631527315283152931530315313153231533315343153531536315373153831539315403154131542315433154431545315463154731548315493155031551315523155331554315553155631557315583155931560315613156231563315643156531566315673156831569315703157131572315733157431575315763157731578315793158031581315823158331584315853158631587315883158931590315913159231593315943159531596315973159831599316003160131602316033160431605316063160731608316093161031611316123161331614316153161631617316183161931620316213162231623316243162531626316273162831629316303163131632316333163431635316363163731638316393164031641316423164331644316453164631647316483164931650316513165231653316543165531656316573165831659316603166131662316633166431665316663166731668316693167031671316723167331674316753167631677316783167931680316813168231683316843168531686316873168831689316903169131692316933169431695316963169731698316993170031701317023170331704317053170631707317083170931710317113171231713317143171531716317173171831719317203172131722317233172431725317263172731728317293173031731317323173331734317353173631737317383173931740317413174231743317443174531746317473174831749317503175131752317533175431755317563175731758317593176031761317623176331764317653176631767317683176931770317713177231773317743177531776317773177831779317803178131782317833178431785317863178731788317893179031791317923179331794317953179631797317983179931800318013180231803318043180531806318073180831809318103181131812318133181431815318163181731818318193182031821318223182331824318253182631827318283182931830318313183231833318343183531836318373183831839318403184131842318433184431845318463184731848318493185031851318523185331854318553185631857318583185931860318613186231863318643186531866318673186831869318703187131872318733187431875318763187731878318793188031881318823188331884318853188631887318883188931890318913189231893318943189531896318973189831899319003190131902319033190431905319063190731908319093191031911319123191331914319153191631917319183191931920319213192231923319243192531926319273192831929319303193131932319333193431935319363193731938319393194031941319423194331944319453194631947319483194931950319513195231953319543195531956319573195831959319603196131962319633196431965319663196731968319693197031971319723197331974319753197631977319783197931980319813198231983319843198531986319873198831989319903199131992319933199431995319963199731998319993200032001320023200332004320053200632007320083200932010320113201232013320143201532016320173201832019320203202132022320233202432025320263202732028320293203032031320323203332034320353203632037320383203932040320413204232043320443204532046320473204832049320503205132052320533205432055320563205732058320593206032061320623206332064320653206632067320683206932070320713207232073320743207532076320773207832079320803208132082320833208432085320863208732088320893209032091320923209332094320953209632097320983209932100321013210232103321043210532106321073210832109321103211132112321133211432115321163211732118321193212032121321223212332124321253212632127321283212932130321313213232133321343213532136321373213832139321403214132142321433214432145321463214732148321493215032151321523215332154321553215632157321583215932160321613216232163321643216532166321673216832169321703217132172321733217432175321763217732178321793218032181321823218332184321853218632187321883218932190321913219232193321943219532196321973219832199322003220132202322033220432205322063220732208322093221032211322123221332214322153221632217322183221932220322213222232223322243222532226322273222832229322303223132232322333223432235322363223732238322393224032241322423224332244322453224632247322483224932250322513225232253322543225532256322573225832259322603226132262322633226432265322663226732268322693227032271322723227332274322753227632277322783227932280322813228232283322843228532286322873228832289322903229132292322933229432295322963229732298322993230032301323023230332304323053230632307323083230932310323113231232313323143231532316323173231832319323203232132322323233232432325323263232732328323293233032331323323233332334323353233632337323383233932340323413234232343323443234532346323473234832349323503235132352323533235432355323563235732358323593236032361323623236332364323653236632367323683236932370323713237232373323743237532376323773237832379323803238132382323833238432385323863238732388323893239032391323923239332394323953239632397323983239932400324013240232403324043240532406324073240832409324103241132412324133241432415324163241732418324193242032421324223242332424324253242632427324283242932430324313243232433324343243532436324373243832439324403244132442324433244432445324463244732448324493245032451324523245332454324553245632457324583245932460324613246232463324643246532466324673246832469324703247132472324733247432475324763247732478324793248032481324823248332484324853248632487324883248932490324913249232493324943249532496324973249832499325003250132502325033250432505325063250732508325093251032511325123251332514325153251632517325183251932520325213252232523325243252532526325273252832529325303253132532325333253432535325363253732538325393254032541325423254332544325453254632547325483254932550325513255232553325543255532556325573255832559325603256132562325633256432565325663256732568325693257032571325723257332574325753257632577325783257932580325813258232583325843258532586325873258832589325903259132592325933259432595325963259732598325993260032601326023260332604326053260632607326083260932610326113261232613326143261532616326173261832619326203262132622326233262432625326263262732628326293263032631326323263332634326353263632637326383263932640326413264232643326443264532646326473264832649326503265132652326533265432655326563265732658326593266032661326623266332664326653266632667326683266932670326713267232673326743267532676326773267832679326803268132682326833268432685326863268732688326893269032691326923269332694326953269632697326983269932700327013270232703327043270532706327073270832709327103271132712327133271432715327163271732718327193272032721327223272332724327253272632727327283272932730327313273232733327343273532736327373273832739327403274132742327433274432745327463274732748327493275032751327523275332754327553275632757327583275932760327613276232763327643276532766327673276832769327703277132772327733277432775327763277732778327793278032781327823278332784327853278632787327883278932790327913279232793327943279532796327973279832799328003280132802328033280432805328063280732808328093281032811328123281332814328153281632817328183281932820328213282232823328243282532826328273282832829328303283132832328333283432835328363283732838328393284032841328423284332844328453284632847328483284932850328513285232853328543285532856328573285832859328603286132862328633286432865328663286732868328693287032871328723287332874328753287632877328783287932880328813288232883328843288532886328873288832889328903289132892328933289432895328963289732898328993290032901329023290332904329053290632907329083290932910329113291232913329143291532916329173291832919329203292132922329233292432925329263292732928329293293032931329323293332934329353293632937329383293932940329413294232943329443294532946329473294832949329503295132952329533295432955329563295732958329593296032961329623296332964329653296632967329683296932970329713297232973329743297532976329773297832979329803298132982329833298432985329863298732988329893299032991329923299332994329953299632997329983299933000330013300233003330043300533006330073300833009330103301133012330133301433015330163301733018330193302033021330223302333024330253302633027330283302933030330313303233033330343303533036330373303833039330403304133042330433304433045330463304733048330493305033051330523305333054330553305633057330583305933060330613306233063330643306533066330673306833069330703307133072330733307433075330763307733078330793308033081330823308333084330853308633087330883308933090330913309233093330943309533096330973309833099331003310133102331033310433105331063310733108331093311033111331123311333114331153311633117331183311933120331213312233123331243312533126331273312833129331303313133132331333313433135331363313733138331393314033141331423314333144331453314633147331483314933150331513315233153331543315533156331573315833159331603316133162331633316433165331663316733168331693317033171331723317333174331753317633177331783317933180331813318233183331843318533186331873318833189331903319133192331933319433195331963319733198331993320033201332023320333204332053320633207332083320933210332113321233213332143321533216332173321833219332203322133222332233322433225332263322733228332293323033231332323323333234332353323633237332383323933240332413324233243332443324533246332473324833249332503325133252332533325433255332563325733258332593326033261332623326333264332653326633267332683326933270332713327233273332743327533276332773327833279332803328133282332833328433285332863328733288332893329033291332923329333294332953329633297332983329933300333013330233303333043330533306333073330833309333103331133312333133331433315333163331733318333193332033321333223332333324333253332633327333283332933330333313333233333333343333533336333373333833339333403334133342333433334433345333463334733348333493335033351333523335333354333553335633357333583335933360333613336233363333643336533366333673336833369333703337133372333733337433375333763337733378333793338033381333823338333384333853338633387333883338933390333913339233393333943339533396333973339833399334003340133402334033340433405334063340733408334093341033411334123341333414334153341633417334183341933420334213342233423334243342533426334273342833429334303343133432334333343433435334363343733438334393344033441334423344333444334453344633447334483344933450334513345233453334543345533456334573345833459334603346133462334633346433465334663346733468334693347033471334723347333474334753347633477334783347933480334813348233483334843348533486334873348833489334903349133492334933349433495334963349733498334993350033501335023350333504335053350633507335083350933510335113351233513335143351533516335173351833519335203352133522335233352433525335263352733528335293353033531335323353333534335353353633537335383353933540335413354233543335443354533546335473354833549335503355133552335533355433555335563355733558335593356033561335623356333564335653356633567335683356933570335713357233573335743357533576335773357833579335803358133582335833358433585335863358733588335893359033591335923359333594335953359633597335983359933600336013360233603336043360533606336073360833609336103361133612336133361433615336163361733618336193362033621336223362333624336253362633627336283362933630336313363233633336343363533636336373363833639336403364133642336433364433645336463364733648336493365033651336523365333654336553365633657336583365933660336613366233663336643366533666336673366833669336703367133672336733367433675336763367733678336793368033681336823368333684336853368633687336883368933690336913369233693336943369533696336973369833699337003370133702337033370433705337063370733708337093371033711337123371333714337153371633717337183371933720337213372233723337243372533726337273372833729337303373133732337333373433735337363373733738337393374033741337423374333744337453374633747337483374933750337513375233753337543375533756337573375833759337603376133762337633376433765337663376733768337693377033771337723377333774337753377633777337783377933780337813378233783337843378533786337873378833789337903379133792337933379433795337963379733798337993380033801338023380333804338053380633807338083380933810338113381233813338143381533816338173381833819338203382133822338233382433825338263382733828338293383033831338323383333834338353383633837338383383933840338413384233843338443384533846338473384833849338503385133852338533385433855338563385733858338593386033861338623386333864338653386633867338683386933870338713387233873338743387533876338773387833879338803388133882338833388433885338863388733888338893389033891338923389333894338953389633897338983389933900339013390233903339043390533906339073390833909339103391133912339133391433915339163391733918339193392033921339223392333924339253392633927339283392933930339313393233933339343393533936339373393833939339403394133942339433394433945339463394733948339493395033951339523395333954339553395633957339583395933960339613396233963339643396533966339673396833969339703397133972339733397433975339763397733978339793398033981339823398333984339853398633987339883398933990339913399233993339943399533996339973399833999340003400134002340033400434005340063400734008340093401034011340123401334014340153401634017340183401934020340213402234023340243402534026340273402834029340303403134032340333403434035340363403734038340393404034041340423404334044340453404634047340483404934050340513405234053340543405534056340573405834059340603406134062340633406434065340663406734068340693407034071340723407334074340753407634077340783407934080340813408234083340843408534086340873408834089340903409134092340933409434095340963409734098340993410034101341023410334104341053410634107341083410934110341113411234113341143411534116341173411834119341203412134122341233412434125341263412734128341293413034131341323413334134341353413634137341383413934140341413414234143341443414534146341473414834149341503415134152341533415434155341563415734158341593416034161341623416334164341653416634167341683416934170341713417234173341743417534176341773417834179341803418134182341833418434185341863418734188341893419034191341923419334194341953419634197341983419934200342013420234203342043420534206342073420834209342103421134212342133421434215342163421734218342193422034221342223422334224342253422634227342283422934230342313423234233342343423534236342373423834239342403424134242342433424434245342463424734248342493425034251342523425334254342553425634257342583425934260342613426234263342643426534266342673426834269342703427134272342733427434275342763427734278342793428034281342823428334284342853428634287342883428934290342913429234293342943429534296342973429834299343003430134302343033430434305343063430734308343093431034311343123431334314343153431634317343183431934320343213432234323343243432534326343273432834329343303433134332343333433434335343363433734338343393434034341343423434334344343453434634347343483434934350343513435234353343543435534356343573435834359343603436134362343633436434365343663436734368343693437034371343723437334374343753437634377343783437934380343813438234383343843438534386343873438834389343903439134392343933439434395343963439734398343993440034401344023440334404344053440634407344083440934410344113441234413344143441534416344173441834419344203442134422344233442434425344263442734428344293443034431344323443334434344353443634437344383443934440344413444234443344443444534446344473444834449344503445134452344533445434455344563445734458344593446034461344623446334464344653446634467344683446934470344713447234473344743447534476344773447834479344803448134482344833448434485344863448734488344893449034491344923449334494344953449634497344983449934500345013450234503345043450534506345073450834509345103451134512345133451434515345163451734518345193452034521345223452334524345253452634527345283452934530345313453234533345343453534536345373453834539345403454134542345433454434545345463454734548345493455034551345523455334554345553455634557345583455934560345613456234563345643456534566345673456834569345703457134572345733457434575345763457734578345793458034581345823458334584345853458634587345883458934590345913459234593345943459534596345973459834599346003460134602346033460434605346063460734608346093461034611346123461334614346153461634617346183461934620346213462234623346243462534626346273462834629346303463134632346333463434635346363463734638346393464034641346423464334644346453464634647346483464934650346513465234653346543465534656346573465834659346603466134662346633466434665346663466734668346693467034671346723467334674346753467634677346783467934680346813468234683346843468534686346873468834689346903469134692346933469434695346963469734698346993470034701347023470334704347053470634707347083470934710347113471234713347143471534716347173471834719347203472134722347233472434725347263472734728347293473034731347323473334734347353473634737347383473934740347413474234743347443474534746347473474834749347503475134752347533475434755347563475734758347593476034761347623476334764347653476634767347683476934770347713477234773347743477534776347773477834779347803478134782347833478434785347863478734788347893479034791347923479334794347953479634797347983479934800348013480234803348043480534806348073480834809348103481134812348133481434815348163481734818348193482034821348223482334824348253482634827348283482934830348313483234833348343483534836348373483834839348403484134842348433484434845348463484734848348493485034851348523485334854348553485634857348583485934860348613486234863348643486534866348673486834869348703487134872348733487434875348763487734878348793488034881348823488334884348853488634887348883488934890348913489234893348943489534896348973489834899349003490134902349033490434905349063490734908349093491034911349123491334914349153491634917349183491934920349213492234923349243492534926349273492834929349303493134932349333493434935349363493734938349393494034941349423494334944349453494634947349483494934950349513495234953349543495534956349573495834959349603496134962349633496434965349663496734968349693497034971349723497334974349753497634977349783497934980349813498234983349843498534986349873498834989349903499134992349933499434995349963499734998349993500035001350023500335004350053500635007350083500935010350113501235013350143501535016350173501835019350203502135022350233502435025350263502735028350293503035031350323503335034350353503635037350383503935040350413504235043350443504535046350473504835049350503505135052350533505435055350563505735058350593506035061350623506335064350653506635067350683506935070350713507235073350743507535076350773507835079350803508135082350833508435085350863508735088350893509035091350923509335094350953509635097350983509935100351013510235103351043510535106351073510835109351103511135112351133511435115351163511735118351193512035121351223512335124351253512635127351283512935130351313513235133351343513535136351373513835139351403514135142351433514435145351463514735148351493515035151351523515335154351553515635157351583515935160351613516235163351643516535166351673516835169351703517135172351733517435175351763517735178351793518035181351823518335184351853518635187351883518935190351913519235193351943519535196351973519835199352003520135202352033520435205352063520735208352093521035211352123521335214352153521635217352183521935220352213522235223352243522535226352273522835229352303523135232352333523435235352363523735238352393524035241352423524335244352453524635247352483524935250352513525235253352543525535256352573525835259352603526135262352633526435265352663526735268352693527035271352723527335274352753527635277352783527935280352813528235283352843528535286352873528835289352903529135292352933529435295352963529735298352993530035301353023530335304353053530635307353083530935310353113531235313353143531535316353173531835319353203532135322353233532435325353263532735328353293533035331353323533335334353353533635337353383533935340353413534235343353443534535346353473534835349353503535135352353533535435355353563535735358353593536035361353623536335364353653536635367353683536935370353713537235373353743537535376353773537835379353803538135382353833538435385353863538735388353893539035391353923539335394353953539635397353983539935400354013540235403354043540535406354073540835409354103541135412354133541435415354163541735418354193542035421354223542335424354253542635427354283542935430354313543235433354343543535436354373543835439354403544135442354433544435445354463544735448354493545035451354523545335454354553545635457354583545935460354613546235463354643546535466354673546835469354703547135472354733547435475354763547735478354793548035481354823548335484354853548635487354883548935490354913549235493354943549535496354973549835499355003550135502355033550435505355063550735508355093551035511355123551335514355153551635517355183551935520355213552235523355243552535526355273552835529355303553135532355333553435535355363553735538355393554035541355423554335544355453554635547355483554935550355513555235553355543555535556355573555835559355603556135562355633556435565355663556735568355693557035571355723557335574355753557635577355783557935580355813558235583355843558535586355873558835589355903559135592355933559435595355963559735598355993560035601356023560335604356053560635607356083560935610356113561235613356143561535616356173561835619356203562135622356233562435625356263562735628356293563035631356323563335634356353563635637356383563935640356413564235643356443564535646356473564835649356503565135652356533565435655356563565735658356593566035661356623566335664356653566635667356683566935670356713567235673356743567535676356773567835679356803568135682356833568435685356863568735688356893569035691356923569335694356953569635697356983569935700357013570235703357043570535706357073570835709357103571135712357133571435715357163571735718357193572035721357223572335724357253572635727357283572935730357313573235733357343573535736357373573835739357403574135742357433574435745357463574735748357493575035751357523575335754357553575635757357583575935760357613576235763357643576535766357673576835769357703577135772357733577435775357763577735778357793578035781357823578335784357853578635787357883578935790357913579235793357943579535796357973579835799358003580135802358033580435805358063580735808358093581035811358123581335814358153581635817358183581935820358213582235823358243582535826358273582835829358303583135832358333583435835358363583735838358393584035841358423584335844358453584635847358483584935850358513585235853358543585535856358573585835859358603586135862358633586435865358663586735868358693587035871358723587335874358753587635877358783587935880358813588235883358843588535886358873588835889358903589135892358933589435895358963589735898358993590035901359023590335904359053590635907359083590935910359113591235913359143591535916359173591835919359203592135922359233592435925359263592735928359293593035931359323593335934359353593635937359383593935940359413594235943359443594535946359473594835949359503595135952359533595435955359563595735958359593596035961359623596335964359653596635967359683596935970359713597235973359743597535976359773597835979359803598135982359833598435985359863598735988359893599035991359923599335994359953599635997359983599936000360013600236003360043600536006360073600836009360103601136012360133601436015360163601736018360193602036021360223602336024360253602636027360283602936030360313603236033360343603536036360373603836039360403604136042360433604436045360463604736048360493605036051360523605336054360553605636057360583605936060360613606236063360643606536066360673606836069360703607136072360733607436075360763607736078360793608036081360823608336084360853608636087360883608936090360913609236093360943609536096360973609836099361003610136102361033610436105361063610736108361093611036111361123611336114361153611636117361183611936120361213612236123361243612536126361273612836129361303613136132361333613436135361363613736138361393614036141361423614336144361453614636147361483614936150361513615236153361543615536156361573615836159361603616136162361633616436165361663616736168361693617036171361723617336174361753617636177361783617936180361813618236183361843618536186361873618836189361903619136192361933619436195361963619736198361993620036201362023620336204362053620636207362083620936210362113621236213362143621536216362173621836219362203622136222362233622436225362263622736228362293623036231362323623336234362353623636237362383623936240362413624236243362443624536246362473624836249362503625136252362533625436255362563625736258362593626036261362623626336264362653626636267362683626936270362713627236273362743627536276362773627836279362803628136282362833628436285362863628736288362893629036291362923629336294362953629636297362983629936300363013630236303363043630536306363073630836309363103631136312363133631436315363163631736318363193632036321363223632336324363253632636327363283632936330363313633236333363343633536336363373633836339363403634136342363433634436345363463634736348363493635036351363523635336354363553635636357363583635936360363613636236363363643636536366363673636836369363703637136372363733637436375363763637736378363793638036381363823638336384363853638636387363883638936390363913639236393363943639536396363973639836399364003640136402364033640436405364063640736408364093641036411364123641336414364153641636417364183641936420364213642236423364243642536426364273642836429364303643136432364333643436435364363643736438364393644036441364423644336444364453644636447364483644936450364513645236453364543645536456364573645836459364603646136462364633646436465364663646736468364693647036471364723647336474364753647636477364783647936480364813648236483364843648536486364873648836489364903649136492364933649436495364963649736498364993650036501365023650336504365053650636507365083650936510365113651236513365143651536516365173651836519365203652136522365233652436525365263652736528365293653036531365323653336534365353653636537365383653936540365413654236543365443654536546365473654836549365503655136552365533655436555365563655736558365593656036561365623656336564365653656636567365683656936570365713657236573365743657536576365773657836579365803658136582365833658436585365863658736588365893659036591365923659336594365953659636597365983659936600366013660236603366043660536606366073660836609366103661136612366133661436615366163661736618366193662036621366223662336624366253662636627366283662936630366313663236633366343663536636366373663836639366403664136642366433664436645366463664736648366493665036651366523665336654366553665636657366583665936660366613666236663366643666536666366673666836669366703667136672366733667436675366763667736678366793668036681366823668336684366853668636687366883668936690366913669236693366943669536696366973669836699367003670136702367033670436705367063670736708367093671036711367123671336714367153671636717367183671936720367213672236723367243672536726367273672836729367303673136732367333673436735367363673736738367393674036741367423674336744367453674636747367483674936750367513675236753367543675536756367573675836759367603676136762367633676436765367663676736768367693677036771367723677336774367753677636777367783677936780367813678236783367843678536786367873678836789367903679136792367933679436795367963679736798367993680036801368023680336804368053680636807368083680936810368113681236813368143681536816368173681836819368203682136822368233682436825368263682736828368293683036831368323683336834368353683636837368383683936840368413684236843368443684536846368473684836849368503685136852368533685436855368563685736858368593686036861368623686336864368653686636867368683686936870368713687236873368743687536876368773687836879368803688136882368833688436885368863688736888368893689036891368923689336894368953689636897368983689936900369013690236903369043690536906369073690836909369103691136912369133691436915369163691736918369193692036921369223692336924369253692636927369283692936930369313693236933369343693536936369373693836939369403694136942369433694436945369463694736948369493695036951369523695336954369553695636957369583695936960369613696236963369643696536966369673696836969369703697136972369733697436975369763697736978369793698036981369823698336984369853698636987369883698936990369913699236993369943699536996369973699836999370003700137002370033700437005370063700737008370093701037011370123701337014370153701637017370183701937020370213702237023370243702537026370273702837029370303703137032370333703437035370363703737038370393704037041370423704337044370453704637047370483704937050370513705237053370543705537056370573705837059370603706137062370633706437065370663706737068370693707037071370723707337074370753707637077370783707937080370813708237083370843708537086370873708837089370903709137092370933709437095370963709737098370993710037101371023710337104371053710637107371083710937110371113711237113371143711537116371173711837119371203712137122371233712437125371263712737128371293713037131371323713337134371353713637137371383713937140371413714237143371443714537146371473714837149371503715137152371533715437155371563715737158371593716037161371623716337164371653716637167371683716937170371713717237173371743717537176371773717837179371803718137182371833718437185371863718737188371893719037191371923719337194371953719637197371983719937200372013720237203372043720537206372073720837209372103721137212372133721437215372163721737218372193722037221372223722337224372253722637227372283722937230372313723237233372343723537236372373723837239372403724137242372433724437245372463724737248372493725037251372523725337254372553725637257372583725937260372613726237263372643726537266372673726837269372703727137272372733727437275372763727737278372793728037281372823728337284372853728637287372883728937290372913729237293372943729537296372973729837299373003730137302373033730437305373063730737308373093731037311373123731337314373153731637317373183731937320373213732237323373243732537326373273732837329373303733137332373333733437335373363733737338373393734037341373423734337344373453734637347373483734937350373513735237353373543735537356373573735837359373603736137362373633736437365373663736737368373693737037371373723737337374373753737637377373783737937380373813738237383373843738537386373873738837389373903739137392373933739437395373963739737398373993740037401374023740337404374053740637407374083740937410374113741237413374143741537416374173741837419374203742137422374233742437425374263742737428374293743037431374323743337434374353743637437374383743937440374413744237443374443744537446374473744837449374503745137452374533745437455374563745737458374593746037461374623746337464374653746637467374683746937470374713747237473374743747537476374773747837479374803748137482374833748437485374863748737488374893749037491374923749337494374953749637497374983749937500375013750237503375043750537506375073750837509375103751137512375133751437515375163751737518375193752037521375223752337524375253752637527375283752937530375313753237533375343753537536375373753837539375403754137542375433754437545375463754737548375493755037551375523755337554375553755637557375583755937560375613756237563375643756537566375673756837569375703757137572375733757437575375763757737578375793758037581375823758337584375853758637587375883758937590375913759237593375943759537596375973759837599376003760137602376033760437605376063760737608376093761037611376123761337614376153761637617376183761937620376213762237623376243762537626376273762837629376303763137632376333763437635376363763737638376393764037641376423764337644376453764637647376483764937650376513765237653376543765537656376573765837659376603766137662376633766437665376663766737668376693767037671376723767337674376753767637677376783767937680376813768237683376843768537686376873768837689376903769137692376933769437695376963769737698376993770037701377023770337704377053770637707377083770937710377113771237713377143771537716377173771837719377203772137722377233772437725377263772737728377293773037731377323773337734377353773637737377383773937740377413774237743377443774537746377473774837749377503775137752377533775437755377563775737758377593776037761377623776337764377653776637767377683776937770377713777237773377743777537776377773777837779377803778137782377833778437785377863778737788377893779037791377923779337794377953779637797377983779937800378013780237803378043780537806378073780837809378103781137812378133781437815378163781737818378193782037821378223782337824378253782637827378283782937830378313783237833378343783537836378373783837839378403784137842378433784437845378463784737848378493785037851378523785337854378553785637857378583785937860378613786237863378643786537866378673786837869378703787137872378733787437875378763787737878378793788037881378823788337884378853788637887378883788937890378913789237893378943789537896378973789837899379003790137902379033790437905379063790737908379093791037911379123791337914379153791637917379183791937920379213792237923379243792537926379273792837929379303793137932379333793437935379363793737938379393794037941379423794337944379453794637947379483794937950379513795237953379543795537956379573795837959379603796137962379633796437965379663796737968379693797037971379723797337974379753797637977379783797937980379813798237983379843798537986379873798837989379903799137992379933799437995379963799737998379993800038001380023800338004380053800638007380083800938010380113801238013380143801538016380173801838019380203802138022380233802438025380263802738028380293803038031380323803338034380353803638037380383803938040380413804238043380443804538046380473804838049380503805138052380533805438055380563805738058380593806038061380623806338064380653806638067380683806938070380713807238073380743807538076380773807838079380803808138082380833808438085380863808738088380893809038091380923809338094380953809638097380983809938100381013810238103381043810538106381073810838109381103811138112381133811438115381163811738118381193812038121381223812338124381253812638127381283812938130381313813238133381343813538136381373813838139381403814138142381433814438145381463814738148381493815038151381523815338154381553815638157381583815938160381613816238163381643816538166381673816838169381703817138172381733817438175381763817738178381793818038181381823818338184381853818638187381883818938190381913819238193381943819538196381973819838199382003820138202382033820438205382063820738208382093821038211382123821338214382153821638217382183821938220382213822238223382243822538226382273822838229382303823138232382333823438235382363823738238382393824038241382423824338244382453824638247382483824938250382513825238253382543825538256382573825838259382603826138262382633826438265382663826738268382693827038271382723827338274382753827638277382783827938280382813828238283382843828538286382873828838289382903829138292382933829438295382963829738298382993830038301383023830338304383053830638307383083830938310383113831238313383143831538316383173831838319383203832138322383233832438325383263832738328383293833038331383323833338334383353833638337383383833938340383413834238343383443834538346383473834838349383503835138352383533835438355383563835738358383593836038361383623836338364383653836638367383683836938370383713837238373383743837538376383773837838379383803838138382383833838438385383863838738388383893839038391383923839338394383953839638397383983839938400384013840238403384043840538406384073840838409384103841138412384133841438415384163841738418384193842038421384223842338424384253842638427384283842938430384313843238433384343843538436384373843838439384403844138442384433844438445384463844738448384493845038451384523845338454384553845638457384583845938460384613846238463384643846538466384673846838469384703847138472384733847438475384763847738478384793848038481384823848338484384853848638487384883848938490384913849238493384943849538496384973849838499385003850138502385033850438505385063850738508385093851038511385123851338514385153851638517385183851938520385213852238523385243852538526385273852838529385303853138532385333853438535385363853738538385393854038541385423854338544385453854638547385483854938550385513855238553385543855538556385573855838559385603856138562385633856438565385663856738568385693857038571385723857338574385753857638577385783857938580385813858238583385843858538586385873858838589385903859138592385933859438595385963859738598385993860038601386023860338604386053860638607386083860938610386113861238613386143861538616386173861838619386203862138622386233862438625386263862738628386293863038631386323863338634386353863638637386383863938640386413864238643386443864538646386473864838649386503865138652386533865438655386563865738658386593866038661386623866338664386653866638667386683866938670386713867238673386743867538676386773867838679386803868138682386833868438685386863868738688386893869038691386923869338694386953869638697386983869938700387013870238703387043870538706387073870838709387103871138712387133871438715387163871738718387193872038721387223872338724387253872638727387283872938730387313873238733387343873538736387373873838739387403874138742387433874438745387463874738748387493875038751387523875338754387553875638757387583875938760387613876238763387643876538766387673876838769387703877138772387733877438775387763877738778387793878038781387823878338784387853878638787387883878938790387913879238793387943879538796387973879838799388003880138802388033880438805388063880738808388093881038811388123881338814388153881638817388183881938820388213882238823388243882538826388273882838829388303883138832388333883438835388363883738838388393884038841388423884338844388453884638847388483884938850388513885238853388543885538856388573885838859388603886138862388633886438865388663886738868388693887038871388723887338874388753887638877388783887938880388813888238883388843888538886388873888838889388903889138892388933889438895388963889738898388993890038901389023890338904389053890638907389083890938910389113891238913389143891538916389173891838919389203892138922389233892438925389263892738928389293893038931389323893338934389353893638937389383893938940389413894238943389443894538946389473894838949389503895138952389533895438955389563895738958389593896038961389623896338964389653896638967389683896938970389713897238973389743897538976389773897838979389803898138982389833898438985389863898738988389893899038991389923899338994389953899638997389983899939000390013900239003390043900539006390073900839009390103901139012390133901439015390163901739018390193902039021390223902339024390253902639027390283902939030390313903239033390343903539036390373903839039390403904139042390433904439045390463904739048390493905039051390523905339054390553905639057390583905939060390613906239063390643906539066390673906839069390703907139072390733907439075390763907739078390793908039081390823908339084390853908639087390883908939090390913909239093390943909539096390973909839099391003910139102391033910439105391063910739108391093911039111391123911339114391153911639117391183911939120391213912239123391243912539126391273912839129391303913139132391333913439135391363913739138391393914039141391423914339144391453914639147391483914939150391513915239153391543915539156391573915839159391603916139162391633916439165391663916739168391693917039171391723917339174391753917639177391783917939180391813918239183391843918539186391873918839189391903919139192391933919439195391963919739198391993920039201392023920339204392053920639207392083920939210392113921239213392143921539216392173921839219392203922139222392233922439225392263922739228392293923039231392323923339234392353923639237392383923939240392413924239243392443924539246392473924839249392503925139252392533925439255392563925739258392593926039261392623926339264392653926639267392683926939270392713927239273392743927539276392773927839279392803928139282392833928439285392863928739288392893929039291392923929339294392953929639297392983929939300393013930239303393043930539306393073930839309393103931139312393133931439315393163931739318393193932039321393223932339324393253932639327393283932939330393313933239333393343933539336393373933839339393403934139342393433934439345393463934739348393493935039351393523935339354393553935639357393583935939360393613936239363393643936539366393673936839369393703937139372393733937439375393763937739378393793938039381393823938339384393853938639387393883938939390393913939239393393943939539396393973939839399394003940139402394033940439405394063940739408394093941039411394123941339414394153941639417394183941939420394213942239423394243942539426394273942839429394303943139432394333943439435394363943739438394393944039441394423944339444394453944639447394483944939450394513945239453394543945539456394573945839459394603946139462394633946439465394663946739468394693947039471394723947339474394753947639477394783947939480394813948239483394843948539486394873948839489394903949139492394933949439495394963949739498394993950039501395023950339504395053950639507395083950939510395113951239513395143951539516395173951839519395203952139522395233952439525395263952739528395293953039531395323953339534395353953639537395383953939540395413954239543395443954539546395473954839549395503955139552395533955439555395563955739558395593956039561395623956339564395653956639567395683956939570395713957239573395743957539576395773957839579395803958139582395833958439585395863958739588395893959039591395923959339594395953959639597395983959939600396013960239603396043960539606396073960839609396103961139612396133961439615396163961739618396193962039621396223962339624396253962639627396283962939630396313963239633396343963539636396373963839639396403964139642396433964439645396463964739648396493965039651396523965339654396553965639657396583965939660396613966239663396643966539666396673966839669396703967139672396733967439675396763967739678396793968039681396823968339684396853968639687396883968939690396913969239693396943969539696396973969839699397003970139702397033970439705397063970739708397093971039711397123971339714397153971639717397183971939720397213972239723397243972539726397273972839729397303973139732397333973439735397363973739738397393974039741397423974339744397453974639747397483974939750397513975239753397543975539756397573975839759397603976139762397633976439765397663976739768397693977039771397723977339774397753977639777397783977939780397813978239783397843978539786397873978839789397903979139792397933979439795397963979739798397993980039801398023980339804398053980639807398083980939810398113981239813398143981539816398173981839819398203982139822398233982439825398263982739828398293983039831398323983339834398353983639837398383983939840398413984239843398443984539846398473984839849398503985139852398533985439855398563985739858398593986039861398623986339864398653986639867398683986939870398713987239873398743987539876398773987839879398803988139882398833988439885398863988739888398893989039891398923989339894398953989639897398983989939900399013990239903399043990539906399073990839909399103991139912399133991439915399163991739918399193992039921399223992339924399253992639927399283992939930399313993239933399343993539936399373993839939399403994139942399433994439945399463994739948399493995039951399523995339954399553995639957399583995939960399613996239963399643996539966399673996839969399703997139972399733997439975399763997739978399793998039981399823998339984399853998639987399883998939990399913999239993399943999539996399973999839999400004000140002400034000440005400064000740008400094001040011400124001340014400154001640017400184001940020400214002240023400244002540026400274002840029400304003140032400334003440035400364003740038400394004040041400424004340044400454004640047400484004940050400514005240053400544005540056400574005840059400604006140062400634006440065400664006740068400694007040071400724007340074400754007640077400784007940080400814008240083400844008540086400874008840089400904009140092400934009440095400964009740098400994010040101401024010340104401054010640107401084010940110401114011240113401144011540116401174011840119401204012140122401234012440125401264012740128401294013040131401324013340134401354013640137401384013940140401414014240143401444014540146401474014840149401504015140152401534015440155401564015740158401594016040161401624016340164401654016640167401684016940170401714017240173401744017540176401774017840179401804018140182401834018440185401864018740188401894019040191401924019340194401954019640197401984019940200402014020240203402044020540206402074020840209402104021140212402134021440215402164021740218402194022040221402224022340224402254022640227402284022940230402314023240233402344023540236402374023840239402404024140242402434024440245402464024740248402494025040251402524025340254402554025640257402584025940260402614026240263402644026540266402674026840269402704027140272402734027440275402764027740278402794028040281402824028340284402854028640287402884028940290402914029240293402944029540296402974029840299403004030140302403034030440305403064030740308403094031040311403124031340314403154031640317403184031940320403214032240323403244032540326403274032840329403304033140332403334033440335403364033740338403394034040341403424034340344403454034640347403484034940350403514035240353403544035540356403574035840359403604036140362403634036440365403664036740368403694037040371403724037340374403754037640377403784037940380403814038240383403844038540386403874038840389403904039140392403934039440395403964039740398403994040040401404024040340404404054040640407404084040940410404114041240413404144041540416404174041840419404204042140422404234042440425404264042740428404294043040431404324043340434404354043640437404384043940440404414044240443404444044540446404474044840449404504045140452404534045440455404564045740458404594046040461404624046340464404654046640467404684046940470404714047240473404744047540476404774047840479404804048140482404834048440485404864048740488404894049040491404924049340494404954049640497404984049940500405014050240503405044050540506405074050840509405104051140512405134051440515405164051740518405194052040521405224052340524405254052640527405284052940530405314053240533405344053540536405374053840539405404054140542405434054440545405464054740548405494055040551405524055340554405554055640557405584055940560405614056240563405644056540566405674056840569405704057140572405734057440575405764057740578405794058040581405824058340584405854058640587405884058940590405914059240593405944059540596405974059840599406004060140602406034060440605406064060740608406094061040611406124061340614406154061640617406184061940620406214062240623406244062540626406274062840629406304063140632406334063440635406364063740638406394064040641406424064340644406454064640647406484064940650406514065240653406544065540656406574065840659406604066140662406634066440665406664066740668406694067040671406724067340674406754067640677406784067940680406814068240683406844068540686406874068840689406904069140692406934069440695406964069740698406994070040701407024070340704407054070640707407084070940710407114071240713407144071540716407174071840719407204072140722407234072440725407264072740728407294073040731407324073340734407354073640737407384073940740407414074240743407444074540746407474074840749407504075140752407534075440755407564075740758407594076040761407624076340764407654076640767407684076940770407714077240773407744077540776407774077840779407804078140782407834078440785407864078740788407894079040791407924079340794407954079640797407984079940800408014080240803408044080540806408074080840809408104081140812408134081440815408164081740818408194082040821408224082340824408254082640827408284082940830408314083240833408344083540836408374083840839408404084140842408434084440845408464084740848408494085040851408524085340854408554085640857408584085940860408614086240863408644086540866408674086840869408704087140872408734087440875408764087740878408794088040881408824088340884408854088640887408884088940890408914089240893408944089540896408974089840899409004090140902409034090440905409064090740908409094091040911409124091340914409154091640917409184091940920409214092240923409244092540926409274092840929409304093140932409334093440935409364093740938409394094040941409424094340944409454094640947409484094940950409514095240953409544095540956409574095840959409604096140962409634096440965409664096740968409694097040971409724097340974409754097640977409784097940980409814098240983409844098540986409874098840989409904099140992409934099440995409964099740998409994100041001410024100341004410054100641007410084100941010410114101241013410144101541016410174101841019410204102141022410234102441025410264102741028410294103041031410324103341034410354103641037410384103941040410414104241043410444104541046410474104841049410504105141052410534105441055410564105741058410594106041061410624106341064410654106641067410684106941070410714107241073410744107541076410774107841079410804108141082410834108441085410864108741088410894109041091410924109341094410954109641097410984109941100411014110241103411044110541106411074110841109411104111141112411134111441115411164111741118411194112041121411224112341124411254112641127411284112941130411314113241133411344113541136411374113841139411404114141142411434114441145411464114741148411494115041151411524115341154411554115641157411584115941160411614116241163411644116541166411674116841169411704117141172411734117441175411764117741178411794118041181411824118341184411854118641187411884118941190411914119241193411944119541196411974119841199412004120141202412034120441205412064120741208412094121041211412124121341214412154121641217412184121941220412214122241223412244122541226412274122841229412304123141232412334123441235412364123741238412394124041241412424124341244412454124641247412484124941250412514125241253412544125541256412574125841259412604126141262412634126441265412664126741268412694127041271412724127341274412754127641277412784127941280412814128241283412844128541286412874128841289412904129141292412934129441295412964129741298412994130041301413024130341304413054130641307413084130941310413114131241313413144131541316413174131841319413204132141322413234132441325413264132741328413294133041331413324133341334413354133641337413384133941340413414134241343413444134541346413474134841349413504135141352413534135441355413564135741358413594136041361413624136341364413654136641367413684136941370413714137241373413744137541376413774137841379413804138141382413834138441385413864138741388413894139041391413924139341394413954139641397413984139941400414014140241403414044140541406414074140841409414104141141412414134141441415414164141741418414194142041421414224142341424414254142641427414284142941430414314143241433414344143541436414374143841439414404144141442414434144441445414464144741448414494145041451414524145341454414554145641457414584145941460414614146241463414644146541466414674146841469414704147141472414734147441475414764147741478414794148041481414824148341484414854148641487414884148941490414914149241493414944149541496414974149841499415004150141502415034150441505415064150741508415094151041511415124151341514415154151641517415184151941520415214152241523415244152541526415274152841529415304153141532415334153441535415364153741538415394154041541415424154341544415454154641547415484154941550415514155241553415544155541556415574155841559415604156141562415634156441565415664156741568415694157041571415724157341574415754157641577415784157941580415814158241583415844158541586415874158841589415904159141592415934159441595415964159741598415994160041601416024160341604416054160641607416084160941610416114161241613416144161541616416174161841619416204162141622416234162441625416264162741628416294163041631416324163341634416354163641637416384163941640416414164241643416444164541646416474164841649416504165141652416534165441655416564165741658416594166041661416624166341664416654166641667416684166941670416714167241673416744167541676416774167841679416804168141682416834168441685416864168741688416894169041691416924169341694416954169641697416984169941700417014170241703417044170541706417074170841709417104171141712417134171441715417164171741718417194172041721417224172341724417254172641727417284172941730417314173241733417344173541736417374173841739417404174141742417434174441745417464174741748417494175041751417524175341754417554175641757417584175941760417614176241763417644176541766417674176841769417704177141772417734177441775417764177741778417794178041781417824178341784417854178641787417884178941790417914179241793417944179541796417974179841799418004180141802418034180441805418064180741808418094181041811418124181341814418154181641817418184181941820418214182241823418244182541826418274182841829418304183141832418334183441835418364183741838418394184041841418424184341844418454184641847418484184941850418514185241853418544185541856418574185841859418604186141862418634186441865418664186741868418694187041871418724187341874418754187641877418784187941880418814188241883418844188541886418874188841889418904189141892418934189441895418964189741898418994190041901419024190341904419054190641907419084190941910419114191241913419144191541916419174191841919419204192141922419234192441925419264192741928419294193041931419324193341934419354193641937419384193941940419414194241943419444194541946419474194841949419504195141952419534195441955419564195741958419594196041961419624196341964419654196641967419684196941970419714197241973419744197541976419774197841979419804198141982419834198441985419864198741988419894199041991419924199341994419954199641997419984199942000420014200242003420044200542006420074200842009420104201142012420134201442015420164201742018420194202042021420224202342024420254202642027420284202942030420314203242033420344203542036420374203842039420404204142042420434204442045420464204742048420494205042051420524205342054420554205642057420584205942060420614206242063420644206542066420674206842069420704207142072420734207442075420764207742078420794208042081420824208342084420854208642087420884208942090420914209242093420944209542096420974209842099421004210142102421034210442105421064210742108421094211042111421124211342114421154211642117421184211942120421214212242123421244212542126421274212842129421304213142132421334213442135421364213742138421394214042141421424214342144421454214642147421484214942150421514215242153421544215542156421574215842159421604216142162421634216442165421664216742168421694217042171421724217342174421754217642177421784217942180421814218242183421844218542186421874218842189421904219142192421934219442195421964219742198421994220042201422024220342204422054220642207422084220942210422114221242213422144221542216422174221842219422204222142222422234222442225422264222742228422294223042231422324223342234422354223642237422384223942240422414224242243422444224542246422474224842249422504225142252422534225442255422564225742258422594226042261422624226342264422654226642267422684226942270422714227242273422744227542276422774227842279422804228142282422834228442285422864228742288422894229042291422924229342294422954229642297422984229942300423014230242303423044230542306423074230842309423104231142312423134231442315423164231742318423194232042321423224232342324423254232642327423284232942330423314233242333423344233542336423374233842339423404234142342423434234442345423464234742348423494235042351423524235342354423554235642357423584235942360423614236242363423644236542366423674236842369423704237142372423734237442375423764237742378423794238042381423824238342384423854238642387423884238942390423914239242393423944239542396423974239842399424004240142402424034240442405424064240742408424094241042411424124241342414424154241642417424184241942420424214242242423424244242542426424274242842429424304243142432424334243442435424364243742438424394244042441424424244342444424454244642447424484244942450424514245242453424544245542456424574245842459424604246142462424634246442465424664246742468424694247042471424724247342474424754247642477424784247942480424814248242483424844248542486424874248842489424904249142492424934249442495424964249742498424994250042501425024250342504425054250642507425084250942510425114251242513425144251542516425174251842519425204252142522425234252442525425264252742528425294253042531425324253342534425354253642537425384253942540425414254242543425444254542546425474254842549425504255142552425534255442555425564255742558425594256042561425624256342564425654256642567425684256942570425714257242573425744257542576425774257842579425804258142582425834258442585425864258742588425894259042591425924259342594425954259642597425984259942600426014260242603426044260542606426074260842609426104261142612426134261442615426164261742618426194262042621426224262342624426254262642627426284262942630426314263242633426344263542636426374263842639426404264142642426434264442645426464264742648426494265042651426524265342654426554265642657426584265942660426614266242663426644266542666426674266842669426704267142672426734267442675426764267742678426794268042681426824268342684426854268642687426884268942690426914269242693426944269542696426974269842699427004270142702427034270442705427064270742708427094271042711427124271342714427154271642717427184271942720427214272242723427244272542726427274272842729427304273142732427334273442735427364273742738427394274042741427424274342744427454274642747427484274942750427514275242753427544275542756427574275842759427604276142762427634276442765427664276742768427694277042771427724277342774427754277642777427784277942780427814278242783427844278542786427874278842789427904279142792427934279442795427964279742798427994280042801428024280342804428054280642807428084280942810428114281242813428144281542816428174281842819428204282142822428234282442825428264282742828428294283042831428324283342834428354283642837428384283942840428414284242843428444284542846428474284842849428504285142852428534285442855428564285742858428594286042861428624286342864428654286642867428684286942870428714287242873428744287542876428774287842879428804288142882428834288442885428864288742888428894289042891428924289342894428954289642897428984289942900429014290242903429044290542906429074290842909429104291142912429134291442915429164291742918429194292042921429224292342924429254292642927429284292942930429314293242933429344293542936429374293842939429404294142942429434294442945429464294742948429494295042951429524295342954429554295642957429584295942960429614296242963429644296542966429674296842969429704297142972429734297442975429764297742978429794298042981429824298342984429854298642987429884298942990429914299242993429944299542996429974299842999430004300143002430034300443005430064300743008430094301043011430124301343014430154301643017430184301943020430214302243023430244302543026430274302843029430304303143032430334303443035430364303743038430394304043041430424304343044430454304643047430484304943050430514305243053430544305543056430574305843059430604306143062430634306443065430664306743068430694307043071430724307343074430754307643077430784307943080430814308243083430844308543086430874308843089430904309143092430934309443095430964309743098430994310043101431024310343104431054310643107431084310943110431114311243113431144311543116431174311843119431204312143122431234312443125431264312743128431294313043131431324313343134431354313643137431384313943140431414314243143431444314543146431474314843149431504315143152431534315443155431564315743158431594316043161431624316343164431654316643167431684316943170431714317243173431744317543176431774317843179431804318143182431834318443185431864318743188431894319043191431924319343194431954319643197431984319943200432014320243203432044320543206432074320843209432104321143212432134321443215432164321743218432194322043221432224322343224432254322643227432284322943230432314323243233432344323543236432374323843239432404324143242432434324443245432464324743248432494325043251432524325343254432554325643257432584325943260432614326243263432644326543266432674326843269432704327143272432734327443275432764327743278432794328043281432824328343284432854328643287432884328943290432914329243293432944329543296432974329843299433004330143302433034330443305433064330743308433094331043311433124331343314433154331643317433184331943320433214332243323433244332543326433274332843329433304333143332433334333443335433364333743338433394334043341433424334343344433454334643347433484334943350433514335243353433544335543356433574335843359433604336143362433634336443365433664336743368433694337043371433724337343374433754337643377433784337943380433814338243383433844338543386433874338843389433904339143392433934339443395433964339743398433994340043401434024340343404434054340643407434084340943410434114341243413434144341543416434174341843419434204342143422434234342443425434264342743428434294343043431434324343343434434354343643437434384343943440434414344243443434444344543446434474344843449434504345143452434534345443455434564345743458434594346043461434624346343464434654346643467434684346943470434714347243473434744347543476434774347843479434804348143482434834348443485434864348743488434894349043491434924349343494434954349643497434984349943500435014350243503435044350543506435074350843509435104351143512435134351443515435164351743518435194352043521435224352343524435254352643527435284352943530435314353243533435344353543536435374353843539435404354143542435434354443545435464354743548435494355043551435524355343554435554355643557435584355943560435614356243563435644356543566435674356843569435704357143572435734357443575435764357743578435794358043581435824358343584435854358643587435884358943590435914359243593435944359543596435974359843599436004360143602436034360443605436064360743608436094361043611436124361343614436154361643617436184361943620436214362243623436244362543626436274362843629436304363143632436334363443635436364363743638436394364043641436424364343644436454364643647436484364943650436514365243653436544365543656436574365843659436604366143662436634366443665436664366743668436694367043671436724367343674436754367643677436784367943680436814368243683436844368543686436874368843689436904369143692436934369443695436964369743698436994370043701437024370343704437054370643707437084370943710437114371243713437144371543716437174371843719437204372143722437234372443725437264372743728437294373043731437324373343734437354373643737437384373943740437414374243743437444374543746437474374843749437504375143752437534375443755437564375743758437594376043761437624376343764437654376643767437684376943770437714377243773437744377543776437774377843779437804378143782437834378443785437864378743788437894379043791437924379343794437954379643797437984379943800438014380243803438044380543806438074380843809438104381143812438134381443815438164381743818438194382043821438224382343824438254382643827438284382943830438314383243833438344383543836438374383843839438404384143842438434384443845438464384743848438494385043851438524385343854438554385643857438584385943860438614386243863438644386543866438674386843869438704387143872438734387443875438764387743878438794388043881438824388343884438854388643887438884388943890438914389243893438944389543896438974389843899439004390143902439034390443905439064390743908439094391043911439124391343914439154391643917439184391943920439214392243923439244392543926439274392843929439304393143932439334393443935439364393743938439394394043941439424394343944439454394643947439484394943950439514395243953439544395543956439574395843959439604396143962439634396443965439664396743968439694397043971439724397343974439754397643977439784397943980439814398243983439844398543986439874398843989439904399143992439934399443995439964399743998439994400044001440024400344004440054400644007440084400944010440114401244013440144401544016440174401844019440204402144022440234402444025440264402744028440294403044031440324403344034440354403644037440384403944040440414404244043440444404544046440474404844049440504405144052440534405444055440564405744058440594406044061440624406344064440654406644067440684406944070440714407244073440744407544076440774407844079440804408144082440834408444085440864408744088440894409044091440924409344094440954409644097440984409944100441014410244103441044410544106441074410844109441104411144112441134411444115441164411744118441194412044121441224412344124441254412644127441284412944130441314413244133441344413544136441374413844139441404414144142441434414444145441464414744148441494415044151441524415344154441554415644157441584415944160441614416244163441644416544166441674416844169441704417144172441734417444175441764417744178441794418044181441824418344184441854418644187441884418944190441914419244193441944419544196441974419844199442004420144202442034420444205442064420744208442094421044211442124421344214442154421644217442184421944220442214422244223442244422544226442274422844229442304423144232442334423444235442364423744238442394424044241442424424344244442454424644247442484424944250442514425244253442544425544256442574425844259442604426144262442634426444265442664426744268442694427044271442724427344274442754427644277442784427944280442814428244283442844428544286442874428844289442904429144292442934429444295442964429744298442994430044301443024430344304443054430644307443084430944310443114431244313443144431544316443174431844319443204432144322443234432444325443264432744328443294433044331443324433344334443354433644337443384433944340443414434244343443444434544346443474434844349443504435144352443534435444355443564435744358443594436044361443624436344364443654436644367443684436944370443714437244373443744437544376443774437844379443804438144382443834438444385443864438744388443894439044391443924439344394443954439644397443984439944400444014440244403444044440544406444074440844409444104441144412444134441444415444164441744418444194442044421444224442344424444254442644427444284442944430444314443244433444344443544436444374443844439444404444144442444434444444445444464444744448444494445044451444524445344454444554445644457444584445944460444614446244463444644446544466444674446844469444704447144472444734447444475444764447744478444794448044481444824448344484444854448644487444884448944490444914449244493444944449544496444974449844499445004450144502445034450444505445064450744508445094451044511445124451344514445154451644517445184451944520445214452244523445244452544526445274452844529445304453144532445334453444535445364453744538445394454044541445424454344544445454454644547445484454944550445514455244553445544455544556445574455844559445604456144562445634456444565445664456744568445694457044571445724457344574445754457644577445784457944580445814458244583445844458544586445874458844589445904459144592445934459444595445964459744598445994460044601446024460344604446054460644607446084460944610446114461244613446144461544616446174461844619446204462144622446234462444625446264462744628446294463044631446324463344634446354463644637446384463944640446414464244643446444464544646446474464844649446504465144652446534465444655446564465744658446594466044661446624466344664446654466644667446684466944670446714467244673446744467544676446774467844679446804468144682446834468444685446864468744688446894469044691446924469344694446954469644697446984469944700447014470244703447044470544706447074470844709447104471144712447134471444715447164471744718447194472044721447224472344724447254472644727447284472944730447314473244733447344473544736447374473844739447404474144742447434474444745447464474744748447494475044751447524475344754447554475644757447584475944760447614476244763447644476544766447674476844769447704477144772447734477444775447764477744778447794478044781447824478344784447854478644787447884478944790447914479244793447944479544796447974479844799448004480144802448034480444805448064480744808448094481044811448124481344814448154481644817448184481944820448214482244823448244482544826448274482844829448304483144832448334483444835448364483744838448394484044841448424484344844448454484644847448484484944850448514485244853448544485544856448574485844859448604486144862448634486444865448664486744868448694487044871448724487344874448754487644877448784487944880448814488244883448844488544886448874488844889448904489144892448934489444895448964489744898448994490044901449024490344904449054490644907449084490944910449114491244913449144491544916449174491844919449204492144922449234492444925449264492744928449294493044931449324493344934449354493644937449384493944940449414494244943449444494544946449474494844949449504495144952449534495444955449564495744958449594496044961449624496344964449654496644967449684496944970449714497244973449744497544976449774497844979449804498144982449834498444985449864498744988449894499044991449924499344994449954499644997449984499945000450014500245003450044500545006450074500845009450104501145012450134501445015450164501745018450194502045021450224502345024450254502645027450284502945030450314503245033450344503545036450374503845039450404504145042450434504445045450464504745048450494505045051450524505345054450554505645057450584505945060450614506245063450644506545066450674506845069450704507145072450734507445075450764507745078450794508045081450824508345084450854508645087450884508945090450914509245093450944509545096450974509845099451004510145102451034510445105451064510745108451094511045111451124511345114451154511645117451184511945120451214512245123451244512545126451274512845129451304513145132451334513445135451364513745138451394514045141451424514345144451454514645147451484514945150451514515245153451544515545156451574515845159451604516145162451634516445165451664516745168451694517045171451724517345174451754517645177451784517945180451814518245183451844518545186451874518845189451904519145192451934519445195451964519745198451994520045201452024520345204452054520645207452084520945210452114521245213452144521545216452174521845219452204522145222452234522445225452264522745228452294523045231452324523345234452354523645237452384523945240452414524245243452444524545246452474524845249452504525145252452534525445255452564525745258452594526045261452624526345264452654526645267452684526945270452714527245273452744527545276452774527845279452804528145282452834528445285452864528745288452894529045291452924529345294452954529645297452984529945300453014530245303453044530545306453074530845309453104531145312453134531445315453164531745318453194532045321453224532345324453254532645327453284532945330453314533245333453344533545336453374533845339453404534145342453434534445345453464534745348453494535045351453524535345354453554535645357453584535945360453614536245363453644536545366453674536845369453704537145372453734537445375453764537745378453794538045381453824538345384453854538645387453884538945390453914539245393453944539545396453974539845399454004540145402454034540445405454064540745408454094541045411454124541345414454154541645417454184541945420454214542245423454244542545426454274542845429454304543145432454334543445435454364543745438454394544045441454424544345444454454544645447454484544945450454514545245453454544545545456454574545845459454604546145462454634546445465454664546745468454694547045471454724547345474454754547645477454784547945480454814548245483454844548545486454874548845489454904549145492454934549445495454964549745498454994550045501455024550345504455054550645507455084550945510455114551245513455144551545516455174551845519455204552145522455234552445525455264552745528455294553045531455324553345534455354553645537455384553945540455414554245543455444554545546455474554845549455504555145552455534555445555455564555745558455594556045561455624556345564455654556645567455684556945570455714557245573455744557545576455774557845579455804558145582455834558445585455864558745588455894559045591455924559345594455954559645597455984559945600456014560245603456044560545606456074560845609456104561145612456134561445615456164561745618456194562045621456224562345624456254562645627456284562945630456314563245633456344563545636456374563845639456404564145642456434564445645456464564745648456494565045651456524565345654456554565645657456584565945660456614566245663456644566545666456674566845669456704567145672456734567445675456764567745678456794568045681456824568345684456854568645687456884568945690456914569245693456944569545696456974569845699457004570145702457034570445705457064570745708457094571045711457124571345714457154571645717457184571945720457214572245723457244572545726457274572845729457304573145732457334573445735457364573745738457394574045741457424574345744457454574645747457484574945750457514575245753457544575545756457574575845759457604576145762457634576445765457664576745768457694577045771457724577345774457754577645777457784577945780457814578245783457844578545786457874578845789457904579145792457934579445795457964579745798457994580045801458024580345804458054580645807458084580945810458114581245813458144581545816458174581845819458204582145822458234582445825458264582745828458294583045831458324583345834458354583645837458384583945840458414584245843458444584545846458474584845849458504585145852458534585445855458564585745858458594586045861458624586345864458654586645867458684586945870458714587245873458744587545876458774587845879458804588145882458834588445885458864588745888458894589045891458924589345894458954589645897458984589945900459014590245903459044590545906459074590845909459104591145912459134591445915459164591745918459194592045921459224592345924459254592645927459284592945930459314593245933459344593545936459374593845939459404594145942459434594445945459464594745948459494595045951459524595345954459554595645957459584595945960459614596245963459644596545966459674596845969459704597145972459734597445975459764597745978459794598045981459824598345984459854598645987459884598945990459914599245993459944599545996459974599845999460004600146002460034600446005460064600746008460094601046011460124601346014460154601646017460184601946020460214602246023460244602546026460274602846029460304603146032460334603446035460364603746038460394604046041460424604346044460454604646047460484604946050460514605246053460544605546056460574605846059460604606146062460634606446065460664606746068460694607046071460724607346074460754607646077460784607946080460814608246083460844608546086460874608846089460904609146092460934609446095460964609746098460994610046101461024610346104461054610646107461084610946110461114611246113461144611546116461174611846119461204612146122461234612446125461264612746128461294613046131461324613346134461354613646137461384613946140461414614246143461444614546146461474614846149461504615146152461534615446155461564615746158461594616046161461624616346164461654616646167461684616946170461714617246173461744617546176461774617846179461804618146182461834618446185461864618746188461894619046191461924619346194461954619646197461984619946200462014620246203462044620546206462074620846209462104621146212462134621446215462164621746218462194622046221462224622346224462254622646227462284622946230462314623246233462344623546236462374623846239462404624146242462434624446245462464624746248462494625046251462524625346254462554625646257462584625946260462614626246263462644626546266462674626846269462704627146272462734627446275462764627746278462794628046281462824628346284462854628646287462884628946290462914629246293462944629546296462974629846299463004630146302463034630446305463064630746308463094631046311463124631346314463154631646317463184631946320463214632246323463244632546326463274632846329463304633146332463334633446335463364633746338463394634046341463424634346344463454634646347463484634946350463514635246353463544635546356463574635846359463604636146362463634636446365463664636746368463694637046371463724637346374463754637646377463784637946380463814638246383463844638546386463874638846389463904639146392463934639446395463964639746398463994640046401464024640346404464054640646407464084640946410464114641246413464144641546416464174641846419464204642146422464234642446425464264642746428464294643046431464324643346434464354643646437464384643946440464414644246443464444644546446464474644846449464504645146452464534645446455464564645746458464594646046461464624646346464464654646646467464684646946470464714647246473464744647546476464774647846479464804648146482464834648446485464864648746488464894649046491464924649346494464954649646497464984649946500465014650246503465044650546506465074650846509465104651146512465134651446515465164651746518465194652046521465224652346524465254652646527465284652946530465314653246533465344653546536465374653846539465404654146542465434654446545465464654746548465494655046551465524655346554465554655646557465584655946560465614656246563465644656546566465674656846569465704657146572465734657446575465764657746578465794658046581465824658346584465854658646587465884658946590465914659246593465944659546596465974659846599466004660146602466034660446605466064660746608466094661046611466124661346614466154661646617466184661946620466214662246623466244662546626466274662846629466304663146632466334663446635466364663746638466394664046641466424664346644466454664646647466484664946650466514665246653466544665546656466574665846659466604666146662466634666446665466664666746668466694667046671466724667346674466754667646677466784667946680466814668246683466844668546686466874668846689466904669146692466934669446695466964669746698466994670046701467024670346704467054670646707467084670946710467114671246713467144671546716467174671846719467204672146722467234672446725467264672746728467294673046731467324673346734467354673646737467384673946740467414674246743467444674546746467474674846749467504675146752467534675446755467564675746758467594676046761467624676346764467654676646767467684676946770467714677246773467744677546776467774677846779467804678146782467834678446785467864678746788467894679046791467924679346794467954679646797467984679946800468014680246803468044680546806468074680846809468104681146812468134681446815468164681746818468194682046821468224682346824468254682646827468284682946830468314683246833468344683546836468374683846839468404684146842468434684446845468464684746848468494685046851468524685346854468554685646857468584685946860468614686246863468644686546866468674686846869468704687146872468734687446875468764687746878468794688046881468824688346884468854688646887468884688946890468914689246893468944689546896468974689846899469004690146902469034690446905469064690746908469094691046911469124691346914469154691646917469184691946920469214692246923469244692546926469274692846929469304693146932469334693446935469364693746938469394694046941469424694346944469454694646947469484694946950469514695246953469544695546956469574695846959469604696146962469634696446965469664696746968469694697046971469724697346974469754697646977469784697946980469814698246983469844698546986469874698846989469904699146992469934699446995469964699746998469994700047001470024700347004470054700647007470084700947010470114701247013470144701547016470174701847019470204702147022470234702447025470264702747028470294703047031470324703347034470354703647037470384703947040470414704247043470444704547046470474704847049470504705147052470534705447055470564705747058470594706047061470624706347064470654706647067470684706947070470714707247073470744707547076470774707847079470804708147082470834708447085470864708747088470894709047091470924709347094470954709647097470984709947100471014710247103471044710547106471074710847109471104711147112471134711447115471164711747118471194712047121471224712347124471254712647127471284712947130471314713247133471344713547136471374713847139471404714147142471434714447145471464714747148471494715047151471524715347154471554715647157471584715947160471614716247163471644716547166471674716847169471704717147172471734717447175471764717747178471794718047181471824718347184471854718647187471884718947190471914719247193471944719547196471974719847199472004720147202472034720447205472064720747208472094721047211472124721347214472154721647217472184721947220472214722247223472244722547226472274722847229472304723147232472334723447235472364723747238472394724047241472424724347244472454724647247472484724947250472514725247253472544725547256472574725847259472604726147262472634726447265472664726747268472694727047271472724727347274472754727647277472784727947280472814728247283472844728547286472874728847289472904729147292472934729447295472964729747298472994730047301473024730347304473054730647307473084730947310473114731247313473144731547316473174731847319473204732147322473234732447325473264732747328473294733047331473324733347334473354733647337473384733947340473414734247343473444734547346473474734847349473504735147352473534735447355473564735747358473594736047361473624736347364473654736647367473684736947370473714737247373473744737547376473774737847379473804738147382473834738447385473864738747388473894739047391473924739347394473954739647397473984739947400474014740247403474044740547406474074740847409474104741147412474134741447415474164741747418474194742047421474224742347424474254742647427474284742947430474314743247433474344743547436474374743847439474404744147442474434744447445474464744747448474494745047451474524745347454474554745647457474584745947460474614746247463474644746547466474674746847469474704747147472474734747447475474764747747478474794748047481474824748347484474854748647487474884748947490474914749247493474944749547496474974749847499475004750147502475034750447505475064750747508475094751047511475124751347514475154751647517475184751947520475214752247523475244752547526475274752847529475304753147532475334753447535475364753747538475394754047541475424754347544475454754647547475484754947550475514755247553475544755547556475574755847559475604756147562475634756447565475664756747568475694757047571475724757347574475754757647577475784757947580475814758247583475844758547586475874758847589475904759147592475934759447595475964759747598475994760047601476024760347604476054760647607476084760947610476114761247613476144761547616476174761847619476204762147622476234762447625476264762747628476294763047631476324763347634476354763647637476384763947640476414764247643476444764547646476474764847649476504765147652476534765447655476564765747658476594766047661476624766347664476654766647667476684766947670476714767247673476744767547676476774767847679476804768147682476834768447685476864768747688476894769047691476924769347694476954769647697476984769947700477014770247703477044770547706477074770847709477104771147712477134771447715477164771747718477194772047721477224772347724477254772647727477284772947730477314773247733477344773547736477374773847739477404774147742477434774447745477464774747748477494775047751477524775347754477554775647757477584775947760477614776247763477644776547766477674776847769477704777147772477734777447775477764777747778477794778047781477824778347784477854778647787477884778947790477914779247793477944779547796477974779847799478004780147802478034780447805478064780747808478094781047811478124781347814478154781647817478184781947820478214782247823478244782547826478274782847829478304783147832478334783447835478364783747838478394784047841478424784347844478454784647847478484784947850478514785247853478544785547856478574785847859478604786147862478634786447865478664786747868478694787047871478724787347874478754787647877478784787947880478814788247883478844788547886478874788847889478904789147892478934789447895478964789747898478994790047901479024790347904479054790647907479084790947910479114791247913479144791547916479174791847919479204792147922479234792447925479264792747928479294793047931479324793347934479354793647937479384793947940479414794247943479444794547946479474794847949479504795147952479534795447955479564795747958479594796047961479624796347964479654796647967479684796947970479714797247973479744797547976479774797847979479804798147982479834798447985479864798747988479894799047991479924799347994479954799647997479984799948000480014800248003480044800548006480074800848009480104801148012480134801448015480164801748018480194802048021480224802348024480254802648027480284802948030480314803248033480344803548036480374803848039480404804148042480434804448045480464804748048480494805048051480524805348054480554805648057480584805948060480614806248063480644806548066480674806848069480704807148072480734807448075480764807748078480794808048081480824808348084480854808648087480884808948090480914809248093480944809548096480974809848099481004810148102481034810448105481064810748108481094811048111481124811348114481154811648117481184811948120481214812248123481244812548126481274812848129481304813148132481334813448135481364813748138481394814048141481424814348144481454814648147481484814948150481514815248153481544815548156481574815848159481604816148162481634816448165481664816748168481694817048171481724817348174481754817648177481784817948180481814818248183481844818548186481874818848189481904819148192481934819448195481964819748198481994820048201482024820348204482054820648207482084820948210482114821248213482144821548216482174821848219482204822148222482234822448225482264822748228482294823048231482324823348234482354823648237482384823948240482414824248243482444824548246482474824848249482504825148252482534825448255482564825748258482594826048261482624826348264482654826648267482684826948270482714827248273482744827548276482774827848279482804828148282482834828448285482864828748288482894829048291482924829348294482954829648297482984829948300483014830248303483044830548306483074830848309483104831148312483134831448315483164831748318483194832048321483224832348324483254832648327483284832948330483314833248333483344833548336483374833848339483404834148342483434834448345483464834748348483494835048351483524835348354483554835648357483584835948360483614836248363483644836548366483674836848369483704837148372483734837448375483764837748378483794838048381483824838348384483854838648387483884838948390483914839248393483944839548396483974839848399484004840148402484034840448405484064840748408484094841048411484124841348414484154841648417484184841948420484214842248423484244842548426484274842848429484304843148432484334843448435484364843748438484394844048441484424844348444484454844648447484484844948450484514845248453484544845548456484574845848459484604846148462484634846448465484664846748468484694847048471484724847348474484754847648477484784847948480484814848248483484844848548486484874848848489484904849148492484934849448495484964849748498484994850048501485024850348504485054850648507485084850948510485114851248513485144851548516485174851848519485204852148522485234852448525485264852748528485294853048531485324853348534485354853648537485384853948540485414854248543485444854548546485474854848549485504855148552485534855448555485564855748558485594856048561485624856348564485654856648567485684856948570485714857248573485744857548576485774857848579485804858148582485834858448585485864858748588485894859048591485924859348594485954859648597485984859948600486014860248603486044860548606486074860848609486104861148612486134861448615486164861748618486194862048621486224862348624486254862648627486284862948630486314863248633486344863548636486374863848639486404864148642486434864448645486464864748648486494865048651486524865348654486554865648657486584865948660486614866248663486644866548666486674866848669486704867148672486734867448675486764867748678486794868048681486824868348684486854868648687486884868948690486914869248693486944869548696486974869848699487004870148702487034870448705487064870748708487094871048711487124871348714487154871648717487184871948720487214872248723487244872548726487274872848729487304873148732487334873448735487364873748738487394874048741487424874348744487454874648747487484874948750487514875248753487544875548756487574875848759487604876148762487634876448765487664876748768487694877048771487724877348774487754877648777487784877948780487814878248783487844878548786487874878848789487904879148792487934879448795487964879748798487994880048801488024880348804488054880648807488084880948810488114881248813488144881548816488174881848819488204882148822488234882448825488264882748828488294883048831488324883348834488354883648837488384883948840488414884248843488444884548846488474884848849488504885148852488534885448855488564885748858488594886048861488624886348864488654886648867488684886948870488714887248873488744887548876488774887848879488804888148882488834888448885488864888748888488894889048891488924889348894488954889648897488984889948900489014890248903489044890548906489074890848909489104891148912489134891448915489164891748918489194892048921489224892348924489254892648927489284892948930489314893248933489344893548936489374893848939489404894148942489434894448945489464894748948489494895048951489524895348954489554895648957489584895948960489614896248963489644896548966489674896848969489704897148972489734897448975489764897748978489794898048981489824898348984489854898648987489884898948990489914899248993489944899548996489974899848999490004900149002490034900449005490064900749008490094901049011490124901349014490154901649017490184901949020490214902249023490244902549026490274902849029490304903149032490334903449035490364903749038490394904049041490424904349044490454904649047490484904949050490514905249053490544905549056490574905849059490604906149062490634906449065490664906749068490694907049071490724907349074490754907649077490784907949080490814908249083490844908549086490874908849089490904909149092490934909449095490964909749098490994910049101491024910349104491054910649107491084910949110491114911249113491144911549116491174911849119491204912149122491234912449125491264912749128491294913049131491324913349134491354913649137491384913949140491414914249143491444914549146491474914849149491504915149152491534915449155491564915749158491594916049161491624916349164491654916649167491684916949170491714917249173491744917549176491774917849179491804918149182491834918449185491864918749188491894919049191491924919349194491954919649197491984919949200492014920249203492044920549206492074920849209492104921149212492134921449215492164921749218492194922049221492224922349224492254922649227492284922949230492314923249233492344923549236492374923849239492404924149242492434924449245492464924749248492494925049251492524925349254492554925649257492584925949260492614926249263492644926549266492674926849269492704927149272492734927449275492764927749278492794928049281492824928349284492854928649287492884928949290492914929249293492944929549296492974929849299493004930149302493034930449305493064930749308493094931049311493124931349314493154931649317493184931949320493214932249323493244932549326493274932849329493304933149332493334933449335493364933749338493394934049341493424934349344493454934649347493484934949350493514935249353493544935549356493574935849359493604936149362493634936449365493664936749368493694937049371493724937349374493754937649377493784937949380493814938249383493844938549386493874938849389493904939149392493934939449395493964939749398493994940049401494024940349404494054940649407494084940949410494114941249413494144941549416494174941849419494204942149422494234942449425494264942749428494294943049431494324943349434494354943649437494384943949440494414944249443494444944549446494474944849449494504945149452494534945449455494564945749458494594946049461494624946349464494654946649467494684946949470494714947249473494744947549476494774947849479494804948149482494834948449485494864948749488494894949049491494924949349494494954949649497494984949949500495014950249503495044950549506495074950849509495104951149512495134951449515495164951749518495194952049521495224952349524495254952649527495284952949530495314953249533495344953549536495374953849539495404954149542495434954449545495464954749548495494955049551495524955349554495554955649557495584955949560495614956249563495644956549566495674956849569495704957149572495734957449575495764957749578495794958049581495824958349584495854958649587495884958949590495914959249593495944959549596495974959849599496004960149602496034960449605496064960749608496094961049611496124961349614496154961649617496184961949620496214962249623496244962549626496274962849629496304963149632496334963449635496364963749638496394964049641496424964349644496454964649647496484964949650496514965249653496544965549656496574965849659496604966149662496634966449665496664966749668496694967049671496724967349674496754967649677496784967949680496814968249683496844968549686496874968849689496904969149692496934969449695496964969749698496994970049701497024970349704497054970649707497084970949710497114971249713497144971549716497174971849719497204972149722497234972449725497264972749728497294973049731497324973349734497354973649737497384973949740497414974249743497444974549746497474974849749497504975149752497534975449755497564975749758497594976049761497624976349764497654976649767497684976949770497714977249773497744977549776497774977849779497804978149782497834978449785497864978749788497894979049791497924979349794497954979649797497984979949800498014980249803498044980549806498074980849809498104981149812498134981449815498164981749818498194982049821498224982349824498254982649827498284982949830498314983249833498344983549836498374983849839498404984149842498434984449845498464984749848498494985049851498524985349854498554985649857498584985949860498614986249863498644986549866498674986849869498704987149872498734987449875498764987749878498794988049881498824988349884498854988649887498884988949890498914989249893498944989549896498974989849899499004990149902499034990449905499064990749908499094991049911499124991349914499154991649917499184991949920499214992249923499244992549926499274992849929499304993149932499334993449935499364993749938499394994049941499424994349944499454994649947499484994949950499514995249953499544995549956499574995849959499604996149962499634996449965499664996749968499694997049971499724997349974499754997649977499784997949980499814998249983499844998549986499874998849989499904999149992499934999449995499964999749998499995000050001500025000350004500055000650007500085000950010500115001250013500145001550016500175001850019500205002150022500235002450025500265002750028500295003050031500325003350034500355003650037500385003950040500415004250043500445004550046500475004850049500505005150052500535005450055500565005750058500595006050061500625006350064500655006650067500685006950070500715007250073500745007550076500775007850079500805008150082500835008450085500865008750088500895009050091500925009350094500955009650097500985009950100501015010250103501045010550106501075010850109501105011150112501135011450115501165011750118501195012050121501225012350124501255012650127501285012950130501315013250133501345013550136501375013850139501405014150142501435014450145501465014750148501495015050151501525015350154501555015650157501585015950160501615016250163501645016550166501675016850169501705017150172501735017450175501765017750178501795018050181501825018350184501855018650187501885018950190501915019250193501945019550196501975019850199502005020150202502035020450205502065020750208502095021050211502125021350214502155021650217502185021950220502215022250223502245022550226502275022850229502305023150232502335023450235502365023750238502395024050241502425024350244502455024650247502485024950250502515025250253502545025550256502575025850259502605026150262502635026450265502665026750268502695027050271502725027350274502755027650277502785027950280502815028250283502845028550286502875028850289502905029150292502935029450295502965029750298502995030050301503025030350304503055030650307503085030950310503115031250313503145031550316503175031850319503205032150322503235032450325503265032750328503295033050331503325033350334503355033650337503385033950340503415034250343503445034550346503475034850349503505035150352503535035450355503565035750358503595036050361503625036350364503655036650367503685036950370503715037250373503745037550376503775037850379503805038150382503835038450385503865038750388503895039050391503925039350394503955039650397503985039950400504015040250403504045040550406504075040850409504105041150412504135041450415504165041750418504195042050421504225042350424504255042650427504285042950430504315043250433504345043550436504375043850439504405044150442504435044450445504465044750448504495045050451504525045350454504555045650457504585045950460504615046250463504645046550466504675046850469504705047150472504735047450475504765047750478504795048050481504825048350484504855048650487504885048950490504915049250493504945049550496504975049850499505005050150502505035050450505505065050750508505095051050511505125051350514505155051650517505185051950520505215052250523505245052550526505275052850529505305053150532505335053450535505365053750538505395054050541505425054350544505455054650547505485054950550505515055250553505545055550556505575055850559505605056150562505635056450565505665056750568505695057050571505725057350574505755057650577505785057950580505815058250583505845058550586505875058850589505905059150592505935059450595505965059750598505995060050601506025060350604506055060650607506085060950610506115061250613506145061550616506175061850619506205062150622506235062450625506265062750628506295063050631506325063350634506355063650637506385063950640506415064250643506445064550646506475064850649506505065150652506535065450655506565065750658506595066050661506625066350664506655066650667506685066950670506715067250673506745067550676506775067850679506805068150682506835068450685506865068750688506895069050691506925069350694506955069650697506985069950700507015070250703507045070550706507075070850709507105071150712507135071450715507165071750718507195072050721507225072350724507255072650727507285072950730507315073250733507345073550736507375073850739507405074150742507435074450745507465074750748507495075050751507525075350754507555075650757507585075950760507615076250763507645076550766507675076850769507705077150772507735077450775507765077750778507795078050781507825078350784507855078650787507885078950790507915079250793507945079550796507975079850799508005080150802508035080450805508065080750808508095081050811508125081350814508155081650817508185081950820508215082250823508245082550826508275082850829508305083150832508335083450835508365083750838508395084050841508425084350844508455084650847508485084950850508515085250853508545085550856508575085850859508605086150862508635086450865508665086750868508695087050871508725087350874508755087650877508785087950880508815088250883508845088550886508875088850889508905089150892508935089450895508965089750898508995090050901509025090350904509055090650907509085090950910509115091250913509145091550916509175091850919509205092150922509235092450925509265092750928509295093050931509325093350934509355093650937509385093950940509415094250943509445094550946509475094850949509505095150952509535095450955509565095750958509595096050961509625096350964509655096650967509685096950970509715097250973509745097550976509775097850979509805098150982509835098450985509865098750988509895099050991509925099350994509955099650997509985099951000510015100251003510045100551006510075100851009510105101151012510135101451015510165101751018510195102051021510225102351024510255102651027510285102951030510315103251033510345103551036510375103851039510405104151042510435104451045510465104751048510495105051051510525105351054510555105651057510585105951060510615106251063510645106551066510675106851069510705107151072510735107451075510765107751078510795108051081510825108351084510855108651087510885108951090510915109251093510945109551096510975109851099511005110151102511035110451105511065110751108511095111051111511125111351114511155111651117511185111951120511215112251123511245112551126511275112851129511305113151132511335113451135511365113751138511395114051141511425114351144511455114651147511485114951150511515115251153511545115551156511575115851159511605116151162511635116451165511665116751168511695117051171511725117351174511755117651177511785117951180511815118251183511845118551186511875118851189511905119151192511935119451195511965119751198511995120051201512025120351204512055120651207512085120951210512115121251213512145121551216512175121851219512205122151222512235122451225512265122751228512295123051231512325123351234512355123651237512385123951240512415124251243512445124551246512475124851249512505125151252512535125451255512565125751258512595126051261512625126351264512655126651267512685126951270512715127251273512745127551276512775127851279512805128151282512835128451285512865128751288512895129051291512925129351294512955129651297512985129951300513015130251303513045130551306513075130851309513105131151312513135131451315513165131751318513195132051321513225132351324513255132651327513285132951330513315133251333513345133551336513375133851339513405134151342513435134451345513465134751348513495135051351513525135351354513555135651357513585135951360513615136251363513645136551366513675136851369513705137151372513735137451375513765137751378513795138051381513825138351384513855138651387513885138951390513915139251393513945139551396513975139851399514005140151402514035140451405514065140751408514095141051411514125141351414514155141651417514185141951420514215142251423514245142551426514275142851429514305143151432514335143451435514365143751438514395144051441514425144351444514455144651447514485144951450514515145251453514545145551456514575145851459514605146151462514635146451465514665146751468514695147051471514725147351474514755147651477514785147951480514815148251483514845148551486514875148851489514905149151492514935149451495514965149751498514995150051501515025150351504515055150651507515085150951510515115151251513515145151551516515175151851519515205152151522515235152451525515265152751528515295153051531515325153351534515355153651537515385153951540515415154251543515445154551546515475154851549515505155151552515535155451555515565155751558515595156051561515625156351564515655156651567515685156951570515715157251573515745157551576515775157851579515805158151582515835158451585515865158751588515895159051591515925159351594515955159651597515985159951600516015160251603516045160551606516075160851609516105161151612516135161451615516165161751618516195162051621516225162351624516255162651627516285162951630516315163251633516345163551636516375163851639516405164151642516435164451645516465164751648516495165051651516525165351654516555165651657516585165951660516615166251663516645166551666516675166851669516705167151672516735167451675516765167751678516795168051681516825168351684516855168651687516885168951690516915169251693516945169551696516975169851699517005170151702517035170451705517065170751708517095171051711517125171351714517155171651717517185171951720517215172251723517245172551726517275172851729517305173151732517335173451735517365173751738517395174051741517425174351744517455174651747517485174951750517515175251753517545175551756517575175851759517605176151762517635176451765517665176751768517695177051771517725177351774517755177651777517785177951780517815178251783517845178551786517875178851789517905179151792517935179451795517965179751798517995180051801518025180351804518055180651807518085180951810518115181251813518145181551816518175181851819518205182151822518235182451825518265182751828518295183051831518325183351834518355183651837518385183951840518415184251843518445184551846518475184851849518505185151852518535185451855518565185751858518595186051861518625186351864518655186651867518685186951870518715187251873518745187551876518775187851879518805188151882518835188451885518865188751888518895189051891518925189351894518955189651897518985189951900519015190251903519045190551906519075190851909519105191151912519135191451915519165191751918519195192051921519225192351924519255192651927519285192951930519315193251933519345193551936519375193851939519405194151942519435194451945519465194751948519495195051951519525195351954519555195651957519585195951960519615196251963519645196551966519675196851969519705197151972519735197451975519765197751978519795198051981519825198351984519855198651987519885198951990519915199251993519945199551996519975199851999520005200152002520035200452005520065200752008520095201052011520125201352014520155201652017520185201952020520215202252023520245202552026520275202852029520305203152032520335203452035520365203752038520395204052041520425204352044520455204652047520485204952050520515205252053520545205552056520575205852059520605206152062520635206452065520665206752068520695207052071520725207352074520755207652077520785207952080520815208252083520845208552086520875208852089520905209152092520935209452095520965209752098520995210052101521025210352104521055210652107521085210952110521115211252113521145211552116521175211852119521205212152122521235212452125521265212752128521295213052131521325213352134521355213652137521385213952140521415214252143521445214552146521475214852149521505215152152521535215452155521565215752158521595216052161521625216352164521655216652167521685216952170521715217252173521745217552176521775217852179521805218152182521835218452185521865218752188521895219052191521925219352194521955219652197521985219952200522015220252203522045220552206522075220852209522105221152212522135221452215522165221752218522195222052221522225222352224522255222652227522285222952230522315223252233522345223552236522375223852239522405224152242522435224452245522465224752248522495225052251522525225352254522555225652257522585225952260522615226252263522645226552266522675226852269522705227152272522735227452275522765227752278522795228052281522825228352284522855228652287522885228952290522915229252293522945229552296522975229852299523005230152302523035230452305523065230752308523095231052311523125231352314523155231652317523185231952320523215232252323523245232552326523275232852329523305233152332523335233452335523365233752338523395234052341523425234352344523455234652347523485234952350523515235252353523545235552356523575235852359523605236152362523635236452365523665236752368523695237052371523725237352374523755237652377523785237952380523815238252383523845238552386523875238852389523905239152392523935239452395523965239752398523995240052401524025240352404524055240652407524085240952410524115241252413524145241552416524175241852419524205242152422524235242452425524265242752428524295243052431524325243352434524355243652437524385243952440524415244252443524445244552446524475244852449524505245152452524535245452455524565245752458524595246052461524625246352464524655246652467524685246952470524715247252473524745247552476524775247852479524805248152482524835248452485524865248752488524895249052491524925249352494524955249652497524985249952500525015250252503525045250552506525075250852509525105251152512525135251452515525165251752518525195252052521525225252352524525255252652527525285252952530525315253252533525345253552536525375253852539525405254152542525435254452545525465254752548525495255052551525525255352554525555255652557525585255952560525615256252563525645256552566525675256852569525705257152572525735257452575525765257752578525795258052581525825258352584525855258652587525885258952590525915259252593525945259552596525975259852599526005260152602526035260452605526065260752608526095261052611526125261352614526155261652617526185261952620526215262252623526245262552626526275262852629526305263152632526335263452635526365263752638526395264052641526425264352644526455264652647526485264952650526515265252653526545265552656526575265852659526605266152662526635266452665526665266752668526695267052671526725267352674526755267652677526785267952680526815268252683526845268552686526875268852689526905269152692526935269452695526965269752698526995270052701527025270352704527055270652707527085270952710527115271252713527145271552716527175271852719527205272152722527235272452725527265272752728527295273052731527325273352734527355273652737527385273952740527415274252743527445274552746527475274852749527505275152752527535275452755527565275752758527595276052761527625276352764527655276652767527685276952770527715277252773527745277552776527775277852779527805278152782527835278452785527865278752788527895279052791527925279352794527955279652797527985279952800528015280252803528045280552806528075280852809528105281152812528135281452815528165281752818528195282052821528225282352824528255282652827528285282952830528315283252833528345283552836528375283852839528405284152842528435284452845528465284752848528495285052851528525285352854528555285652857528585285952860528615286252863528645286552866528675286852869528705287152872528735287452875528765287752878528795288052881528825288352884528855288652887528885288952890528915289252893528945289552896528975289852899529005290152902529035290452905529065290752908529095291052911529125291352914529155291652917529185291952920529215292252923529245292552926529275292852929529305293152932529335293452935529365293752938529395294052941529425294352944529455294652947529485294952950529515295252953529545295552956529575295852959529605296152962529635296452965529665296752968529695297052971529725297352974529755297652977529785297952980529815298252983529845298552986529875298852989529905299152992529935299452995529965299752998529995300053001530025300353004530055300653007530085300953010530115301253013530145301553016530175301853019530205302153022530235302453025530265302753028530295303053031530325303353034530355303653037530385303953040530415304253043530445304553046530475304853049530505305153052530535305453055530565305753058530595306053061530625306353064530655306653067530685306953070530715307253073530745307553076530775307853079530805308153082530835308453085530865308753088530895309053091530925309353094530955309653097530985309953100531015310253103531045310553106531075310853109531105311153112531135311453115531165311753118531195312053121531225312353124531255312653127531285312953130531315313253133531345313553136531375313853139531405314153142531435314453145531465314753148531495315053151531525315353154531555315653157531585315953160531615316253163531645316553166531675316853169531705317153172531735317453175531765317753178531795318053181531825318353184531855318653187531885318953190531915319253193531945319553196531975319853199532005320153202532035320453205532065320753208532095321053211532125321353214532155321653217532185321953220532215322253223532245322553226532275322853229532305323153232532335323453235532365323753238532395324053241532425324353244532455324653247532485324953250532515325253253532545325553256532575325853259532605326153262532635326453265532665326753268532695327053271532725327353274532755327653277532785327953280532815328253283532845328553286532875328853289532905329153292532935329453295532965329753298532995330053301533025330353304533055330653307533085330953310533115331253313533145331553316533175331853319533205332153322533235332453325533265332753328533295333053331533325333353334533355333653337533385333953340533415334253343533445334553346533475334853349533505335153352533535335453355533565335753358533595336053361533625336353364533655336653367533685336953370533715337253373533745337553376533775337853379533805338153382533835338453385533865338753388533895339053391533925339353394533955339653397533985339953400534015340253403534045340553406534075340853409534105341153412534135341453415534165341753418534195342053421534225342353424534255342653427534285342953430534315343253433534345343553436534375343853439534405344153442534435344453445534465344753448534495345053451534525345353454534555345653457534585345953460534615346253463534645346553466534675346853469534705347153472534735347453475534765347753478534795348053481534825348353484534855348653487534885348953490534915349253493534945349553496534975349853499535005350153502535035350453505535065350753508535095351053511535125351353514535155351653517535185351953520535215352253523535245352553526535275352853529535305353153532535335353453535535365353753538535395354053541535425354353544535455354653547535485354953550535515355253553535545355553556535575355853559535605356153562535635356453565535665356753568535695357053571535725357353574535755357653577535785357953580535815358253583535845358553586535875358853589535905359153592535935359453595535965359753598535995360053601536025360353604536055360653607536085360953610536115361253613536145361553616536175361853619536205362153622536235362453625536265362753628536295363053631536325363353634536355363653637536385363953640536415364253643536445364553646536475364853649536505365153652536535365453655536565365753658536595366053661536625366353664536655366653667536685366953670536715367253673536745367553676536775367853679536805368153682536835368453685536865368753688536895369053691536925369353694536955369653697536985369953700537015370253703537045370553706537075370853709537105371153712537135371453715537165371753718537195372053721537225372353724537255372653727537285372953730537315373253733537345373553736537375373853739537405374153742537435374453745537465374753748537495375053751537525375353754537555375653757537585375953760537615376253763537645376553766537675376853769537705377153772537735377453775537765377753778537795378053781537825378353784537855378653787537885378953790537915379253793537945379553796537975379853799538005380153802538035380453805538065380753808538095381053811538125381353814538155381653817538185381953820538215382253823538245382553826538275382853829538305383153832538335383453835538365383753838538395384053841538425384353844538455384653847538485384953850538515385253853538545385553856538575385853859538605386153862538635386453865538665386753868538695387053871538725387353874538755387653877538785387953880538815388253883538845388553886538875388853889538905389153892538935389453895538965389753898538995390053901539025390353904539055390653907539085390953910539115391253913539145391553916539175391853919539205392153922539235392453925539265392753928539295393053931539325393353934539355393653937539385393953940539415394253943539445394553946539475394853949539505395153952539535395453955539565395753958539595396053961539625396353964539655396653967539685396953970539715397253973539745397553976539775397853979539805398153982539835398453985539865398753988539895399053991539925399353994539955399653997539985399954000540015400254003540045400554006540075400854009540105401154012540135401454015540165401754018540195402054021540225402354024540255402654027540285402954030540315403254033540345403554036540375403854039540405404154042540435404454045540465404754048540495405054051540525405354054540555405654057540585405954060540615406254063540645406554066540675406854069540705407154072540735407454075540765407754078540795408054081540825408354084540855408654087540885408954090540915409254093540945409554096540975409854099541005410154102541035410454105541065410754108541095411054111541125411354114541155411654117541185411954120541215412254123541245412554126541275412854129541305413154132541335413454135541365413754138541395414054141541425414354144541455414654147541485414954150541515415254153541545415554156541575415854159541605416154162541635416454165541665416754168541695417054171541725417354174541755417654177541785417954180541815418254183541845418554186541875418854189541905419154192541935419454195541965419754198541995420054201542025420354204542055420654207542085420954210542115421254213542145421554216542175421854219542205422154222542235422454225542265422754228542295423054231542325423354234542355423654237542385423954240542415424254243542445424554246542475424854249542505425154252542535425454255542565425754258542595426054261542625426354264542655426654267542685426954270542715427254273542745427554276542775427854279542805428154282542835428454285542865428754288542895429054291542925429354294542955429654297542985429954300543015430254303543045430554306543075430854309543105431154312543135431454315543165431754318543195432054321543225432354324543255432654327543285432954330543315433254333543345433554336543375433854339543405434154342543435434454345543465434754348543495435054351543525435354354543555435654357543585435954360543615436254363543645436554366543675436854369543705437154372543735437454375543765437754378543795438054381543825438354384543855438654387543885438954390543915439254393543945439554396543975439854399544005440154402544035440454405544065440754408544095441054411544125441354414544155441654417544185441954420544215442254423544245442554426544275442854429544305443154432544335443454435544365443754438544395444054441544425444354444544455444654447544485444954450544515445254453544545445554456544575445854459544605446154462544635446454465544665446754468544695447054471544725447354474544755447654477544785447954480544815448254483544845448554486544875448854489544905449154492544935449454495544965449754498544995450054501545025450354504545055450654507545085450954510545115451254513545145451554516545175451854519545205452154522545235452454525545265452754528545295453054531545325453354534545355453654537545385453954540545415454254543545445454554546545475454854549545505455154552545535455454555545565455754558545595456054561545625456354564545655456654567545685456954570545715457254573545745457554576545775457854579545805458154582545835458454585545865458754588545895459054591545925459354594545955459654597545985459954600546015460254603546045460554606546075460854609546105461154612546135461454615546165461754618546195462054621546225462354624546255462654627546285462954630546315463254633546345463554636546375463854639546405464154642546435464454645546465464754648546495465054651546525465354654546555465654657546585465954660546615466254663546645466554666546675466854669546705467154672546735467454675546765467754678546795468054681546825468354684546855468654687546885468954690546915469254693546945469554696546975469854699547005470154702547035470454705547065470754708547095471054711547125471354714547155471654717547185471954720547215472254723547245472554726547275472854729547305473154732547335473454735547365473754738547395474054741547425474354744547455474654747547485474954750547515475254753547545475554756547575475854759547605476154762547635476454765547665476754768547695477054771547725477354774547755477654777547785477954780547815478254783547845478554786547875478854789547905479154792547935479454795547965479754798547995480054801548025480354804548055480654807548085480954810548115481254813548145481554816548175481854819548205482154822548235482454825548265482754828548295483054831548325483354834548355483654837548385483954840548415484254843548445484554846548475484854849548505485154852548535485454855548565485754858548595486054861548625486354864548655486654867548685486954870548715487254873548745487554876548775487854879548805488154882548835488454885548865488754888548895489054891548925489354894548955489654897548985489954900549015490254903549045490554906549075490854909549105491154912549135491454915549165491754918549195492054921549225492354924549255492654927549285492954930549315493254933549345493554936549375493854939549405494154942549435494454945549465494754948549495495054951549525495354954549555495654957549585495954960549615496254963549645496554966549675496854969549705497154972549735497454975549765497754978549795498054981549825498354984549855498654987549885498954990549915499254993549945499554996549975499854999550005500155002550035500455005550065500755008550095501055011550125501355014550155501655017550185501955020550215502255023550245502555026550275502855029550305503155032550335503455035550365503755038550395504055041550425504355044550455504655047550485504955050550515505255053550545505555056550575505855059550605506155062550635506455065550665506755068550695507055071550725507355074550755507655077550785507955080550815508255083550845508555086550875508855089550905509155092550935509455095550965509755098550995510055101551025510355104551055510655107551085510955110551115511255113551145511555116551175511855119551205512155122551235512455125551265512755128551295513055131551325513355134551355513655137551385513955140551415514255143551445514555146551475514855149551505515155152551535515455155551565515755158551595516055161551625516355164551655516655167551685516955170551715517255173551745517555176551775517855179551805518155182551835518455185551865518755188551895519055191551925519355194551955519655197551985519955200552015520255203552045520555206552075520855209552105521155212552135521455215552165521755218552195522055221552225522355224552255522655227552285522955230552315523255233552345523555236552375523855239552405524155242552435524455245552465524755248552495525055251552525525355254552555525655257552585525955260552615526255263552645526555266552675526855269552705527155272552735527455275552765527755278552795528055281552825528355284552855528655287552885528955290552915529255293552945529555296552975529855299553005530155302553035530455305553065530755308553095531055311553125531355314553155531655317553185531955320553215532255323553245532555326553275532855329553305533155332553335533455335553365533755338553395534055341553425534355344553455534655347553485534955350553515535255353553545535555356553575535855359553605536155362553635536455365553665536755368553695537055371553725537355374553755537655377553785537955380553815538255383553845538555386553875538855389553905539155392553935539455395553965539755398553995540055401554025540355404554055540655407554085540955410554115541255413554145541555416554175541855419554205542155422554235542455425554265542755428554295543055431554325543355434554355543655437554385543955440554415544255443554445544555446554475544855449554505545155452554535545455455554565545755458554595546055461554625546355464554655546655467554685546955470554715547255473554745547555476554775547855479554805548155482554835548455485554865548755488554895549055491554925549355494554955549655497554985549955500555015550255503555045550555506555075550855509555105551155512555135551455515555165551755518555195552055521555225552355524555255552655527555285552955530555315553255533555345553555536555375553855539555405554155542555435554455545555465554755548555495555055551555525555355554555555555655557555585555955560555615556255563555645556555566555675556855569555705557155572555735557455575555765557755578555795558055581555825558355584555855558655587555885558955590555915559255593555945559555596555975559855599556005560155602556035560455605556065560755608556095561055611556125561355614556155561655617556185561955620556215562255623556245562555626556275562855629556305563155632556335563455635556365563755638556395564055641556425564355644556455564655647556485564955650556515565255653556545565555656556575565855659556605566155662556635566455665556665566755668556695567055671556725567355674556755567655677556785567955680556815568255683556845568555686556875568855689556905569155692556935569455695556965569755698556995570055701557025570355704557055570655707557085570955710557115571255713557145571555716557175571855719557205572155722557235572455725557265572755728557295573055731557325573355734557355573655737557385573955740557415574255743557445574555746557475574855749557505575155752557535575455755557565575755758557595576055761557625576355764557655576655767557685576955770557715577255773557745577555776557775577855779557805578155782557835578455785557865578755788557895579055791557925579355794557955579655797557985579955800558015580255803558045580555806558075580855809558105581155812558135581455815558165581755818558195582055821558225582355824558255582655827558285582955830558315583255833558345583555836558375583855839558405584155842558435584455845558465584755848558495585055851558525585355854558555585655857558585585955860558615586255863558645586555866558675586855869558705587155872558735587455875558765587755878558795588055881558825588355884558855588655887558885588955890558915589255893558945589555896558975589855899559005590155902559035590455905559065590755908559095591055911559125591355914559155591655917559185591955920559215592255923559245592555926559275592855929559305593155932559335593455935559365593755938559395594055941559425594355944559455594655947559485594955950559515595255953559545595555956559575595855959559605596155962559635596455965559665596755968559695597055971559725597355974559755597655977559785597955980559815598255983559845598555986559875598855989559905599155992559935599455995559965599755998559995600056001560025600356004560055600656007560085600956010560115601256013560145601556016560175601856019560205602156022560235602456025560265602756028560295603056031560325603356034560355603656037560385603956040560415604256043560445604556046560475604856049560505605156052560535605456055560565605756058560595606056061560625606356064560655606656067560685606956070560715607256073560745607556076560775607856079560805608156082560835608456085560865608756088560895609056091560925609356094560955609656097560985609956100561015610256103561045610556106561075610856109561105611156112561135611456115561165611756118561195612056121561225612356124561255612656127561285612956130561315613256133561345613556136561375613856139561405614156142561435614456145561465614756148561495615056151561525615356154561555615656157561585615956160561615616256163561645616556166561675616856169561705617156172561735617456175561765617756178561795618056181561825618356184561855618656187561885618956190561915619256193561945619556196561975619856199562005620156202562035620456205562065620756208562095621056211562125621356214562155621656217562185621956220562215622256223562245622556226562275622856229562305623156232562335623456235562365623756238562395624056241562425624356244562455624656247562485624956250562515625256253562545625556256562575625856259562605626156262562635626456265562665626756268562695627056271562725627356274562755627656277562785627956280562815628256283562845628556286562875628856289562905629156292562935629456295562965629756298562995630056301563025630356304563055630656307563085630956310563115631256313563145631556316563175631856319563205632156322563235632456325563265632756328563295633056331563325633356334563355633656337563385633956340563415634256343563445634556346563475634856349563505635156352563535635456355563565635756358563595636056361563625636356364563655636656367563685636956370563715637256373563745637556376563775637856379563805638156382563835638456385563865638756388563895639056391563925639356394563955639656397563985639956400564015640256403564045640556406564075640856409564105641156412564135641456415564165641756418564195642056421564225642356424564255642656427564285642956430564315643256433564345643556436564375643856439564405644156442564435644456445564465644756448564495645056451564525645356454564555645656457564585645956460564615646256463564645646556466564675646856469564705647156472564735647456475564765647756478564795648056481564825648356484564855648656487564885648956490564915649256493564945649556496564975649856499565005650156502565035650456505565065650756508565095651056511565125651356514565155651656517565185651956520565215652256523565245652556526565275652856529565305653156532565335653456535565365653756538565395654056541565425654356544565455654656547565485654956550565515655256553565545655556556565575655856559565605656156562565635656456565565665656756568565695657056571565725657356574565755657656577565785657956580565815658256583565845658556586565875658856589565905659156592565935659456595565965659756598565995660056601566025660356604566055660656607566085660956610566115661256613566145661556616566175661856619566205662156622566235662456625566265662756628566295663056631566325663356634566355663656637566385663956640566415664256643566445664556646566475664856649566505665156652566535665456655566565665756658566595666056661566625666356664566655666656667566685666956670566715667256673566745667556676566775667856679566805668156682566835668456685566865668756688566895669056691566925669356694566955669656697566985669956700567015670256703567045670556706567075670856709567105671156712567135671456715567165671756718567195672056721567225672356724567255672656727567285672956730567315673256733567345673556736567375673856739567405674156742567435674456745567465674756748567495675056751567525675356754567555675656757567585675956760567615676256763567645676556766567675676856769567705677156772567735677456775567765677756778567795678056781567825678356784567855678656787567885678956790567915679256793567945679556796567975679856799568005680156802568035680456805568065680756808568095681056811568125681356814568155681656817568185681956820568215682256823568245682556826568275682856829568305683156832568335683456835568365683756838568395684056841568425684356844568455684656847568485684956850568515685256853568545685556856568575685856859568605686156862568635686456865568665686756868568695687056871568725687356874568755687656877568785687956880568815688256883568845688556886568875688856889568905689156892568935689456895568965689756898568995690056901569025690356904569055690656907569085690956910569115691256913569145691556916569175691856919569205692156922569235692456925569265692756928569295693056931569325693356934569355693656937569385693956940569415694256943569445694556946569475694856949569505695156952569535695456955569565695756958569595696056961569625696356964569655696656967569685696956970569715697256973569745697556976569775697856979569805698156982569835698456985569865698756988569895699056991569925699356994569955699656997569985699957000570015700257003570045700557006570075700857009570105701157012570135701457015570165701757018570195702057021570225702357024570255702657027570285702957030570315703257033570345703557036570375703857039570405704157042570435704457045570465704757048570495705057051570525705357054570555705657057570585705957060570615706257063570645706557066570675706857069570705707157072570735707457075570765707757078570795708057081570825708357084570855708657087570885708957090570915709257093570945709557096570975709857099571005710157102571035710457105571065710757108571095711057111571125711357114571155711657117571185711957120571215712257123571245712557126571275712857129571305713157132571335713457135571365713757138571395714057141571425714357144571455714657147571485714957150571515715257153571545715557156571575715857159571605716157162571635716457165571665716757168571695717057171571725717357174571755717657177571785717957180571815718257183571845718557186571875718857189571905719157192571935719457195571965719757198571995720057201572025720357204572055720657207572085720957210572115721257213572145721557216572175721857219572205722157222572235722457225572265722757228572295723057231572325723357234572355723657237572385723957240572415724257243572445724557246572475724857249572505725157252572535725457255572565725757258572595726057261572625726357264572655726657267572685726957270572715727257273572745727557276572775727857279572805728157282572835728457285572865728757288572895729057291572925729357294572955729657297572985729957300573015730257303573045730557306573075730857309573105731157312573135731457315573165731757318573195732057321573225732357324573255732657327573285732957330573315733257333573345733557336573375733857339573405734157342573435734457345573465734757348573495735057351573525735357354573555735657357573585735957360573615736257363573645736557366573675736857369573705737157372573735737457375573765737757378573795738057381573825738357384573855738657387573885738957390573915739257393573945739557396573975739857399574005740157402574035740457405574065740757408574095741057411574125741357414574155741657417574185741957420574215742257423574245742557426574275742857429574305743157432574335743457435574365743757438574395744057441574425744357444574455744657447574485744957450574515745257453574545745557456574575745857459574605746157462574635746457465574665746757468574695747057471574725747357474574755747657477574785747957480574815748257483574845748557486574875748857489574905749157492574935749457495574965749757498574995750057501575025750357504575055750657507575085750957510575115751257513575145751557516575175751857519575205752157522575235752457525575265752757528575295753057531575325753357534575355753657537575385753957540575415754257543575445754557546575475754857549575505755157552575535755457555575565755757558575595756057561575625756357564575655756657567575685756957570575715757257573575745757557576575775757857579575805758157582575835758457585575865758757588575895759057591575925759357594575955759657597575985759957600576015760257603576045760557606576075760857609576105761157612576135761457615576165761757618576195762057621576225762357624576255762657627576285762957630576315763257633576345763557636576375763857639576405764157642576435764457645576465764757648576495765057651576525765357654576555765657657576585765957660576615766257663576645766557666576675766857669576705767157672576735767457675576765767757678576795768057681576825768357684576855768657687576885768957690576915769257693576945769557696576975769857699577005770157702577035770457705577065770757708577095771057711577125771357714577155771657717577185771957720577215772257723577245772557726577275772857729577305773157732577335773457735577365773757738577395774057741577425774357744577455774657747577485774957750577515775257753577545775557756577575775857759577605776157762577635776457765577665776757768577695777057771577725777357774577755777657777577785777957780577815778257783577845778557786577875778857789577905779157792577935779457795577965779757798577995780057801578025780357804578055780657807578085780957810578115781257813578145781557816578175781857819578205782157822578235782457825578265782757828578295783057831578325783357834578355783657837578385783957840578415784257843578445784557846578475784857849578505785157852578535785457855578565785757858578595786057861578625786357864578655786657867578685786957870578715787257873578745787557876578775787857879578805788157882578835788457885578865788757888578895789057891578925789357894578955789657897578985789957900579015790257903579045790557906579075790857909579105791157912579135791457915579165791757918579195792057921579225792357924579255792657927579285792957930579315793257933579345793557936579375793857939579405794157942579435794457945579465794757948579495795057951579525795357954579555795657957579585795957960579615796257963579645796557966579675796857969579705797157972579735797457975579765797757978579795798057981579825798357984579855798657987579885798957990579915799257993579945799557996579975799857999580005800158002580035800458005580065800758008580095801058011580125801358014580155801658017580185801958020580215802258023580245802558026580275802858029580305803158032580335803458035580365803758038580395804058041580425804358044580455804658047580485804958050580515805258053580545805558056580575805858059580605806158062580635806458065580665806758068580695807058071580725807358074580755807658077580785807958080580815808258083580845808558086580875808858089580905809158092580935809458095580965809758098580995810058101581025810358104581055810658107581085810958110581115811258113581145811558116581175811858119581205812158122581235812458125581265812758128581295813058131581325813358134581355813658137581385813958140581415814258143581445814558146581475814858149581505815158152581535815458155581565815758158581595816058161581625816358164581655816658167581685816958170581715817258173581745817558176581775817858179581805818158182581835818458185581865818758188581895819058191581925819358194581955819658197581985819958200582015820258203582045820558206582075820858209582105821158212582135821458215582165821758218582195822058221582225822358224582255822658227582285822958230582315823258233582345823558236582375823858239582405824158242582435824458245582465824758248582495825058251582525825358254582555825658257582585825958260582615826258263582645826558266582675826858269582705827158272582735827458275582765827758278582795828058281582825828358284582855828658287582885828958290582915829258293582945829558296582975829858299583005830158302583035830458305583065830758308583095831058311583125831358314583155831658317583185831958320583215832258323583245832558326583275832858329583305833158332583335833458335583365833758338583395834058341583425834358344583455834658347583485834958350583515835258353583545835558356583575835858359583605836158362583635836458365583665836758368583695837058371583725837358374583755837658377583785837958380583815838258383583845838558386583875838858389583905839158392583935839458395583965839758398583995840058401584025840358404584055840658407584085840958410584115841258413584145841558416584175841858419584205842158422584235842458425584265842758428584295843058431584325843358434584355843658437584385843958440584415844258443584445844558446584475844858449584505845158452584535845458455584565845758458584595846058461584625846358464584655846658467584685846958470584715847258473584745847558476584775847858479584805848158482584835848458485584865848758488584895849058491584925849358494584955849658497584985849958500585015850258503585045850558506585075850858509585105851158512585135851458515585165851758518585195852058521585225852358524585255852658527585285852958530585315853258533585345853558536585375853858539585405854158542585435854458545585465854758548585495855058551585525855358554585555855658557585585855958560585615856258563585645856558566585675856858569585705857158572585735857458575585765857758578585795858058581585825858358584585855858658587585885858958590585915859258593585945859558596585975859858599586005860158602586035860458605586065860758608586095861058611586125861358614586155861658617586185861958620586215862258623586245862558626586275862858629586305863158632586335863458635586365863758638586395864058641586425864358644586455864658647586485864958650586515865258653586545865558656586575865858659586605866158662586635866458665586665866758668586695867058671586725867358674586755867658677586785867958680586815868258683586845868558686586875868858689586905869158692586935869458695586965869758698586995870058701587025870358704587055870658707587085870958710587115871258713587145871558716587175871858719587205872158722587235872458725587265872758728587295873058731587325873358734587355873658737587385873958740587415874258743587445874558746587475874858749587505875158752587535875458755587565875758758587595876058761587625876358764587655876658767587685876958770587715877258773587745877558776587775877858779587805878158782587835878458785587865878758788587895879058791587925879358794587955879658797587985879958800588015880258803588045880558806588075880858809588105881158812588135881458815588165881758818588195882058821588225882358824588255882658827588285882958830588315883258833588345883558836588375883858839588405884158842588435884458845588465884758848588495885058851588525885358854588555885658857588585885958860588615886258863588645886558866588675886858869588705887158872588735887458875588765887758878588795888058881588825888358884588855888658887588885888958890588915889258893588945889558896588975889858899589005890158902589035890458905589065890758908589095891058911589125891358914589155891658917589185891958920589215892258923589245892558926589275892858929589305893158932589335893458935589365893758938589395894058941589425894358944589455894658947589485894958950589515895258953589545895558956589575895858959589605896158962589635896458965589665896758968589695897058971589725897358974589755897658977589785897958980589815898258983589845898558986589875898858989589905899158992589935899458995589965899758998589995900059001590025900359004590055900659007590085900959010590115901259013590145901559016590175901859019590205902159022590235902459025590265902759028590295903059031590325903359034590355903659037590385903959040590415904259043590445904559046590475904859049590505905159052590535905459055590565905759058590595906059061590625906359064590655906659067590685906959070590715907259073590745907559076590775907859079590805908159082590835908459085590865908759088590895909059091590925909359094590955909659097590985909959100591015910259103591045910559106591075910859109591105911159112591135911459115591165911759118591195912059121591225912359124591255912659127591285912959130591315913259133591345913559136591375913859139591405914159142591435914459145591465914759148591495915059151591525915359154591555915659157591585915959160591615916259163591645916559166591675916859169591705917159172591735917459175591765917759178591795918059181591825918359184591855918659187591885918959190591915919259193591945919559196591975919859199592005920159202592035920459205592065920759208592095921059211592125921359214592155921659217592185921959220592215922259223592245922559226592275922859229592305923159232592335923459235592365923759238592395924059241592425924359244592455924659247592485924959250592515925259253592545925559256592575925859259592605926159262592635926459265592665926759268592695927059271592725927359274592755927659277592785927959280592815928259283592845928559286592875928859289592905929159292592935929459295592965929759298592995930059301593025930359304593055930659307593085930959310593115931259313593145931559316593175931859319593205932159322593235932459325593265932759328593295933059331593325933359334593355933659337593385933959340593415934259343593445934559346593475934859349593505935159352593535935459355593565935759358593595936059361593625936359364593655936659367593685936959370593715937259373593745937559376593775937859379593805938159382593835938459385593865938759388593895939059391593925939359394593955939659397593985939959400594015940259403594045940559406594075940859409594105941159412594135941459415594165941759418594195942059421594225942359424594255942659427594285942959430594315943259433594345943559436594375943859439594405944159442594435944459445594465944759448594495945059451594525945359454594555945659457594585945959460594615946259463594645946559466594675946859469594705947159472594735947459475594765947759478594795948059481594825948359484594855948659487594885948959490594915949259493594945949559496594975949859499595005950159502595035950459505595065950759508595095951059511595125951359514595155951659517595185951959520595215952259523595245952559526595275952859529595305953159532595335953459535595365953759538595395954059541595425954359544595455954659547595485954959550595515955259553595545955559556595575955859559595605956159562595635956459565595665956759568595695957059571595725957359574595755957659577595785957959580595815958259583595845958559586595875958859589595905959159592595935959459595595965959759598595995960059601596025960359604596055960659607596085960959610596115961259613596145961559616596175961859619596205962159622596235962459625596265962759628596295963059631596325963359634596355963659637596385963959640596415964259643596445964559646596475964859649596505965159652596535965459655596565965759658596595966059661596625966359664596655966659667596685966959670596715967259673596745967559676596775967859679596805968159682596835968459685596865968759688596895969059691596925969359694596955969659697596985969959700597015970259703597045970559706597075970859709597105971159712597135971459715597165971759718597195972059721597225972359724597255972659727597285972959730597315973259733597345973559736597375973859739597405974159742597435974459745597465974759748597495975059751597525975359754597555975659757597585975959760597615976259763597645976559766597675976859769597705977159772597735977459775597765977759778597795978059781597825978359784597855978659787597885978959790597915979259793597945979559796597975979859799598005980159802598035980459805598065980759808598095981059811598125981359814598155981659817598185981959820598215982259823598245982559826598275982859829598305983159832598335983459835598365983759838598395984059841598425984359844598455984659847598485984959850598515985259853598545985559856598575985859859598605986159862598635986459865598665986759868598695987059871598725987359874598755987659877598785987959880598815988259883598845988559886598875988859889598905989159892598935989459895598965989759898598995990059901599025990359904599055990659907599085990959910599115991259913599145991559916599175991859919599205992159922599235992459925599265992759928599295993059931599325993359934599355993659937599385993959940599415994259943599445994559946599475994859949599505995159952599535995459955599565995759958599595996059961599625996359964599655996659967599685996959970599715997259973599745997559976599775997859979599805998159982599835998459985599865998759988599895999059991599925999359994599955999659997599985999960000600016000260003600046000560006600076000860009600106001160012600136001460015600166001760018600196002060021600226002360024600256002660027600286002960030600316003260033600346003560036600376003860039600406004160042600436004460045600466004760048600496005060051600526005360054600556005660057600586005960060600616006260063600646006560066600676006860069600706007160072600736007460075600766007760078600796008060081600826008360084600856008660087600886008960090600916009260093600946009560096600976009860099601006010160102601036010460105601066010760108601096011060111601126011360114601156011660117601186011960120601216012260123601246012560126601276012860129601306013160132601336013460135601366013760138601396014060141601426014360144601456014660147601486014960150601516015260153601546015560156601576015860159601606016160162601636016460165601666016760168601696017060171601726017360174601756017660177601786017960180601816018260183601846018560186601876018860189601906019160192601936019460195601966019760198601996020060201602026020360204602056020660207602086020960210602116021260213602146021560216602176021860219602206022160222602236022460225602266022760228602296023060231602326023360234602356023660237602386023960240602416024260243602446024560246602476024860249602506025160252602536025460255602566025760258602596026060261602626026360264602656026660267602686026960270602716027260273602746027560276602776027860279602806028160282602836028460285602866028760288602896029060291602926029360294602956029660297602986029960300603016030260303603046030560306603076030860309603106031160312603136031460315603166031760318603196032060321603226032360324603256032660327603286032960330603316033260333603346033560336603376033860339603406034160342603436034460345603466034760348603496035060351603526035360354603556035660357603586035960360603616036260363603646036560366603676036860369603706037160372603736037460375603766037760378603796038060381603826038360384603856038660387603886038960390603916039260393603946039560396603976039860399604006040160402604036040460405604066040760408604096041060411604126041360414604156041660417604186041960420604216042260423604246042560426604276042860429604306043160432604336043460435604366043760438604396044060441604426044360444604456044660447604486044960450604516045260453604546045560456604576045860459604606046160462604636046460465604666046760468604696047060471604726047360474604756047660477604786047960480604816048260483604846048560486604876048860489604906049160492604936049460495604966049760498604996050060501605026050360504605056050660507605086050960510605116051260513605146051560516605176051860519605206052160522605236052460525605266052760528605296053060531605326053360534605356053660537605386053960540605416054260543605446054560546605476054860549605506055160552605536055460555605566055760558605596056060561605626056360564605656056660567605686056960570605716057260573605746057560576605776057860579605806058160582605836058460585605866058760588605896059060591605926059360594605956059660597605986059960600606016060260603606046060560606606076060860609606106061160612606136061460615606166061760618606196062060621606226062360624606256062660627606286062960630606316063260633606346063560636606376063860639606406064160642606436064460645606466064760648606496065060651606526065360654606556065660657606586065960660606616066260663606646066560666606676066860669606706067160672606736067460675606766067760678606796068060681606826068360684606856068660687606886068960690606916069260693606946069560696606976069860699607006070160702607036070460705607066070760708607096071060711607126071360714607156071660717607186071960720607216072260723607246072560726607276072860729607306073160732607336073460735607366073760738607396074060741607426074360744607456074660747607486074960750607516075260753607546075560756607576075860759607606076160762607636076460765607666076760768607696077060771607726077360774607756077660777607786077960780607816078260783607846078560786607876078860789607906079160792607936079460795607966079760798607996080060801608026080360804608056080660807608086080960810608116081260813608146081560816608176081860819608206082160822608236082460825608266082760828608296083060831608326083360834608356083660837608386083960840608416084260843608446084560846608476084860849608506085160852608536085460855608566085760858608596086060861608626086360864608656086660867608686086960870608716087260873608746087560876608776087860879608806088160882608836088460885608866088760888608896089060891608926089360894608956089660897608986089960900609016090260903609046090560906609076090860909609106091160912609136091460915609166091760918609196092060921609226092360924609256092660927609286092960930609316093260933609346093560936609376093860939609406094160942609436094460945609466094760948609496095060951609526095360954609556095660957609586095960960609616096260963609646096560966609676096860969609706097160972609736097460975609766097760978609796098060981609826098360984609856098660987609886098960990609916099260993609946099560996609976099860999610006100161002610036100461005610066100761008610096101061011610126101361014610156101661017610186101961020610216102261023610246102561026610276102861029610306103161032610336103461035610366103761038610396104061041610426104361044610456104661047610486104961050610516105261053610546105561056610576105861059610606106161062610636106461065610666106761068610696107061071610726107361074610756107661077610786107961080610816108261083610846108561086610876108861089610906109161092610936109461095610966109761098610996110061101611026110361104611056110661107611086110961110611116111261113611146111561116611176111861119611206112161122611236112461125611266112761128611296113061131611326113361134611356113661137611386113961140611416114261143611446114561146611476114861149611506115161152611536115461155611566115761158611596116061161611626116361164611656116661167611686116961170611716117261173611746117561176611776117861179611806118161182611836118461185611866118761188611896119061191611926119361194611956119661197611986119961200612016120261203612046120561206612076120861209612106121161212612136121461215612166121761218612196122061221612226122361224612256122661227612286122961230612316123261233612346123561236612376123861239612406124161242612436124461245612466124761248612496125061251612526125361254612556125661257612586125961260612616126261263612646126561266612676126861269612706127161272612736127461275612766127761278612796128061281612826128361284612856128661287612886128961290612916129261293612946129561296612976129861299613006130161302613036130461305613066130761308613096131061311613126131361314613156131661317613186131961320613216132261323613246132561326613276132861329613306133161332613336133461335613366133761338613396134061341613426134361344613456134661347613486134961350613516135261353613546135561356613576135861359613606136161362613636136461365613666136761368613696137061371613726137361374613756137661377613786137961380613816138261383613846138561386613876138861389613906139161392613936139461395613966139761398613996140061401614026140361404614056140661407614086140961410614116141261413614146141561416614176141861419614206142161422614236142461425614266142761428614296143061431614326143361434614356143661437614386143961440614416144261443614446144561446614476144861449614506145161452614536145461455614566145761458614596146061461614626146361464614656146661467614686146961470614716147261473614746147561476614776147861479614806148161482614836148461485614866148761488614896149061491614926149361494614956149661497614986149961500615016150261503615046150561506615076150861509615106151161512615136151461515615166151761518615196152061521615226152361524615256152661527615286152961530615316153261533615346153561536615376153861539615406154161542615436154461545615466154761548615496155061551615526155361554615556155661557615586155961560615616156261563615646156561566615676156861569615706157161572615736157461575615766157761578615796158061581615826158361584615856158661587615886158961590615916159261593615946159561596615976159861599616006160161602616036160461605616066160761608616096161061611616126161361614616156161661617616186161961620616216162261623616246162561626616276162861629616306163161632616336163461635616366163761638616396164061641616426164361644616456164661647616486164961650616516165261653616546165561656616576165861659616606166161662616636166461665616666166761668616696167061671616726167361674616756167661677616786167961680616816168261683616846168561686616876168861689616906169161692616936169461695616966169761698616996170061701617026170361704617056170661707617086170961710617116171261713617146171561716617176171861719617206172161722617236172461725617266172761728617296173061731617326173361734617356173661737617386173961740617416174261743617446174561746617476174861749617506175161752617536175461755617566175761758617596176061761617626176361764617656176661767617686176961770617716177261773617746177561776617776177861779617806178161782617836178461785617866178761788617896179061791617926179361794617956179661797617986179961800618016180261803618046180561806618076180861809618106181161812618136181461815618166181761818618196182061821618226182361824618256182661827618286182961830618316183261833618346183561836618376183861839618406184161842618436184461845618466184761848618496185061851618526185361854618556185661857618586185961860618616186261863618646186561866618676186861869618706187161872618736187461875618766187761878618796188061881618826188361884618856188661887618886188961890618916189261893618946189561896618976189861899619006190161902619036190461905619066190761908619096191061911619126191361914619156191661917619186191961920619216192261923619246192561926619276192861929619306193161932619336193461935619366193761938619396194061941619426194361944619456194661947619486194961950619516195261953619546195561956619576195861959619606196161962619636196461965619666196761968619696197061971619726197361974619756197661977619786197961980619816198261983619846198561986619876198861989619906199161992619936199461995619966199761998619996200062001620026200362004620056200662007620086200962010620116201262013620146201562016620176201862019620206202162022620236202462025620266202762028620296203062031620326203362034620356203662037620386203962040620416204262043620446204562046620476204862049620506205162052620536205462055620566205762058620596206062061620626206362064620656206662067620686206962070620716207262073620746207562076620776207862079620806208162082620836208462085620866208762088620896209062091620926209362094620956209662097620986209962100621016210262103621046210562106621076210862109621106211162112621136211462115621166211762118621196212062121621226212362124621256212662127621286212962130621316213262133621346213562136621376213862139621406214162142621436214462145621466214762148621496215062151621526215362154621556215662157621586215962160621616216262163621646216562166621676216862169621706217162172621736217462175621766217762178621796218062181621826218362184621856218662187621886218962190621916219262193621946219562196621976219862199622006220162202622036220462205622066220762208622096221062211622126221362214622156221662217622186221962220622216222262223622246222562226622276222862229622306223162232622336223462235622366223762238622396224062241622426224362244622456224662247622486224962250622516225262253622546225562256622576225862259622606226162262622636226462265622666226762268622696227062271622726227362274622756227662277622786227962280622816228262283622846228562286622876228862289622906229162292622936229462295622966229762298622996230062301623026230362304623056230662307623086230962310623116231262313623146231562316623176231862319623206232162322623236232462325623266232762328623296233062331623326233362334623356233662337623386233962340623416234262343623446234562346623476234862349623506235162352623536235462355623566235762358623596236062361623626236362364623656236662367623686236962370623716237262373623746237562376623776237862379623806238162382623836238462385623866238762388623896239062391623926239362394623956239662397623986239962400624016240262403624046240562406624076240862409624106241162412624136241462415624166241762418624196242062421624226242362424624256242662427624286242962430624316243262433624346243562436624376243862439624406244162442624436244462445624466244762448624496245062451624526245362454624556245662457624586245962460624616246262463624646246562466624676246862469624706247162472624736247462475624766247762478624796248062481624826248362484624856248662487624886248962490624916249262493624946249562496624976249862499625006250162502625036250462505625066250762508625096251062511625126251362514625156251662517625186251962520625216252262523625246252562526625276252862529625306253162532625336253462535625366253762538625396254062541625426254362544625456254662547625486254962550625516255262553625546255562556625576255862559625606256162562625636256462565625666256762568625696257062571625726257362574625756257662577625786257962580625816258262583625846258562586625876258862589625906259162592625936259462595625966259762598625996260062601626026260362604626056260662607626086260962610626116261262613626146261562616626176261862619626206262162622626236262462625626266262762628626296263062631626326263362634626356263662637626386263962640626416264262643626446264562646626476264862649626506265162652626536265462655626566265762658626596266062661626626266362664626656266662667626686266962670626716267262673626746267562676626776267862679626806268162682626836268462685626866268762688626896269062691626926269362694626956269662697626986269962700627016270262703627046270562706627076270862709627106271162712627136271462715627166271762718627196272062721627226272362724627256272662727627286272962730627316273262733627346273562736627376273862739627406274162742627436274462745627466274762748627496275062751627526275362754627556275662757627586275962760627616276262763627646276562766627676276862769627706277162772627736277462775627766277762778627796278062781627826278362784627856278662787627886278962790627916279262793627946279562796627976279862799628006280162802628036280462805628066280762808628096281062811628126281362814628156281662817628186281962820628216282262823628246282562826628276282862829628306283162832628336283462835628366283762838628396284062841628426284362844628456284662847628486284962850628516285262853628546285562856628576285862859628606286162862628636286462865628666286762868628696287062871628726287362874628756287662877628786287962880628816288262883628846288562886628876288862889628906289162892628936289462895628966289762898628996290062901629026290362904629056290662907629086290962910629116291262913629146291562916629176291862919629206292162922629236292462925629266292762928629296293062931629326293362934629356293662937629386293962940629416294262943629446294562946629476294862949629506295162952629536295462955629566295762958629596296062961629626296362964629656296662967629686296962970629716297262973629746297562976629776297862979629806298162982629836298462985629866298762988629896299062991629926299362994629956299662997629986299963000630016300263003630046300563006630076300863009630106301163012630136301463015630166301763018630196302063021630226302363024630256302663027630286302963030630316303263033630346303563036630376303863039630406304163042630436304463045630466304763048630496305063051630526305363054630556305663057630586305963060630616306263063630646306563066630676306863069630706307163072630736307463075630766307763078630796308063081630826308363084630856308663087630886308963090630916309263093630946309563096630976309863099631006310163102631036310463105631066310763108631096311063111631126311363114631156311663117631186311963120631216312263123631246312563126631276312863129631306313163132631336313463135631366313763138631396314063141631426314363144631456314663147631486314963150631516315263153631546315563156631576315863159631606316163162631636316463165631666316763168631696317063171631726317363174631756317663177631786317963180631816318263183631846318563186631876318863189631906319163192631936319463195631966319763198631996320063201632026320363204632056320663207632086320963210632116321263213632146321563216632176321863219632206322163222632236322463225632266322763228632296323063231632326323363234632356323663237632386323963240632416324263243632446324563246632476324863249632506325163252632536325463255632566325763258632596326063261632626326363264632656326663267632686326963270632716327263273632746327563276632776327863279632806328163282632836328463285632866328763288632896329063291632926329363294632956329663297632986329963300633016330263303633046330563306633076330863309633106331163312633136331463315633166331763318633196332063321633226332363324633256332663327633286332963330633316333263333633346333563336633376333863339633406334163342633436334463345633466334763348633496335063351633526335363354633556335663357633586335963360633616336263363633646336563366633676336863369633706337163372633736337463375633766337763378633796338063381633826338363384633856338663387633886338963390633916339263393633946339563396633976339863399634006340163402634036340463405634066340763408634096341063411634126341363414634156341663417634186341963420634216342263423634246342563426634276342863429634306343163432634336343463435634366343763438634396344063441634426344363444634456344663447634486344963450634516345263453634546345563456634576345863459634606346163462634636346463465634666346763468634696347063471634726347363474634756347663477634786347963480634816348263483634846348563486634876348863489634906349163492634936349463495634966349763498634996350063501635026350363504635056350663507635086350963510635116351263513635146351563516635176351863519635206352163522635236352463525635266352763528635296353063531635326353363534635356353663537635386353963540635416354263543635446354563546635476354863549635506355163552635536355463555635566355763558635596356063561635626356363564635656356663567635686356963570635716357263573635746357563576635776357863579635806358163582635836358463585635866358763588635896359063591635926359363594635956359663597635986359963600636016360263603636046360563606636076360863609636106361163612636136361463615636166361763618636196362063621636226362363624636256362663627636286362963630636316363263633636346363563636636376363863639636406364163642636436364463645636466364763648636496365063651636526365363654636556365663657636586365963660636616366263663636646366563666636676366863669636706367163672636736367463675636766367763678636796368063681636826368363684636856368663687636886368963690636916369263693636946369563696636976369863699637006370163702637036370463705637066370763708637096371063711637126371363714637156371663717637186371963720637216372263723637246372563726637276372863729637306373163732637336373463735637366373763738637396374063741637426374363744637456374663747637486374963750637516375263753637546375563756637576375863759637606376163762637636376463765637666376763768637696377063771637726377363774637756377663777637786377963780637816378263783637846378563786637876378863789637906379163792637936379463795637966379763798637996380063801638026380363804638056380663807638086380963810638116381263813638146381563816638176381863819638206382163822638236382463825638266382763828638296383063831638326383363834638356383663837638386383963840638416384263843638446384563846638476384863849638506385163852638536385463855638566385763858638596386063861638626386363864638656386663867638686386963870638716387263873638746387563876638776387863879638806388163882638836388463885638866388763888638896389063891638926389363894638956389663897638986389963900639016390263903639046390563906639076390863909639106391163912639136391463915639166391763918639196392063921639226392363924639256392663927639286392963930639316393263933639346393563936639376393863939639406394163942639436394463945639466394763948639496395063951639526395363954639556395663957639586395963960639616396263963639646396563966639676396863969639706397163972639736397463975639766397763978639796398063981639826398363984639856398663987639886398963990639916399263993639946399563996639976399863999640006400164002640036400464005640066400764008640096401064011640126401364014640156401664017640186401964020640216402264023640246402564026640276402864029640306403164032640336403464035640366403764038640396404064041640426404364044640456404664047640486404964050640516405264053640546405564056640576405864059640606406164062640636406464065640666406764068640696407064071640726407364074640756407664077640786407964080640816408264083640846408564086640876408864089640906409164092640936409464095640966409764098640996410064101641026410364104641056410664107641086410964110641116411264113641146411564116641176411864119641206412164122641236412464125641266412764128641296413064131641326413364134641356413664137641386413964140641416414264143641446414564146641476414864149641506415164152641536415464155641566415764158641596416064161641626416364164641656416664167641686416964170641716417264173641746417564176641776417864179641806418164182641836418464185641866418764188641896419064191641926419364194641956419664197641986419964200642016420264203642046420564206642076420864209642106421164212642136421464215642166421764218642196422064221642226422364224642256422664227642286422964230642316423264233642346423564236642376423864239642406424164242642436424464245642466424764248642496425064251642526425364254642556425664257642586425964260642616426264263642646426564266642676426864269642706427164272642736427464275642766427764278642796428064281642826428364284642856428664287642886428964290642916429264293642946429564296642976429864299643006430164302643036430464305643066430764308643096431064311643126431364314643156431664317643186431964320643216432264323643246432564326643276432864329643306433164332643336433464335643366433764338643396434064341643426434364344643456434664347643486434964350643516435264353643546435564356643576435864359643606436164362643636436464365643666436764368643696437064371643726437364374643756437664377643786437964380643816438264383643846438564386643876438864389643906439164392643936439464395643966439764398643996440064401644026440364404644056440664407644086440964410644116441264413644146441564416644176441864419644206442164422644236442464425644266442764428644296443064431644326443364434644356443664437644386443964440644416444264443644446444564446644476444864449644506445164452644536445464455644566445764458644596446064461644626446364464644656446664467644686446964470644716447264473644746447564476644776447864479644806448164482644836448464485644866448764488644896449064491644926449364494644956449664497644986449964500645016450264503645046450564506645076450864509645106451164512645136451464515645166451764518645196452064521645226452364524645256452664527645286452964530645316453264533645346453564536645376453864539645406454164542645436454464545645466454764548645496455064551645526455364554645556455664557645586455964560645616456264563645646456564566645676456864569645706457164572645736457464575645766457764578645796458064581645826458364584645856458664587645886458964590645916459264593645946459564596645976459864599646006460164602646036460464605646066460764608646096461064611646126461364614646156461664617646186461964620646216462264623646246462564626646276462864629646306463164632646336463464635646366463764638646396464064641646426464364644646456464664647646486464964650646516465264653646546465564656646576465864659646606466164662646636466464665646666466764668646696467064671646726467364674646756467664677646786467964680646816468264683646846468564686646876468864689646906469164692646936469464695646966469764698646996470064701647026470364704647056470664707647086470964710647116471264713647146471564716647176471864719647206472164722647236472464725647266472764728647296473064731647326473364734647356473664737647386473964740647416474264743647446474564746647476474864749647506475164752647536475464755647566475764758647596476064761647626476364764647656476664767647686476964770647716477264773647746477564776647776477864779647806478164782647836478464785647866478764788647896479064791647926479364794647956479664797647986479964800648016480264803648046480564806648076480864809648106481164812648136481464815648166481764818648196482064821648226482364824648256482664827648286482964830648316483264833648346483564836648376483864839648406484164842648436484464845648466484764848648496485064851648526485364854648556485664857648586485964860648616486264863648646486564866648676486864869648706487164872648736487464875648766487764878648796488064881648826488364884648856488664887648886488964890648916489264893648946489564896648976489864899649006490164902649036490464905649066490764908649096491064911649126491364914649156491664917649186491964920649216492264923649246492564926649276492864929649306493164932649336493464935649366493764938649396494064941649426494364944649456494664947649486494964950649516495264953649546495564956649576495864959649606496164962649636496464965649666496764968649696497064971649726497364974649756497664977649786497964980649816498264983649846498564986649876498864989649906499164992649936499464995649966499764998649996500065001650026500365004650056500665007650086500965010650116501265013650146501565016650176501865019650206502165022650236502465025650266502765028650296503065031650326503365034650356503665037650386503965040650416504265043650446504565046650476504865049650506505165052650536505465055650566505765058650596506065061650626506365064650656506665067650686506965070650716507265073650746507565076650776507865079650806508165082650836508465085650866508765088650896509065091650926509365094650956509665097650986509965100651016510265103651046510565106651076510865109651106511165112651136511465115651166511765118651196512065121651226512365124651256512665127651286512965130651316513265133651346513565136651376513865139651406514165142651436514465145651466514765148651496515065151651526515365154651556515665157651586515965160651616516265163651646516565166651676516865169651706517165172651736517465175651766517765178651796518065181651826518365184651856518665187651886518965190651916519265193651946519565196651976519865199652006520165202652036520465205652066520765208652096521065211652126521365214652156521665217652186521965220652216522265223652246522565226652276522865229652306523165232652336523465235652366523765238652396524065241652426524365244652456524665247652486524965250652516525265253652546525565256652576525865259652606526165262652636526465265652666526765268652696527065271652726527365274652756527665277652786527965280652816528265283652846528565286652876528865289652906529165292652936529465295652966529765298652996530065301653026530365304653056530665307653086530965310653116531265313653146531565316653176531865319653206532165322653236532465325653266532765328653296533065331653326533365334653356533665337653386533965340653416534265343653446534565346653476534865349653506535165352653536535465355653566535765358653596536065361653626536365364653656536665367653686536965370653716537265373653746537565376653776537865379653806538165382653836538465385653866538765388653896539065391653926539365394653956539665397653986539965400654016540265403654046540565406654076540865409654106541165412654136541465415654166541765418654196542065421654226542365424654256542665427654286542965430654316543265433654346543565436654376543865439654406544165442654436544465445654466544765448654496545065451654526545365454654556545665457654586545965460654616546265463654646546565466654676546865469654706547165472654736547465475654766547765478654796548065481654826548365484654856548665487654886548965490654916549265493654946549565496654976549865499655006550165502655036550465505655066550765508655096551065511655126551365514655156551665517655186551965520655216552265523655246552565526655276552865529655306553165532655336553465535655366553765538655396554065541655426554365544655456554665547655486554965550655516555265553655546555565556655576555865559655606556165562655636556465565655666556765568655696557065571655726557365574655756557665577655786557965580655816558265583655846558565586655876558865589655906559165592655936559465595655966559765598655996560065601656026560365604656056560665607656086560965610656116561265613656146561565616656176561865619656206562165622656236562465625656266562765628656296563065631656326563365634656356563665637656386563965640656416564265643656446564565646656476564865649656506565165652656536565465655656566565765658656596566065661656626566365664656656566665667656686566965670656716567265673656746567565676656776567865679656806568165682656836568465685656866568765688656896569065691656926569365694656956569665697656986569965700657016570265703657046570565706657076570865709657106571165712657136571465715657166571765718657196572065721657226572365724657256572665727657286572965730657316573265733657346573565736657376573865739657406574165742657436574465745657466574765748657496575065751657526575365754657556575665757657586575965760657616576265763657646576565766657676576865769657706577165772657736577465775657766577765778657796578065781657826578365784657856578665787657886578965790657916579265793657946579565796657976579865799658006580165802658036580465805658066580765808658096581065811658126581365814658156581665817658186581965820658216582265823658246582565826658276582865829658306583165832658336583465835658366583765838658396584065841658426584365844658456584665847658486584965850658516585265853658546585565856658576585865859658606586165862658636586465865658666586765868658696587065871658726587365874658756587665877658786587965880658816588265883658846588565886658876588865889658906589165892658936589465895658966589765898658996590065901659026590365904659056590665907659086590965910659116591265913659146591565916659176591865919659206592165922659236592465925659266592765928659296593065931659326593365934659356593665937659386593965940659416594265943659446594565946659476594865949659506595165952659536595465955659566595765958659596596065961659626596365964659656596665967659686596965970659716597265973659746597565976659776597865979659806598165982659836598465985659866598765988659896599065991659926599365994659956599665997659986599966000660016600266003660046600566006660076600866009660106601166012660136601466015660166601766018660196602066021660226602366024660256602666027660286602966030660316603266033660346603566036660376603866039660406604166042660436604466045660466604766048660496605066051660526605366054660556605666057660586605966060660616606266063660646606566066660676606866069660706607166072660736607466075660766607766078660796608066081660826608366084660856608666087660886608966090660916609266093660946609566096660976609866099661006610166102661036610466105661066610766108661096611066111661126611366114661156611666117661186611966120661216612266123661246612566126661276612866129661306613166132661336613466135661366613766138661396614066141661426614366144661456614666147661486614966150661516615266153661546615566156661576615866159661606616166162661636616466165661666616766168661696617066171661726617366174661756617666177661786617966180661816618266183661846618566186661876618866189661906619166192661936619466195661966619766198661996620066201662026620366204662056620666207662086620966210662116621266213662146621566216662176621866219662206622166222662236622466225662266622766228662296623066231662326623366234662356623666237662386623966240662416624266243662446624566246662476624866249662506625166252662536625466255662566625766258662596626066261662626626366264662656626666267662686626966270662716627266273662746627566276662776627866279662806628166282662836628466285662866628766288662896629066291662926629366294662956629666297662986629966300663016630266303663046630566306663076630866309663106631166312663136631466315663166631766318663196632066321663226632366324663256632666327663286632966330663316633266333663346633566336663376633866339663406634166342663436634466345663466634766348663496635066351663526635366354663556635666357663586635966360663616636266363663646636566366663676636866369663706637166372663736637466375663766637766378663796638066381663826638366384663856638666387663886638966390663916639266393663946639566396663976639866399664006640166402664036640466405664066640766408664096641066411664126641366414664156641666417664186641966420664216642266423664246642566426664276642866429664306643166432664336643466435664366643766438664396644066441664426644366444664456644666447664486644966450664516645266453664546645566456664576645866459664606646166462664636646466465664666646766468664696647066471664726647366474664756647666477664786647966480664816648266483664846648566486664876648866489664906649166492664936649466495664966649766498664996650066501665026650366504665056650666507665086650966510665116651266513665146651566516665176651866519665206652166522665236652466525665266652766528665296653066531665326653366534665356653666537665386653966540665416654266543665446654566546665476654866549665506655166552665536655466555665566655766558665596656066561665626656366564665656656666567665686656966570665716657266573665746657566576665776657866579665806658166582665836658466585665866658766588665896659066591665926659366594665956659666597665986659966600666016660266603666046660566606666076660866609666106661166612666136661466615666166661766618666196662066621666226662366624666256662666627666286662966630666316663266633666346663566636666376663866639666406664166642666436664466645666466664766648666496665066651666526665366654666556665666657666586665966660666616666266663666646666566666666676666866669666706667166672666736667466675666766667766678666796668066681666826668366684666856668666687666886668966690666916669266693666946669566696666976669866699667006670166702667036670466705667066670766708667096671066711667126671366714667156671666717667186671966720667216672266723667246672566726667276672866729667306673166732667336673466735667366673766738667396674066741667426674366744667456674666747667486674966750667516675266753667546675566756667576675866759667606676166762667636676466765667666676766768667696677066771667726677366774667756677666777667786677966780667816678266783667846678566786667876678866789667906679166792667936679466795667966679766798667996680066801668026680366804668056680666807668086680966810668116681266813668146681566816668176681866819668206682166822668236682466825668266682766828668296683066831668326683366834668356683666837668386683966840668416684266843668446684566846668476684866849668506685166852668536685466855668566685766858668596686066861668626686366864668656686666867668686686966870668716687266873668746687566876668776687866879668806688166882668836688466885668866688766888668896689066891668926689366894668956689666897668986689966900669016690266903669046690566906669076690866909669106691166912669136691466915669166691766918669196692066921669226692366924669256692666927669286692966930669316693266933669346693566936669376693866939669406694166942669436694466945669466694766948669496695066951669526695366954669556695666957669586695966960669616696266963669646696566966669676696866969669706697166972669736697466975669766697766978669796698066981669826698366984669856698666987669886698966990669916699266993669946699566996669976699866999670006700167002670036700467005670066700767008670096701067011670126701367014670156701667017670186701967020670216702267023670246702567026670276702867029670306703167032670336703467035670366703767038670396704067041670426704367044670456704667047670486704967050670516705267053670546705567056670576705867059670606706167062670636706467065670666706767068670696707067071670726707367074670756707667077670786707967080670816708267083670846708567086670876708867089670906709167092670936709467095670966709767098670996710067101671026710367104671056710667107671086710967110671116711267113671146711567116671176711867119671206712167122671236712467125671266712767128671296713067131671326713367134671356713667137671386713967140671416714267143671446714567146671476714867149671506715167152671536715467155671566715767158671596716067161671626716367164671656716667167671686716967170671716717267173671746717567176671776717867179671806718167182671836718467185671866718767188671896719067191671926719367194671956719667197671986719967200672016720267203672046720567206672076720867209672106721167212672136721467215672166721767218672196722067221672226722367224672256722667227672286722967230672316723267233672346723567236672376723867239672406724167242672436724467245672466724767248672496725067251672526725367254672556725667257672586725967260672616726267263672646726567266672676726867269672706727167272672736727467275672766727767278672796728067281672826728367284672856728667287672886728967290672916729267293672946729567296672976729867299673006730167302673036730467305673066730767308673096731067311673126731367314673156731667317673186731967320673216732267323673246732567326673276732867329673306733167332673336733467335673366733767338673396734067341673426734367344673456734667347673486734967350673516735267353673546735567356673576735867359673606736167362673636736467365673666736767368673696737067371673726737367374673756737667377673786737967380673816738267383673846738567386673876738867389673906739167392673936739467395673966739767398673996740067401674026740367404674056740667407674086740967410674116741267413674146741567416674176741867419674206742167422674236742467425674266742767428674296743067431674326743367434674356743667437674386743967440674416744267443674446744567446674476744867449674506745167452674536745467455674566745767458674596746067461674626746367464674656746667467674686746967470674716747267473674746747567476674776747867479674806748167482674836748467485674866748767488674896749067491674926749367494674956749667497674986749967500675016750267503675046750567506675076750867509675106751167512675136751467515675166751767518675196752067521675226752367524675256752667527675286752967530675316753267533675346753567536675376753867539675406754167542675436754467545675466754767548675496755067551675526755367554675556755667557675586755967560675616756267563675646756567566675676756867569675706757167572675736757467575675766757767578675796758067581675826758367584675856758667587675886758967590675916759267593675946759567596675976759867599676006760167602676036760467605676066760767608676096761067611676126761367614676156761667617676186761967620676216762267623676246762567626676276762867629676306763167632676336763467635676366763767638676396764067641676426764367644676456764667647676486764967650676516765267653676546765567656676576765867659676606766167662676636766467665676666766767668676696767067671676726767367674676756767667677676786767967680676816768267683676846768567686676876768867689676906769167692676936769467695676966769767698676996770067701677026770367704677056770667707677086770967710677116771267713677146771567716677176771867719677206772167722677236772467725677266772767728677296773067731677326773367734677356773667737677386773967740677416774267743677446774567746677476774867749677506775167752677536775467755677566775767758677596776067761677626776367764677656776667767677686776967770677716777267773677746777567776677776777867779677806778167782677836778467785677866778767788677896779067791677926779367794677956779667797677986779967800678016780267803678046780567806678076780867809678106781167812678136781467815678166781767818678196782067821678226782367824678256782667827678286782967830678316783267833678346783567836678376783867839678406784167842678436784467845678466784767848678496785067851678526785367854678556785667857678586785967860678616786267863678646786567866678676786867869678706787167872678736787467875678766787767878678796788067881678826788367884678856788667887678886788967890678916789267893678946789567896678976789867899679006790167902679036790467905679066790767908679096791067911679126791367914679156791667917679186791967920679216792267923679246792567926679276792867929679306793167932679336793467935679366793767938679396794067941679426794367944679456794667947679486794967950679516795267953679546795567956679576795867959679606796167962679636796467965679666796767968679696797067971679726797367974679756797667977679786797967980679816798267983679846798567986679876798867989679906799167992679936799467995679966799767998679996800068001680026800368004680056800668007680086800968010680116801268013680146801568016680176801868019680206802168022680236802468025680266802768028680296803068031680326803368034680356803668037680386803968040680416804268043680446804568046680476804868049680506805168052680536805468055680566805768058680596806068061680626806368064680656806668067680686806968070680716807268073680746807568076680776807868079680806808168082680836808468085680866808768088680896809068091680926809368094680956809668097680986809968100681016810268103681046810568106681076810868109681106811168112681136811468115681166811768118681196812068121681226812368124681256812668127681286812968130681316813268133681346813568136681376813868139681406814168142681436814468145681466814768148681496815068151681526815368154681556815668157681586815968160681616816268163681646816568166681676816868169681706817168172681736817468175681766817768178681796818068181681826818368184681856818668187681886818968190681916819268193681946819568196681976819868199682006820168202682036820468205682066820768208682096821068211682126821368214682156821668217682186821968220682216822268223682246822568226682276822868229682306823168232682336823468235682366823768238682396824068241682426824368244682456824668247682486824968250682516825268253682546825568256682576825868259682606826168262682636826468265682666826768268682696827068271682726827368274682756827668277682786827968280682816828268283682846828568286682876828868289682906829168292682936829468295682966829768298682996830068301683026830368304683056830668307683086830968310683116831268313683146831568316683176831868319683206832168322683236832468325683266832768328683296833068331683326833368334683356833668337683386833968340683416834268343683446834568346683476834868349683506835168352683536835468355683566835768358683596836068361683626836368364683656836668367683686836968370683716837268373683746837568376683776837868379683806838168382683836838468385683866838768388683896839068391683926839368394683956839668397683986839968400684016840268403684046840568406684076840868409684106841168412684136841468415684166841768418684196842068421684226842368424684256842668427684286842968430684316843268433684346843568436684376843868439684406844168442684436844468445684466844768448684496845068451684526845368454684556845668457684586845968460684616846268463684646846568466684676846868469684706847168472684736847468475684766847768478684796848068481684826848368484684856848668487684886848968490684916849268493684946849568496684976849868499685006850168502685036850468505685066850768508685096851068511685126851368514685156851668517685186851968520685216852268523685246852568526685276852868529685306853168532685336853468535685366853768538685396854068541685426854368544685456854668547685486854968550685516855268553685546855568556685576855868559685606856168562685636856468565685666856768568685696857068571685726857368574685756857668577685786857968580685816858268583685846858568586685876858868589685906859168592685936859468595685966859768598685996860068601686026860368604686056860668607686086860968610686116861268613686146861568616686176861868619686206862168622686236862468625686266862768628686296863068631686326863368634686356863668637686386863968640686416864268643686446864568646686476864868649686506865168652686536865468655686566865768658686596866068661686626866368664686656866668667686686866968670686716867268673686746867568676686776867868679686806868168682686836868468685686866868768688686896869068691686926869368694686956869668697686986869968700687016870268703687046870568706687076870868709687106871168712687136871468715687166871768718687196872068721687226872368724687256872668727687286872968730687316873268733687346873568736687376873868739687406874168742687436874468745687466874768748687496875068751687526875368754687556875668757687586875968760687616876268763687646876568766687676876868769687706877168772687736877468775687766877768778687796878068781687826878368784687856878668787687886878968790687916879268793687946879568796687976879868799688006880168802688036880468805688066880768808688096881068811688126881368814688156881668817688186881968820688216882268823688246882568826688276882868829688306883168832688336883468835688366883768838688396884068841688426884368844688456884668847688486884968850688516885268853688546885568856688576885868859688606886168862688636886468865688666886768868688696887068871688726887368874688756887668877688786887968880688816888268883688846888568886688876888868889688906889168892688936889468895688966889768898688996890068901689026890368904689056890668907689086890968910689116891268913689146891568916689176891868919689206892168922689236892468925689266892768928689296893068931689326893368934689356893668937689386893968940689416894268943689446894568946689476894868949689506895168952689536895468955689566895768958689596896068961689626896368964689656896668967689686896968970689716897268973689746897568976689776897868979689806898168982689836898468985689866898768988689896899068991689926899368994689956899668997689986899969000690016900269003690046900569006690076900869009690106901169012690136901469015690166901769018690196902069021690226902369024690256902669027690286902969030690316903269033690346903569036690376903869039690406904169042690436904469045690466904769048690496905069051690526905369054690556905669057690586905969060690616906269063690646906569066690676906869069690706907169072690736907469075690766907769078690796908069081690826908369084690856908669087690886908969090690916909269093690946909569096690976909869099691006910169102691036910469105691066910769108691096911069111691126911369114691156911669117691186911969120691216912269123691246912569126691276912869129691306913169132691336913469135691366913769138691396914069141691426914369144691456914669147691486914969150691516915269153691546915569156691576915869159691606916169162691636916469165691666916769168691696917069171691726917369174691756917669177691786917969180691816918269183691846918569186691876918869189691906919169192691936919469195691966919769198691996920069201692026920369204692056920669207692086920969210692116921269213692146921569216692176921869219692206922169222692236922469225692266922769228692296923069231692326923369234692356923669237692386923969240692416924269243692446924569246692476924869249692506925169252692536925469255692566925769258692596926069261692626926369264692656926669267692686926969270692716927269273692746927569276692776927869279692806928169282692836928469285692866928769288692896929069291692926929369294692956929669297692986929969300693016930269303693046930569306693076930869309693106931169312693136931469315693166931769318693196932069321693226932369324693256932669327693286932969330693316933269333693346933569336693376933869339693406934169342693436934469345693466934769348693496935069351693526935369354693556935669357693586935969360693616936269363693646936569366693676936869369693706937169372693736937469375693766937769378693796938069381693826938369384693856938669387693886938969390693916939269393693946939569396693976939869399694006940169402694036940469405694066940769408694096941069411694126941369414694156941669417694186941969420694216942269423694246942569426694276942869429694306943169432694336943469435694366943769438694396944069441694426944369444694456944669447694486944969450694516945269453694546945569456694576945869459694606946169462694636946469465694666946769468694696947069471694726947369474694756947669477694786947969480694816948269483694846948569486694876948869489694906949169492694936949469495694966949769498694996950069501695026950369504695056950669507695086950969510695116951269513695146951569516695176951869519695206952169522695236952469525695266952769528695296953069531695326953369534695356953669537695386953969540695416954269543695446954569546695476954869549695506955169552695536955469555695566955769558695596956069561695626956369564695656956669567695686956969570695716957269573695746957569576695776957869579695806958169582695836958469585695866958769588695896959069591695926959369594695956959669597695986959969600696016960269603696046960569606696076960869609696106961169612696136961469615696166961769618696196962069621696226962369624696256962669627696286962969630696316963269633696346963569636696376963869639696406964169642696436964469645696466964769648696496965069651696526965369654696556965669657696586965969660696616966269663696646966569666696676966869669696706967169672696736967469675696766967769678696796968069681696826968369684696856968669687696886968969690696916969269693696946969569696696976969869699697006970169702697036970469705697066970769708697096971069711697126971369714697156971669717697186971969720697216972269723697246972569726697276972869729697306973169732697336973469735697366973769738697396974069741697426974369744697456974669747697486974969750697516975269753697546975569756697576975869759697606976169762697636976469765697666976769768697696977069771697726977369774697756977669777697786977969780697816978269783697846978569786697876978869789697906979169792697936979469795697966979769798697996980069801698026980369804698056980669807698086980969810698116981269813698146981569816698176981869819698206982169822698236982469825698266982769828698296983069831698326983369834698356983669837698386983969840698416984269843698446984569846698476984869849698506985169852698536985469855698566985769858698596986069861698626986369864698656986669867698686986969870698716987269873698746987569876698776987869879698806988169882698836988469885698866988769888698896989069891698926989369894698956989669897698986989969900699016990269903699046990569906699076990869909699106991169912699136991469915699166991769918699196992069921699226992369924699256992669927699286992969930699316993269933699346993569936699376993869939699406994169942699436994469945699466994769948699496995069951699526995369954699556995669957699586995969960699616996269963699646996569966699676996869969699706997169972699736997469975699766997769978699796998069981699826998369984699856998669987699886998969990699916999269993699946999569996699976999869999700007000170002700037000470005700067000770008700097001070011700127001370014700157001670017700187001970020700217002270023700247002570026700277002870029700307003170032700337003470035700367003770038700397004070041700427004370044700457004670047700487004970050700517005270053700547005570056700577005870059700607006170062700637006470065700667006770068700697007070071700727007370074700757007670077700787007970080700817008270083700847008570086700877008870089700907009170092700937009470095700967009770098700997010070101701027010370104701057010670107701087010970110701117011270113701147011570116701177011870119701207012170122701237012470125701267012770128701297013070131701327013370134701357013670137701387013970140701417014270143701447014570146701477014870149701507015170152701537015470155701567015770158701597016070161701627016370164701657016670167701687016970170701717017270173701747017570176701777017870179701807018170182701837018470185701867018770188701897019070191701927019370194701957019670197701987019970200702017020270203702047020570206702077020870209702107021170212702137021470215702167021770218702197022070221702227022370224702257022670227702287022970230702317023270233702347023570236702377023870239702407024170242702437024470245702467024770248702497025070251702527025370254702557025670257702587025970260702617026270263702647026570266702677026870269702707027170272702737027470275702767027770278702797028070281702827028370284702857028670287702887028970290702917029270293702947029570296702977029870299703007030170302703037030470305703067030770308703097031070311703127031370314703157031670317703187031970320703217032270323703247032570326703277032870329703307033170332703337033470335703367033770338703397034070341703427034370344703457034670347703487034970350703517035270353703547035570356703577035870359703607036170362703637036470365703667036770368703697037070371703727037370374703757037670377703787037970380703817038270383703847038570386703877038870389703907039170392703937039470395703967039770398703997040070401704027040370404704057040670407704087040970410704117041270413704147041570416704177041870419704207042170422704237042470425704267042770428704297043070431704327043370434704357043670437704387043970440704417044270443704447044570446704477044870449704507045170452704537045470455704567045770458704597046070461704627046370464704657046670467704687046970470704717047270473704747047570476704777047870479704807048170482704837048470485704867048770488704897049070491704927049370494704957049670497704987049970500705017050270503705047050570506705077050870509705107051170512705137051470515705167051770518705197052070521705227052370524705257052670527705287052970530705317053270533705347053570536705377053870539705407054170542705437054470545705467054770548705497055070551705527055370554705557055670557705587055970560705617056270563705647056570566705677056870569705707057170572705737057470575705767057770578705797058070581705827058370584705857058670587705887058970590705917059270593705947059570596705977059870599706007060170602706037060470605706067060770608706097061070611706127061370614706157061670617706187061970620706217062270623706247062570626706277062870629706307063170632706337063470635706367063770638706397064070641706427064370644706457064670647706487064970650706517065270653706547065570656706577065870659706607066170662706637066470665706667066770668706697067070671706727067370674706757067670677706787067970680706817068270683706847068570686706877068870689706907069170692706937069470695706967069770698706997070070701707027070370704707057070670707707087070970710707117071270713707147071570716707177071870719707207072170722707237072470725707267072770728707297073070731707327073370734707357073670737707387073970740707417074270743707447074570746707477074870749707507075170752707537075470755707567075770758707597076070761707627076370764707657076670767707687076970770707717077270773707747077570776707777077870779707807078170782707837078470785707867078770788707897079070791707927079370794707957079670797707987079970800708017080270803708047080570806708077080870809708107081170812708137081470815708167081770818708197082070821708227082370824708257082670827708287082970830708317083270833708347083570836708377083870839708407084170842708437084470845708467084770848708497085070851708527085370854708557085670857708587085970860708617086270863708647086570866708677086870869708707087170872708737087470875708767087770878708797088070881708827088370884708857088670887708887088970890708917089270893708947089570896708977089870899709007090170902709037090470905709067090770908709097091070911709127091370914709157091670917709187091970920709217092270923709247092570926709277092870929709307093170932709337093470935709367093770938709397094070941709427094370944709457094670947709487094970950709517095270953709547095570956709577095870959709607096170962709637096470965709667096770968709697097070971709727097370974709757097670977709787097970980709817098270983709847098570986709877098870989709907099170992709937099470995709967099770998709997100071001710027100371004710057100671007710087100971010710117101271013710147101571016710177101871019710207102171022710237102471025710267102771028710297103071031710327103371034710357103671037710387103971040710417104271043710447104571046710477104871049710507105171052710537105471055710567105771058710597106071061710627106371064710657106671067710687106971070710717107271073710747107571076710777107871079710807108171082710837108471085710867108771088710897109071091710927109371094710957109671097710987109971100711017110271103711047110571106711077110871109711107111171112711137111471115711167111771118711197112071121711227112371124711257112671127711287112971130711317113271133711347113571136711377113871139711407114171142711437114471145711467114771148711497115071151711527115371154711557115671157711587115971160711617116271163711647116571166711677116871169711707117171172711737117471175711767117771178711797118071181711827118371184711857118671187711887118971190711917119271193711947119571196711977119871199712007120171202712037120471205712067120771208712097121071211712127121371214712157121671217712187121971220712217122271223712247122571226712277122871229712307123171232712337123471235712367123771238712397124071241712427124371244712457124671247712487124971250712517125271253712547125571256712577125871259712607126171262712637126471265712667126771268712697127071271712727127371274712757127671277712787127971280712817128271283712847128571286712877128871289712907129171292712937129471295712967129771298712997130071301713027130371304713057130671307713087130971310713117131271313713147131571316713177131871319713207132171322713237132471325713267132771328713297133071331713327133371334713357133671337713387133971340713417134271343713447134571346713477134871349713507135171352713537135471355713567135771358713597136071361713627136371364713657136671367713687136971370713717137271373713747137571376713777137871379713807138171382713837138471385713867138771388713897139071391713927139371394713957139671397713987139971400714017140271403714047140571406714077140871409714107141171412714137141471415714167141771418714197142071421714227142371424714257142671427714287142971430714317143271433714347143571436714377143871439714407144171442714437144471445714467144771448714497145071451714527145371454714557145671457714587145971460714617146271463714647146571466714677146871469714707147171472714737147471475714767147771478714797148071481714827148371484714857148671487714887148971490714917149271493714947149571496714977149871499715007150171502715037150471505715067150771508715097151071511715127151371514715157151671517715187151971520715217152271523715247152571526715277152871529715307153171532715337153471535715367153771538715397154071541715427154371544715457154671547715487154971550715517155271553715547155571556715577155871559715607156171562715637156471565715667156771568715697157071571715727157371574715757157671577715787157971580715817158271583715847158571586715877158871589715907159171592715937159471595715967159771598715997160071601716027160371604716057160671607716087160971610716117161271613716147161571616716177161871619716207162171622716237162471625716267162771628716297163071631716327163371634716357163671637716387163971640716417164271643716447164571646716477164871649716507165171652716537165471655716567165771658716597166071661716627166371664716657166671667716687166971670716717167271673716747167571676716777167871679716807168171682716837168471685716867168771688716897169071691716927169371694716957169671697716987169971700717017170271703717047170571706717077170871709717107171171712717137171471715717167171771718717197172071721717227172371724717257172671727717287172971730717317173271733717347173571736717377173871739717407174171742717437174471745717467174771748717497175071751717527175371754717557175671757717587175971760717617176271763717647176571766717677176871769717707177171772717737177471775717767177771778717797178071781717827178371784717857178671787717887178971790717917179271793717947179571796717977179871799718007180171802718037180471805718067180771808718097181071811718127181371814718157181671817718187181971820718217182271823718247182571826718277182871829718307183171832718337183471835718367183771838718397184071841718427184371844718457184671847718487184971850718517185271853718547185571856718577185871859718607186171862718637186471865718667186771868718697187071871718727187371874718757187671877718787187971880718817188271883718847188571886718877188871889718907189171892718937189471895718967189771898718997190071901719027190371904719057190671907719087190971910719117191271913719147191571916719177191871919719207192171922719237192471925719267192771928719297193071931719327193371934719357193671937719387193971940719417194271943719447194571946719477194871949719507195171952719537195471955719567195771958719597196071961719627196371964719657196671967719687196971970719717197271973719747197571976719777197871979719807198171982719837198471985719867198771988719897199071991719927199371994719957199671997719987199972000720017200272003720047200572006720077200872009720107201172012720137201472015720167201772018720197202072021720227202372024720257202672027720287202972030720317203272033720347203572036720377203872039720407204172042720437204472045720467204772048720497205072051720527205372054720557205672057720587205972060720617206272063720647206572066720677206872069720707207172072720737207472075720767207772078720797208072081720827208372084720857208672087720887208972090720917209272093720947209572096720977209872099721007210172102721037210472105721067210772108721097211072111721127211372114721157211672117721187211972120721217212272123721247212572126721277212872129721307213172132721337213472135721367213772138721397214072141721427214372144721457214672147721487214972150721517215272153721547215572156721577215872159721607216172162721637216472165721667216772168721697217072171721727217372174721757217672177721787217972180721817218272183721847218572186721877218872189721907219172192721937219472195721967219772198721997220072201722027220372204722057220672207722087220972210722117221272213722147221572216722177221872219722207222172222722237222472225722267222772228722297223072231722327223372234722357223672237722387223972240722417224272243722447224572246722477224872249722507225172252722537225472255722567225772258722597226072261722627226372264722657226672267722687226972270722717227272273722747227572276722777227872279722807228172282722837228472285722867228772288722897229072291722927229372294722957229672297722987229972300723017230272303723047230572306723077230872309723107231172312723137231472315723167231772318723197232072321723227232372324723257232672327723287232972330723317233272333723347233572336723377233872339723407234172342723437234472345723467234772348723497235072351723527235372354723557235672357723587235972360723617236272363723647236572366723677236872369723707237172372723737237472375723767237772378723797238072381723827238372384723857238672387723887238972390723917239272393723947239572396723977239872399724007240172402724037240472405724067240772408724097241072411724127241372414724157241672417724187241972420724217242272423724247242572426724277242872429724307243172432724337243472435724367243772438724397244072441724427244372444724457244672447724487244972450724517245272453724547245572456724577245872459724607246172462724637246472465724667246772468724697247072471724727247372474724757247672477724787247972480724817248272483724847248572486724877248872489724907249172492724937249472495724967249772498724997250072501725027250372504725057250672507725087250972510725117251272513725147251572516725177251872519725207252172522725237252472525725267252772528725297253072531725327253372534725357253672537725387253972540725417254272543725447254572546725477254872549725507255172552725537255472555725567255772558725597256072561725627256372564725657256672567725687256972570725717257272573725747257572576725777257872579725807258172582725837258472585725867258772588725897259072591725927259372594725957259672597725987259972600726017260272603726047260572606726077260872609726107261172612726137261472615726167261772618726197262072621726227262372624726257262672627726287262972630726317263272633726347263572636726377263872639726407264172642726437264472645726467264772648726497265072651726527265372654726557265672657726587265972660726617266272663726647266572666726677266872669726707267172672726737267472675726767267772678726797268072681726827268372684726857268672687726887268972690726917269272693726947269572696726977269872699727007270172702727037270472705727067270772708727097271072711727127271372714727157271672717727187271972720727217272272723727247272572726727277272872729727307273172732727337273472735727367273772738727397274072741727427274372744727457274672747727487274972750727517275272753727547275572756727577275872759727607276172762727637276472765727667276772768727697277072771727727277372774727757277672777727787277972780727817278272783727847278572786727877278872789727907279172792727937279472795727967279772798727997280072801728027280372804728057280672807728087280972810728117281272813728147281572816728177281872819728207282172822728237282472825728267282772828728297283072831728327283372834728357283672837728387283972840728417284272843728447284572846728477284872849728507285172852728537285472855728567285772858728597286072861728627286372864728657286672867728687286972870728717287272873728747287572876728777287872879728807288172882728837288472885728867288772888728897289072891728927289372894728957289672897728987289972900729017290272903729047290572906729077290872909729107291172912729137291472915729167291772918729197292072921729227292372924729257292672927729287292972930729317293272933729347293572936729377293872939729407294172942729437294472945729467294772948729497295072951729527295372954729557295672957729587295972960729617296272963729647296572966729677296872969729707297172972729737297472975729767297772978729797298072981729827298372984729857298672987729887298972990729917299272993729947299572996729977299872999730007300173002730037300473005730067300773008730097301073011730127301373014730157301673017730187301973020730217302273023730247302573026730277302873029730307303173032730337303473035730367303773038730397304073041730427304373044730457304673047730487304973050730517305273053730547305573056730577305873059730607306173062730637306473065730667306773068730697307073071730727307373074730757307673077730787307973080730817308273083730847308573086730877308873089730907309173092730937309473095730967309773098730997310073101731027310373104731057310673107731087310973110731117311273113731147311573116731177311873119731207312173122731237312473125731267312773128731297313073131731327313373134731357313673137731387313973140731417314273143731447314573146731477314873149731507315173152731537315473155731567315773158731597316073161731627316373164731657316673167731687316973170731717317273173731747317573176731777317873179731807318173182731837318473185731867318773188731897319073191731927319373194731957319673197731987319973200732017320273203732047320573206732077320873209732107321173212732137321473215732167321773218732197322073221732227322373224732257322673227732287322973230732317323273233732347323573236732377323873239732407324173242732437324473245732467324773248732497325073251732527325373254732557325673257732587325973260732617326273263732647326573266732677326873269732707327173272732737327473275732767327773278732797328073281732827328373284732857328673287732887328973290732917329273293732947329573296732977329873299733007330173302733037330473305733067330773308733097331073311733127331373314733157331673317733187331973320733217332273323733247332573326733277332873329733307333173332733337333473335733367333773338733397334073341733427334373344733457334673347733487334973350733517335273353733547335573356733577335873359733607336173362733637336473365733667336773368733697337073371733727337373374733757337673377733787337973380733817338273383733847338573386733877338873389733907339173392733937339473395733967339773398733997340073401734027340373404734057340673407734087340973410734117341273413734147341573416734177341873419734207342173422734237342473425734267342773428734297343073431734327343373434734357343673437734387343973440734417344273443734447344573446734477344873449734507345173452734537345473455734567345773458734597346073461734627346373464734657346673467734687346973470734717347273473734747347573476734777347873479734807348173482734837348473485734867348773488734897349073491734927349373494734957349673497734987349973500735017350273503735047350573506735077350873509735107351173512735137351473515735167351773518735197352073521735227352373524735257352673527735287352973530735317353273533735347353573536735377353873539735407354173542735437354473545735467354773548735497355073551735527355373554735557355673557735587355973560735617356273563735647356573566735677356873569735707357173572735737357473575735767357773578735797358073581735827358373584735857358673587735887358973590735917359273593735947359573596735977359873599736007360173602736037360473605736067360773608736097361073611736127361373614736157361673617736187361973620736217362273623736247362573626736277362873629736307363173632736337363473635736367363773638736397364073641736427364373644736457364673647736487364973650736517365273653736547365573656736577365873659736607366173662736637366473665736667366773668736697367073671736727367373674736757367673677736787367973680736817368273683736847368573686736877368873689736907369173692736937369473695736967369773698736997370073701737027370373704737057370673707737087370973710737117371273713737147371573716737177371873719737207372173722737237372473725737267372773728737297373073731737327373373734737357373673737737387373973740737417374273743737447374573746737477374873749737507375173752737537375473755737567375773758737597376073761737627376373764737657376673767737687376973770737717377273773737747377573776737777377873779737807378173782737837378473785737867378773788737897379073791737927379373794737957379673797737987379973800738017380273803738047380573806738077380873809738107381173812738137381473815738167381773818738197382073821738227382373824738257382673827738287382973830738317383273833738347383573836738377383873839738407384173842738437384473845738467384773848738497385073851738527385373854738557385673857738587385973860738617386273863738647386573866738677386873869738707387173872738737387473875738767387773878738797388073881738827388373884738857388673887738887388973890738917389273893738947389573896738977389873899739007390173902739037390473905739067390773908739097391073911739127391373914739157391673917739187391973920739217392273923739247392573926739277392873929739307393173932739337393473935739367393773938739397394073941739427394373944739457394673947739487394973950739517395273953739547395573956739577395873959739607396173962739637396473965739667396773968739697397073971739727397373974739757397673977739787397973980739817398273983739847398573986739877398873989739907399173992739937399473995739967399773998739997400074001740027400374004740057400674007740087400974010740117401274013740147401574016740177401874019740207402174022740237402474025740267402774028740297403074031740327403374034740357403674037740387403974040740417404274043740447404574046740477404874049740507405174052740537405474055740567405774058740597406074061740627406374064740657406674067740687406974070740717407274073740747407574076740777407874079740807408174082740837408474085740867408774088740897409074091740927409374094740957409674097740987409974100741017410274103741047410574106741077410874109741107411174112741137411474115741167411774118741197412074121741227412374124741257412674127741287412974130741317413274133741347413574136741377413874139741407414174142741437414474145741467414774148741497415074151741527415374154741557415674157741587415974160741617416274163741647416574166741677416874169741707417174172741737417474175741767417774178741797418074181741827418374184741857418674187741887418974190741917419274193741947419574196741977419874199742007420174202742037420474205742067420774208742097421074211742127421374214742157421674217742187421974220742217422274223742247422574226742277422874229742307423174232742337423474235742367423774238742397424074241742427424374244742457424674247742487424974250742517425274253742547425574256742577425874259742607426174262742637426474265742667426774268742697427074271742727427374274742757427674277742787427974280742817428274283742847428574286742877428874289742907429174292742937429474295742967429774298742997430074301743027430374304743057430674307743087430974310743117431274313743147431574316743177431874319743207432174322743237432474325743267432774328743297433074331743327433374334743357433674337743387433974340743417434274343743447434574346743477434874349743507435174352743537435474355743567435774358743597436074361743627436374364743657436674367743687436974370743717437274373743747437574376743777437874379743807438174382743837438474385743867438774388743897439074391743927439374394743957439674397743987439974400744017440274403744047440574406744077440874409744107441174412744137441474415744167441774418744197442074421744227442374424744257442674427744287442974430744317443274433744347443574436744377443874439744407444174442744437444474445744467444774448744497445074451744527445374454744557445674457744587445974460744617446274463744647446574466744677446874469744707447174472744737447474475744767447774478744797448074481744827448374484744857448674487744887448974490744917449274493744947449574496744977449874499745007450174502745037450474505745067450774508745097451074511745127451374514745157451674517745187451974520745217452274523745247452574526745277452874529745307453174532745337453474535745367453774538745397454074541745427454374544745457454674547745487454974550745517455274553745547455574556745577455874559745607456174562745637456474565745667456774568745697457074571745727457374574745757457674577745787457974580745817458274583745847458574586745877458874589745907459174592745937459474595745967459774598745997460074601746027460374604746057460674607746087460974610746117461274613746147461574616746177461874619746207462174622746237462474625746267462774628746297463074631746327463374634746357463674637746387463974640746417464274643746447464574646746477464874649746507465174652746537465474655746567465774658746597466074661746627466374664746657466674667746687466974670746717467274673746747467574676746777467874679746807468174682746837468474685746867468774688746897469074691746927469374694746957469674697746987469974700747017470274703747047470574706747077470874709747107471174712747137471474715747167471774718747197472074721747227472374724747257472674727747287472974730747317473274733747347473574736747377473874739747407474174742747437474474745747467474774748747497475074751747527475374754747557475674757747587475974760747617476274763747647476574766747677476874769747707477174772747737477474775747767477774778747797478074781747827478374784747857478674787747887478974790747917479274793747947479574796747977479874799748007480174802748037480474805748067480774808748097481074811748127481374814748157481674817748187481974820748217482274823748247482574826748277482874829748307483174832748337483474835748367483774838748397484074841748427484374844748457484674847748487484974850748517485274853748547485574856748577485874859748607486174862748637486474865748667486774868748697487074871748727487374874748757487674877748787487974880748817488274883748847488574886748877488874889748907489174892748937489474895748967489774898748997490074901749027490374904749057490674907749087490974910749117491274913749147491574916749177491874919749207492174922749237492474925749267492774928749297493074931749327493374934749357493674937749387493974940749417494274943749447494574946749477494874949749507495174952749537495474955749567495774958749597496074961749627496374964749657496674967749687496974970749717497274973749747497574976749777497874979749807498174982749837498474985749867498774988749897499074991749927499374994749957499674997749987499975000750017500275003750047500575006750077500875009750107501175012750137501475015750167501775018750197502075021750227502375024750257502675027750287502975030750317503275033750347503575036750377503875039750407504175042750437504475045750467504775048750497505075051750527505375054750557505675057750587505975060750617506275063750647506575066750677506875069750707507175072750737507475075750767507775078750797508075081750827508375084750857508675087750887508975090750917509275093750947509575096750977509875099751007510175102751037510475105751067510775108751097511075111751127511375114751157511675117751187511975120751217512275123751247512575126751277512875129751307513175132751337513475135751367513775138751397514075141751427514375144751457514675147751487514975150751517515275153751547515575156751577515875159751607516175162751637516475165751667516775168751697517075171751727517375174751757517675177751787517975180751817518275183751847518575186751877518875189751907519175192751937519475195751967519775198751997520075201752027520375204752057520675207752087520975210752117521275213752147521575216752177521875219752207522175222752237522475225752267522775228752297523075231752327523375234752357523675237752387523975240752417524275243752447524575246752477524875249752507525175252752537525475255752567525775258752597526075261752627526375264752657526675267752687526975270752717527275273752747527575276752777527875279752807528175282752837528475285752867528775288752897529075291752927529375294752957529675297752987529975300753017530275303753047530575306753077530875309753107531175312753137531475315753167531775318753197532075321753227532375324753257532675327753287532975330753317533275333753347533575336753377533875339753407534175342753437534475345753467534775348753497535075351753527535375354753557535675357753587535975360753617536275363753647536575366753677536875369753707537175372753737537475375753767537775378753797538075381753827538375384753857538675387753887538975390753917539275393753947539575396753977539875399754007540175402754037540475405754067540775408754097541075411754127541375414754157541675417754187541975420754217542275423754247542575426754277542875429754307543175432754337543475435754367543775438754397544075441754427544375444754457544675447754487544975450754517545275453754547545575456754577545875459754607546175462754637546475465754667546775468754697547075471754727547375474754757547675477754787547975480754817548275483754847548575486754877548875489754907549175492754937549475495754967549775498754997550075501755027550375504755057550675507755087550975510755117551275513755147551575516755177551875519755207552175522755237552475525755267552775528755297553075531755327553375534755357553675537755387553975540755417554275543755447554575546755477554875549755507555175552755537555475555755567555775558755597556075561755627556375564755657556675567755687556975570755717557275573755747557575576755777557875579755807558175582755837558475585755867558775588755897559075591755927559375594755957559675597755987559975600756017560275603756047560575606756077560875609756107561175612756137561475615756167561775618756197562075621756227562375624756257562675627756287562975630756317563275633756347563575636756377563875639756407564175642756437564475645756467564775648756497565075651756527565375654756557565675657756587565975660756617566275663756647566575666756677566875669756707567175672756737567475675756767567775678756797568075681756827568375684756857568675687756887568975690756917569275693756947569575696756977569875699757007570175702757037570475705757067570775708757097571075711757127571375714757157571675717757187571975720757217572275723757247572575726757277572875729757307573175732757337573475735757367573775738757397574075741757427574375744757457574675747757487574975750757517575275753757547575575756757577575875759757607576175762757637576475765757667576775768757697577075771757727577375774757757577675777757787577975780757817578275783757847578575786757877578875789757907579175792757937579475795757967579775798757997580075801758027580375804758057580675807758087580975810758117581275813758147581575816758177581875819758207582175822758237582475825758267582775828758297583075831758327583375834758357583675837758387583975840758417584275843758447584575846758477584875849758507585175852758537585475855758567585775858758597586075861758627586375864758657586675867758687586975870758717587275873758747587575876758777587875879758807588175882758837588475885758867588775888758897589075891758927589375894758957589675897758987589975900759017590275903759047590575906759077590875909759107591175912759137591475915759167591775918759197592075921759227592375924759257592675927759287592975930759317593275933759347593575936759377593875939759407594175942759437594475945759467594775948759497595075951759527595375954759557595675957759587595975960759617596275963759647596575966759677596875969759707597175972759737597475975759767597775978759797598075981759827598375984759857598675987759887598975990759917599275993759947599575996759977599875999760007600176002760037600476005760067600776008760097601076011760127601376014760157601676017760187601976020760217602276023760247602576026760277602876029760307603176032760337603476035760367603776038760397604076041760427604376044760457604676047760487604976050760517605276053760547605576056760577605876059760607606176062760637606476065760667606776068760697607076071760727607376074760757607676077760787607976080760817608276083760847608576086760877608876089760907609176092760937609476095760967609776098760997610076101761027610376104761057610676107761087610976110761117611276113761147611576116761177611876119761207612176122761237612476125761267612776128761297613076131761327613376134761357613676137761387613976140761417614276143761447614576146761477614876149761507615176152761537615476155761567615776158761597616076161761627616376164761657616676167761687616976170761717617276173761747617576176761777617876179761807618176182761837618476185761867618776188761897619076191761927619376194761957619676197761987619976200762017620276203762047620576206762077620876209762107621176212762137621476215762167621776218762197622076221762227622376224762257622676227762287622976230762317623276233762347623576236762377623876239762407624176242762437624476245762467624776248762497625076251762527625376254762557625676257762587625976260762617626276263762647626576266762677626876269762707627176272762737627476275762767627776278762797628076281762827628376284762857628676287762887628976290762917629276293762947629576296762977629876299763007630176302763037630476305763067630776308763097631076311763127631376314763157631676317763187631976320763217632276323763247632576326763277632876329763307633176332763337633476335763367633776338763397634076341763427634376344763457634676347763487634976350763517635276353763547635576356763577635876359763607636176362763637636476365763667636776368763697637076371763727637376374763757637676377763787637976380763817638276383763847638576386763877638876389763907639176392763937639476395763967639776398763997640076401764027640376404764057640676407764087640976410764117641276413764147641576416764177641876419764207642176422764237642476425764267642776428764297643076431764327643376434764357643676437764387643976440764417644276443764447644576446764477644876449764507645176452764537645476455764567645776458764597646076461764627646376464764657646676467764687646976470764717647276473764747647576476764777647876479764807648176482764837648476485764867648776488764897649076491764927649376494764957649676497764987649976500765017650276503765047650576506765077650876509765107651176512765137651476515765167651776518765197652076521765227652376524765257652676527765287652976530765317653276533765347653576536765377653876539765407654176542765437654476545765467654776548765497655076551765527655376554765557655676557765587655976560765617656276563765647656576566765677656876569765707657176572765737657476575765767657776578765797658076581765827658376584765857658676587765887658976590765917659276593765947659576596765977659876599766007660176602766037660476605766067660776608766097661076611766127661376614766157661676617766187661976620766217662276623766247662576626766277662876629766307663176632766337663476635766367663776638766397664076641766427664376644766457664676647766487664976650766517665276653766547665576656766577665876659766607666176662766637666476665766667666776668766697667076671766727667376674766757667676677766787667976680766817668276683766847668576686766877668876689766907669176692766937669476695766967669776698766997670076701767027670376704767057670676707767087670976710767117671276713767147671576716767177671876719767207672176722767237672476725767267672776728767297673076731767327673376734767357673676737767387673976740767417674276743767447674576746767477674876749767507675176752767537675476755767567675776758767597676076761767627676376764767657676676767767687676976770767717677276773767747677576776767777677876779767807678176782767837678476785767867678776788767897679076791767927679376794767957679676797767987679976800768017680276803768047680576806768077680876809768107681176812768137681476815768167681776818768197682076821768227682376824768257682676827768287682976830768317683276833768347683576836768377683876839768407684176842768437684476845768467684776848768497685076851768527685376854768557685676857768587685976860768617686276863768647686576866768677686876869768707687176872768737687476875768767687776878768797688076881768827688376884768857688676887768887688976890768917689276893768947689576896768977689876899769007690176902769037690476905769067690776908769097691076911769127691376914769157691676917769187691976920769217692276923769247692576926769277692876929769307693176932769337693476935769367693776938769397694076941769427694376944769457694676947769487694976950769517695276953769547695576956769577695876959769607696176962769637696476965769667696776968769697697076971769727697376974769757697676977769787697976980769817698276983769847698576986769877698876989769907699176992769937699476995769967699776998769997700077001770027700377004770057700677007770087700977010770117701277013770147701577016770177701877019770207702177022770237702477025770267702777028770297703077031770327703377034770357703677037770387703977040770417704277043770447704577046770477704877049770507705177052770537705477055770567705777058770597706077061770627706377064770657706677067770687706977070770717707277073770747707577076770777707877079770807708177082770837708477085770867708777088770897709077091770927709377094770957709677097770987709977100771017710277103771047710577106771077710877109771107711177112771137711477115771167711777118771197712077121771227712377124771257712677127771287712977130771317713277133771347713577136771377713877139771407714177142771437714477145771467714777148771497715077151771527715377154771557715677157771587715977160771617716277163771647716577166771677716877169771707717177172771737717477175771767717777178771797718077181771827718377184771857718677187771887718977190771917719277193771947719577196771977719877199772007720177202772037720477205772067720777208772097721077211772127721377214772157721677217772187721977220772217722277223772247722577226772277722877229772307723177232772337723477235772367723777238772397724077241772427724377244772457724677247772487724977250772517725277253772547725577256772577725877259772607726177262772637726477265772667726777268772697727077271772727727377274772757727677277772787727977280772817728277283772847728577286772877728877289772907729177292772937729477295772967729777298772997730077301773027730377304773057730677307773087730977310773117731277313773147731577316773177731877319773207732177322773237732477325773267732777328773297733077331773327733377334773357733677337773387733977340773417734277343773447734577346773477734877349773507735177352773537735477355773567735777358773597736077361773627736377364773657736677367773687736977370773717737277373773747737577376773777737877379773807738177382773837738477385773867738777388773897739077391773927739377394773957739677397773987739977400774017740277403774047740577406774077740877409774107741177412774137741477415774167741777418774197742077421774227742377424774257742677427774287742977430774317743277433774347743577436774377743877439774407744177442774437744477445774467744777448774497745077451774527745377454774557745677457774587745977460774617746277463774647746577466774677746877469774707747177472774737747477475774767747777478774797748077481774827748377484774857748677487774887748977490774917749277493774947749577496774977749877499775007750177502775037750477505775067750777508775097751077511775127751377514775157751677517775187751977520775217752277523775247752577526775277752877529775307753177532775337753477535775367753777538775397754077541775427754377544775457754677547775487754977550775517755277553775547755577556775577755877559775607756177562775637756477565775667756777568775697757077571775727757377574775757757677577775787757977580775817758277583775847758577586775877758877589775907759177592775937759477595775967759777598775997760077601776027760377604776057760677607776087760977610776117761277613776147761577616776177761877619776207762177622776237762477625776267762777628776297763077631776327763377634776357763677637776387763977640776417764277643776447764577646776477764877649776507765177652776537765477655776567765777658776597766077661776627766377664776657766677667776687766977670776717767277673776747767577676776777767877679776807768177682776837768477685776867768777688776897769077691776927769377694776957769677697776987769977700777017770277703777047770577706777077770877709777107771177712777137771477715777167771777718777197772077721777227772377724777257772677727777287772977730777317773277733777347773577736777377773877739777407774177742777437774477745777467774777748777497775077751777527775377754777557775677757777587775977760777617776277763777647776577766777677776877769777707777177772777737777477775777767777777778777797778077781777827778377784777857778677787777887778977790777917779277793777947779577796777977779877799778007780177802778037780477805778067780777808778097781077811778127781377814778157781677817778187781977820778217782277823778247782577826778277782877829778307783177832778337783477835778367783777838778397784077841778427784377844778457784677847778487784977850778517785277853778547785577856778577785877859778607786177862778637786477865778667786777868778697787077871778727787377874778757787677877778787787977880778817788277883778847788577886778877788877889778907789177892778937789477895778967789777898778997790077901779027790377904779057790677907779087790977910779117791277913779147791577916779177791877919779207792177922779237792477925779267792777928779297793077931779327793377934779357793677937779387793977940779417794277943779447794577946779477794877949779507795177952779537795477955779567795777958779597796077961779627796377964779657796677967779687796977970779717797277973779747797577976779777797877979779807798177982779837798477985779867798777988779897799077991779927799377994779957799677997779987799978000780017800278003780047800578006780077800878009780107801178012780137801478015780167801778018780197802078021780227802378024780257802678027780287802978030780317803278033780347803578036780377803878039780407804178042780437804478045780467804778048780497805078051780527805378054780557805678057780587805978060780617806278063780647806578066780677806878069780707807178072780737807478075780767807778078780797808078081780827808378084780857808678087780887808978090780917809278093780947809578096780977809878099781007810178102781037810478105781067810778108781097811078111781127811378114781157811678117781187811978120781217812278123781247812578126781277812878129781307813178132781337813478135781367813778138781397814078141781427814378144781457814678147781487814978150781517815278153781547815578156781577815878159781607816178162781637816478165781667816778168781697817078171781727817378174781757817678177781787817978180781817818278183781847818578186781877818878189781907819178192781937819478195781967819778198781997820078201782027820378204782057820678207782087820978210782117821278213782147821578216782177821878219782207822178222782237822478225782267822778228782297823078231782327823378234782357823678237782387823978240782417824278243782447824578246782477824878249782507825178252782537825478255782567825778258782597826078261782627826378264782657826678267782687826978270782717827278273782747827578276782777827878279782807828178282782837828478285782867828778288782897829078291782927829378294782957829678297782987829978300783017830278303783047830578306783077830878309783107831178312783137831478315783167831778318783197832078321783227832378324783257832678327783287832978330783317833278333783347833578336783377833878339783407834178342783437834478345783467834778348783497835078351783527835378354783557835678357783587835978360783617836278363783647836578366783677836878369783707837178372783737837478375783767837778378783797838078381783827838378384783857838678387783887838978390783917839278393783947839578396783977839878399784007840178402784037840478405784067840778408784097841078411784127841378414784157841678417784187841978420784217842278423784247842578426784277842878429784307843178432784337843478435784367843778438784397844078441784427844378444784457844678447784487844978450784517845278453784547845578456784577845878459784607846178462784637846478465784667846778468784697847078471784727847378474784757847678477784787847978480784817848278483784847848578486784877848878489784907849178492784937849478495784967849778498784997850078501785027850378504785057850678507785087850978510785117851278513785147851578516785177851878519785207852178522785237852478525785267852778528785297853078531785327853378534785357853678537785387853978540785417854278543785447854578546785477854878549785507855178552785537855478555785567855778558785597856078561785627856378564785657856678567785687856978570785717857278573785747857578576785777857878579785807858178582785837858478585785867858778588785897859078591785927859378594785957859678597785987859978600786017860278603786047860578606786077860878609786107861178612786137861478615786167861778618786197862078621786227862378624786257862678627786287862978630786317863278633786347863578636786377863878639786407864178642786437864478645786467864778648786497865078651786527865378654786557865678657786587865978660786617866278663786647866578666786677866878669786707867178672786737867478675786767867778678786797868078681786827868378684786857868678687786887868978690786917869278693786947869578696786977869878699787007870178702787037870478705787067870778708787097871078711787127871378714787157871678717787187871978720787217872278723787247872578726787277872878729787307873178732787337873478735787367873778738787397874078741787427874378744787457874678747787487874978750787517875278753787547875578756787577875878759787607876178762787637876478765787667876778768787697877078771787727877378774787757877678777787787877978780787817878278783787847878578786787877878878789787907879178792787937879478795787967879778798787997880078801788027880378804788057880678807788087880978810788117881278813788147881578816788177881878819788207882178822788237882478825788267882778828788297883078831788327883378834788357883678837788387883978840788417884278843788447884578846788477884878849788507885178852788537885478855788567885778858788597886078861788627886378864788657886678867788687886978870788717887278873788747887578876788777887878879788807888178882788837888478885788867888778888788897889078891788927889378894788957889678897788987889978900789017890278903789047890578906789077890878909789107891178912789137891478915789167891778918789197892078921789227892378924789257892678927789287892978930789317893278933789347893578936789377893878939789407894178942789437894478945789467894778948789497895078951789527895378954789557895678957789587895978960789617896278963789647896578966789677896878969789707897178972789737897478975789767897778978789797898078981789827898378984789857898678987789887898978990789917899278993789947899578996789977899878999790007900179002790037900479005790067900779008790097901079011790127901379014790157901679017790187901979020790217902279023790247902579026790277902879029790307903179032790337903479035790367903779038790397904079041790427904379044790457904679047790487904979050790517905279053790547905579056790577905879059790607906179062790637906479065790667906779068790697907079071790727907379074790757907679077790787907979080790817908279083790847908579086790877908879089790907909179092790937909479095790967909779098790997910079101791027910379104791057910679107791087910979110791117911279113791147911579116791177911879119791207912179122791237912479125791267912779128791297913079131791327913379134791357913679137791387913979140791417914279143791447914579146791477914879149791507915179152791537915479155791567915779158791597916079161791627916379164791657916679167791687916979170791717917279173791747917579176791777917879179791807918179182791837918479185791867918779188791897919079191791927919379194791957919679197791987919979200792017920279203792047920579206792077920879209792107921179212792137921479215792167921779218792197922079221792227922379224792257922679227792287922979230792317923279233792347923579236792377923879239792407924179242792437924479245792467924779248792497925079251792527925379254792557925679257792587925979260792617926279263792647926579266792677926879269792707927179272792737927479275792767927779278792797928079281792827928379284792857928679287792887928979290792917929279293792947929579296792977929879299793007930179302793037930479305793067930779308793097931079311793127931379314793157931679317793187931979320793217932279323793247932579326793277932879329793307933179332793337933479335793367933779338793397934079341793427934379344793457934679347793487934979350793517935279353793547935579356793577935879359793607936179362793637936479365793667936779368793697937079371793727937379374793757937679377793787937979380793817938279383793847938579386793877938879389793907939179392793937939479395793967939779398793997940079401794027940379404794057940679407794087940979410794117941279413794147941579416794177941879419794207942179422794237942479425794267942779428794297943079431794327943379434794357943679437794387943979440794417944279443794447944579446794477944879449794507945179452794537945479455794567945779458794597946079461794627946379464794657946679467794687946979470794717947279473794747947579476794777947879479794807948179482794837948479485794867948779488794897949079491794927949379494794957949679497794987949979500795017950279503795047950579506795077950879509795107951179512795137951479515795167951779518795197952079521795227952379524795257952679527795287952979530795317953279533795347953579536795377953879539795407954179542795437954479545795467954779548795497955079551795527955379554795557955679557795587955979560795617956279563795647956579566795677956879569795707957179572795737957479575795767957779578795797958079581795827958379584795857958679587795887958979590795917959279593795947959579596795977959879599796007960179602796037960479605796067960779608796097961079611796127961379614796157961679617796187961979620796217962279623796247962579626796277962879629796307963179632796337963479635796367963779638796397964079641796427964379644796457964679647796487964979650796517965279653796547965579656796577965879659796607966179662796637966479665796667966779668796697967079671796727967379674796757967679677796787967979680796817968279683796847968579686796877968879689796907969179692796937969479695796967969779698796997970079701797027970379704797057970679707797087970979710797117971279713797147971579716797177971879719797207972179722797237972479725797267972779728797297973079731797327973379734797357973679737797387973979740797417974279743797447974579746797477974879749797507975179752797537975479755797567975779758797597976079761797627976379764797657976679767797687976979770797717977279773797747977579776797777977879779797807978179782797837978479785797867978779788797897979079791797927979379794797957979679797797987979979800798017980279803798047980579806798077980879809798107981179812798137981479815798167981779818798197982079821798227982379824798257982679827798287982979830798317983279833798347983579836798377983879839798407984179842798437984479845798467984779848798497985079851798527985379854798557985679857798587985979860798617986279863798647986579866798677986879869798707987179872798737987479875798767987779878798797988079881798827988379884798857988679887798887988979890798917989279893798947989579896798977989879899799007990179902799037990479905799067990779908799097991079911799127991379914799157991679917799187991979920799217992279923799247992579926799277992879929799307993179932799337993479935799367993779938799397994079941799427994379944799457994679947799487994979950799517995279953799547995579956799577995879959799607996179962799637996479965799667996779968799697997079971799727997379974799757997679977799787997979980799817998279983799847998579986799877998879989799907999179992799937999479995799967999779998799998000080001800028000380004800058000680007800088000980010800118001280013800148001580016800178001880019800208002180022800238002480025800268002780028800298003080031800328003380034800358003680037800388003980040800418004280043800448004580046800478004880049800508005180052800538005480055800568005780058800598006080061800628006380064800658006680067800688006980070800718007280073800748007580076800778007880079800808008180082800838008480085800868008780088800898009080091800928009380094800958009680097800988009980100801018010280103801048010580106801078010880109801108011180112801138011480115801168011780118801198012080121801228012380124801258012680127801288012980130801318013280133801348013580136801378013880139801408014180142801438014480145801468014780148801498015080151801528015380154801558015680157801588015980160801618016280163801648016580166801678016880169801708017180172801738017480175801768017780178801798018080181801828018380184801858018680187801888018980190801918019280193801948019580196801978019880199802008020180202802038020480205802068020780208802098021080211802128021380214802158021680217802188021980220802218022280223802248022580226802278022880229802308023180232802338023480235802368023780238802398024080241802428024380244802458024680247802488024980250802518025280253802548025580256802578025880259802608026180262802638026480265802668026780268802698027080271802728027380274802758027680277802788027980280802818028280283802848028580286802878028880289802908029180292802938029480295802968029780298802998030080301803028030380304803058030680307803088030980310803118031280313803148031580316803178031880319803208032180322803238032480325803268032780328803298033080331803328033380334803358033680337803388033980340803418034280343803448034580346803478034880349803508035180352803538035480355803568035780358803598036080361803628036380364803658036680367803688036980370803718037280373803748037580376803778037880379803808038180382803838038480385803868038780388803898039080391803928039380394803958039680397803988039980400804018040280403804048040580406804078040880409804108041180412804138041480415804168041780418804198042080421804228042380424804258042680427804288042980430804318043280433804348043580436804378043880439804408044180442804438044480445804468044780448804498045080451804528045380454804558045680457804588045980460804618046280463804648046580466804678046880469804708047180472804738047480475804768047780478804798048080481804828048380484804858048680487804888048980490804918049280493804948049580496804978049880499805008050180502805038050480505805068050780508805098051080511805128051380514805158051680517805188051980520805218052280523805248052580526805278052880529805308053180532805338053480535805368053780538805398054080541805428054380544805458054680547805488054980550805518055280553805548055580556805578055880559805608056180562805638056480565805668056780568805698057080571805728057380574805758057680577805788057980580805818058280583805848058580586805878058880589805908059180592805938059480595805968059780598805998060080601806028060380604806058060680607806088060980610806118061280613806148061580616806178061880619806208062180622806238062480625806268062780628806298063080631806328063380634806358063680637806388063980640806418064280643806448064580646806478064880649806508065180652806538065480655806568065780658806598066080661806628066380664806658066680667806688066980670806718067280673806748067580676806778067880679806808068180682806838068480685806868068780688806898069080691806928069380694806958069680697806988069980700807018070280703807048070580706807078070880709807108071180712807138071480715807168071780718807198072080721807228072380724807258072680727807288072980730807318073280733807348073580736807378073880739807408074180742807438074480745807468074780748807498075080751807528075380754807558075680757807588075980760807618076280763807648076580766807678076880769807708077180772807738077480775807768077780778807798078080781807828078380784807858078680787807888078980790807918079280793807948079580796807978079880799808008080180802808038080480805808068080780808808098081080811808128081380814808158081680817808188081980820808218082280823808248082580826808278082880829808308083180832808338083480835808368083780838808398084080841808428084380844808458084680847808488084980850808518085280853808548085580856808578085880859808608086180862808638086480865808668086780868808698087080871808728087380874808758087680877808788087980880808818088280883808848088580886808878088880889808908089180892808938089480895808968089780898808998090080901809028090380904809058090680907809088090980910809118091280913809148091580916809178091880919809208092180922809238092480925809268092780928809298093080931809328093380934809358093680937809388093980940809418094280943809448094580946809478094880949809508095180952809538095480955809568095780958809598096080961809628096380964809658096680967809688096980970809718097280973809748097580976809778097880979809808098180982809838098480985809868098780988809898099080991809928099380994809958099680997809988099981000810018100281003810048100581006810078100881009810108101181012810138101481015810168101781018810198102081021810228102381024810258102681027810288102981030810318103281033810348103581036810378103881039810408104181042810438104481045810468104781048810498105081051810528105381054810558105681057810588105981060810618106281063810648106581066810678106881069810708107181072810738107481075810768107781078810798108081081810828108381084810858108681087810888108981090810918109281093810948109581096810978109881099811008110181102811038110481105811068110781108811098111081111811128111381114811158111681117811188111981120811218112281123811248112581126811278112881129811308113181132811338113481135811368113781138811398114081141811428114381144811458114681147811488114981150811518115281153811548115581156811578115881159811608116181162811638116481165811668116781168811698117081171811728117381174811758117681177811788117981180811818118281183811848118581186811878118881189811908119181192811938119481195811968119781198811998120081201812028120381204812058120681207812088120981210812118121281213812148121581216812178121881219812208122181222812238122481225812268122781228812298123081231812328123381234812358123681237812388123981240812418124281243812448124581246812478124881249812508125181252812538125481255812568125781258812598126081261812628126381264812658126681267812688126981270812718127281273812748127581276812778127881279812808128181282812838128481285812868128781288812898129081291812928129381294812958129681297812988129981300813018130281303813048130581306813078130881309813108131181312813138131481315813168131781318813198132081321813228132381324813258132681327813288132981330813318133281333813348133581336813378133881339813408134181342813438134481345813468134781348813498135081351813528135381354813558135681357813588135981360813618136281363813648136581366813678136881369813708137181372813738137481375813768137781378813798138081381813828138381384813858138681387813888138981390813918139281393813948139581396813978139881399814008140181402814038140481405814068140781408814098141081411814128141381414814158141681417814188141981420814218142281423814248142581426814278142881429814308143181432814338143481435814368143781438814398144081441814428144381444814458144681447814488144981450814518145281453814548145581456814578145881459814608146181462814638146481465814668146781468814698147081471814728147381474814758147681477814788147981480814818148281483814848148581486814878148881489814908149181492814938149481495814968149781498814998150081501815028150381504815058150681507815088150981510815118151281513815148151581516815178151881519815208152181522815238152481525815268152781528815298153081531815328153381534815358153681537815388153981540815418154281543815448154581546815478154881549815508155181552815538155481555815568155781558815598156081561815628156381564815658156681567815688156981570815718157281573815748157581576815778157881579815808158181582815838158481585815868158781588815898159081591815928159381594815958159681597815988159981600816018160281603816048160581606816078160881609816108161181612816138161481615816168161781618816198162081621816228162381624816258162681627816288162981630816318163281633816348163581636816378163881639816408164181642816438164481645816468164781648816498165081651816528165381654816558165681657816588165981660816618166281663816648166581666816678166881669816708167181672816738167481675816768167781678816798168081681816828168381684816858168681687816888168981690816918169281693816948169581696816978169881699817008170181702817038170481705817068170781708817098171081711817128171381714817158171681717817188171981720817218172281723817248172581726817278172881729817308173181732817338173481735817368173781738817398174081741817428174381744817458174681747817488174981750817518175281753817548175581756817578175881759817608176181762817638176481765817668176781768817698177081771817728177381774817758177681777817788177981780817818178281783817848178581786817878178881789817908179181792817938179481795817968179781798817998180081801818028180381804818058180681807818088180981810818118181281813818148181581816818178181881819818208182181822818238182481825818268182781828818298183081831818328183381834818358183681837818388183981840818418184281843818448184581846818478184881849818508185181852818538185481855818568185781858818598186081861818628186381864818658186681867818688186981870818718187281873818748187581876818778187881879818808188181882818838188481885818868188781888818898189081891818928189381894818958189681897818988189981900819018190281903819048190581906819078190881909819108191181912819138191481915819168191781918819198192081921819228192381924819258192681927819288192981930819318193281933819348193581936819378193881939819408194181942819438194481945819468194781948819498195081951819528195381954819558195681957819588195981960819618196281963819648196581966819678196881969819708197181972819738197481975819768197781978819798198081981819828198381984819858198681987819888198981990819918199281993819948199581996819978199881999820008200182002820038200482005820068200782008820098201082011820128201382014820158201682017820188201982020820218202282023820248202582026820278202882029820308203182032820338203482035820368203782038820398204082041820428204382044820458204682047820488204982050820518205282053820548205582056820578205882059820608206182062820638206482065820668206782068820698207082071820728207382074820758207682077820788207982080820818208282083820848208582086820878208882089820908209182092820938209482095820968209782098820998210082101821028210382104821058210682107821088210982110821118211282113821148211582116821178211882119821208212182122821238212482125821268212782128821298213082131821328213382134821358213682137821388213982140821418214282143821448214582146821478214882149821508215182152821538215482155821568215782158821598216082161821628216382164821658216682167821688216982170821718217282173821748217582176821778217882179821808218182182821838218482185821868218782188821898219082191821928219382194821958219682197821988219982200822018220282203822048220582206822078220882209822108221182212822138221482215822168221782218822198222082221822228222382224822258222682227822288222982230822318223282233822348223582236822378223882239822408224182242822438224482245822468224782248822498225082251822528225382254822558225682257822588225982260822618226282263822648226582266822678226882269822708227182272822738227482275822768227782278822798228082281822828228382284822858228682287822888228982290822918229282293822948229582296822978229882299823008230182302823038230482305823068230782308823098231082311823128231382314823158231682317823188231982320823218232282323823248232582326823278232882329823308233182332823338233482335823368233782338823398234082341823428234382344823458234682347823488234982350823518235282353823548235582356823578235882359823608236182362823638236482365823668236782368823698237082371823728237382374823758237682377823788237982380823818238282383823848238582386823878238882389823908239182392823938239482395823968239782398823998240082401824028240382404824058240682407824088240982410824118241282413824148241582416824178241882419824208242182422824238242482425824268242782428824298243082431824328243382434824358243682437824388243982440824418244282443824448244582446824478244882449824508245182452824538245482455824568245782458824598246082461824628246382464824658246682467824688246982470824718247282473824748247582476824778247882479824808248182482824838248482485824868248782488824898249082491824928249382494824958249682497824988249982500825018250282503825048250582506825078250882509825108251182512825138251482515825168251782518825198252082521825228252382524825258252682527825288252982530825318253282533825348253582536825378253882539825408254182542825438254482545825468254782548825498255082551825528255382554825558255682557825588255982560825618256282563825648256582566825678256882569825708257182572825738257482575825768257782578825798258082581825828258382584825858258682587825888258982590825918259282593825948259582596825978259882599826008260182602826038260482605826068260782608826098261082611826128261382614826158261682617826188261982620826218262282623826248262582626826278262882629826308263182632826338263482635826368263782638826398264082641826428264382644826458264682647826488264982650826518265282653826548265582656826578265882659826608266182662826638266482665826668266782668826698267082671826728267382674826758267682677826788267982680826818268282683826848268582686826878268882689826908269182692826938269482695826968269782698826998270082701827028270382704827058270682707827088270982710827118271282713827148271582716827178271882719827208272182722827238272482725827268272782728827298273082731827328273382734827358273682737827388273982740827418274282743827448274582746827478274882749827508275182752827538275482755827568275782758827598276082761827628276382764827658276682767827688276982770827718277282773827748277582776827778277882779827808278182782827838278482785827868278782788827898279082791827928279382794827958279682797827988279982800828018280282803828048280582806828078280882809828108281182812828138281482815828168281782818828198282082821828228282382824828258282682827828288282982830828318283282833828348283582836828378283882839828408284182842828438284482845828468284782848828498285082851828528285382854828558285682857828588285982860828618286282863828648286582866828678286882869828708287182872828738287482875828768287782878828798288082881828828288382884828858288682887828888288982890828918289282893828948289582896828978289882899829008290182902829038290482905829068290782908829098291082911829128291382914829158291682917829188291982920829218292282923829248292582926829278292882929829308293182932829338293482935829368293782938829398294082941829428294382944829458294682947829488294982950829518295282953829548295582956829578295882959829608296182962829638296482965829668296782968829698297082971829728297382974829758297682977829788297982980829818298282983829848298582986829878298882989829908299182992829938299482995829968299782998829998300083001830028300383004830058300683007830088300983010830118301283013830148301583016830178301883019830208302183022830238302483025830268302783028830298303083031830328303383034830358303683037830388303983040830418304283043830448304583046830478304883049830508305183052830538305483055830568305783058830598306083061830628306383064830658306683067830688306983070830718307283073830748307583076830778307883079830808308183082830838308483085830868308783088830898309083091830928309383094830958309683097830988309983100831018310283103831048310583106831078310883109831108311183112831138311483115831168311783118831198312083121831228312383124831258312683127831288312983130831318313283133831348313583136831378313883139831408314183142831438314483145831468314783148831498315083151831528315383154831558315683157831588315983160831618316283163831648316583166831678316883169831708317183172831738317483175831768317783178831798318083181831828318383184831858318683187831888318983190831918319283193831948319583196831978319883199832008320183202832038320483205832068320783208832098321083211832128321383214832158321683217832188321983220832218322283223832248322583226832278322883229832308323183232832338323483235832368323783238832398324083241832428324383244832458324683247832488324983250832518325283253832548325583256832578325883259832608326183262832638326483265832668326783268832698327083271832728327383274832758327683277832788327983280832818328283283832848328583286832878328883289832908329183292832938329483295832968329783298832998330083301833028330383304833058330683307833088330983310833118331283313833148331583316833178331883319833208332183322833238332483325833268332783328833298333083331833328333383334833358333683337833388333983340833418334283343833448334583346833478334883349833508335183352833538335483355833568335783358833598336083361833628336383364833658336683367833688336983370833718337283373833748337583376833778337883379833808338183382833838338483385833868338783388833898339083391833928339383394833958339683397833988339983400834018340283403834048340583406834078340883409834108341183412834138341483415834168341783418834198342083421834228342383424834258342683427834288342983430834318343283433834348343583436834378343883439834408344183442834438344483445834468344783448834498345083451834528345383454834558345683457834588345983460834618346283463834648346583466834678346883469834708347183472834738347483475834768347783478834798348083481834828348383484834858348683487834888348983490834918349283493834948349583496834978349883499835008350183502835038350483505835068350783508835098351083511835128351383514835158351683517835188351983520835218352283523835248352583526835278352883529835308353183532835338353483535835368353783538835398354083541835428354383544835458354683547835488354983550835518355283553835548355583556835578355883559835608356183562835638356483565835668356783568835698357083571835728357383574835758357683577835788357983580835818358283583835848358583586835878358883589835908359183592835938359483595835968359783598835998360083601836028360383604836058360683607836088360983610836118361283613836148361583616836178361883619836208362183622836238362483625836268362783628836298363083631836328363383634836358363683637836388363983640836418364283643836448364583646836478364883649836508365183652836538365483655836568365783658836598366083661836628366383664836658366683667836688366983670836718367283673836748367583676836778367883679836808368183682836838368483685836868368783688836898369083691836928369383694836958369683697836988369983700837018370283703837048370583706837078370883709837108371183712837138371483715837168371783718837198372083721837228372383724837258372683727837288372983730837318373283733837348373583736837378373883739837408374183742837438374483745837468374783748837498375083751837528375383754837558375683757837588375983760837618376283763837648376583766837678376883769837708377183772837738377483775837768377783778837798378083781837828378383784837858378683787837888378983790837918379283793837948379583796837978379883799838008380183802838038380483805838068380783808838098381083811838128381383814838158381683817838188381983820838218382283823838248382583826838278382883829838308383183832838338383483835838368383783838838398384083841838428384383844838458384683847838488384983850838518385283853838548385583856838578385883859838608386183862838638386483865838668386783868838698387083871838728387383874838758387683877838788387983880838818388283883838848388583886838878388883889838908389183892838938389483895838968389783898838998390083901839028390383904839058390683907839088390983910839118391283913839148391583916839178391883919839208392183922839238392483925839268392783928839298393083931839328393383934839358393683937839388393983940839418394283943839448394583946839478394883949839508395183952839538395483955839568395783958839598396083961839628396383964839658396683967839688396983970839718397283973839748397583976839778397883979839808398183982839838398483985839868398783988839898399083991839928399383994839958399683997839988399984000840018400284003840048400584006840078400884009840108401184012840138401484015840168401784018840198402084021840228402384024840258402684027840288402984030840318403284033840348403584036840378403884039840408404184042840438404484045840468404784048840498405084051840528405384054840558405684057840588405984060840618406284063840648406584066840678406884069840708407184072840738407484075840768407784078840798408084081840828408384084840858408684087840888408984090840918409284093840948409584096840978409884099841008410184102841038410484105841068410784108841098411084111841128411384114841158411684117841188411984120841218412284123841248412584126841278412884129841308413184132841338413484135841368413784138841398414084141841428414384144841458414684147841488414984150841518415284153841548415584156841578415884159841608416184162841638416484165841668416784168841698417084171841728417384174841758417684177841788417984180841818418284183841848418584186841878418884189841908419184192841938419484195841968419784198841998420084201842028420384204842058420684207842088420984210842118421284213842148421584216842178421884219842208422184222842238422484225842268422784228842298423084231842328423384234842358423684237842388423984240842418424284243842448424584246842478424884249842508425184252842538425484255842568425784258842598426084261842628426384264842658426684267842688426984270842718427284273842748427584276842778427884279842808428184282842838428484285842868428784288842898429084291842928429384294842958429684297842988429984300843018430284303843048430584306843078430884309843108431184312843138431484315843168431784318843198432084321843228432384324843258432684327843288432984330843318433284333843348433584336843378433884339843408434184342843438434484345843468434784348843498435084351843528435384354843558435684357843588435984360843618436284363843648436584366843678436884369843708437184372843738437484375843768437784378843798438084381843828438384384843858438684387843888438984390843918439284393843948439584396843978439884399844008440184402844038440484405844068440784408844098441084411844128441384414844158441684417844188441984420844218442284423844248442584426844278442884429844308443184432844338443484435844368443784438844398444084441844428444384444844458444684447844488444984450844518445284453844548445584456844578445884459844608446184462844638446484465844668446784468844698447084471844728447384474844758447684477844788447984480844818448284483844848448584486844878448884489844908449184492844938449484495844968449784498844998450084501845028450384504845058450684507845088450984510845118451284513845148451584516845178451884519845208452184522845238452484525845268452784528845298453084531845328453384534845358453684537845388453984540845418454284543845448454584546845478454884549845508455184552845538455484555845568455784558845598456084561845628456384564845658456684567845688456984570845718457284573845748457584576845778457884579845808458184582845838458484585845868458784588845898459084591845928459384594845958459684597845988459984600846018460284603846048460584606846078460884609846108461184612846138461484615846168461784618846198462084621846228462384624846258462684627846288462984630846318463284633846348463584636846378463884639846408464184642846438464484645846468464784648846498465084651846528465384654846558465684657846588465984660846618466284663846648466584666846678466884669846708467184672846738467484675846768467784678846798468084681846828468384684846858468684687846888468984690846918469284693846948469584696846978469884699847008470184702847038470484705847068470784708847098471084711847128471384714847158471684717847188471984720847218472284723847248472584726847278472884729847308473184732847338473484735847368473784738847398474084741847428474384744847458474684747847488474984750847518475284753847548475584756847578475884759847608476184762847638476484765847668476784768847698477084771847728477384774847758477684777847788477984780847818478284783847848478584786847878478884789847908479184792847938479484795847968479784798847998480084801848028480384804848058480684807848088480984810848118481284813848148481584816848178481884819848208482184822848238482484825848268482784828848298483084831848328483384834848358483684837848388483984840848418484284843848448484584846848478484884849848508485184852848538485484855848568485784858848598486084861848628486384864848658486684867848688486984870848718487284873848748487584876848778487884879848808488184882848838488484885848868488784888848898489084891848928489384894848958489684897848988489984900849018490284903849048490584906849078490884909849108491184912849138491484915849168491784918849198492084921849228492384924849258492684927849288492984930849318493284933849348493584936849378493884939849408494184942849438494484945849468494784948849498495084951849528495384954849558495684957849588495984960849618496284963849648496584966849678496884969849708497184972849738497484975849768497784978849798498084981849828498384984849858498684987849888498984990849918499284993849948499584996849978499884999850008500185002850038500485005850068500785008850098501085011850128501385014850158501685017850188501985020850218502285023850248502585026850278502885029850308503185032850338503485035850368503785038850398504085041850428504385044850458504685047850488504985050850518505285053850548505585056850578505885059850608506185062850638506485065850668506785068850698507085071850728507385074850758507685077850788507985080850818508285083850848508585086850878508885089850908509185092850938509485095850968509785098850998510085101851028510385104851058510685107851088510985110851118511285113851148511585116851178511885119851208512185122851238512485125851268512785128851298513085131851328513385134851358513685137851388513985140851418514285143851448514585146851478514885149851508515185152851538515485155851568515785158851598516085161851628516385164851658516685167851688516985170851718517285173851748517585176851778517885179851808518185182851838518485185851868518785188851898519085191851928519385194851958519685197851988519985200852018520285203852048520585206852078520885209852108521185212852138521485215852168521785218852198522085221852228522385224852258522685227852288522985230852318523285233852348523585236852378523885239852408524185242852438524485245852468524785248852498525085251852528525385254852558525685257852588525985260852618526285263852648526585266852678526885269852708527185272852738527485275852768527785278852798528085281852828528385284852858528685287852888528985290852918529285293852948529585296852978529885299853008530185302853038530485305853068530785308853098531085311853128531385314853158531685317853188531985320853218532285323853248532585326853278532885329853308533185332853338533485335853368533785338853398534085341853428534385344853458534685347853488534985350853518535285353853548535585356853578535885359853608536185362853638536485365853668536785368853698537085371853728537385374853758537685377853788537985380853818538285383853848538585386853878538885389853908539185392853938539485395853968539785398853998540085401854028540385404854058540685407854088540985410854118541285413854148541585416854178541885419854208542185422854238542485425854268542785428854298543085431854328543385434854358543685437854388543985440854418544285443854448544585446854478544885449854508545185452854538545485455854568545785458854598546085461854628546385464854658546685467854688546985470854718547285473854748547585476854778547885479854808548185482854838548485485854868548785488854898549085491854928549385494854958549685497854988549985500855018550285503855048550585506855078550885509855108551185512855138551485515855168551785518855198552085521855228552385524855258552685527855288552985530855318553285533855348553585536855378553885539855408554185542855438554485545855468554785548855498555085551855528555385554855558555685557855588555985560855618556285563855648556585566855678556885569855708557185572855738557485575855768557785578855798558085581855828558385584855858558685587855888558985590855918559285593855948559585596855978559885599856008560185602856038560485605856068560785608856098561085611856128561385614856158561685617856188561985620856218562285623856248562585626856278562885629856308563185632856338563485635856368563785638856398564085641856428564385644856458564685647856488564985650856518565285653856548565585656856578565885659856608566185662856638566485665856668566785668856698567085671856728567385674856758567685677856788567985680856818568285683856848568585686856878568885689856908569185692856938569485695856968569785698856998570085701857028570385704857058570685707857088570985710857118571285713857148571585716857178571885719857208572185722857238572485725857268572785728857298573085731857328573385734857358573685737857388573985740857418574285743857448574585746857478574885749857508575185752857538575485755857568575785758857598576085761857628576385764857658576685767857688576985770857718577285773857748577585776857778577885779857808578185782857838578485785857868578785788857898579085791857928579385794857958579685797857988579985800858018580285803858048580585806858078580885809858108581185812858138581485815858168581785818858198582085821858228582385824858258582685827858288582985830858318583285833858348583585836858378583885839858408584185842858438584485845858468584785848858498585085851858528585385854858558585685857858588585985860858618586285863858648586585866858678586885869858708587185872858738587485875858768587785878858798588085881858828588385884858858588685887858888588985890858918589285893858948589585896858978589885899859008590185902859038590485905859068590785908859098591085911859128591385914859158591685917859188591985920859218592285923859248592585926859278592885929859308593185932859338593485935859368593785938859398594085941859428594385944859458594685947859488594985950859518595285953859548595585956859578595885959859608596185962859638596485965859668596785968859698597085971859728597385974859758597685977859788597985980859818598285983859848598585986859878598885989859908599185992859938599485995859968599785998859998600086001860028600386004860058600686007860088600986010860118601286013860148601586016860178601886019860208602186022860238602486025860268602786028860298603086031860328603386034860358603686037860388603986040860418604286043860448604586046860478604886049860508605186052860538605486055860568605786058860598606086061860628606386064860658606686067860688606986070860718607286073860748607586076860778607886079860808608186082860838608486085860868608786088860898609086091860928609386094860958609686097860988609986100861018610286103861048610586106861078610886109861108611186112861138611486115861168611786118861198612086121861228612386124861258612686127861288612986130861318613286133861348613586136861378613886139861408614186142861438614486145861468614786148861498615086151861528615386154861558615686157861588615986160861618616286163861648616586166861678616886169861708617186172861738617486175861768617786178861798618086181861828618386184861858618686187861888618986190861918619286193861948619586196861978619886199862008620186202862038620486205862068620786208862098621086211862128621386214862158621686217862188621986220862218622286223862248622586226862278622886229862308623186232862338623486235862368623786238862398624086241862428624386244862458624686247862488624986250862518625286253862548625586256862578625886259862608626186262862638626486265862668626786268862698627086271862728627386274862758627686277862788627986280862818628286283862848628586286862878628886289862908629186292862938629486295862968629786298862998630086301863028630386304863058630686307863088630986310863118631286313863148631586316863178631886319863208632186322863238632486325863268632786328863298633086331863328633386334863358633686337863388633986340863418634286343863448634586346863478634886349863508635186352863538635486355863568635786358863598636086361863628636386364863658636686367863688636986370863718637286373863748637586376863778637886379863808638186382863838638486385863868638786388863898639086391863928639386394863958639686397863988639986400864018640286403864048640586406864078640886409864108641186412864138641486415864168641786418864198642086421864228642386424864258642686427864288642986430864318643286433864348643586436864378643886439864408644186442864438644486445864468644786448864498645086451864528645386454864558645686457864588645986460864618646286463864648646586466864678646886469864708647186472864738647486475864768647786478864798648086481864828648386484864858648686487864888648986490864918649286493864948649586496864978649886499865008650186502865038650486505865068650786508865098651086511865128651386514865158651686517865188651986520865218652286523865248652586526865278652886529865308653186532865338653486535865368653786538865398654086541865428654386544865458654686547865488654986550865518655286553865548655586556865578655886559865608656186562865638656486565865668656786568865698657086571865728657386574865758657686577865788657986580865818658286583865848658586586865878658886589865908659186592865938659486595865968659786598865998660086601866028660386604866058660686607866088660986610866118661286613866148661586616866178661886619866208662186622866238662486625866268662786628866298663086631866328663386634866358663686637866388663986640866418664286643866448664586646866478664886649866508665186652866538665486655866568665786658866598666086661866628666386664866658666686667866688666986670866718667286673866748667586676866778667886679866808668186682866838668486685866868668786688866898669086691866928669386694866958669686697866988669986700867018670286703867048670586706867078670886709867108671186712867138671486715867168671786718867198672086721867228672386724867258672686727867288672986730867318673286733867348673586736867378673886739867408674186742867438674486745867468674786748867498675086751867528675386754867558675686757867588675986760867618676286763867648676586766867678676886769867708677186772867738677486775867768677786778867798678086781867828678386784867858678686787867888678986790867918679286793867948679586796867978679886799868008680186802868038680486805868068680786808868098681086811868128681386814868158681686817868188681986820868218682286823868248682586826868278682886829868308683186832868338683486835868368683786838868398684086841868428684386844868458684686847868488684986850868518685286853868548685586856868578685886859868608686186862868638686486865868668686786868868698687086871868728687386874868758687686877868788687986880868818688286883868848688586886868878688886889868908689186892868938689486895868968689786898868998690086901869028690386904869058690686907869088690986910869118691286913869148691586916869178691886919869208692186922869238692486925869268692786928869298693086931869328693386934869358693686937869388693986940869418694286943869448694586946869478694886949869508695186952869538695486955869568695786958869598696086961869628696386964869658696686967869688696986970869718697286973869748697586976869778697886979869808698186982869838698486985869868698786988869898699086991869928699386994869958699686997869988699987000870018700287003870048700587006870078700887009870108701187012870138701487015870168701787018870198702087021870228702387024870258702687027870288702987030870318703287033870348703587036870378703887039870408704187042870438704487045870468704787048870498705087051870528705387054870558705687057870588705987060870618706287063870648706587066870678706887069870708707187072870738707487075870768707787078870798708087081870828708387084870858708687087870888708987090870918709287093870948709587096870978709887099871008710187102871038710487105871068710787108871098711087111871128711387114871158711687117871188711987120871218712287123871248712587126871278712887129871308713187132871338713487135871368713787138871398714087141871428714387144871458714687147871488714987150871518715287153871548715587156871578715887159871608716187162871638716487165871668716787168871698717087171871728717387174871758717687177871788717987180871818718287183871848718587186871878718887189871908719187192871938719487195871968719787198871998720087201872028720387204872058720687207872088720987210872118721287213872148721587216872178721887219872208722187222872238722487225872268722787228872298723087231872328723387234872358723687237872388723987240872418724287243872448724587246872478724887249872508725187252872538725487255872568725787258872598726087261872628726387264872658726687267872688726987270872718727287273872748727587276872778727887279872808728187282872838728487285872868728787288872898729087291872928729387294872958729687297872988729987300873018730287303873048730587306873078730887309873108731187312873138731487315873168731787318873198732087321873228732387324873258732687327873288732987330873318733287333873348733587336873378733887339873408734187342873438734487345873468734787348873498735087351873528735387354873558735687357873588735987360873618736287363873648736587366873678736887369873708737187372873738737487375873768737787378873798738087381873828738387384873858738687387873888738987390873918739287393873948739587396873978739887399874008740187402874038740487405874068740787408874098741087411874128741387414874158741687417874188741987420874218742287423874248742587426874278742887429874308743187432874338743487435874368743787438874398744087441874428744387444874458744687447874488744987450874518745287453874548745587456874578745887459874608746187462874638746487465874668746787468874698747087471874728747387474874758747687477874788747987480874818748287483874848748587486874878748887489874908749187492874938749487495874968749787498874998750087501875028750387504875058750687507875088750987510875118751287513875148751587516875178751887519875208752187522875238752487525875268752787528875298753087531875328753387534875358753687537875388753987540875418754287543875448754587546875478754887549875508755187552875538755487555875568755787558875598756087561875628756387564875658756687567875688756987570875718757287573875748757587576875778757887579875808758187582875838758487585875868758787588875898759087591875928759387594875958759687597875988759987600876018760287603876048760587606876078760887609876108761187612876138761487615876168761787618876198762087621876228762387624876258762687627876288762987630876318763287633876348763587636876378763887639876408764187642876438764487645876468764787648876498765087651876528765387654876558765687657876588765987660876618766287663876648766587666876678766887669876708767187672876738767487675876768767787678876798768087681876828768387684876858768687687876888768987690876918769287693876948769587696876978769887699877008770187702877038770487705877068770787708877098771087711877128771387714877158771687717877188771987720877218772287723877248772587726877278772887729877308773187732877338773487735877368773787738877398774087741877428774387744877458774687747877488774987750877518775287753877548775587756877578775887759877608776187762877638776487765877668776787768877698777087771877728777387774877758777687777877788777987780877818778287783877848778587786877878778887789877908779187792877938779487795877968779787798877998780087801878028780387804878058780687807878088780987810878118781287813878148781587816878178781887819878208782187822878238782487825878268782787828878298783087831878328783387834878358783687837878388783987840878418784287843878448784587846878478784887849878508785187852878538785487855878568785787858878598786087861878628786387864878658786687867878688786987870878718787287873878748787587876878778787887879878808788187882878838788487885878868788787888878898789087891878928789387894878958789687897878988789987900879018790287903879048790587906879078790887909879108791187912879138791487915879168791787918879198792087921879228792387924879258792687927879288792987930879318793287933879348793587936879378793887939879408794187942879438794487945879468794787948879498795087951879528795387954879558795687957879588795987960879618796287963879648796587966879678796887969879708797187972879738797487975879768797787978879798798087981879828798387984879858798687987879888798987990879918799287993879948799587996879978799887999880008800188002880038800488005880068800788008880098801088011880128801388014880158801688017880188801988020880218802288023880248802588026880278802888029880308803188032880338803488035880368803788038880398804088041880428804388044880458804688047880488804988050880518805288053880548805588056880578805888059880608806188062880638806488065880668806788068880698807088071880728807388074880758807688077880788807988080880818808288083880848808588086880878808888089880908809188092880938809488095880968809788098880998810088101881028810388104881058810688107881088810988110881118811288113881148811588116881178811888119881208812188122881238812488125881268812788128881298813088131881328813388134881358813688137881388813988140881418814288143881448814588146881478814888149881508815188152881538815488155881568815788158881598816088161881628816388164881658816688167881688816988170881718817288173881748817588176881778817888179881808818188182881838818488185881868818788188881898819088191881928819388194881958819688197881988819988200882018820288203882048820588206882078820888209882108821188212882138821488215882168821788218882198822088221882228822388224882258822688227882288822988230882318823288233882348823588236882378823888239882408824188242882438824488245882468824788248882498825088251882528825388254882558825688257882588825988260882618826288263882648826588266882678826888269882708827188272882738827488275882768827788278882798828088281882828828388284882858828688287882888828988290882918829288293882948829588296882978829888299883008830188302883038830488305883068830788308883098831088311883128831388314883158831688317883188831988320883218832288323883248832588326883278832888329883308833188332883338833488335883368833788338883398834088341883428834388344883458834688347883488834988350883518835288353883548835588356883578835888359883608836188362883638836488365883668836788368883698837088371883728837388374883758837688377883788837988380883818838288383883848838588386883878838888389883908839188392883938839488395883968839788398883998840088401884028840388404884058840688407884088840988410884118841288413884148841588416884178841888419884208842188422884238842488425884268842788428884298843088431884328843388434884358843688437884388843988440884418844288443884448844588446884478844888449884508845188452884538845488455884568845788458884598846088461884628846388464884658846688467884688846988470884718847288473884748847588476884778847888479884808848188482884838848488485884868848788488884898849088491884928849388494884958849688497884988849988500885018850288503885048850588506885078850888509885108851188512885138851488515885168851788518885198852088521885228852388524885258852688527885288852988530885318853288533885348853588536885378853888539885408854188542885438854488545885468854788548885498855088551885528855388554885558855688557885588855988560885618856288563885648856588566885678856888569885708857188572885738857488575885768857788578885798858088581885828858388584885858858688587885888858988590885918859288593885948859588596885978859888599886008860188602886038860488605886068860788608886098861088611886128861388614886158861688617886188861988620886218862288623886248862588626886278862888629886308863188632886338863488635886368863788638886398864088641886428864388644886458864688647886488864988650886518865288653886548865588656886578865888659886608866188662886638866488665886668866788668886698867088671886728867388674886758867688677886788867988680886818868288683886848868588686886878868888689886908869188692886938869488695886968869788698886998870088701887028870388704887058870688707887088870988710887118871288713887148871588716887178871888719887208872188722887238872488725887268872788728887298873088731887328873388734887358873688737887388873988740887418874288743887448874588746887478874888749887508875188752887538875488755887568875788758887598876088761887628876388764887658876688767887688876988770887718877288773887748877588776887778877888779887808878188782887838878488785887868878788788887898879088791887928879388794887958879688797887988879988800888018880288803888048880588806888078880888809888108881188812888138881488815888168881788818888198882088821888228882388824888258882688827888288882988830888318883288833888348883588836888378883888839888408884188842888438884488845888468884788848888498885088851888528885388854888558885688857888588885988860888618886288863888648886588866888678886888869888708887188872888738887488875888768887788878888798888088881888828888388884888858888688887888888888988890888918889288893888948889588896888978889888899889008890188902889038890488905889068890788908889098891088911889128891388914889158891688917889188891988920889218892288923889248892588926889278892888929889308893188932889338893488935889368893788938889398894088941889428894388944889458894688947889488894988950889518895288953889548895588956889578895888959889608896188962889638896488965889668896788968889698897088971889728897388974889758897688977889788897988980889818898288983889848898588986889878898888989889908899188992889938899488995889968899788998889998900089001890028900389004890058900689007890088900989010890118901289013890148901589016890178901889019890208902189022890238902489025890268902789028890298903089031890328903389034890358903689037890388903989040890418904289043890448904589046890478904889049890508905189052890538905489055890568905789058890598906089061890628906389064890658906689067890688906989070890718907289073890748907589076890778907889079890808908189082890838908489085890868908789088890898909089091890928909389094890958909689097890988909989100891018910289103891048910589106891078910889109891108911189112891138911489115891168911789118891198912089121891228912389124891258912689127891288912989130891318913289133891348913589136891378913889139891408914189142891438914489145891468914789148891498915089151891528915389154891558915689157891588915989160891618916289163891648916589166891678916889169891708917189172891738917489175891768917789178891798918089181891828918389184891858918689187891888918989190891918919289193891948919589196891978919889199892008920189202892038920489205892068920789208892098921089211892128921389214892158921689217892188921989220892218922289223892248922589226892278922889229892308923189232892338923489235892368923789238892398924089241892428924389244892458924689247892488924989250892518925289253892548925589256892578925889259892608926189262892638926489265892668926789268892698927089271892728927389274892758927689277892788927989280892818928289283892848928589286892878928889289892908929189292892938929489295892968929789298892998930089301893028930389304893058930689307893088930989310893118931289313893148931589316893178931889319893208932189322893238932489325893268932789328893298933089331893328933389334893358933689337893388933989340893418934289343893448934589346893478934889349893508935189352893538935489355893568935789358893598936089361893628936389364893658936689367893688936989370893718937289373893748937589376893778937889379893808938189382893838938489385893868938789388893898939089391893928939389394893958939689397893988939989400894018940289403894048940589406894078940889409894108941189412894138941489415894168941789418894198942089421894228942389424894258942689427894288942989430894318943289433894348943589436894378943889439894408944189442894438944489445894468944789448894498945089451894528945389454894558945689457894588945989460894618946289463894648946589466894678946889469894708947189472894738947489475894768947789478894798948089481894828948389484894858948689487894888948989490894918949289493894948949589496894978949889499895008950189502895038950489505895068950789508895098951089511895128951389514895158951689517895188951989520895218952289523895248952589526895278952889529895308953189532895338953489535895368953789538895398954089541895428954389544895458954689547895488954989550895518955289553895548955589556895578955889559895608956189562895638956489565895668956789568895698957089571895728957389574895758957689577895788957989580895818958289583895848958589586895878958889589895908959189592895938959489595895968959789598895998960089601896028960389604896058960689607896088960989610896118961289613896148961589616896178961889619896208962189622896238962489625896268962789628896298963089631896328963389634896358963689637896388963989640896418964289643896448964589646896478964889649896508965189652896538965489655896568965789658896598966089661896628966389664896658966689667896688966989670896718967289673896748967589676896778967889679896808968189682896838968489685896868968789688896898969089691896928969389694896958969689697896988969989700897018970289703897048970589706897078970889709897108971189712897138971489715897168971789718897198972089721897228972389724897258972689727897288972989730897318973289733897348973589736897378973889739897408974189742897438974489745897468974789748897498975089751897528975389754897558975689757897588975989760897618976289763897648976589766897678976889769897708977189772897738977489775897768977789778897798978089781897828978389784897858978689787897888978989790897918979289793897948979589796897978979889799898008980189802898038980489805898068980789808898098981089811898128981389814898158981689817898188981989820898218982289823898248982589826898278982889829898308983189832898338983489835898368983789838898398984089841898428984389844898458984689847898488984989850898518985289853898548985589856898578985889859898608986189862898638986489865898668986789868898698987089871898728987389874898758987689877898788987989880898818988289883898848988589886898878988889889898908989189892898938989489895898968989789898898998990089901899028990389904899058990689907899088990989910899118991289913899148991589916899178991889919899208992189922899238992489925899268992789928899298993089931899328993389934899358993689937899388993989940899418994289943899448994589946899478994889949899508995189952899538995489955899568995789958899598996089961899628996389964899658996689967899688996989970899718997289973899748997589976899778997889979899808998189982899838998489985899868998789988899898999089991899928999389994899958999689997899988999990000900019000290003900049000590006900079000890009900109001190012900139001490015900169001790018900199002090021900229002390024900259002690027900289002990030900319003290033900349003590036900379003890039900409004190042900439004490045900469004790048900499005090051900529005390054900559005690057900589005990060900619006290063900649006590066900679006890069900709007190072900739007490075900769007790078900799008090081900829008390084900859008690087900889008990090900919009290093900949009590096900979009890099901009010190102901039010490105901069010790108901099011090111901129011390114901159011690117901189011990120901219012290123901249012590126901279012890129901309013190132901339013490135901369013790138901399014090141901429014390144901459014690147901489014990150901519015290153901549015590156901579015890159901609016190162901639016490165901669016790168901699017090171901729017390174901759017690177901789017990180901819018290183901849018590186901879018890189901909019190192901939019490195901969019790198901999020090201902029020390204902059020690207902089020990210902119021290213902149021590216902179021890219902209022190222902239022490225902269022790228902299023090231902329023390234902359023690237902389023990240902419024290243902449024590246902479024890249902509025190252902539025490255902569025790258902599026090261902629026390264902659026690267902689026990270902719027290273902749027590276902779027890279902809028190282902839028490285902869028790288902899029090291902929029390294902959029690297902989029990300903019030290303903049030590306903079030890309903109031190312903139031490315903169031790318903199032090321903229032390324903259032690327903289032990330903319033290333903349033590336903379033890339903409034190342903439034490345903469034790348903499035090351903529035390354903559035690357903589035990360903619036290363903649036590366903679036890369903709037190372903739037490375903769037790378903799038090381903829038390384903859038690387903889038990390903919039290393903949039590396903979039890399904009040190402904039040490405904069040790408904099041090411904129041390414904159041690417904189041990420904219042290423904249042590426904279042890429904309043190432904339043490435904369043790438904399044090441904429044390444904459044690447904489044990450904519045290453904549045590456904579045890459904609046190462904639046490465904669046790468904699047090471904729047390474904759047690477904789047990480904819048290483904849048590486904879048890489904909049190492904939049490495904969049790498904999050090501905029050390504905059050690507905089050990510905119051290513905149051590516905179051890519905209052190522905239052490525905269052790528905299053090531905329053390534905359053690537905389053990540905419054290543905449054590546905479054890549905509055190552905539055490555905569055790558905599056090561905629056390564905659056690567905689056990570905719057290573905749057590576905779057890579905809058190582905839058490585905869058790588905899059090591905929059390594905959059690597905989059990600906019060290603906049060590606906079060890609906109061190612906139061490615906169061790618906199062090621906229062390624906259062690627906289062990630906319063290633906349063590636906379063890639906409064190642906439064490645906469064790648906499065090651906529065390654906559065690657906589065990660906619066290663906649066590666906679066890669906709067190672906739067490675906769067790678906799068090681906829068390684906859068690687906889068990690906919069290693906949069590696906979069890699907009070190702907039070490705907069070790708907099071090711907129071390714907159071690717907189071990720907219072290723907249072590726907279072890729907309073190732907339073490735907369073790738907399074090741907429074390744907459074690747907489074990750907519075290753907549075590756907579075890759907609076190762907639076490765907669076790768907699077090771907729077390774907759077690777907789077990780907819078290783907849078590786907879078890789907909079190792907939079490795907969079790798907999080090801908029080390804908059080690807908089080990810908119081290813908149081590816908179081890819908209082190822908239082490825908269082790828908299083090831908329083390834908359083690837908389083990840908419084290843908449084590846908479084890849908509085190852908539085490855908569085790858908599086090861908629086390864908659086690867908689086990870908719087290873908749087590876908779087890879908809088190882908839088490885908869088790888908899089090891908929089390894908959089690897908989089990900909019090290903909049090590906909079090890909909109091190912909139091490915909169091790918909199092090921909229092390924909259092690927909289092990930909319093290933909349093590936909379093890939909409094190942909439094490945909469094790948909499095090951909529095390954909559095690957909589095990960909619096290963909649096590966909679096890969909709097190972909739097490975909769097790978909799098090981909829098390984909859098690987909889098990990909919099290993909949099590996909979099890999910009100191002910039100491005910069100791008910099101091011910129101391014910159101691017910189101991020910219102291023910249102591026910279102891029910309103191032910339103491035910369103791038910399104091041910429104391044910459104691047910489104991050910519105291053910549105591056910579105891059910609106191062910639106491065910669106791068910699107091071910729107391074910759107691077910789107991080910819108291083910849108591086910879108891089910909109191092910939109491095910969109791098910999110091101911029110391104911059110691107911089110991110911119111291113911149111591116911179111891119911209112191122911239112491125911269112791128911299113091131911329113391134911359113691137911389113991140911419114291143911449114591146911479114891149911509115191152911539115491155911569115791158911599116091161911629116391164911659116691167911689116991170911719117291173911749117591176911779117891179911809118191182911839118491185911869118791188911899119091191911929119391194911959119691197911989119991200912019120291203912049120591206912079120891209912109121191212912139121491215912169121791218912199122091221912229122391224912259122691227912289122991230912319123291233912349123591236912379123891239912409124191242912439124491245912469124791248912499125091251912529125391254912559125691257912589125991260912619126291263912649126591266912679126891269912709127191272912739127491275912769127791278912799128091281912829128391284912859128691287912889128991290912919129291293912949129591296912979129891299913009130191302913039130491305913069130791308913099131091311913129131391314913159131691317913189131991320913219132291323913249132591326913279132891329913309133191332913339133491335913369133791338913399134091341913429134391344913459134691347913489134991350913519135291353913549135591356913579135891359913609136191362913639136491365913669136791368913699137091371913729137391374913759137691377913789137991380913819138291383913849138591386913879138891389913909139191392913939139491395913969139791398913999140091401914029140391404914059140691407914089140991410914119141291413914149141591416914179141891419914209142191422914239142491425914269142791428914299143091431914329143391434914359143691437914389143991440914419144291443914449144591446914479144891449914509145191452914539145491455914569145791458914599146091461914629146391464914659146691467914689146991470914719147291473914749147591476914779147891479914809148191482914839148491485914869148791488914899149091491914929149391494914959149691497914989149991500915019150291503915049150591506915079150891509915109151191512915139151491515915169151791518915199152091521915229152391524915259152691527915289152991530915319153291533915349153591536915379153891539915409154191542915439154491545915469154791548915499155091551915529155391554915559155691557915589155991560915619156291563915649156591566915679156891569915709157191572915739157491575915769157791578915799158091581915829158391584915859158691587915889158991590915919159291593915949159591596915979159891599916009160191602916039160491605916069160791608916099161091611916129161391614916159161691617916189161991620916219162291623916249162591626916279162891629916309163191632916339163491635916369163791638916399164091641916429164391644916459164691647916489164991650916519165291653916549165591656916579165891659916609166191662916639166491665916669166791668916699167091671916729167391674916759167691677916789167991680916819168291683916849168591686916879168891689916909169191692916939169491695916969169791698916999170091701917029170391704917059170691707917089170991710917119171291713917149171591716917179171891719917209172191722917239172491725917269172791728917299173091731917329173391734917359173691737917389173991740917419174291743917449174591746917479174891749917509175191752917539175491755917569175791758917599176091761917629176391764917659176691767917689176991770917719177291773917749177591776917779177891779917809178191782917839178491785917869178791788917899179091791917929179391794917959179691797917989179991800918019180291803918049180591806918079180891809918109181191812918139181491815918169181791818918199182091821918229182391824918259182691827918289182991830918319183291833918349183591836918379183891839918409184191842918439184491845918469184791848918499185091851918529185391854918559185691857918589185991860918619186291863918649186591866918679186891869918709187191872918739187491875918769187791878918799188091881918829188391884918859188691887918889188991890918919189291893918949189591896918979189891899919009190191902919039190491905919069190791908919099191091911919129191391914919159191691917919189191991920919219192291923919249192591926919279192891929919309193191932919339193491935919369193791938919399194091941919429194391944919459194691947919489194991950919519195291953919549195591956919579195891959919609196191962919639196491965919669196791968919699197091971919729197391974919759197691977919789197991980919819198291983919849198591986919879198891989919909199191992919939199491995919969199791998919999200092001920029200392004920059200692007920089200992010920119201292013920149201592016920179201892019920209202192022920239202492025920269202792028920299203092031920329203392034920359203692037920389203992040920419204292043920449204592046920479204892049920509205192052920539205492055920569205792058920599206092061920629206392064920659206692067920689206992070920719207292073920749207592076920779207892079920809208192082920839208492085920869208792088920899209092091920929209392094920959209692097920989209992100921019210292103921049210592106921079210892109921109211192112921139211492115921169211792118921199212092121921229212392124921259212692127921289212992130921319213292133921349213592136921379213892139921409214192142921439214492145921469214792148921499215092151921529215392154921559215692157921589215992160921619216292163921649216592166921679216892169921709217192172921739217492175921769217792178921799218092181921829218392184921859218692187921889218992190921919219292193921949219592196921979219892199922009220192202922039220492205922069220792208922099221092211922129221392214922159221692217922189221992220922219222292223922249222592226922279222892229922309223192232922339223492235922369223792238922399224092241922429224392244922459224692247922489224992250922519225292253922549225592256922579225892259922609226192262922639226492265922669226792268922699227092271922729227392274922759227692277922789227992280922819228292283922849228592286922879228892289922909229192292922939229492295922969229792298922999230092301923029230392304923059230692307923089230992310923119231292313923149231592316923179231892319923209232192322923239232492325923269232792328923299233092331923329233392334923359233692337923389233992340923419234292343923449234592346923479234892349923509235192352923539235492355923569235792358923599236092361923629236392364923659236692367923689236992370923719237292373923749237592376923779237892379923809238192382923839238492385923869238792388923899239092391923929239392394923959239692397923989239992400924019240292403924049240592406924079240892409924109241192412924139241492415924169241792418924199242092421924229242392424924259242692427924289242992430924319243292433924349243592436924379243892439924409244192442924439244492445924469244792448924499245092451924529245392454924559245692457924589245992460924619246292463924649246592466924679246892469924709247192472924739247492475924769247792478924799248092481924829248392484924859248692487924889248992490924919249292493924949249592496924979249892499925009250192502925039250492505925069250792508925099251092511925129251392514925159251692517925189251992520925219252292523925249252592526925279252892529925309253192532925339253492535925369253792538925399254092541925429254392544925459254692547925489254992550925519255292553925549255592556925579255892559925609256192562925639256492565925669256792568925699257092571925729257392574925759257692577925789257992580925819258292583925849258592586925879258892589925909259192592925939259492595925969259792598925999260092601926029260392604926059260692607926089260992610926119261292613926149261592616926179261892619926209262192622926239262492625926269262792628926299263092631926329263392634926359263692637926389263992640926419264292643926449264592646926479264892649926509265192652926539265492655926569265792658926599266092661926629266392664926659266692667926689266992670926719267292673926749267592676926779267892679926809268192682926839268492685926869268792688926899269092691926929269392694926959269692697926989269992700927019270292703927049270592706927079270892709927109271192712927139271492715927169271792718927199272092721927229272392724927259272692727927289272992730927319273292733927349273592736927379273892739927409274192742927439274492745927469274792748927499275092751927529275392754927559275692757927589275992760927619276292763927649276592766927679276892769927709277192772927739277492775927769277792778927799278092781927829278392784927859278692787927889278992790927919279292793927949279592796927979279892799928009280192802928039280492805928069280792808928099281092811928129281392814928159281692817928189281992820928219282292823928249282592826928279282892829928309283192832928339283492835928369283792838928399284092841928429284392844928459284692847928489284992850928519285292853928549285592856928579285892859928609286192862928639286492865928669286792868928699287092871928729287392874928759287692877928789287992880928819288292883928849288592886928879288892889928909289192892928939289492895928969289792898928999290092901929029290392904929059290692907929089290992910929119291292913929149291592916929179291892919929209292192922929239292492925929269292792928929299293092931929329293392934929359293692937929389293992940929419294292943929449294592946929479294892949929509295192952929539295492955929569295792958929599296092961929629296392964929659296692967929689296992970929719297292973929749297592976929779297892979929809298192982929839298492985929869298792988929899299092991929929299392994929959299692997929989299993000930019300293003930049300593006930079300893009930109301193012930139301493015930169301793018930199302093021930229302393024930259302693027930289302993030930319303293033930349303593036930379303893039930409304193042930439304493045930469304793048930499305093051930529305393054930559305693057930589305993060930619306293063930649306593066930679306893069930709307193072930739307493075930769307793078930799308093081930829308393084930859308693087930889308993090930919309293093930949309593096930979309893099931009310193102931039310493105931069310793108931099311093111931129311393114931159311693117931189311993120931219312293123931249312593126931279312893129931309313193132931339313493135931369313793138931399314093141931429314393144931459314693147931489314993150931519315293153931549315593156931579315893159931609316193162931639316493165931669316793168931699317093171931729317393174931759317693177931789317993180931819318293183931849318593186931879318893189931909319193192931939319493195931969319793198931999320093201932029320393204932059320693207932089320993210932119321293213932149321593216932179321893219932209322193222932239322493225932269322793228932299323093231932329323393234932359323693237932389323993240932419324293243932449324593246932479324893249932509325193252932539325493255932569325793258932599326093261932629326393264932659326693267932689326993270932719327293273932749327593276932779327893279932809328193282932839328493285932869328793288932899329093291932929329393294932959329693297932989329993300933019330293303933049330593306933079330893309933109331193312933139331493315933169331793318933199332093321933229332393324933259332693327933289332993330933319333293333933349333593336933379333893339933409334193342933439334493345933469334793348933499335093351933529335393354933559335693357933589335993360933619336293363933649336593366933679336893369933709337193372933739337493375933769337793378933799338093381933829338393384933859338693387933889338993390933919339293393933949339593396933979339893399934009340193402934039340493405934069340793408934099341093411934129341393414934159341693417934189341993420934219342293423934249342593426934279342893429934309343193432934339343493435934369343793438934399344093441934429344393444934459344693447934489344993450934519345293453934549345593456934579345893459934609346193462934639346493465934669346793468934699347093471934729347393474934759347693477934789347993480934819348293483934849348593486934879348893489934909349193492934939349493495934969349793498934999350093501935029350393504935059350693507935089350993510935119351293513935149351593516935179351893519935209352193522935239352493525935269352793528935299353093531935329353393534935359353693537935389353993540935419354293543935449354593546935479354893549935509355193552935539355493555935569355793558935599356093561935629356393564935659356693567935689356993570935719357293573935749357593576935779357893579935809358193582935839358493585935869358793588935899359093591935929359393594935959359693597935989359993600936019360293603936049360593606936079360893609936109361193612936139361493615936169361793618936199362093621936229362393624936259362693627936289362993630936319363293633936349363593636936379363893639936409364193642936439364493645936469364793648936499365093651936529365393654936559365693657936589365993660936619366293663936649366593666936679366893669936709367193672936739367493675936769367793678936799368093681936829368393684936859368693687936889368993690936919369293693936949369593696936979369893699937009370193702937039370493705937069370793708937099371093711937129371393714937159371693717937189371993720937219372293723937249372593726937279372893729937309373193732937339373493735937369373793738937399374093741937429374393744937459374693747937489374993750937519375293753937549375593756937579375893759937609376193762937639376493765937669376793768937699377093771937729377393774937759377693777937789377993780937819378293783937849378593786937879378893789937909379193792937939379493795937969379793798937999380093801938029380393804938059380693807938089380993810938119381293813938149381593816938179381893819938209382193822938239382493825938269382793828938299383093831938329383393834938359383693837938389383993840938419384293843938449384593846938479384893849938509385193852938539385493855938569385793858938599386093861938629386393864938659386693867938689386993870938719387293873938749387593876938779387893879938809388193882938839388493885938869388793888938899389093891938929389393894938959389693897938989389993900939019390293903939049390593906939079390893909939109391193912939139391493915939169391793918939199392093921939229392393924939259392693927939289392993930939319393293933939349393593936939379393893939939409394193942939439394493945939469394793948939499395093951939529395393954939559395693957939589395993960939619396293963939649396593966939679396893969939709397193972939739397493975939769397793978939799398093981939829398393984939859398693987939889398993990939919399293993939949399593996939979399893999940009400194002940039400494005940069400794008940099401094011940129401394014940159401694017940189401994020940219402294023940249402594026940279402894029940309403194032940339403494035940369403794038940399404094041940429404394044940459404694047940489404994050940519405294053940549405594056940579405894059940609406194062940639406494065940669406794068940699407094071940729407394074940759407694077940789407994080940819408294083940849408594086940879408894089940909409194092940939409494095940969409794098940999410094101941029410394104941059410694107941089410994110941119411294113941149411594116941179411894119941209412194122941239412494125941269412794128941299413094131941329413394134941359413694137941389413994140941419414294143941449414594146941479414894149941509415194152941539415494155941569415794158941599416094161941629416394164941659416694167941689416994170941719417294173941749417594176941779417894179941809418194182941839418494185941869418794188941899419094191941929419394194941959419694197941989419994200942019420294203942049420594206942079420894209942109421194212942139421494215942169421794218942199422094221942229422394224942259422694227942289422994230942319423294233942349423594236942379423894239942409424194242942439424494245942469424794248942499425094251942529425394254942559425694257942589425994260942619426294263942649426594266942679426894269942709427194272942739427494275942769427794278942799428094281942829428394284942859428694287942889428994290942919429294293942949429594296942979429894299943009430194302943039430494305943069430794308943099431094311943129431394314943159431694317943189431994320943219432294323943249432594326943279432894329943309433194332943339433494335943369433794338943399434094341943429434394344943459434694347943489434994350943519435294353943549435594356943579435894359943609436194362943639436494365943669436794368943699437094371943729437394374943759437694377943789437994380943819438294383943849438594386943879438894389943909439194392943939439494395943969439794398943999440094401944029440394404944059440694407944089440994410944119441294413944149441594416944179441894419944209442194422944239442494425944269442794428944299443094431944329443394434944359443694437944389443994440944419444294443944449444594446944479444894449944509445194452944539445494455944569445794458944599446094461944629446394464944659446694467944689446994470944719447294473944749447594476944779447894479944809448194482944839448494485944869448794488944899449094491944929449394494944959449694497944989449994500945019450294503945049450594506945079450894509945109451194512945139451494515945169451794518945199452094521945229452394524945259452694527945289452994530945319453294533945349453594536945379453894539945409454194542945439454494545945469454794548945499455094551945529455394554945559455694557945589455994560945619456294563945649456594566945679456894569945709457194572945739457494575945769457794578945799458094581945829458394584945859458694587945889458994590945919459294593945949459594596945979459894599946009460194602946039460494605946069460794608946099461094611946129461394614946159461694617946189461994620946219462294623946249462594626946279462894629946309463194632946339463494635946369463794638946399464094641946429464394644946459464694647946489464994650946519465294653946549465594656946579465894659946609466194662946639466494665946669466794668946699467094671946729467394674946759467694677946789467994680946819468294683946849468594686946879468894689946909469194692946939469494695946969469794698946999470094701947029470394704947059470694707947089470994710947119471294713947149471594716947179471894719947209472194722947239472494725947269472794728947299473094731947329473394734947359473694737947389473994740947419474294743947449474594746947479474894749947509475194752947539475494755947569475794758947599476094761947629476394764947659476694767947689476994770947719477294773947749477594776947779477894779947809478194782947839478494785947869478794788947899479094791947929479394794947959479694797947989479994800948019480294803948049480594806948079480894809948109481194812948139481494815948169481794818948199482094821948229482394824948259482694827948289482994830948319483294833948349483594836948379483894839948409484194842948439484494845948469484794848948499485094851948529485394854948559485694857948589485994860948619486294863948649486594866948679486894869948709487194872948739487494875948769487794878948799488094881948829488394884948859488694887948889488994890948919489294893948949489594896948979489894899949009490194902949039490494905949069490794908949099491094911949129491394914949159491694917949189491994920949219492294923949249492594926949279492894929949309493194932949339493494935949369493794938949399494094941949429494394944949459494694947949489494994950949519495294953949549495594956949579495894959949609496194962949639496494965949669496794968949699497094971949729497394974949759497694977949789497994980949819498294983949849498594986949879498894989949909499194992949939499494995949969499794998949999500095001950029500395004950059500695007950089500995010950119501295013950149501595016950179501895019950209502195022950239502495025950269502795028950299503095031950329503395034950359503695037950389503995040950419504295043950449504595046950479504895049950509505195052950539505495055950569505795058950599506095061950629506395064950659506695067950689506995070950719507295073950749507595076950779507895079950809508195082950839508495085950869508795088950899509095091950929509395094950959509695097950989509995100951019510295103951049510595106951079510895109951109511195112951139511495115951169511795118951199512095121951229512395124951259512695127951289512995130951319513295133951349513595136951379513895139951409514195142951439514495145951469514795148951499515095151951529515395154951559515695157951589515995160951619516295163951649516595166951679516895169951709517195172951739517495175951769517795178951799518095181951829518395184951859518695187951889518995190951919519295193951949519595196951979519895199952009520195202952039520495205952069520795208952099521095211952129521395214952159521695217952189521995220952219522295223952249522595226952279522895229952309523195232952339523495235952369523795238952399524095241952429524395244952459524695247952489524995250952519525295253952549525595256952579525895259952609526195262952639526495265952669526795268952699527095271952729527395274952759527695277952789527995280952819528295283952849528595286952879528895289952909529195292952939529495295952969529795298952999530095301953029530395304953059530695307953089530995310953119531295313953149531595316953179531895319953209532195322953239532495325953269532795328953299533095331953329533395334953359533695337953389533995340953419534295343953449534595346953479534895349953509535195352953539535495355953569535795358953599536095361953629536395364953659536695367953689536995370953719537295373953749537595376953779537895379953809538195382953839538495385953869538795388953899539095391953929539395394953959539695397953989539995400954019540295403954049540595406954079540895409954109541195412954139541495415954169541795418954199542095421954229542395424954259542695427954289542995430954319543295433954349543595436954379543895439954409544195442954439544495445954469544795448954499545095451954529545395454954559545695457954589545995460954619546295463954649546595466954679546895469954709547195472954739547495475954769547795478954799548095481954829548395484954859548695487954889548995490954919549295493954949549595496954979549895499955009550195502955039550495505955069550795508955099551095511955129551395514955159551695517955189551995520955219552295523955249552595526955279552895529955309553195532955339553495535955369553795538955399554095541955429554395544955459554695547955489554995550955519555295553955549555595556955579555895559955609556195562955639556495565955669556795568955699557095571955729557395574955759557695577955789557995580955819558295583955849558595586955879558895589955909559195592955939559495595955969559795598955999560095601956029560395604956059560695607956089560995610956119561295613956149561595616956179561895619956209562195622956239562495625956269562795628956299563095631956329563395634956359563695637956389563995640956419564295643956449564595646956479564895649956509565195652956539565495655956569565795658956599566095661956629566395664956659566695667956689566995670956719567295673956749567595676956779567895679956809568195682956839568495685956869568795688956899569095691956929569395694956959569695697956989569995700957019570295703957049570595706957079570895709957109571195712957139571495715957169571795718957199572095721957229572395724957259572695727957289572995730957319573295733957349573595736957379573895739957409574195742957439574495745957469574795748957499575095751957529575395754957559575695757957589575995760957619576295763957649576595766957679576895769957709577195772957739577495775957769577795778957799578095781957829578395784957859578695787957889578995790957919579295793957949579595796957979579895799958009580195802958039580495805958069580795808958099581095811958129581395814958159581695817958189581995820958219582295823958249582595826958279582895829958309583195832958339583495835958369583795838958399584095841958429584395844958459584695847958489584995850958519585295853958549585595856958579585895859958609586195862958639586495865958669586795868958699587095871958729587395874958759587695877958789587995880958819588295883958849588595886958879588895889958909589195892958939589495895958969589795898958999590095901959029590395904959059590695907959089590995910959119591295913959149591595916959179591895919959209592195922959239592495925959269592795928959299593095931959329593395934959359593695937959389593995940959419594295943959449594595946959479594895949959509595195952959539595495955959569595795958959599596095961959629596395964959659596695967959689596995970959719597295973959749597595976959779597895979959809598195982959839598495985959869598795988959899599095991959929599395994959959599695997959989599996000960019600296003960049600596006960079600896009960109601196012960139601496015960169601796018960199602096021960229602396024960259602696027960289602996030960319603296033960349603596036960379603896039960409604196042960439604496045960469604796048960499605096051960529605396054960559605696057960589605996060960619606296063960649606596066960679606896069960709607196072960739607496075960769607796078960799608096081960829608396084960859608696087960889608996090960919609296093960949609596096960979609896099961009610196102961039610496105961069610796108961099611096111961129611396114961159611696117961189611996120961219612296123961249612596126961279612896129961309613196132961339613496135961369613796138961399614096141961429614396144961459614696147961489614996150961519615296153961549615596156961579615896159961609616196162961639616496165961669616796168961699617096171961729617396174961759617696177961789617996180961819618296183961849618596186961879618896189961909619196192961939619496195961969619796198961999620096201962029620396204962059620696207962089620996210962119621296213962149621596216962179621896219962209622196222962239622496225962269622796228962299623096231962329623396234962359623696237962389623996240962419624296243962449624596246962479624896249962509625196252962539625496255962569625796258962599626096261962629626396264962659626696267962689626996270962719627296273962749627596276962779627896279962809628196282962839628496285962869628796288962899629096291962929629396294962959629696297962989629996300963019630296303963049630596306963079630896309963109631196312963139631496315963169631796318963199632096321963229632396324963259632696327963289632996330963319633296333963349633596336963379633896339963409634196342963439634496345963469634796348963499635096351963529635396354963559635696357963589635996360963619636296363963649636596366963679636896369963709637196372963739637496375963769637796378963799638096381963829638396384963859638696387963889638996390963919639296393963949639596396963979639896399964009640196402964039640496405964069640796408964099641096411964129641396414964159641696417964189641996420964219642296423964249642596426964279642896429964309643196432964339643496435964369643796438964399644096441964429644396444964459644696447964489644996450964519645296453964549645596456964579645896459964609646196462964639646496465964669646796468964699647096471964729647396474964759647696477964789647996480964819648296483964849648596486964879648896489964909649196492964939649496495964969649796498964999650096501965029650396504965059650696507965089650996510965119651296513965149651596516965179651896519965209652196522965239652496525965269652796528965299653096531965329653396534965359653696537965389653996540965419654296543965449654596546965479654896549965509655196552965539655496555965569655796558965599656096561965629656396564965659656696567965689656996570965719657296573965749657596576965779657896579965809658196582965839658496585965869658796588965899659096591965929659396594965959659696597965989659996600966019660296603966049660596606966079660896609966109661196612966139661496615966169661796618966199662096621966229662396624966259662696627966289662996630966319663296633966349663596636966379663896639966409664196642966439664496645966469664796648966499665096651966529665396654966559665696657966589665996660966619666296663966649666596666966679666896669966709667196672966739667496675966769667796678966799668096681966829668396684966859668696687966889668996690966919669296693966949669596696966979669896699967009670196702967039670496705967069670796708967099671096711967129671396714967159671696717967189671996720967219672296723967249672596726967279672896729967309673196732967339673496735967369673796738967399674096741967429674396744967459674696747967489674996750967519675296753967549675596756967579675896759967609676196762967639676496765967669676796768967699677096771967729677396774967759677696777967789677996780967819678296783967849678596786967879678896789967909679196792967939679496795967969679796798967999680096801968029680396804968059680696807968089680996810968119681296813968149681596816968179681896819968209682196822968239682496825968269682796828968299683096831968329683396834968359683696837968389683996840968419684296843968449684596846968479684896849968509685196852968539685496855968569685796858968599686096861968629686396864968659686696867968689686996870968719687296873968749687596876968779687896879968809688196882968839688496885968869688796888968899689096891968929689396894968959689696897968989689996900969019690296903969049690596906969079690896909969109691196912969139691496915969169691796918969199692096921969229692396924969259692696927969289692996930969319693296933969349693596936969379693896939969409694196942969439694496945969469694796948969499695096951969529695396954969559695696957969589695996960969619696296963969649696596966969679696896969969709697196972969739697496975969769697796978969799698096981969829698396984969859698696987969889698996990969919699296993969949699596996969979699896999970009700197002970039700497005970069700797008970099701097011970129701397014970159701697017970189701997020970219702297023970249702597026970279702897029970309703197032970339703497035970369703797038970399704097041970429704397044970459704697047970489704997050970519705297053970549705597056970579705897059970609706197062970639706497065970669706797068970699707097071970729707397074970759707697077970789707997080970819708297083970849708597086970879708897089970909709197092970939709497095970969709797098970999710097101971029710397104971059710697107971089710997110971119711297113971149711597116971179711897119971209712197122971239712497125971269712797128971299713097131971329713397134971359713697137971389713997140971419714297143971449714597146971479714897149971509715197152971539715497155971569715797158971599716097161971629716397164971659716697167971689716997170971719717297173971749717597176971779717897179971809718197182971839718497185971869718797188971899719097191971929719397194971959719697197971989719997200972019720297203972049720597206972079720897209972109721197212972139721497215972169721797218972199722097221972229722397224972259722697227972289722997230972319723297233972349723597236972379723897239972409724197242972439724497245972469724797248972499725097251972529725397254972559725697257972589725997260972619726297263972649726597266972679726897269972709727197272972739727497275972769727797278972799728097281972829728397284972859728697287972889728997290972919729297293972949729597296972979729897299973009730197302973039730497305973069730797308973099731097311973129731397314973159731697317973189731997320973219732297323973249732597326973279732897329973309733197332973339733497335973369733797338973399734097341973429734397344973459734697347973489734997350973519735297353973549735597356973579735897359973609736197362973639736497365973669736797368973699737097371973729737397374973759737697377973789737997380973819738297383973849738597386973879738897389973909739197392973939739497395973969739797398973999740097401974029740397404974059740697407974089740997410974119741297413974149741597416974179741897419974209742197422974239742497425974269742797428974299743097431974329743397434974359743697437974389743997440974419744297443974449744597446974479744897449974509745197452974539745497455974569745797458974599746097461974629746397464974659746697467974689746997470974719747297473974749747597476974779747897479974809748197482974839748497485974869748797488974899749097491974929749397494974959749697497974989749997500975019750297503975049750597506975079750897509975109751197512975139751497515975169751797518975199752097521975229752397524975259752697527975289752997530975319753297533975349753597536975379753897539975409754197542975439754497545975469754797548975499755097551975529755397554975559755697557975589755997560975619756297563975649756597566975679756897569975709757197572975739757497575975769757797578975799758097581975829758397584975859758697587975889758997590975919759297593975949759597596975979759897599976009760197602976039760497605976069760797608976099761097611976129761397614976159761697617976189761997620976219762297623976249762597626976279762897629976309763197632976339763497635976369763797638976399764097641976429764397644976459764697647976489764997650976519765297653976549765597656976579765897659976609766197662976639766497665976669766797668976699767097671976729767397674976759767697677976789767997680976819768297683976849768597686976879768897689976909769197692976939769497695976969769797698976999770097701977029770397704977059770697707977089770997710977119771297713977149771597716977179771897719977209772197722977239772497725977269772797728977299773097731977329773397734977359773697737977389773997740977419774297743977449774597746977479774897749977509775197752977539775497755977569775797758977599776097761977629776397764977659776697767977689776997770977719777297773977749777597776977779777897779977809778197782977839778497785977869778797788977899779097791977929779397794977959779697797977989779997800978019780297803978049780597806978079780897809978109781197812978139781497815978169781797818978199782097821978229782397824978259782697827978289782997830978319783297833978349783597836978379783897839978409784197842978439784497845978469784797848978499785097851978529785397854978559785697857978589785997860978619786297863978649786597866978679786897869978709787197872978739787497875978769787797878978799788097881978829788397884978859788697887978889788997890978919789297893978949789597896978979789897899979009790197902979039790497905979069790797908979099791097911979129791397914979159791697917979189791997920979219792297923979249792597926979279792897929979309793197932979339793497935979369793797938979399794097941979429794397944979459794697947979489794997950979519795297953979549795597956979579795897959979609796197962979639796497965979669796797968979699797097971979729797397974979759797697977979789797997980979819798297983979849798597986979879798897989979909799197992979939799497995979969799797998979999800098001980029800398004980059800698007980089800998010980119801298013980149801598016980179801898019980209802198022980239802498025980269802798028980299803098031980329803398034980359803698037980389803998040980419804298043980449804598046980479804898049980509805198052980539805498055980569805798058980599806098061980629806398064980659806698067980689806998070980719807298073980749807598076980779807898079980809808198082980839808498085980869808798088980899809098091980929809398094980959809698097980989809998100981019810298103981049810598106981079810898109981109811198112981139811498115981169811798118981199812098121981229812398124981259812698127981289812998130981319813298133981349813598136981379813898139981409814198142981439814498145981469814798148981499815098151981529815398154981559815698157981589815998160981619816298163981649816598166981679816898169981709817198172981739817498175981769817798178981799818098181981829818398184981859818698187981889818998190981919819298193981949819598196981979819898199982009820198202982039820498205982069820798208982099821098211982129821398214982159821698217982189821998220982219822298223982249822598226982279822898229982309823198232982339823498235982369823798238982399824098241982429824398244982459824698247982489824998250982519825298253982549825598256982579825898259982609826198262982639826498265982669826798268982699827098271982729827398274982759827698277982789827998280982819828298283982849828598286982879828898289982909829198292982939829498295982969829798298982999830098301983029830398304983059830698307983089830998310983119831298313983149831598316983179831898319983209832198322983239832498325983269832798328983299833098331983329833398334983359833698337983389833998340983419834298343983449834598346983479834898349983509835198352983539835498355983569835798358983599836098361983629836398364983659836698367983689836998370983719837298373983749837598376983779837898379983809838198382983839838498385983869838798388983899839098391983929839398394983959839698397983989839998400984019840298403984049840598406984079840898409984109841198412984139841498415984169841798418984199842098421984229842398424984259842698427984289842998430984319843298433984349843598436984379843898439984409844198442984439844498445984469844798448984499845098451984529845398454984559845698457984589845998460984619846298463984649846598466984679846898469984709847198472984739847498475984769847798478984799848098481984829848398484984859848698487984889848998490984919849298493984949849598496984979849898499985009850198502985039850498505985069850798508985099851098511985129851398514985159851698517985189851998520985219852298523985249852598526985279852898529985309853198532985339853498535985369853798538985399854098541985429854398544985459854698547985489854998550985519855298553985549855598556985579855898559985609856198562985639856498565985669856798568985699857098571985729857398574985759857698577985789857998580985819858298583985849858598586985879858898589985909859198592985939859498595985969859798598985999860098601986029860398604986059860698607986089860998610986119861298613986149861598616986179861898619986209862198622986239862498625986269862798628986299863098631986329863398634986359863698637986389863998640986419864298643986449864598646986479864898649986509865198652986539865498655986569865798658986599866098661986629866398664986659866698667986689866998670986719867298673986749867598676986779867898679986809868198682986839868498685986869868798688986899869098691986929869398694986959869698697986989869998700987019870298703987049870598706987079870898709987109871198712987139871498715987169871798718987199872098721987229872398724987259872698727987289872998730987319873298733987349873598736987379873898739987409874198742987439874498745987469874798748987499875098751987529875398754987559875698757987589875998760987619876298763987649876598766987679876898769987709877198772987739877498775987769877798778987799878098781987829878398784987859878698787987889878998790987919879298793987949879598796987979879898799988009880198802988039880498805988069880798808988099881098811988129881398814988159881698817988189881998820988219882298823988249882598826988279882898829988309883198832988339883498835988369883798838988399884098841988429884398844988459884698847988489884998850988519885298853988549885598856988579885898859988609886198862988639886498865988669886798868988699887098871988729887398874988759887698877988789887998880988819888298883988849888598886988879888898889988909889198892988939889498895988969889798898988999890098901989029890398904989059890698907989089890998910989119891298913989149891598916989179891898919989209892198922989239892498925989269892798928989299893098931989329893398934989359893698937989389893998940989419894298943989449894598946989479894898949989509895198952989539895498955989569895798958989599896098961989629896398964989659896698967989689896998970989719897298973989749897598976989779897898979989809898198982989839898498985989869898798988989899899098991989929899398994989959899698997989989899999000990019900299003990049900599006990079900899009990109901199012990139901499015990169901799018990199902099021990229902399024990259902699027990289902999030990319903299033990349903599036990379903899039990409904199042990439904499045990469904799048990499905099051990529905399054990559905699057990589905999060990619906299063990649906599066990679906899069990709907199072990739907499075990769907799078990799908099081990829908399084990859908699087990889908999090990919909299093990949909599096990979909899099991009910199102991039910499105991069910799108991099911099111991129911399114991159911699117991189911999120991219912299123991249912599126991279912899129991309913199132991339913499135991369913799138991399914099141991429914399144991459914699147991489914999150991519915299153991549915599156991579915899159991609916199162991639916499165991669916799168991699917099171991729917399174991759917699177991789917999180991819918299183991849918599186991879918899189991909919199192991939919499195991969919799198991999920099201992029920399204992059920699207992089920999210992119921299213992149921599216992179921899219992209922199222992239922499225992269922799228992299923099231992329923399234992359923699237992389923999240992419924299243992449924599246992479924899249992509925199252992539925499255992569925799258992599926099261992629926399264992659926699267992689926999270992719927299273992749927599276992779927899279992809928199282992839928499285992869928799288992899929099291992929929399294992959929699297992989929999300993019930299303993049930599306993079930899309993109931199312993139931499315993169931799318993199932099321993229932399324993259932699327993289932999330993319933299333993349933599336993379933899339993409934199342993439934499345993469934799348993499935099351993529935399354993559935699357993589935999360993619936299363993649936599366993679936899369993709937199372993739937499375993769937799378993799938099381993829938399384993859938699387993889938999390993919939299393993949939599396993979939899399994009940199402994039940499405994069940799408994099941099411994129941399414994159941699417994189941999420994219942299423994249942599426994279942899429994309943199432994339943499435994369943799438994399944099441994429944399444994459944699447994489944999450994519945299453994549945599456994579945899459994609946199462994639946499465994669946799468994699947099471994729947399474994759947699477994789947999480994819948299483994849948599486994879948899489994909949199492994939949499495994969949799498994999950099501995029950399504995059950699507995089950999510995119951299513995149951599516995179951899519995209952199522995239952499525995269952799528995299953099531995329953399534995359953699537995389953999540995419954299543995449954599546995479954899549995509955199552995539955499555995569955799558995599956099561995629956399564995659956699567995689956999570995719957299573995749957599576995779957899579995809958199582995839958499585995869958799588995899959099591995929959399594995959959699597995989959999600996019960299603996049960599606996079960899609996109961199612996139961499615996169961799618996199962099621996229962399624996259962699627996289962999630996319963299633996349963599636996379963899639996409964199642996439964499645996469964799648996499965099651996529965399654996559965699657996589965999660996619966299663996649966599666996679966899669996709967199672996739967499675996769967799678996799968099681996829968399684996859968699687996889968999690996919969299693996949969599696996979969899699997009970199702997039970499705997069970799708997099971099711997129971399714997159971699717997189971999720997219972299723997249972599726997279972899729997309973199732997339973499735997369973799738997399974099741997429974399744997459974699747997489974999750997519975299753997549975599756997579975899759997609976199762997639976499765997669976799768997699977099771997729977399774997759977699777997789977999780997819978299783997849978599786997879978899789997909979199792997939979499795997969979799798997999980099801998029980399804998059980699807998089980999810998119981299813998149981599816998179981899819998209982199822998239982499825998269982799828998299983099831998329983399834998359983699837998389983999840998419984299843998449984599846998479984899849998509985199852998539985499855998569985799858998599986099861998629986399864998659986699867998689986999870998719987299873998749987599876998779987899879998809988199882998839988499885998869988799888998899989099891998929989399894998959989699897998989989999900999019990299903999049990599906999079990899909999109991199912999139991499915999169991799918999199992099921999229992399924999259992699927999289992999930999319993299933999349993599936999379993899939999409994199942999439994499945999469994799948999499995099951999529995399954999559995699957999589995999960999619996299963999649996599966999679996899969999709997199972999739997499975999769997799978999799998099981999829998399984999859998699987999889998999990999919999299993999949999599996999979999899999100000100001100002100003100004100005100006100007100008100009100010100011100012100013100014100015100016100017100018100019100020100021100022100023100024100025100026100027100028100029100030100031100032100033100034100035100036100037100038100039100040100041100042100043100044100045100046100047100048100049100050100051100052100053100054100055100056100057100058100059100060100061100062100063100064100065100066100067100068100069100070100071100072100073100074100075100076100077100078100079100080100081100082100083100084100085100086100087100088100089100090100091100092100093100094100095100096100097100098100099100100100101100102100103100104100105100106100107100108100109100110100111100112100113100114100115100116100117100118100119100120100121100122100123100124100125100126100127100128100129100130100131100132100133100134100135100136100137100138100139100140100141100142100143100144100145100146100147100148100149100150100151100152100153100154100155100156100157100158100159100160100161100162100163100164100165100166100167100168100169100170100171100172100173100174100175100176100177100178100179100180100181100182100183100184100185100186100187100188100189100190100191100192100193100194100195100196100197100198100199100200100201100202100203100204100205100206100207100208100209100210100211100212100213100214100215100216100217100218100219100220100221100222100223100224100225100226100227100228100229100230100231100232100233100234100235100236100237100238100239100240100241100242100243100244100245100246100247100248100249100250100251100252100253100254100255100256100257100258100259100260100261100262100263100264100265100266100267100268100269100270100271100272100273100274100275100276100277100278100279100280100281100282100283100284100285100286100287100288100289100290100291100292100293100294100295100296100297100298100299100300100301100302100303100304100305100306100307100308100309100310100311100312100313100314100315100316100317100318100319100320100321100322100323100324100325100326100327100328100329100330100331100332100333100334100335100336100337100338100339100340100341100342100343100344100345100346100347100348100349100350100351100352100353100354100355100356100357100358100359100360100361100362100363100364100365100366100367100368100369100370100371100372100373100374100375100376100377100378100379100380100381100382100383100384100385100386100387100388100389100390100391100392100393100394100395100396100397100398100399100400100401100402100403100404100405100406100407100408100409100410100411100412100413100414100415100416100417100418100419100420100421100422100423100424100425100426100427100428100429100430100431100432100433100434100435100436100437100438100439100440100441100442100443100444100445100446100447100448100449100450100451100452100453100454100455100456100457100458100459100460100461100462100463100464100465100466100467100468100469100470100471100472100473100474100475100476100477100478100479100480100481100482100483100484100485100486100487100488100489100490100491100492100493100494100495100496100497100498100499100500100501100502100503100504100505100506100507100508100509100510100511100512100513100514100515100516100517100518100519100520100521100522100523100524100525100526100527100528100529100530100531100532100533100534100535100536100537100538100539100540100541100542100543100544100545100546100547100548100549100550100551100552100553100554100555100556100557100558100559100560100561100562100563100564100565100566100567100568100569100570100571100572100573100574100575100576100577100578100579100580100581100582100583100584100585100586100587100588100589100590100591100592100593100594100595100596100597100598100599100600100601100602100603100604100605100606100607100608100609100610100611100612100613100614100615100616100617100618100619100620100621100622100623100624100625100626100627100628100629100630100631100632100633100634100635100636100637100638100639100640100641100642100643100644100645100646100647100648100649100650100651100652100653100654100655100656100657100658100659100660100661100662100663100664100665100666100667100668100669100670100671100672100673100674100675100676100677100678100679100680100681100682100683100684100685100686100687100688100689100690100691100692100693100694100695100696100697100698100699100700100701100702100703100704100705100706100707100708100709100710100711100712100713100714100715100716100717100718100719100720100721100722100723100724100725100726100727100728100729100730100731100732100733100734100735100736100737100738100739100740100741100742100743100744100745100746100747100748100749100750100751100752100753100754100755100756100757100758100759100760100761100762100763100764100765100766100767100768100769100770100771100772100773100774100775100776100777100778100779100780100781100782100783100784100785100786100787100788100789100790100791100792100793100794100795100796100797100798100799100800100801100802100803100804100805100806100807100808100809100810100811100812100813100814100815100816100817100818100819100820100821100822100823100824100825100826100827100828100829100830100831100832100833100834100835100836100837100838100839100840100841100842100843100844100845100846100847100848100849100850100851100852100853100854100855100856100857100858100859100860100861100862100863100864100865100866100867100868100869100870100871100872100873100874100875100876100877100878100879100880100881100882100883100884100885100886100887100888100889100890100891100892100893100894100895100896100897100898100899100900100901100902100903100904100905100906100907100908100909100910100911100912100913100914100915100916100917100918100919100920100921100922100923100924100925100926100927100928100929100930100931100932100933100934100935100936100937100938100939100940100941100942100943100944100945100946100947100948100949100950100951100952100953100954100955100956100957100958100959100960100961100962100963100964100965100966100967100968100969100970100971100972100973100974100975100976100977100978100979100980100981100982100983100984100985100986100987100988100989100990100991100992100993100994100995100996100997100998100999101000101001101002101003101004101005101006101007101008101009101010101011101012101013101014101015101016101017101018101019101020101021101022101023101024101025101026101027101028101029101030101031101032101033101034101035101036101037101038101039101040101041101042101043101044101045101046101047101048101049101050101051101052101053101054101055101056101057101058101059101060101061101062101063101064101065101066101067101068101069101070101071101072101073101074101075101076101077101078101079101080101081101082101083101084101085101086101087101088101089101090101091101092101093101094101095101096101097101098101099101100101101101102101103101104101105101106101107101108101109101110101111101112101113101114101115101116101117101118101119101120101121101122101123101124101125101126101127101128101129101130101131101132101133101134101135101136101137101138101139101140101141101142101143101144101145101146101147101148101149101150101151101152101153101154101155101156101157101158101159101160101161101162101163101164101165101166101167101168101169101170101171101172101173101174101175101176101177101178101179101180101181101182101183101184101185101186101187101188101189101190101191101192101193101194101195101196101197101198101199101200101201101202101203101204101205101206101207101208101209101210101211101212101213101214101215101216101217101218101219101220101221101222101223101224101225101226101227101228101229101230101231101232101233101234101235101236101237101238101239101240101241101242101243101244101245101246101247101248101249101250101251101252101253101254101255101256101257101258101259101260101261101262101263101264101265101266101267101268101269101270101271101272101273101274101275101276101277101278101279101280101281101282101283101284101285101286101287101288101289101290101291101292101293101294101295101296101297101298101299101300101301101302101303101304101305101306101307101308101309101310101311101312101313101314101315101316101317101318101319101320101321101322101323101324101325101326101327101328101329101330101331101332101333101334101335101336101337101338101339101340101341101342101343101344101345101346101347101348101349101350101351101352101353101354101355101356101357101358101359101360101361101362101363101364101365101366101367101368101369101370101371101372101373101374101375101376101377101378101379101380101381101382101383101384101385101386101387101388101389101390101391101392101393101394101395101396101397101398101399101400101401101402101403101404101405101406101407101408101409101410101411101412101413101414101415101416101417101418101419101420101421101422101423101424101425101426101427101428101429101430101431101432101433101434101435101436101437101438101439101440101441101442101443101444101445101446101447101448101449101450101451101452101453101454101455101456101457101458101459101460101461101462101463101464101465101466101467101468101469101470101471101472101473101474101475101476101477101478101479101480101481101482101483101484101485101486101487101488101489101490101491101492101493101494101495101496101497101498101499101500101501101502101503101504101505101506101507101508101509101510101511101512101513101514101515101516101517101518101519101520101521101522101523101524101525101526101527101528101529101530101531101532101533101534101535101536101537101538101539101540101541101542101543101544101545101546101547101548101549101550101551101552101553101554101555101556101557101558101559101560101561101562101563101564101565101566101567101568101569101570101571101572101573101574101575101576101577101578101579101580101581101582101583101584101585101586101587101588101589101590101591101592101593101594101595101596101597101598101599101600101601101602101603101604101605101606101607101608101609101610101611101612101613101614101615101616101617101618101619101620101621101622101623101624101625101626101627101628101629101630101631101632101633101634101635101636101637101638101639101640101641101642101643101644101645101646101647101648101649101650101651101652101653101654101655101656101657101658101659101660101661101662101663101664101665101666101667101668101669101670101671101672101673101674101675101676101677101678101679101680101681101682101683101684101685101686101687101688101689101690101691101692101693101694101695101696101697101698101699101700101701101702101703101704101705101706101707101708101709101710101711101712101713101714101715101716101717101718101719101720101721101722101723101724101725101726101727101728101729101730101731101732101733101734101735101736101737101738101739101740101741101742101743101744101745101746101747101748101749101750101751101752101753101754101755101756101757101758101759101760101761101762101763101764101765101766101767101768101769101770101771101772101773101774101775101776101777101778101779101780101781101782101783101784101785101786101787101788101789101790101791101792101793101794101795101796101797101798101799101800101801101802101803101804101805101806101807101808101809101810101811101812101813101814101815101816101817101818101819101820101821101822101823101824101825101826101827101828101829101830101831101832101833101834101835101836101837101838101839101840101841101842101843101844101845101846101847101848101849101850101851101852101853101854101855101856101857101858101859101860101861101862101863101864101865101866101867101868101869101870101871101872101873101874101875101876101877101878101879101880101881101882101883101884101885101886101887101888101889101890101891101892101893101894101895101896101897101898101899101900101901101902101903101904101905101906101907101908101909101910101911101912101913101914101915101916101917101918101919101920101921101922101923101924101925101926101927101928101929101930101931101932101933101934101935101936101937101938101939101940101941101942101943101944101945101946101947101948101949101950101951101952101953101954101955101956101957101958101959101960101961101962101963101964101965101966101967101968101969101970101971101972101973101974101975101976101977101978101979101980101981101982101983101984101985101986101987101988101989101990101991101992101993101994101995101996101997101998101999102000102001102002102003102004102005102006102007102008102009102010102011102012102013102014102015102016102017102018102019102020102021102022102023102024102025102026102027102028102029102030102031102032102033102034102035102036102037102038102039102040102041102042102043102044102045102046102047102048102049102050102051102052102053102054102055102056102057102058102059102060102061102062102063102064102065102066102067102068102069102070102071102072102073102074102075102076102077102078102079102080102081102082102083102084102085102086102087102088102089102090102091102092102093102094102095102096102097102098102099102100102101102102102103102104102105102106102107102108102109102110102111102112102113102114102115102116102117102118102119102120102121102122102123102124102125102126102127102128102129102130102131102132102133102134102135102136102137102138102139102140102141102142102143102144102145102146102147102148102149102150102151102152102153102154102155102156102157102158102159102160102161102162102163102164102165102166102167102168102169102170102171102172102173102174102175102176102177102178102179102180102181102182102183102184102185102186102187102188102189102190102191102192102193102194102195102196102197102198102199102200102201102202102203102204102205102206102207102208102209102210102211102212102213102214102215102216102217102218102219102220102221102222102223102224102225102226102227102228102229102230102231102232102233102234102235102236102237102238102239102240102241102242102243102244102245102246102247102248102249102250102251102252102253102254102255102256102257102258102259102260102261102262102263102264102265102266102267102268102269102270102271102272102273102274102275102276102277102278102279102280102281102282102283102284102285102286102287102288102289102290102291102292102293102294102295102296102297102298102299102300102301102302102303102304102305102306102307102308102309102310102311102312102313102314102315102316102317102318102319102320102321102322102323102324102325102326102327102328102329102330102331102332102333102334102335102336102337102338102339102340102341102342102343102344102345102346102347102348102349102350102351102352102353102354102355102356102357102358102359102360102361102362102363102364102365102366102367102368102369102370102371102372102373102374102375102376102377102378102379102380102381102382102383102384102385102386102387102388102389102390102391102392102393102394102395102396102397102398102399102400102401102402102403102404102405102406102407102408102409102410102411102412102413102414102415102416102417102418102419102420102421102422102423102424102425102426102427102428102429102430102431102432102433102434102435102436102437102438102439102440102441102442102443102444102445102446102447102448102449102450102451102452102453102454102455102456102457102458102459102460102461102462102463102464102465102466102467102468102469102470102471102472102473102474102475102476102477102478102479102480102481102482102483102484102485102486102487102488102489102490102491102492102493102494102495102496102497102498102499102500102501102502102503102504102505102506102507102508102509102510102511102512102513102514102515102516102517102518102519102520102521102522102523102524102525102526102527102528102529102530102531102532102533102534102535102536102537102538102539102540102541102542102543102544102545102546102547102548102549102550102551102552102553102554102555102556102557102558102559102560102561102562102563102564102565102566102567102568102569102570102571102572102573102574102575102576102577102578102579102580102581102582102583102584102585102586102587102588102589102590102591102592102593102594102595102596102597102598102599102600102601102602102603102604102605102606102607102608102609102610102611102612102613102614102615102616102617102618102619102620102621102622102623102624102625102626102627102628102629102630102631102632102633102634102635102636102637102638102639102640102641102642102643102644102645102646102647102648102649102650102651102652102653102654102655102656102657102658102659102660102661102662102663102664102665102666102667102668102669102670102671102672102673102674102675102676102677102678102679102680102681102682102683102684102685102686102687102688102689102690102691102692102693102694102695102696102697102698102699102700102701102702102703102704102705102706102707102708102709102710102711102712102713102714102715102716102717102718102719102720102721102722102723102724102725102726102727102728102729102730102731102732102733102734102735102736102737102738102739102740102741102742102743102744102745102746102747102748102749102750102751102752102753102754102755102756102757102758102759102760102761102762102763102764102765102766102767102768102769102770102771102772102773102774102775102776102777102778102779102780102781102782102783102784102785102786102787102788102789102790102791102792102793102794102795102796102797102798102799102800102801102802102803102804102805102806102807102808102809102810102811102812102813102814102815102816102817102818102819102820102821102822102823102824102825102826102827102828102829102830102831102832102833102834102835102836102837102838102839102840102841102842102843102844102845102846102847102848102849102850102851102852102853102854102855102856102857102858102859102860102861102862102863102864102865102866102867102868102869102870102871102872102873102874102875102876102877102878102879102880102881102882102883102884102885102886102887102888102889102890102891102892102893102894102895102896102897102898102899102900102901102902102903102904102905102906102907102908102909102910102911102912102913102914102915102916102917102918102919102920102921102922102923102924102925102926102927102928102929102930102931102932102933102934102935102936102937102938102939102940102941102942102943102944102945102946102947102948102949102950102951102952102953102954102955102956102957102958102959102960102961102962102963102964102965102966102967102968102969102970102971102972102973102974102975102976102977102978102979102980102981102982102983102984102985102986102987102988102989102990102991102992102993102994102995102996102997102998102999103000103001103002103003103004103005103006103007103008103009103010103011103012103013103014103015103016103017103018103019103020103021103022103023103024103025103026103027103028103029103030103031103032103033103034103035103036103037103038103039103040103041103042103043103044103045103046103047103048103049103050103051103052103053103054103055103056103057103058103059103060103061103062103063103064103065103066103067103068103069103070103071103072103073103074103075103076103077103078103079103080103081103082103083103084103085103086103087103088103089103090103091103092103093103094103095103096103097103098103099103100103101103102103103103104103105103106103107103108103109103110103111103112103113103114103115103116103117103118103119103120103121103122103123103124103125103126103127103128103129103130103131103132103133103134103135103136103137103138103139103140103141103142103143103144103145103146103147103148103149103150103151103152103153103154103155103156103157103158103159103160103161103162103163103164103165103166103167103168103169103170103171103172103173103174103175103176103177103178103179103180103181103182103183103184103185103186103187103188103189103190103191103192103193103194103195103196103197103198103199103200103201103202103203103204103205103206103207103208103209103210103211103212103213103214103215103216103217103218103219103220103221103222103223103224103225103226103227103228103229103230103231103232103233103234103235103236103237103238103239103240103241103242103243103244103245103246103247103248103249103250103251103252103253103254103255103256103257103258103259103260103261103262103263103264103265103266103267103268103269103270103271103272103273103274103275103276103277103278103279103280103281103282103283103284103285103286103287103288103289103290103291103292103293103294103295103296103297103298103299103300103301103302103303103304103305103306103307103308103309103310103311103312103313103314103315103316103317103318103319103320103321103322103323103324103325103326103327103328103329103330103331103332103333103334103335103336103337103338103339103340103341103342103343103344103345103346103347103348103349103350103351103352103353103354103355103356103357103358103359103360103361103362103363103364103365103366103367103368103369103370103371103372103373103374103375103376103377103378103379103380103381103382103383103384103385103386103387103388103389103390103391103392103393103394103395103396103397103398103399103400103401103402103403103404103405103406103407103408103409103410103411103412103413103414103415103416103417103418103419103420103421103422103423103424103425103426103427103428103429103430103431103432103433103434103435103436103437103438103439103440103441103442103443103444103445103446103447103448103449103450103451103452103453103454103455103456103457103458103459103460103461103462103463103464103465103466103467103468103469103470103471103472103473103474103475103476103477103478103479103480103481103482103483103484103485103486103487103488103489103490103491103492103493103494103495103496103497103498103499103500103501103502103503103504103505103506103507103508103509103510103511103512103513103514103515103516103517103518103519103520103521103522103523103524103525103526103527103528103529103530103531103532103533103534103535103536103537103538103539103540103541103542103543103544103545103546103547103548103549103550103551103552103553103554103555103556103557103558103559103560103561103562103563103564103565103566103567103568103569103570103571103572103573103574103575103576103577103578103579103580103581103582103583103584103585103586103587103588103589103590103591103592103593103594103595103596103597103598103599103600103601103602103603103604103605103606103607103608103609103610103611103612103613103614103615103616103617103618103619103620103621103622103623103624103625103626103627103628103629103630103631103632103633103634103635103636103637103638103639103640103641103642103643103644103645103646103647103648103649103650103651103652103653103654103655103656103657103658103659103660103661103662103663103664103665103666103667103668103669103670103671103672103673103674103675103676103677103678103679103680103681103682103683103684103685103686103687103688103689103690103691103692103693103694103695103696103697103698103699103700103701103702103703103704103705103706103707103708103709103710103711103712103713103714103715103716103717103718103719103720103721103722103723103724103725103726103727103728103729103730103731103732103733103734103735103736103737103738103739103740103741103742103743103744103745103746103747103748103749103750103751103752103753103754103755103756103757103758103759103760103761103762103763103764103765103766103767103768103769103770103771103772103773103774103775103776103777103778103779103780103781103782103783103784103785103786103787103788103789103790103791103792103793103794103795103796103797103798103799103800103801103802103803103804103805103806103807103808103809103810103811103812103813103814103815103816103817103818103819103820103821103822103823103824103825103826103827103828103829103830103831103832103833103834103835103836103837103838103839103840103841103842103843103844103845103846103847103848103849103850103851103852103853103854103855103856103857103858103859103860103861103862103863103864103865103866103867103868103869103870103871103872103873103874103875103876103877103878103879103880103881103882103883103884103885103886103887103888103889103890103891103892103893103894103895103896103897103898103899103900103901103902103903103904103905103906103907103908103909103910103911103912103913103914103915103916103917103918103919103920103921103922103923103924103925103926103927103928103929103930103931103932103933103934103935103936103937103938103939103940103941103942103943103944103945103946103947103948103949103950103951103952103953103954103955103956103957103958103959103960103961103962103963103964103965103966103967103968103969103970103971103972103973103974103975103976103977103978103979103980103981103982103983103984103985103986103987103988103989103990103991103992103993103994103995103996103997103998103999104000104001104002104003104004104005104006104007104008104009104010104011104012104013104014104015104016104017104018104019104020104021104022104023104024104025104026104027104028104029104030104031104032104033104034104035104036104037104038104039104040104041104042104043104044104045104046104047104048104049104050104051104052104053104054104055104056104057104058104059104060104061104062104063104064104065104066104067104068104069104070104071104072104073104074104075104076104077104078104079104080104081104082104083104084104085104086104087104088104089104090104091104092104093104094104095104096104097104098104099104100104101104102104103104104104105104106104107104108104109104110104111104112104113104114104115104116104117104118104119104120104121104122104123104124104125104126104127104128104129104130104131104132104133104134104135104136104137104138104139104140104141104142104143104144104145104146104147104148104149104150104151104152104153104154104155104156104157104158104159104160104161104162104163104164104165104166104167104168104169104170104171104172104173104174104175104176104177104178104179104180104181104182104183104184104185104186104187104188104189104190104191104192104193104194104195104196104197104198104199104200104201104202104203104204104205104206104207104208104209104210104211104212104213104214104215104216104217104218104219104220104221104222104223104224104225104226104227104228104229104230104231104232104233104234104235104236104237104238104239104240104241104242104243104244104245104246104247104248104249104250104251104252104253104254104255104256104257104258104259104260104261104262104263104264104265104266104267104268104269104270104271104272104273104274104275104276104277104278104279104280104281104282104283104284104285104286104287104288104289104290104291104292104293104294104295104296104297104298104299104300104301104302104303104304104305104306104307104308104309104310104311104312104313104314104315104316104317104318104319104320104321104322104323104324104325104326104327104328104329104330104331104332104333104334104335104336104337104338104339104340104341104342104343104344104345104346104347104348104349104350104351104352104353104354104355104356104357104358104359104360104361104362104363104364104365104366104367104368104369104370104371104372104373104374104375104376104377104378104379104380104381104382104383104384104385104386104387104388104389104390104391104392104393104394104395104396104397104398104399104400104401104402104403104404104405104406104407104408104409104410104411104412104413104414104415104416104417104418104419104420104421104422104423104424104425104426104427104428104429104430104431104432104433104434104435104436104437104438104439104440104441104442104443104444104445104446104447104448104449104450104451104452104453104454104455104456104457104458104459104460104461104462104463104464104465104466104467104468104469104470104471104472104473104474104475104476104477104478104479104480104481104482104483104484104485104486104487104488104489104490104491104492104493104494104495104496104497104498104499104500104501104502104503104504104505104506104507104508104509104510104511104512104513104514104515104516104517104518104519104520104521104522104523104524104525104526104527104528104529104530104531104532104533104534104535104536104537104538104539104540104541104542104543104544104545104546104547104548104549104550104551104552104553104554104555104556104557104558104559104560104561104562104563104564104565104566104567104568104569104570104571104572104573104574104575104576104577104578104579104580104581104582104583104584104585104586104587104588104589104590104591104592104593104594104595104596104597104598104599104600104601104602104603104604104605104606104607104608104609104610104611104612104613104614104615104616104617104618104619104620104621104622104623104624104625104626104627104628104629104630104631104632104633104634104635104636104637104638104639104640104641104642104643104644104645104646104647104648104649104650104651104652104653104654104655104656104657104658104659104660104661104662104663104664104665104666104667104668104669104670104671104672104673104674104675104676104677104678104679104680104681104682104683104684104685104686104687104688104689104690104691104692104693104694104695104696104697104698104699104700104701104702104703104704104705104706104707104708104709104710104711104712104713104714104715104716104717104718104719104720104721104722104723104724104725104726104727104728104729104730104731104732104733104734104735104736104737104738104739104740104741104742104743104744104745104746104747104748104749104750104751104752104753104754104755104756104757104758104759104760104761104762104763104764104765104766104767104768104769104770104771104772104773104774104775104776104777104778104779104780104781104782104783104784104785104786104787104788104789104790104791104792104793104794104795104796104797104798104799104800104801104802104803104804104805104806104807104808104809104810104811104812104813104814104815104816104817104818104819104820104821104822104823104824104825104826104827104828104829104830104831104832104833104834104835104836104837104838104839104840104841104842104843104844104845104846104847104848104849104850104851104852104853104854104855104856104857104858104859104860104861104862104863104864104865104866104867104868104869104870104871104872104873104874104875104876104877104878104879104880104881104882104883104884104885104886104887104888104889104890104891104892104893104894104895104896104897104898104899104900104901104902104903104904104905104906104907104908104909104910104911104912104913104914104915104916104917104918104919104920104921104922104923104924104925104926104927104928104929104930104931104932104933104934104935104936104937104938104939104940104941104942104943104944104945104946104947104948104949104950104951104952104953104954104955104956104957104958104959104960104961104962104963104964104965104966104967104968104969104970104971104972104973104974104975104976104977104978104979104980104981104982104983104984104985104986104987104988104989104990104991104992104993104994104995104996104997104998104999105000105001105002105003105004105005105006105007105008105009105010105011105012105013105014105015105016105017105018105019105020105021105022105023105024105025105026105027105028105029105030105031105032105033105034105035105036105037105038105039105040105041105042105043105044105045105046105047105048105049105050105051105052105053105054105055105056105057105058105059105060105061105062105063105064105065105066105067105068105069105070105071105072105073105074105075105076105077105078105079105080105081105082105083105084105085105086105087105088105089105090105091105092105093105094105095105096105097105098105099105100105101105102105103105104105105105106105107105108105109105110105111105112105113105114105115105116105117105118105119105120105121105122105123105124105125105126105127105128105129105130105131105132105133105134105135105136105137105138105139105140105141105142105143105144105145105146105147105148105149105150105151105152105153105154105155105156105157105158105159105160105161105162105163105164105165105166105167105168105169105170105171105172105173105174105175105176105177105178105179105180105181105182105183105184105185105186105187105188105189105190105191105192105193105194105195105196105197105198105199105200105201105202105203105204105205105206105207105208105209105210105211105212105213105214105215105216105217105218105219105220105221105222105223105224105225105226105227105228105229105230105231105232105233105234105235105236105237105238105239105240105241105242105243105244105245105246105247105248105249105250105251105252105253105254105255105256105257105258105259105260105261105262105263105264105265105266105267105268105269105270105271105272105273105274105275105276105277105278105279105280105281105282105283105284105285105286105287105288105289105290105291105292105293105294105295105296105297105298105299105300105301105302105303105304105305105306105307105308105309105310105311105312105313105314105315105316105317105318105319105320105321105322105323105324105325105326105327105328105329105330105331105332105333105334105335105336105337105338105339105340105341105342105343105344105345105346105347105348105349105350105351105352105353105354105355105356105357105358105359105360105361105362105363105364105365105366105367105368105369105370105371105372105373105374105375105376105377105378105379105380105381105382105383105384105385105386105387105388105389105390105391105392105393105394105395105396105397105398105399105400105401105402105403105404105405105406105407105408105409105410105411105412105413105414105415105416105417105418105419105420105421105422105423105424105425105426105427105428105429105430105431105432105433105434105435105436105437105438105439105440105441105442105443105444105445105446105447105448105449105450105451105452105453105454105455105456105457105458105459105460105461105462105463105464105465105466105467105468105469105470105471105472105473105474105475105476105477105478105479105480105481105482105483105484105485105486105487105488105489105490105491105492105493105494105495105496105497105498105499105500105501105502105503105504105505105506105507105508105509105510105511105512105513105514105515105516105517105518105519105520105521105522105523105524105525105526105527105528105529105530105531105532105533105534105535105536105537105538105539105540105541105542105543105544105545105546105547105548105549105550105551105552105553105554105555105556105557105558105559105560105561105562105563105564105565105566105567105568105569105570105571105572105573105574105575105576105577105578105579105580105581105582105583105584105585105586105587105588105589105590105591105592105593105594105595105596105597105598105599105600105601105602105603105604105605105606105607105608105609105610105611105612105613105614105615105616105617105618105619105620105621105622105623105624105625105626105627105628105629105630105631105632105633105634105635105636105637105638105639105640105641105642105643105644105645105646105647105648105649105650105651105652105653105654105655105656105657105658105659105660105661105662105663105664105665105666105667105668105669105670105671105672105673105674105675105676105677105678105679105680105681105682105683105684105685105686105687105688105689105690105691105692105693105694105695105696105697105698105699105700105701105702105703105704105705105706105707105708105709105710105711105712105713105714105715105716105717105718105719105720105721105722105723105724105725105726105727105728105729105730105731105732105733105734105735105736105737105738105739105740105741105742105743105744105745105746105747105748105749105750105751105752105753105754105755105756105757105758105759105760105761105762105763105764105765105766105767105768105769105770105771105772105773105774105775105776105777105778105779105780105781105782105783105784105785105786105787105788105789105790105791105792105793105794105795105796105797105798105799105800105801105802105803105804105805105806105807105808105809105810105811105812105813105814105815105816105817105818105819105820105821105822105823105824105825105826105827105828105829105830105831105832105833105834105835105836105837105838105839105840105841105842105843105844105845105846105847105848105849105850105851105852105853105854105855105856105857105858105859105860105861105862105863105864105865105866105867105868105869105870105871105872105873105874105875105876105877105878105879105880105881105882105883105884105885105886105887105888105889105890105891105892105893105894105895105896105897105898105899105900105901105902105903105904105905105906105907105908105909105910105911105912105913105914105915105916105917105918105919105920105921105922105923105924105925105926105927105928105929105930105931105932105933105934105935105936105937105938105939105940105941105942105943105944105945105946105947105948105949105950105951105952105953105954105955105956105957105958105959105960105961105962105963105964105965105966105967105968105969105970105971105972105973105974105975105976105977105978105979105980105981105982105983105984105985105986105987105988105989105990105991105992105993105994105995105996105997105998105999106000106001106002106003106004106005106006106007106008106009106010106011106012106013106014106015106016106017106018106019106020106021106022106023106024106025106026106027106028106029106030106031106032106033106034106035106036106037106038106039106040106041106042106043106044106045106046106047106048106049106050106051106052106053106054106055106056106057106058106059106060106061106062106063106064106065106066106067106068106069106070106071106072106073106074106075106076106077106078106079106080106081106082106083106084106085106086106087106088106089106090106091106092106093106094106095106096106097106098106099106100106101106102106103106104106105106106106107106108106109106110106111106112106113106114106115106116106117106118106119106120106121106122106123106124106125106126106127106128106129106130106131106132106133106134106135106136106137106138106139106140106141106142106143106144106145106146106147106148106149106150106151106152106153106154106155106156106157106158106159106160106161106162106163106164106165106166106167106168106169106170106171106172106173106174106175106176106177106178106179106180106181106182106183106184106185106186106187106188106189106190106191106192106193106194106195106196106197106198106199106200106201106202106203106204106205106206106207106208106209106210106211106212106213106214106215106216106217106218106219106220106221106222106223106224106225106226106227106228106229106230106231106232106233106234106235106236106237106238106239106240106241106242106243106244106245106246106247106248106249106250106251106252106253106254106255106256106257106258106259106260106261106262106263106264106265106266106267106268106269106270106271106272106273106274106275106276106277106278106279106280106281106282106283106284106285106286106287106288106289106290106291106292106293106294106295106296106297106298106299106300106301106302106303106304106305106306106307106308106309106310106311106312106313106314106315106316106317106318106319106320106321106322106323106324106325106326106327106328106329106330106331106332106333106334106335106336106337106338106339106340106341106342106343106344106345106346106347106348106349106350106351106352106353106354106355106356106357106358106359106360106361106362106363106364106365106366106367106368106369106370106371106372106373106374106375106376106377106378106379106380106381106382106383106384106385106386106387106388106389106390106391106392106393106394106395106396106397106398106399106400106401106402106403106404106405106406106407106408106409106410106411106412106413106414106415106416106417106418106419106420106421106422106423106424106425106426106427106428106429106430106431106432106433106434106435106436106437106438106439106440106441106442106443106444106445106446106447106448106449106450106451106452106453106454106455106456106457106458106459106460106461106462106463106464106465106466106467106468106469106470106471106472106473106474106475106476106477106478106479106480106481106482106483106484106485106486106487106488106489106490106491106492106493106494106495106496106497106498106499106500106501106502106503106504106505106506106507106508106509106510106511106512106513106514106515106516106517106518106519106520106521106522106523106524106525106526106527106528106529106530106531106532106533106534106535106536106537106538106539106540106541106542106543106544106545106546106547106548106549106550106551106552106553106554106555106556106557106558106559106560106561106562106563106564106565106566106567106568106569106570106571106572106573106574106575106576106577106578106579106580106581106582106583106584106585106586106587106588106589106590106591106592106593106594106595106596106597106598106599106600106601106602106603106604106605106606106607106608106609106610106611106612106613106614106615106616106617106618106619106620106621106622106623106624106625106626106627106628106629106630106631106632106633106634106635106636106637106638106639106640106641106642106643106644106645106646106647106648106649106650106651106652106653106654106655106656106657106658106659106660106661106662106663106664106665106666106667106668106669106670106671106672106673106674106675106676106677106678106679106680106681106682106683106684106685106686106687106688106689106690106691106692106693106694106695106696106697106698106699106700106701106702106703106704106705106706106707106708106709106710106711106712106713106714106715106716106717106718106719106720106721106722106723106724106725106726106727106728106729106730106731106732106733106734106735106736106737106738106739106740106741106742106743106744106745106746106747106748106749106750106751106752106753106754106755106756106757106758106759106760106761106762106763106764106765106766106767106768106769106770106771106772106773106774106775106776106777106778106779106780106781106782106783106784106785106786106787106788106789106790106791106792106793106794106795106796106797106798106799106800106801106802106803106804106805106806106807106808106809106810106811106812106813106814106815106816106817106818106819106820106821106822106823106824106825106826106827106828106829106830106831106832106833106834106835106836106837106838106839106840106841106842106843106844106845106846106847106848106849106850106851106852106853106854106855106856106857106858106859106860106861106862106863106864106865106866106867106868106869106870106871106872106873106874106875106876106877106878106879106880106881106882106883106884106885106886106887106888106889106890106891106892106893106894106895106896106897106898106899106900106901106902106903106904106905106906106907106908106909106910106911106912106913106914106915106916106917106918106919106920106921106922106923106924106925106926106927106928106929106930106931106932106933106934106935106936106937106938106939106940106941106942106943106944106945106946106947106948106949106950106951106952106953106954106955106956106957106958106959106960106961106962106963106964106965106966106967106968106969106970106971106972106973106974106975106976106977106978106979106980106981106982106983106984106985106986106987106988106989106990106991106992106993106994106995106996106997106998106999107000107001107002107003107004107005107006107007107008107009107010107011107012107013107014107015107016107017107018107019107020107021107022107023107024107025107026107027107028107029107030107031107032107033107034107035107036107037107038107039107040107041107042107043107044107045107046107047107048107049107050107051107052107053107054107055107056107057107058107059107060107061107062107063107064107065107066107067107068107069107070107071107072107073107074107075107076107077107078107079107080107081107082107083107084107085107086107087107088107089107090107091107092107093107094107095107096107097107098107099107100107101107102107103107104107105107106107107107108107109107110107111107112107113107114107115107116107117107118107119107120107121107122107123107124107125107126107127107128107129107130107131107132107133107134107135107136107137107138107139107140107141107142107143107144107145107146107147107148107149107150107151107152107153107154107155107156107157107158107159107160107161107162107163107164107165107166107167107168107169107170107171107172107173107174107175107176107177107178107179107180107181107182107183107184107185107186107187107188107189107190107191107192107193107194107195107196107197107198107199107200107201107202107203107204107205107206107207107208107209107210107211107212107213107214107215107216107217107218107219107220107221107222107223107224107225107226107227107228107229107230107231107232107233107234107235107236107237107238107239107240107241107242107243107244107245107246107247107248107249107250107251107252107253107254107255107256107257107258107259107260107261107262107263107264107265107266107267107268107269107270107271107272107273107274107275107276107277107278107279107280107281107282107283107284107285107286107287107288107289107290107291107292107293107294107295107296107297107298107299107300107301107302107303107304107305107306107307107308107309107310107311107312107313107314107315107316107317107318107319107320107321107322107323107324107325107326107327107328107329107330107331107332107333107334107335107336107337107338107339107340107341107342107343107344107345107346107347107348107349107350107351107352107353107354107355107356107357107358107359107360107361107362107363107364107365107366107367107368107369107370107371107372107373107374107375107376107377107378107379107380107381107382107383107384107385107386107387107388107389107390107391107392107393107394107395107396107397107398107399107400107401107402107403107404107405107406107407107408107409107410107411107412107413107414107415107416107417107418107419107420107421107422107423107424107425107426107427107428107429107430107431107432107433107434107435107436107437107438107439107440107441107442107443107444107445107446107447107448107449107450107451107452107453107454107455107456107457107458107459107460107461107462107463107464107465107466107467107468107469107470107471107472107473107474107475107476107477107478107479107480107481107482107483107484107485107486107487107488107489107490107491107492107493107494107495107496107497107498107499107500107501107502107503107504107505107506107507107508107509107510107511107512107513107514107515107516107517107518107519107520107521107522107523107524107525107526107527107528107529107530107531107532107533107534107535107536107537107538107539107540107541107542107543107544107545107546107547107548107549107550107551107552107553107554107555107556107557107558107559107560107561107562107563107564107565107566107567107568107569107570107571107572107573107574107575107576107577107578107579107580107581107582107583107584107585107586107587107588107589107590107591107592107593107594107595107596107597107598107599107600107601107602107603107604107605107606107607107608107609107610107611107612107613107614107615107616107617107618107619107620107621107622107623107624107625107626107627107628107629107630107631107632107633107634107635107636107637107638107639107640107641107642107643107644107645107646107647107648107649107650107651107652107653107654107655107656107657107658107659107660107661107662107663107664107665107666107667107668107669107670107671107672107673107674107675107676107677107678107679107680107681107682107683107684107685107686107687107688107689107690107691107692107693107694107695107696107697107698107699107700107701107702107703107704107705107706107707107708107709107710107711107712107713107714107715107716107717107718107719107720107721107722107723107724107725107726107727107728107729107730107731107732107733107734107735107736107737107738107739107740107741107742107743107744107745107746107747107748107749107750107751107752107753107754107755107756107757107758107759107760107761107762107763107764107765107766107767107768107769107770107771107772107773107774107775107776107777107778107779107780107781107782107783107784107785107786107787107788107789107790107791107792107793107794107795107796107797107798107799107800107801107802107803107804107805107806107807107808107809107810107811107812107813107814107815107816107817107818107819107820107821107822107823107824107825107826107827107828107829107830107831107832107833107834107835107836107837107838107839107840107841107842107843107844107845107846107847107848107849107850107851107852107853107854107855107856107857107858107859107860107861107862107863107864107865107866107867107868107869107870107871107872107873107874107875107876107877107878107879107880107881107882107883107884107885107886107887107888107889107890107891107892107893107894107895107896107897107898107899107900107901107902107903107904107905107906107907107908107909107910107911107912107913107914107915107916107917107918107919107920107921107922107923107924107925107926107927107928107929107930107931107932107933107934107935107936107937107938107939107940107941107942107943107944107945107946107947107948107949107950107951107952107953107954107955107956107957107958107959107960107961107962107963107964107965107966107967107968107969107970107971107972107973107974107975107976107977107978107979107980107981107982107983107984107985107986107987107988107989107990107991107992107993107994107995107996107997107998107999108000108001108002108003108004108005108006108007108008108009108010108011108012108013108014108015108016108017108018108019108020108021108022108023108024108025108026108027108028108029108030108031108032108033108034108035108036108037108038108039108040108041108042108043108044108045108046108047108048108049108050108051108052108053108054108055108056108057108058108059108060108061108062108063108064108065108066108067108068108069108070108071108072108073108074108075108076108077108078108079108080108081108082108083108084108085108086108087108088108089108090108091108092108093108094108095108096108097108098108099108100108101108102108103108104108105108106108107108108108109108110108111108112108113108114108115108116108117108118108119108120108121108122108123108124108125108126108127108128108129108130108131108132108133108134108135108136108137108138108139108140108141108142108143108144108145108146108147108148108149108150108151108152108153108154108155108156108157108158108159108160108161108162108163108164108165108166108167108168108169108170108171108172108173108174108175108176108177108178108179108180108181108182108183108184108185108186108187108188108189108190108191108192108193108194108195108196108197108198108199108200108201108202108203108204108205108206108207108208108209108210108211108212108213108214108215108216108217108218108219108220108221108222108223108224108225108226108227108228108229108230108231108232108233108234108235108236108237108238108239108240108241108242108243108244108245108246108247108248108249108250108251108252108253108254108255108256108257108258108259108260108261108262108263108264108265108266108267108268108269108270108271108272108273108274108275108276108277108278108279108280108281108282108283108284108285108286108287108288108289108290108291108292108293108294108295108296108297108298108299108300108301108302108303108304108305108306108307108308108309108310108311108312108313108314108315108316108317108318108319108320108321108322108323108324108325108326108327108328108329108330108331108332108333108334108335108336108337108338108339108340108341108342108343108344108345108346108347108348108349108350108351108352108353108354108355108356108357108358108359108360108361108362108363108364108365108366108367108368108369108370108371108372108373108374108375108376108377108378108379108380108381108382108383108384108385108386108387108388108389108390108391108392108393108394108395108396108397108398108399108400108401108402108403108404108405108406108407108408108409108410108411108412108413108414108415108416108417108418108419108420108421108422108423108424108425108426108427108428108429108430108431108432108433108434108435108436108437108438108439108440108441108442108443108444108445108446108447108448108449108450108451108452108453108454108455108456108457108458108459108460108461108462108463108464108465108466108467108468108469108470108471108472108473108474108475108476108477108478108479108480108481108482108483108484108485108486108487108488108489108490108491108492108493108494108495108496108497108498108499108500108501108502108503108504108505108506108507108508108509108510108511108512108513108514108515108516108517108518108519108520108521108522108523108524108525108526108527108528108529108530108531108532108533108534108535108536108537108538108539108540108541108542108543108544108545108546108547108548108549108550108551108552108553108554108555108556108557108558108559108560108561108562108563108564108565108566108567108568108569108570108571108572108573108574108575108576108577108578108579108580108581108582108583108584108585108586108587108588108589108590108591108592108593108594108595108596108597108598108599108600108601108602108603108604108605108606108607108608108609108610108611108612108613108614108615108616108617108618108619108620108621108622108623108624108625108626108627108628108629108630108631108632108633108634108635108636108637108638108639108640108641108642108643108644108645108646108647108648108649108650108651108652108653108654108655108656108657108658108659108660108661108662108663108664108665108666108667108668108669108670108671108672108673108674108675108676108677108678108679108680108681108682108683108684108685108686108687108688108689108690108691108692108693108694108695108696108697108698108699108700108701108702108703108704108705108706108707108708108709108710108711108712108713108714108715108716108717108718108719108720108721108722108723108724108725108726108727108728108729108730108731108732108733108734108735108736108737108738108739108740108741108742108743108744108745108746108747108748108749108750108751108752108753108754108755108756108757108758108759108760108761108762108763108764108765108766108767108768108769108770108771108772108773108774108775108776108777108778108779108780108781108782108783108784108785108786108787108788108789108790108791108792108793108794108795108796108797108798108799108800108801108802108803108804108805108806108807108808108809108810108811108812108813108814108815108816108817108818108819108820108821108822108823108824108825108826108827108828108829108830108831108832108833108834108835108836108837108838108839108840108841108842108843108844108845108846108847108848108849108850108851108852108853108854108855108856108857108858108859108860108861108862108863108864108865108866108867108868108869108870108871108872108873108874108875108876108877108878108879108880108881108882108883108884108885108886108887108888108889108890108891108892108893108894108895108896108897108898108899108900108901108902108903108904108905108906108907108908108909108910108911108912108913108914108915108916108917108918108919108920108921108922108923108924108925108926108927108928108929108930108931108932108933108934108935108936108937108938108939108940108941108942108943108944108945108946108947108948108949108950108951108952108953108954108955108956108957108958108959108960108961108962108963108964108965108966108967108968108969108970108971108972108973108974108975108976108977108978108979108980108981108982108983108984108985108986108987108988108989108990108991108992108993108994108995108996108997108998108999109000109001109002109003109004109005109006109007109008109009109010109011109012109013109014109015109016109017109018109019109020109021109022109023109024109025109026109027109028109029109030109031109032109033109034109035109036109037109038109039109040109041109042109043109044109045109046109047109048109049109050109051109052109053109054109055109056109057109058109059109060109061109062109063109064109065109066109067109068109069109070109071109072109073109074109075109076109077109078109079109080109081109082109083109084109085109086109087109088109089109090109091109092109093109094109095109096109097109098109099109100109101109102109103109104109105109106109107109108109109109110109111109112109113109114109115109116109117109118109119109120109121109122109123109124109125109126109127109128109129109130109131109132109133109134109135109136109137109138109139109140109141109142109143109144109145109146109147109148109149109150109151109152109153109154109155109156109157109158109159109160109161109162109163109164109165109166109167109168109169109170109171109172109173109174109175109176109177109178109179109180109181109182109183109184109185109186109187109188109189109190109191109192109193109194109195109196109197109198109199109200109201109202109203109204109205109206109207109208109209109210109211109212109213109214109215109216109217109218109219109220109221109222109223109224109225109226109227109228109229109230109231109232109233109234109235109236109237109238109239109240109241109242109243109244109245109246109247109248109249109250109251109252109253109254109255109256109257109258109259109260109261109262109263109264109265109266109267109268109269109270109271109272109273109274109275109276109277109278109279109280109281109282109283109284109285109286109287109288109289109290109291109292109293109294109295109296109297109298109299109300109301109302109303109304109305109306109307109308109309109310109311109312109313109314109315109316109317109318109319109320109321109322109323109324109325109326109327109328109329109330109331109332109333109334109335109336109337109338109339109340109341109342109343109344109345109346109347109348109349109350109351109352109353109354109355109356109357109358109359109360109361109362109363109364109365109366109367109368109369109370109371109372109373109374109375109376109377109378109379109380109381109382109383109384109385109386109387109388109389109390109391109392109393109394109395109396109397109398109399109400109401109402109403109404109405109406109407109408109409109410109411109412109413109414109415109416109417109418109419109420109421109422109423109424109425109426109427109428109429109430109431109432109433109434109435109436109437109438109439109440109441109442109443109444109445109446109447109448109449109450109451109452109453109454109455109456109457109458109459109460109461109462109463109464109465109466109467109468109469109470109471109472109473109474109475109476109477109478109479109480109481109482109483109484109485109486109487109488109489109490109491109492109493109494109495109496109497109498109499109500109501109502109503109504109505109506109507109508109509109510109511109512109513109514109515109516109517109518109519109520109521109522109523109524109525109526109527109528109529109530109531109532109533109534109535109536109537109538109539109540109541109542109543109544109545109546109547109548109549109550109551109552109553109554109555109556109557109558109559109560109561109562109563109564109565109566109567109568109569109570109571109572109573109574109575109576109577109578109579109580109581109582109583109584109585109586109587109588109589109590109591109592109593109594109595109596109597109598109599109600109601109602109603109604109605109606109607109608109609109610109611109612109613109614109615109616109617109618109619109620109621109622109623109624109625109626109627109628109629109630109631109632109633109634109635109636109637109638109639109640109641109642109643109644109645109646109647109648109649109650109651109652109653109654109655109656109657109658109659109660109661109662109663109664109665109666109667109668109669109670109671109672109673109674109675109676109677109678109679109680109681109682109683109684109685109686109687109688109689109690109691109692109693109694109695109696109697109698109699109700109701109702109703109704109705109706109707109708109709109710109711109712109713109714109715109716109717109718109719109720109721109722109723109724109725109726109727109728109729109730109731109732109733109734109735109736109737109738109739109740109741109742109743109744109745109746109747109748109749109750109751109752109753109754109755109756109757109758109759109760109761109762109763109764109765109766109767109768109769109770109771109772109773109774109775109776109777109778109779109780109781109782109783109784109785109786109787109788109789109790109791109792109793109794109795109796109797109798109799109800109801109802109803109804109805109806109807109808109809109810109811109812109813109814109815109816109817109818109819109820109821109822109823109824109825109826109827109828109829109830109831109832109833109834109835109836109837109838109839109840109841109842109843109844109845109846109847109848109849109850109851109852109853109854109855109856109857109858109859109860109861109862109863109864109865109866109867109868109869109870109871109872109873109874109875109876109877109878109879109880109881109882109883109884109885109886109887109888109889109890109891109892109893109894109895109896109897109898109899109900109901109902109903109904109905109906109907109908109909109910109911109912109913109914109915109916109917109918109919109920109921109922109923109924109925109926109927109928109929109930109931109932109933109934109935109936109937109938109939109940109941109942109943109944109945109946109947109948109949109950109951109952109953109954109955109956109957109958109959109960109961109962109963109964109965109966109967109968109969109970109971109972109973109974109975109976109977109978109979109980109981109982109983109984109985109986109987109988109989109990109991109992109993109994109995109996109997109998109999110000110001110002110003110004110005110006110007110008110009110010110011110012110013110014110015110016110017110018110019110020110021110022110023110024110025110026110027110028110029110030110031110032110033110034110035110036110037110038110039110040110041110042110043110044110045110046110047110048110049110050110051110052110053110054110055110056110057110058110059110060110061110062110063110064110065110066110067110068110069110070110071110072110073110074110075110076110077110078110079110080110081110082110083110084110085110086110087110088110089110090110091110092110093110094110095110096110097110098110099110100110101110102110103110104110105110106110107110108110109110110110111110112110113110114110115110116110117110118110119110120110121110122110123110124110125110126110127110128110129110130110131110132110133110134110135110136110137110138110139110140110141110142110143110144110145110146110147110148110149110150110151110152110153110154110155110156110157110158110159110160110161110162110163110164110165110166110167110168110169110170110171110172110173110174110175110176110177110178110179110180110181110182110183110184110185110186110187110188110189110190110191110192110193110194110195110196110197110198110199110200110201110202110203110204110205110206110207110208110209110210110211110212110213110214110215110216110217110218110219110220110221110222110223110224110225110226110227110228110229110230110231110232110233110234110235110236110237110238110239110240110241110242110243110244110245110246110247110248110249110250110251110252110253110254110255110256110257110258110259110260110261110262110263110264110265110266110267110268110269110270110271110272110273110274110275110276110277110278110279110280110281110282110283110284110285110286110287110288110289110290110291110292110293110294110295110296110297110298110299110300110301110302110303110304110305110306110307110308110309110310110311110312110313110314110315110316110317110318110319110320110321110322110323110324110325110326110327110328110329110330110331110332110333110334110335110336110337110338110339110340110341110342110343110344110345110346110347110348110349110350110351110352110353110354110355110356110357110358110359110360110361110362110363110364110365110366110367110368110369110370110371110372110373110374110375110376110377110378110379110380110381110382110383110384110385110386110387110388110389110390110391110392110393110394110395110396110397110398110399110400110401110402110403110404110405110406110407110408110409110410110411110412110413110414110415110416110417110418110419110420110421110422110423110424110425110426110427110428110429110430110431110432110433110434110435110436110437110438110439110440110441110442110443110444110445110446110447110448110449110450110451110452110453110454110455110456110457110458110459110460110461110462110463110464110465110466110467110468110469110470110471110472110473110474110475110476110477110478110479110480110481110482110483110484110485110486110487110488110489110490110491110492110493110494110495110496110497110498110499110500110501110502110503110504110505110506110507110508110509110510110511110512110513110514110515110516110517110518110519110520110521110522110523110524110525110526110527110528110529110530110531110532110533110534110535110536110537110538110539110540110541110542110543110544110545110546110547110548110549110550110551110552110553110554110555110556110557110558110559110560110561110562110563110564110565110566110567110568110569110570110571110572110573110574110575110576110577110578110579110580110581110582110583110584110585110586110587110588110589110590110591110592110593110594110595110596110597110598110599110600110601110602110603110604110605110606110607110608110609110610110611110612110613110614110615110616110617110618110619110620110621110622110623110624110625110626110627110628110629110630110631110632110633110634110635110636110637110638110639110640110641110642110643110644110645110646110647110648110649110650110651110652110653110654110655110656110657110658110659110660110661110662110663110664110665110666110667110668110669110670110671110672110673110674110675110676110677110678110679110680110681110682110683110684110685110686110687110688110689110690110691110692110693110694110695110696110697110698110699110700110701110702110703110704110705110706110707110708110709110710110711110712110713110714110715110716110717110718110719110720110721110722110723110724110725110726110727110728110729110730110731110732110733110734110735110736110737110738110739110740110741110742110743110744110745110746110747110748110749110750110751110752110753110754110755110756110757110758110759110760110761110762110763110764110765110766110767110768110769110770110771110772110773110774110775110776110777110778110779110780110781110782110783110784110785110786110787110788110789110790110791110792110793110794110795110796110797110798110799110800110801110802110803110804110805110806110807110808110809110810110811110812110813110814110815110816110817110818110819110820110821110822110823110824110825110826110827110828110829110830110831110832110833110834110835110836110837110838110839110840110841110842110843110844110845110846110847110848110849110850110851110852110853110854110855110856110857110858110859110860110861110862110863110864110865110866110867110868110869110870110871110872110873110874110875110876110877110878110879110880110881110882110883110884110885110886110887110888110889110890110891110892110893110894110895110896110897110898110899110900110901110902110903110904110905110906110907110908110909110910110911110912110913110914110915110916110917110918110919110920110921110922110923110924110925110926110927110928110929110930110931110932110933110934110935110936110937110938110939110940110941110942110943110944110945110946110947110948110949110950110951110952110953110954110955110956110957110958110959110960110961110962110963110964110965110966110967110968110969110970110971110972110973110974110975110976110977110978110979110980110981110982110983110984110985110986110987110988110989110990110991110992110993110994110995110996110997110998110999111000111001111002111003111004111005111006111007111008111009111010111011111012111013111014111015111016111017111018111019111020111021111022111023111024111025111026111027111028111029111030111031111032111033111034111035111036111037111038111039111040111041111042111043111044111045111046111047111048111049111050111051111052111053111054111055111056111057111058111059111060111061111062111063111064111065111066111067111068111069111070111071111072111073111074111075111076111077111078111079111080111081111082111083111084111085111086111087111088111089111090111091111092111093111094111095111096111097111098111099111100111101111102111103111104111105111106111107111108111109111110111111111112111113111114111115111116111117111118111119111120111121111122111123111124111125111126111127111128111129111130111131111132111133111134111135111136111137111138111139111140111141111142111143111144111145111146111147111148111149111150111151111152111153111154111155111156111157111158111159111160111161111162111163111164111165111166111167111168111169111170111171111172111173111174111175111176111177111178111179111180111181111182111183111184111185111186111187111188111189111190111191111192111193111194111195111196111197111198111199111200111201111202111203111204111205111206111207111208111209111210111211111212111213111214111215111216111217111218111219111220111221111222111223111224111225111226111227111228111229111230111231111232111233111234111235111236111237111238111239111240111241111242111243111244111245111246111247111248111249111250111251111252111253111254111255111256111257111258111259111260111261111262111263111264111265111266111267111268111269111270111271111272111273111274111275111276111277111278111279111280111281111282111283111284111285111286111287111288111289111290111291111292111293111294111295111296111297111298111299111300111301111302111303111304111305111306111307111308111309111310111311111312111313111314111315111316111317111318111319111320111321111322111323111324111325111326111327111328111329111330111331111332111333111334111335111336111337111338111339111340111341111342111343111344111345111346111347111348111349111350111351111352111353111354111355111356111357111358111359111360111361111362111363111364111365111366111367111368111369111370111371111372111373111374111375111376111377111378111379111380111381111382111383111384111385111386111387111388111389111390111391111392111393111394111395111396111397111398111399111400111401111402111403111404111405111406111407111408111409111410111411111412111413111414111415111416111417111418111419111420111421111422111423111424111425111426111427111428111429111430111431111432111433111434111435111436111437111438111439111440111441111442111443111444111445111446111447111448111449111450111451111452111453111454111455111456111457111458111459111460111461111462111463111464111465111466111467111468111469111470111471111472111473111474111475111476111477111478111479111480111481111482111483111484111485111486111487111488111489111490111491111492111493111494111495111496111497111498111499111500111501111502111503111504111505111506111507111508111509111510111511111512111513111514111515111516111517111518111519111520111521111522111523111524111525111526111527111528111529111530111531111532111533111534111535111536111537111538111539111540111541111542111543111544111545111546111547111548111549111550111551111552111553111554111555111556111557111558111559111560111561111562111563111564111565111566111567111568111569111570111571111572111573111574111575111576111577111578111579111580111581111582111583111584111585111586111587111588111589111590111591111592111593111594111595111596111597111598111599111600111601111602111603111604111605111606111607111608111609111610111611111612111613111614111615111616111617111618111619111620111621111622111623111624111625111626111627111628111629111630111631111632111633111634111635111636111637111638111639111640111641111642111643111644111645111646111647111648111649111650111651111652111653111654111655111656111657111658111659111660111661111662111663111664111665111666111667111668111669111670111671111672111673111674111675111676111677111678111679111680111681111682111683111684111685111686111687111688111689111690111691111692111693111694111695111696111697111698111699111700111701111702111703111704111705111706111707111708111709111710111711111712111713111714111715111716111717111718111719111720111721111722111723111724111725111726111727111728111729111730111731111732111733111734111735111736111737111738111739111740111741111742111743111744111745111746111747111748111749111750111751111752111753111754111755111756111757111758111759111760111761111762111763111764111765111766111767111768111769111770111771111772111773111774111775111776111777111778111779111780111781111782111783111784111785111786111787111788111789111790111791111792111793111794111795111796111797111798111799111800111801111802111803111804111805111806111807111808111809111810111811111812111813111814111815111816111817111818111819111820111821111822111823111824111825111826111827111828111829111830111831111832111833111834111835111836111837111838111839111840111841111842111843111844111845111846111847111848111849111850111851111852111853111854111855111856111857111858111859111860111861111862111863111864111865111866111867111868111869111870111871111872111873111874111875111876111877111878111879111880111881111882111883111884111885111886111887111888111889111890111891111892111893111894111895111896111897111898111899111900111901111902111903111904111905111906111907111908111909111910111911111912111913111914111915111916111917111918111919111920111921111922111923111924111925111926111927111928111929111930111931111932111933111934111935111936111937111938111939111940111941111942111943111944111945111946111947111948111949111950111951111952111953111954111955111956111957111958111959111960111961111962111963111964111965111966111967111968111969111970111971111972111973111974111975111976111977111978111979111980111981111982111983111984111985111986111987111988111989111990111991111992111993111994111995111996111997111998111999112000112001112002112003112004112005112006112007112008112009112010112011112012112013112014112015112016112017112018112019112020112021112022112023112024112025112026112027112028112029112030112031112032112033112034112035112036112037112038112039112040112041112042112043112044112045112046112047112048112049112050112051112052112053112054112055112056112057112058112059112060112061112062112063112064112065112066112067112068112069112070112071112072112073112074112075112076112077112078112079112080112081112082112083112084112085112086112087112088112089112090112091112092112093112094112095112096112097112098112099112100112101112102112103112104112105112106112107112108112109112110112111112112112113112114112115112116112117112118112119112120112121112122112123112124112125112126112127112128112129112130112131112132112133112134112135112136112137112138112139112140112141112142112143112144112145112146112147112148112149112150112151112152112153112154112155112156112157112158112159112160112161112162112163112164112165112166112167112168112169112170112171112172112173112174112175112176112177112178112179112180112181112182112183112184112185112186112187112188112189112190112191112192112193112194112195112196112197112198112199112200112201112202112203112204112205112206112207112208112209112210112211112212112213112214112215112216112217112218112219112220112221112222112223112224112225112226112227112228112229112230112231112232112233112234112235112236112237112238112239112240112241112242112243112244112245112246112247112248112249112250112251112252112253112254112255112256112257112258112259112260112261112262112263112264112265112266112267112268112269112270112271112272112273112274112275112276112277112278112279112280112281112282112283112284112285112286112287112288112289112290112291112292112293112294112295112296112297112298112299112300112301112302112303112304112305112306112307112308112309112310112311112312112313112314112315112316112317112318112319112320112321112322112323112324112325112326112327112328112329112330112331112332112333112334112335112336112337112338112339112340112341112342112343112344112345112346112347112348112349112350112351112352112353112354112355112356112357112358112359112360112361112362112363112364112365112366112367112368112369112370112371112372112373112374112375112376112377112378112379112380112381112382112383112384112385112386112387112388112389112390112391112392112393112394112395112396112397112398112399112400112401112402112403112404112405112406112407112408112409112410112411112412112413112414112415112416112417112418112419112420112421112422112423112424112425112426112427112428112429112430112431112432112433112434112435112436112437112438112439112440112441112442112443112444112445112446112447112448112449112450112451112452112453112454112455112456112457112458112459112460112461112462112463112464112465112466112467112468112469112470112471112472112473112474112475112476112477112478112479112480112481112482112483112484112485112486112487112488112489112490112491112492112493112494112495112496112497112498112499112500112501112502112503112504112505112506112507112508112509112510112511112512112513112514112515112516112517112518112519112520112521112522112523112524112525112526112527112528112529112530112531112532112533112534112535112536112537112538112539112540112541112542112543112544112545112546112547112548112549112550112551112552112553112554112555112556112557112558112559112560112561112562112563112564112565112566112567112568112569112570112571112572112573112574112575112576112577112578112579112580112581112582112583112584112585112586112587112588112589112590112591112592112593112594112595112596112597112598112599112600112601112602112603112604112605112606112607112608112609112610112611112612112613112614112615112616112617112618112619112620112621112622112623112624112625112626112627112628112629112630112631112632112633112634112635112636112637112638112639112640112641112642112643112644112645112646112647112648112649112650112651112652112653112654112655112656112657112658112659112660112661112662112663112664112665112666112667112668112669112670112671112672112673112674112675112676112677112678112679112680112681112682112683112684112685112686112687112688112689112690112691112692112693112694112695112696112697112698112699112700112701112702112703112704112705112706112707112708112709112710112711112712112713112714112715112716112717112718112719112720112721112722112723112724112725112726112727112728112729112730112731112732112733112734112735112736112737112738112739112740112741112742112743112744112745112746112747112748112749112750112751112752112753112754112755112756112757112758112759112760112761112762112763112764112765112766112767112768112769112770112771112772112773112774112775112776112777112778112779112780112781112782112783112784112785112786112787112788112789112790112791112792112793112794112795112796112797112798112799112800112801112802112803112804112805112806112807112808112809112810112811112812112813112814112815112816112817112818112819112820112821112822112823112824112825112826112827112828112829112830112831112832112833112834112835112836112837112838112839112840112841112842112843112844112845112846112847112848112849112850112851112852112853112854112855112856112857112858112859112860112861112862112863112864112865112866112867112868112869112870112871112872112873112874112875112876112877112878112879112880112881112882112883112884112885112886112887112888112889112890112891112892112893112894112895112896112897112898112899112900112901112902112903112904112905112906112907112908112909112910112911112912112913112914112915112916112917112918112919112920112921112922112923112924112925112926112927112928112929112930112931112932112933112934112935112936112937112938112939112940112941112942112943112944112945112946112947112948112949112950112951112952112953112954112955112956112957112958112959112960112961112962112963112964112965112966112967112968112969112970112971112972112973112974112975112976112977112978112979112980112981112982112983112984112985112986112987112988112989112990112991112992112993112994112995112996112997112998112999113000113001113002113003113004113005113006113007113008113009113010113011113012113013113014113015113016113017113018113019113020113021113022113023113024113025113026113027113028113029113030113031113032113033113034113035113036113037113038113039113040113041113042113043113044113045113046113047113048113049113050113051113052113053113054113055113056113057113058113059113060113061113062113063113064113065113066113067113068113069113070113071113072113073113074113075113076113077113078113079113080113081113082113083113084113085113086113087113088113089113090113091113092113093113094113095113096113097113098113099113100113101113102113103113104113105113106113107113108113109113110113111113112113113113114113115113116113117113118113119113120113121113122113123113124113125113126113127113128113129113130113131113132113133113134113135113136113137113138113139113140113141113142113143113144113145113146113147113148113149113150113151113152113153113154113155113156113157113158113159113160113161113162113163113164113165113166113167113168113169113170113171113172113173113174113175113176113177113178113179113180113181113182113183113184113185113186113187113188113189113190113191113192113193113194113195113196113197113198113199113200113201113202113203113204113205113206113207113208113209113210113211113212113213113214113215113216113217113218113219113220113221113222113223113224113225113226113227113228113229113230113231113232113233113234113235113236113237113238113239113240113241113242113243113244113245113246113247113248113249113250113251113252113253113254113255113256113257113258113259113260113261113262113263113264113265113266113267113268113269113270113271113272113273113274113275113276113277113278113279113280113281113282113283113284113285113286113287113288113289113290113291113292113293113294113295113296113297113298113299113300113301113302113303113304113305113306113307113308113309113310113311113312113313113314113315113316113317113318113319113320113321113322113323113324113325113326113327113328113329113330113331113332113333113334113335113336113337113338113339113340113341113342113343113344113345113346113347113348113349113350113351113352113353113354113355113356113357113358113359113360113361113362113363113364113365113366113367113368113369113370113371113372113373113374113375113376113377113378113379113380113381113382113383113384113385113386113387113388113389113390113391113392113393113394113395113396113397113398113399113400113401113402113403113404113405113406113407113408113409113410113411113412113413113414113415113416113417113418113419113420113421113422113423113424113425113426113427113428113429113430113431113432113433113434113435113436113437113438113439113440113441113442113443113444113445113446113447113448113449113450113451113452113453113454113455113456113457113458113459113460113461113462113463113464113465113466113467113468113469113470113471113472113473113474113475113476113477113478113479113480113481113482113483113484113485113486113487113488113489113490113491113492113493113494113495113496113497113498113499113500113501113502113503113504113505113506113507113508113509113510113511113512113513113514113515113516113517113518113519113520113521113522113523113524113525113526113527113528113529113530113531113532113533113534113535113536113537113538113539113540113541113542113543113544113545113546113547113548113549113550113551113552113553113554113555113556113557113558113559113560113561113562113563113564113565113566113567113568113569113570113571113572113573113574113575113576113577113578113579113580113581113582113583113584113585113586113587113588113589113590113591113592113593113594113595113596113597113598113599113600113601113602113603113604113605113606113607113608113609113610113611113612113613113614113615113616113617113618113619113620113621113622113623113624113625113626113627113628113629113630113631113632113633113634113635113636113637113638113639113640113641113642113643113644113645113646113647113648113649113650113651113652113653113654113655113656113657113658113659113660113661113662113663113664113665113666113667113668113669113670113671113672113673113674113675113676113677113678113679113680113681113682113683113684113685113686113687113688113689113690113691113692113693113694113695113696113697113698113699113700113701113702113703113704113705113706113707113708113709113710113711113712113713113714113715113716113717113718113719113720113721113722113723113724113725113726113727113728113729113730113731113732113733113734113735113736113737113738113739113740113741113742113743113744113745113746113747113748113749113750113751113752113753113754113755113756113757113758113759113760113761113762113763113764113765113766113767113768113769113770113771113772113773113774113775113776113777113778113779113780113781113782113783113784113785113786113787113788113789113790113791113792113793113794113795113796113797113798113799113800113801113802113803113804113805113806113807113808113809113810113811113812113813113814113815113816113817113818113819113820113821113822113823113824113825113826113827113828113829113830113831113832113833113834113835113836113837113838113839113840113841113842113843113844113845113846113847113848113849113850113851113852113853113854113855113856113857113858113859113860113861113862113863113864113865113866113867113868113869113870113871113872113873113874113875113876113877113878113879113880113881113882113883113884113885113886113887113888113889113890113891113892113893113894113895113896113897113898113899113900113901113902113903113904113905113906113907113908113909113910113911113912113913113914113915113916113917113918113919113920113921113922113923113924113925113926113927113928113929113930113931113932113933113934113935113936113937113938113939113940113941113942113943113944113945113946113947113948113949113950113951113952113953113954113955113956113957113958113959113960113961113962113963113964113965113966113967113968113969113970113971113972113973113974113975113976113977113978113979113980113981113982113983113984113985113986113987113988113989113990113991113992113993113994113995113996113997113998113999114000114001114002114003114004114005114006114007114008114009114010114011114012114013114014114015114016114017114018114019114020114021114022114023114024114025114026114027114028114029114030114031114032114033114034114035114036114037114038114039114040114041114042114043114044114045114046114047114048114049114050114051114052114053114054114055114056114057114058114059114060114061114062114063114064114065114066114067114068114069114070114071114072114073114074114075114076114077114078114079114080114081114082114083114084114085114086114087114088114089114090114091114092114093114094114095114096114097114098114099114100114101114102114103114104114105114106114107114108114109114110114111114112114113114114114115114116114117114118114119114120114121114122114123114124114125114126114127114128114129114130114131114132114133114134114135114136114137114138114139114140114141114142114143114144114145114146114147114148114149114150114151114152114153114154114155114156114157114158114159114160114161114162114163114164114165114166114167114168114169114170114171114172114173114174114175114176114177114178114179114180114181114182114183114184114185114186114187114188114189114190114191114192114193114194114195114196114197114198114199114200114201114202114203114204114205114206114207114208114209114210114211114212114213114214114215114216114217114218114219114220114221114222114223114224114225114226114227114228114229114230114231114232114233114234114235114236114237114238114239114240114241114242114243114244114245114246114247114248114249114250114251114252114253114254114255114256114257114258114259114260114261114262114263114264114265114266114267114268114269114270114271114272114273114274114275114276114277114278114279114280114281114282114283114284114285114286114287114288114289114290114291114292114293114294114295114296114297114298114299114300114301114302114303114304114305114306114307114308114309114310114311114312114313114314114315114316114317114318114319114320114321114322114323114324114325114326114327114328114329114330114331114332114333114334114335114336114337114338114339114340114341114342114343114344114345114346114347114348114349114350114351114352114353114354114355114356114357114358114359114360114361114362114363114364114365114366114367114368114369114370114371114372114373114374114375114376114377114378114379114380114381114382114383114384114385114386114387114388114389114390114391114392114393114394114395114396114397114398114399114400114401114402114403114404114405114406114407114408114409114410114411114412114413114414114415114416114417114418114419114420114421114422114423114424114425114426114427114428114429114430114431114432114433114434114435114436114437114438114439114440114441114442114443114444114445114446114447114448114449114450114451114452114453114454114455114456114457114458114459114460114461114462114463114464114465114466114467114468114469114470114471114472114473114474114475114476114477114478114479114480114481114482114483114484114485114486114487114488114489114490114491114492114493114494114495114496114497114498114499114500114501114502114503114504114505114506114507114508114509114510114511114512114513114514114515114516114517114518114519114520114521114522114523114524114525114526114527114528114529114530114531114532114533114534114535114536114537114538114539114540114541114542114543114544114545114546114547114548114549114550114551114552114553114554114555114556114557114558114559114560114561114562114563114564114565114566114567114568114569114570114571114572114573114574114575114576114577114578114579114580114581114582114583114584114585114586114587114588114589114590114591114592114593114594114595114596114597114598114599114600114601114602114603114604114605114606114607114608114609114610114611114612114613114614114615114616114617114618114619114620114621114622114623114624114625114626114627114628114629114630114631114632114633114634114635114636114637114638114639114640114641114642114643114644114645114646114647114648114649114650114651114652114653114654114655114656114657114658114659114660114661114662114663114664114665114666114667114668114669114670114671114672114673114674114675114676114677114678114679114680114681114682114683114684114685114686114687114688114689114690114691114692114693114694114695114696114697114698114699114700114701114702114703114704114705114706114707114708114709114710114711114712114713114714114715114716114717114718114719114720114721114722114723114724114725114726114727114728114729114730114731114732114733114734114735114736114737114738114739114740114741114742114743114744114745114746114747114748114749114750114751114752114753114754114755114756114757114758114759114760114761114762114763114764114765114766114767114768114769114770114771114772114773114774114775114776114777114778114779114780114781114782114783114784114785114786114787114788114789114790114791114792114793114794114795114796114797114798114799114800114801114802114803114804114805114806114807114808114809114810114811114812114813114814114815114816114817114818114819114820114821114822114823114824114825114826114827114828114829114830114831114832114833114834114835114836114837114838114839114840114841114842114843114844114845114846114847114848114849114850114851114852114853114854114855114856114857114858114859114860114861114862114863114864114865114866114867114868114869114870114871114872114873114874114875114876114877114878114879114880114881114882114883114884114885114886114887114888114889114890114891114892114893114894114895114896114897114898114899114900114901114902114903114904114905114906114907114908114909114910114911114912114913114914114915114916114917114918114919114920114921114922114923114924114925114926114927114928114929114930114931114932114933114934114935114936114937114938114939114940114941114942114943114944114945114946114947114948114949114950114951114952114953114954114955114956114957114958114959114960114961114962114963114964114965114966114967114968114969114970114971114972114973114974114975114976114977114978114979114980114981114982114983114984114985114986114987114988114989114990114991114992114993114994114995114996114997114998114999115000115001115002115003115004115005115006115007115008115009115010115011115012115013115014115015115016115017115018115019115020115021115022115023115024115025115026115027115028115029115030115031115032115033115034115035115036115037115038115039115040115041115042115043115044115045115046115047115048115049115050115051115052115053115054115055115056115057115058115059115060115061115062115063115064115065115066115067115068115069115070115071115072115073115074115075115076115077115078115079115080115081115082115083115084115085115086115087115088115089115090115091115092115093115094115095115096115097115098115099115100115101115102115103115104115105115106115107115108115109115110115111115112115113115114115115115116115117115118115119115120115121115122115123115124115125115126115127115128115129115130115131115132115133115134115135115136115137115138115139115140115141115142115143115144115145115146115147115148115149115150115151115152115153115154115155115156115157115158115159115160115161115162115163115164115165115166115167115168115169115170115171115172115173115174115175115176115177115178115179115180115181115182115183115184115185115186115187115188115189115190115191115192115193115194115195115196115197115198115199115200115201115202115203115204115205115206115207115208115209115210115211115212115213115214115215115216115217115218115219115220115221115222115223115224115225115226115227115228115229115230115231115232115233115234115235115236115237115238115239115240115241115242115243115244115245115246115247115248115249115250115251115252115253115254115255115256115257115258115259115260115261115262115263115264115265115266115267115268115269115270115271115272115273115274115275115276115277115278115279115280115281115282115283115284115285115286115287115288115289115290115291115292115293115294115295115296115297115298115299115300115301115302115303115304115305115306115307115308115309115310115311115312115313115314115315115316115317115318115319115320115321115322115323115324115325115326115327115328115329115330115331115332115333115334115335115336115337115338115339115340115341115342115343115344115345115346115347115348115349115350115351115352115353115354115355115356115357115358115359115360115361115362115363115364115365115366115367115368115369115370115371115372115373115374115375115376115377115378115379115380115381115382115383115384115385115386115387115388115389115390115391115392115393115394115395115396115397115398115399115400115401115402115403115404115405115406115407115408115409115410115411115412115413115414115415115416115417115418115419115420115421115422115423115424115425115426115427115428115429115430115431115432115433115434115435115436115437115438115439115440115441115442115443115444115445115446115447115448115449115450115451115452115453115454115455115456115457115458115459115460115461115462115463115464115465115466115467115468115469115470115471115472115473115474115475115476115477115478115479115480115481115482115483115484115485115486115487115488115489115490115491115492115493115494115495115496115497115498115499115500115501115502115503115504115505115506115507115508115509115510115511115512115513115514115515115516115517115518115519115520115521115522115523115524115525115526115527115528115529115530115531115532115533115534115535115536115537115538115539115540115541115542115543115544115545115546115547115548115549115550115551115552115553115554115555115556115557115558115559115560115561115562115563115564115565115566115567115568115569115570115571115572115573115574115575115576115577115578115579115580115581115582115583115584115585115586115587115588115589115590115591115592115593115594115595115596115597115598115599115600115601115602115603115604115605115606115607115608115609115610115611115612115613115614115615115616115617115618115619115620115621115622115623115624115625115626115627115628115629115630115631115632115633115634115635115636115637115638115639115640115641115642115643115644115645115646115647115648115649115650115651115652115653115654115655115656115657115658115659115660115661115662115663115664115665115666115667115668115669115670115671115672115673115674115675115676115677115678115679115680115681115682115683115684115685115686115687115688115689115690115691115692115693115694115695115696115697115698115699115700115701115702115703115704115705115706115707115708115709115710115711115712115713115714115715115716115717115718115719115720115721115722115723115724115725115726115727115728115729115730115731115732115733115734115735115736115737115738115739115740115741115742115743115744115745115746115747115748115749115750115751115752115753115754115755115756115757115758115759115760115761115762115763115764115765115766115767115768115769115770115771115772115773115774115775115776115777115778115779115780115781115782115783115784115785115786115787115788115789115790115791115792115793115794115795115796115797115798115799115800115801115802115803115804115805115806115807115808115809115810115811115812115813115814115815115816115817115818115819115820115821115822115823115824115825115826115827115828115829115830115831115832115833115834115835115836115837115838115839115840115841115842115843115844115845115846115847115848115849115850115851115852115853115854115855115856115857115858115859115860115861115862115863115864115865115866115867115868115869115870115871115872115873115874115875115876115877115878115879115880115881115882115883115884115885115886115887115888115889115890115891115892115893115894115895115896115897115898115899115900115901115902115903115904115905115906115907115908115909115910115911115912115913115914115915115916115917115918115919115920115921115922115923115924115925115926115927115928115929115930115931115932115933115934115935115936115937115938115939115940115941115942115943115944115945115946115947115948115949115950115951115952115953115954115955115956115957115958115959115960115961115962115963115964115965115966115967115968115969115970115971115972115973115974115975115976115977115978115979115980115981115982115983115984115985115986115987115988115989115990115991115992115993115994115995115996115997115998115999116000116001116002116003116004116005116006116007116008116009116010116011116012116013116014116015116016116017116018116019116020116021116022116023116024116025116026116027116028116029116030116031116032116033116034116035116036116037116038116039116040116041116042116043116044116045116046116047116048116049116050116051116052116053116054116055116056116057116058116059116060116061116062116063116064116065116066116067116068116069116070116071116072116073116074116075116076116077116078116079116080116081116082116083116084116085116086116087116088116089116090116091116092116093116094116095116096116097116098116099116100116101116102116103116104116105116106116107116108116109116110116111116112116113116114116115116116116117116118116119116120116121116122116123116124116125116126116127116128116129116130116131116132116133116134116135116136116137116138116139116140116141116142116143116144116145116146116147116148116149116150116151116152116153116154116155116156116157116158116159116160116161116162116163116164116165116166116167116168116169116170116171116172116173116174116175116176116177116178116179116180116181116182116183116184116185116186116187116188116189116190116191116192116193116194116195116196116197116198116199116200116201116202116203116204116205116206116207116208116209116210116211116212116213116214116215116216116217116218116219116220116221116222116223116224116225116226116227116228116229116230116231116232116233116234116235116236116237116238116239116240116241116242116243116244116245116246116247116248116249116250116251116252116253116254116255116256116257116258116259116260116261116262116263116264116265116266116267116268116269116270116271116272116273116274116275116276116277116278116279116280116281116282116283116284116285116286116287116288116289116290116291116292116293116294116295116296116297116298116299116300116301116302116303116304116305116306116307116308116309116310116311116312116313116314116315116316116317116318116319116320116321116322116323116324116325116326116327116328116329116330116331116332116333116334116335116336116337116338116339116340116341116342116343116344116345116346116347116348116349116350116351116352116353116354116355116356116357116358116359116360116361116362116363116364116365116366116367116368116369116370116371116372116373116374116375116376116377116378116379116380116381116382116383116384116385116386116387116388116389116390116391116392116393116394116395116396116397116398116399116400116401116402116403116404116405116406116407116408116409116410116411116412116413116414116415116416116417116418116419116420116421116422116423116424116425116426116427116428116429116430116431116432116433116434116435116436116437116438116439116440116441116442116443116444116445116446116447116448116449116450116451116452116453116454116455116456116457116458116459116460116461116462116463116464116465116466116467116468116469116470116471116472116473116474116475116476116477116478116479116480116481116482116483116484116485116486116487116488116489116490116491116492116493116494116495116496116497116498116499116500116501116502116503116504116505116506116507116508116509116510116511116512116513116514116515116516116517116518116519116520116521116522116523116524116525116526116527116528116529116530116531116532116533116534116535116536116537116538116539116540116541116542116543116544116545116546116547116548116549116550116551116552116553116554116555116556116557116558116559116560116561116562116563116564116565116566116567116568116569116570116571116572116573116574116575116576116577116578116579116580116581116582116583116584116585116586116587116588116589116590116591116592116593116594116595116596116597116598116599116600116601116602116603116604116605116606116607116608116609116610116611116612116613116614116615116616116617116618116619116620116621116622116623116624116625116626116627116628116629116630116631116632116633116634116635116636116637116638116639116640116641116642116643116644116645116646116647116648116649116650116651116652116653116654116655116656116657116658116659116660116661116662116663116664116665116666116667116668116669116670116671116672116673116674116675116676116677116678116679116680116681116682116683116684116685116686116687116688116689116690116691116692116693116694116695116696116697116698116699116700116701116702116703116704116705116706116707116708116709116710116711116712116713116714116715116716116717116718116719116720116721116722116723116724116725116726116727116728116729116730116731116732116733116734116735116736116737116738116739116740116741116742116743116744116745116746116747116748116749116750116751116752116753116754116755116756116757116758116759116760116761116762116763116764116765116766116767116768116769116770116771116772116773116774116775116776116777116778116779116780116781116782116783116784116785116786116787116788116789116790116791116792116793116794116795116796116797116798116799116800116801116802116803116804116805116806116807116808116809116810116811116812116813116814116815116816116817116818116819116820116821116822116823116824116825116826116827116828116829116830116831116832116833116834116835116836116837116838116839116840116841116842116843116844116845116846116847116848116849116850116851116852116853116854116855116856116857116858116859116860116861116862116863116864116865116866116867116868116869116870116871116872116873116874116875116876116877116878116879116880116881116882116883116884116885116886116887116888116889116890116891116892116893116894116895116896116897116898116899116900116901116902116903116904116905116906116907116908116909116910116911116912116913116914116915116916116917116918116919116920116921116922116923116924116925116926116927116928116929116930116931116932116933116934116935116936116937116938116939116940116941116942116943116944116945116946116947116948116949116950116951116952116953116954116955116956116957116958116959116960116961116962116963116964116965116966116967116968116969116970116971116972116973116974116975116976116977116978116979116980116981116982116983116984116985116986116987116988116989116990116991116992116993116994116995116996116997116998116999117000117001117002117003117004117005117006117007117008117009117010117011117012117013117014117015117016117017117018117019117020117021117022117023117024117025117026117027117028117029117030117031117032117033117034117035117036117037117038117039117040117041117042117043117044117045117046117047117048117049117050117051117052117053117054117055117056117057117058117059117060117061117062117063117064117065117066117067117068117069117070117071117072117073117074117075117076117077117078117079117080117081117082117083117084117085117086117087117088117089117090117091117092117093117094117095117096117097117098117099117100117101117102117103117104117105117106117107117108117109117110117111117112117113117114117115117116117117117118117119117120117121117122117123117124117125117126117127117128117129117130117131117132117133117134117135117136117137117138117139117140117141117142117143117144117145117146117147117148117149117150117151117152117153117154117155117156117157117158117159117160117161117162117163117164117165117166117167117168117169117170117171117172117173117174117175117176117177117178117179117180117181117182117183117184117185117186117187117188117189117190117191117192117193117194117195117196117197117198117199117200117201117202117203117204117205117206117207117208117209117210117211117212117213117214117215117216117217117218117219117220117221117222117223117224117225117226117227117228117229117230117231117232117233117234117235117236117237117238117239117240117241117242117243117244117245117246117247117248117249117250117251117252117253117254117255117256117257117258117259117260117261117262117263117264117265117266117267117268117269117270117271117272117273117274117275117276117277117278117279117280117281117282117283117284117285117286117287117288117289117290117291117292117293117294117295117296117297117298117299117300117301117302117303117304117305117306117307117308117309117310117311117312117313117314117315117316117317117318117319117320117321117322117323117324117325117326117327117328117329117330117331117332117333117334117335117336117337117338117339117340117341117342117343117344117345117346117347117348117349117350117351117352117353117354117355117356117357117358117359117360117361117362117363117364117365117366117367117368117369117370117371117372117373117374117375117376117377117378117379117380117381117382117383117384117385117386117387117388117389117390117391117392117393117394117395117396117397117398117399117400117401117402117403117404117405117406117407117408117409117410117411117412117413117414117415117416117417117418117419117420117421117422117423117424117425117426117427117428117429117430117431117432117433117434117435117436117437117438117439117440117441117442117443117444117445117446117447117448117449117450117451117452117453117454117455117456117457117458117459117460117461117462117463117464117465117466117467117468117469117470117471117472117473117474117475117476117477117478117479117480117481117482117483117484117485117486117487117488117489117490117491117492117493117494117495117496117497117498117499117500117501117502117503117504117505117506117507117508117509117510117511117512117513117514117515117516117517117518117519117520117521117522117523117524117525117526117527117528117529117530117531117532117533117534117535117536117537117538117539117540117541117542117543117544117545117546117547117548117549117550117551117552117553117554117555117556117557117558117559117560117561117562117563117564117565117566117567117568117569117570117571117572117573117574117575117576117577117578117579117580117581117582117583117584117585117586117587117588117589117590117591117592117593117594117595117596117597117598117599117600117601117602117603117604117605117606117607117608117609117610117611117612117613117614117615117616117617117618117619117620117621117622117623117624117625117626117627117628117629117630117631117632117633117634117635117636117637117638117639117640117641117642117643117644117645117646117647117648117649117650117651117652117653117654117655117656117657117658117659117660117661117662117663117664117665117666117667117668117669117670117671117672117673117674117675117676117677117678117679117680117681117682117683117684117685117686117687117688117689117690117691117692117693117694117695117696117697117698117699117700117701117702117703117704117705117706117707117708117709117710117711117712117713117714117715117716117717117718117719117720117721117722117723117724117725117726117727117728117729117730117731117732117733117734117735117736117737117738117739117740117741117742117743117744117745117746117747117748117749117750117751117752117753117754117755117756117757117758117759117760117761117762117763117764117765117766117767117768117769117770117771117772117773117774117775117776117777117778117779117780117781117782117783117784117785117786117787117788117789117790117791117792117793117794117795117796117797117798117799117800117801117802117803117804117805117806117807117808117809117810117811117812117813117814117815117816117817117818117819117820117821117822117823117824117825117826117827117828117829117830117831117832117833117834117835117836117837117838117839117840117841117842117843117844117845117846117847117848117849117850117851117852117853117854117855117856117857117858117859117860117861117862117863117864117865117866117867117868117869117870117871117872117873117874117875117876117877117878117879117880117881117882117883117884117885117886117887117888117889117890117891117892117893117894117895117896117897117898117899117900117901117902117903117904117905117906117907117908117909117910117911117912117913117914117915117916117917117918117919117920117921117922117923117924117925117926117927117928117929117930117931117932117933117934117935117936117937117938117939117940117941117942117943117944117945117946117947117948117949117950117951117952117953117954117955117956117957117958117959117960117961117962117963117964117965117966117967117968117969117970117971117972117973117974117975117976117977117978117979117980117981117982117983117984117985117986117987117988117989117990117991117992117993117994117995117996117997117998117999118000118001118002118003118004118005118006118007118008118009118010118011118012118013118014118015118016118017118018118019118020118021118022118023118024118025118026118027118028118029118030118031118032118033118034118035118036118037118038118039118040118041118042118043118044118045118046118047118048118049118050118051118052118053118054118055118056118057118058118059118060118061118062118063118064118065118066118067118068118069118070118071118072118073118074118075118076118077118078118079118080118081118082118083118084118085118086118087118088118089118090118091118092118093118094118095118096118097118098118099118100118101118102118103118104118105118106118107118108118109118110118111118112118113118114118115118116118117118118118119118120118121118122118123118124118125118126118127118128118129118130118131118132118133118134118135118136118137118138118139118140118141118142118143118144118145118146118147118148118149118150118151118152118153118154118155118156118157118158118159118160118161118162118163118164118165118166118167118168118169118170118171118172118173118174118175118176118177118178118179118180118181118182118183118184118185118186118187118188118189118190118191118192118193118194118195118196118197118198118199118200118201118202118203118204118205118206118207118208118209118210118211118212118213118214118215118216118217118218118219118220118221118222118223118224118225118226118227118228118229118230118231118232118233118234118235118236118237118238118239118240118241118242118243118244118245118246118247118248118249118250118251118252118253118254118255118256118257118258118259118260118261118262118263118264118265118266118267118268118269118270118271118272118273118274118275118276118277118278118279118280118281118282118283118284118285118286118287118288118289118290118291118292118293118294118295118296118297118298118299118300118301118302118303118304118305118306118307118308118309118310118311118312118313118314118315118316118317118318118319118320118321118322118323118324118325118326118327118328118329118330118331118332118333118334118335118336118337118338118339118340118341118342118343118344118345118346118347118348118349118350118351118352118353118354118355118356118357118358118359118360118361118362118363118364118365118366118367118368118369118370118371118372118373118374118375118376118377118378118379118380118381118382118383118384118385118386118387118388118389118390118391118392118393118394118395118396118397118398118399118400118401118402118403118404118405118406118407118408118409118410118411118412118413118414118415118416118417118418118419118420118421118422118423118424118425118426118427118428118429118430118431118432118433118434118435118436118437118438118439118440118441118442118443118444118445118446118447118448118449118450118451118452118453118454118455118456118457118458118459118460118461118462118463118464118465118466118467118468118469118470118471118472118473118474118475118476118477118478118479118480118481118482118483118484118485118486118487118488118489118490118491118492118493118494118495118496118497118498118499118500118501118502118503118504118505118506118507118508118509118510118511118512118513118514118515118516118517118518118519118520118521118522118523118524118525118526118527118528118529118530118531118532118533118534118535118536118537118538118539118540118541118542118543118544118545118546118547118548118549118550118551118552118553118554118555118556118557118558118559118560118561118562118563118564118565118566118567118568118569118570118571118572118573118574118575118576118577118578118579118580118581118582118583118584118585118586118587118588118589118590118591118592118593118594118595118596118597118598118599118600118601118602118603118604118605118606118607118608118609118610118611118612118613118614118615118616118617118618118619118620118621118622118623118624118625118626118627118628118629118630118631118632118633118634118635118636118637118638118639118640118641118642118643118644118645118646118647118648118649118650118651118652118653118654118655118656118657118658118659118660118661118662118663118664118665118666118667118668118669118670118671118672118673118674118675118676118677118678118679118680118681118682118683118684118685118686118687118688118689118690118691118692118693118694118695118696118697118698118699118700118701118702118703118704118705118706118707118708118709118710118711118712118713118714118715118716118717118718118719118720118721118722118723118724118725118726118727118728118729118730118731118732118733118734118735118736118737118738118739118740118741118742118743118744118745118746118747118748118749118750118751118752118753118754118755118756118757118758118759118760118761118762118763118764118765118766118767118768118769118770118771118772118773118774118775118776118777118778118779118780118781118782118783118784118785118786118787118788118789118790118791118792118793118794118795118796118797118798118799118800118801118802118803118804118805118806118807118808118809118810118811118812118813118814118815118816118817118818118819118820118821118822118823118824118825118826118827118828118829118830118831118832118833118834118835118836118837118838118839118840118841118842118843118844118845118846118847118848118849118850118851118852118853118854118855118856118857118858118859118860118861118862118863118864118865118866118867118868118869118870118871118872118873118874118875118876118877118878118879118880118881118882118883118884118885118886118887118888118889118890118891118892118893118894118895118896118897118898118899118900118901118902118903118904118905118906118907118908118909118910118911118912118913118914118915118916118917118918118919118920118921118922118923118924118925118926118927118928118929118930118931118932118933118934118935118936118937118938118939118940118941118942118943118944118945118946118947118948118949118950118951118952118953118954118955118956118957118958118959118960118961118962118963118964118965118966118967118968118969118970118971118972118973118974118975118976118977118978118979118980118981118982118983118984118985118986118987118988118989118990118991118992118993118994118995118996118997118998118999119000119001119002119003119004119005119006119007119008119009119010119011119012119013119014119015119016119017119018119019119020119021119022119023119024119025119026119027119028119029119030119031119032119033119034119035119036119037119038119039119040119041119042119043119044119045119046119047119048119049119050119051119052119053119054119055119056119057119058119059119060119061119062119063119064119065119066119067119068119069119070119071119072119073119074119075119076119077119078119079119080119081119082119083119084119085119086119087119088119089119090119091119092119093119094119095119096119097119098119099119100119101119102119103119104119105119106119107119108119109119110119111119112119113119114119115119116119117119118119119119120119121119122119123119124119125119126119127119128119129119130119131119132119133119134119135119136119137119138119139119140119141119142119143119144119145119146119147119148119149119150119151119152119153119154119155119156119157119158119159119160119161119162119163119164119165119166119167119168119169119170119171119172119173119174119175119176119177119178119179119180119181119182119183119184119185119186119187119188119189119190119191119192119193119194119195119196119197119198119199119200119201119202119203119204119205119206119207119208119209119210119211119212119213119214119215119216119217119218119219119220119221119222119223119224119225119226119227119228119229119230119231119232119233119234119235119236119237119238119239119240119241119242119243119244119245119246119247119248119249119250119251119252119253119254119255119256119257119258119259119260119261119262119263119264119265119266119267119268119269119270119271119272119273119274119275119276119277119278119279119280119281119282119283119284119285119286119287119288119289119290119291119292119293119294119295119296119297119298119299119300119301119302119303119304119305119306119307119308119309119310119311119312119313119314119315119316119317119318119319119320119321119322119323119324119325119326119327119328119329119330119331119332119333119334119335119336119337119338119339119340119341119342119343119344119345119346119347119348119349119350119351119352119353119354119355119356119357119358119359119360119361119362119363119364119365119366119367119368119369119370119371119372119373119374119375119376119377119378119379119380119381119382119383119384119385119386119387119388119389119390119391119392119393119394119395119396119397119398119399119400119401119402119403119404119405119406119407119408119409119410119411119412119413119414119415119416119417119418119419119420119421119422119423119424119425119426119427119428119429119430119431119432119433119434119435119436119437119438119439119440119441119442119443119444119445119446119447119448119449119450119451119452119453119454119455119456119457119458119459119460119461119462119463119464119465119466119467119468119469119470119471119472119473119474119475119476119477119478119479119480119481119482119483119484119485119486119487119488119489119490119491119492119493119494119495119496119497119498119499119500119501119502119503119504119505119506119507119508119509119510119511119512119513119514119515119516119517119518119519119520119521119522119523119524119525119526119527119528119529119530119531119532119533119534119535119536119537119538119539119540119541119542119543119544119545119546119547119548119549119550119551119552119553119554119555119556119557119558119559119560119561119562119563119564119565119566119567119568119569119570119571119572119573119574119575119576119577119578119579119580119581119582119583119584119585119586119587119588119589119590119591119592119593119594119595119596119597119598119599119600119601119602119603119604119605119606119607119608119609119610119611119612119613119614119615119616119617119618119619119620119621119622119623119624119625119626119627119628119629119630119631119632119633119634119635119636119637119638119639119640119641119642119643119644119645119646119647119648119649119650119651119652119653119654119655119656119657119658119659119660119661119662119663119664119665119666119667119668119669119670119671119672119673119674119675119676119677119678119679119680119681119682119683119684119685119686119687119688119689119690119691119692119693119694119695119696119697119698119699119700119701119702119703119704119705119706119707119708119709119710119711119712119713119714119715119716119717119718119719119720119721119722119723119724119725119726119727119728119729119730119731119732119733119734119735119736119737119738119739119740119741119742119743119744119745119746119747119748119749119750119751119752119753119754119755119756119757119758119759119760119761119762119763119764119765119766119767119768119769119770119771119772119773119774119775119776119777119778119779119780119781119782119783119784119785119786119787119788119789119790119791119792119793119794119795119796119797119798119799119800119801119802119803119804119805119806119807119808119809119810119811119812119813119814119815119816119817119818119819119820119821119822119823119824119825119826119827119828119829119830119831119832119833119834119835119836119837119838119839119840119841119842119843119844119845119846119847119848119849119850119851119852119853119854119855119856119857119858119859119860119861119862119863119864119865119866119867119868119869119870119871119872119873119874119875119876119877119878119879119880119881119882119883119884119885119886119887119888119889119890119891119892119893119894119895119896119897119898119899119900119901119902119903119904119905119906119907119908119909119910119911119912119913119914119915119916119917119918119919119920119921119922119923119924119925119926119927119928119929119930119931119932119933119934119935119936119937119938119939119940119941119942119943119944119945119946119947119948119949119950119951119952119953119954119955119956119957119958119959119960119961119962119963119964119965119966119967119968119969119970119971119972119973119974119975119976119977119978119979119980119981119982119983119984119985119986119987119988119989119990119991119992119993119994119995119996119997119998119999120000120001120002120003120004120005120006120007120008120009120010120011120012120013120014120015120016120017120018120019120020120021120022120023120024120025120026120027120028120029120030120031120032120033120034120035120036120037120038120039120040120041120042120043120044120045120046120047120048120049120050120051120052120053120054120055120056120057120058120059120060120061120062120063120064120065120066120067120068120069120070120071120072120073120074120075120076120077120078120079120080120081120082120083120084120085120086120087120088120089120090120091120092120093120094120095120096120097120098120099120100120101120102120103120104120105120106120107120108120109120110120111120112120113120114120115120116120117120118120119120120120121120122120123120124120125120126120127120128120129120130120131120132120133120134120135120136120137120138120139120140120141120142120143120144120145120146120147120148120149120150120151120152120153120154120155120156120157120158120159120160120161120162120163120164120165120166120167120168120169120170120171120172120173120174120175120176120177120178120179120180120181120182120183120184120185120186120187120188120189120190120191120192120193120194120195120196120197120198120199120200120201120202120203120204120205120206120207120208120209120210120211120212120213120214120215120216120217120218120219120220120221120222120223120224120225120226120227120228120229120230120231120232120233120234120235120236120237120238120239120240120241120242120243120244120245120246120247120248120249120250120251120252120253120254120255120256120257120258120259120260120261120262120263120264120265120266120267120268120269120270120271120272120273120274120275120276120277120278120279120280120281120282120283120284120285120286120287120288120289120290120291120292120293120294120295120296120297120298120299120300120301120302120303120304120305120306120307120308120309120310120311120312120313120314120315120316120317120318120319120320120321120322120323120324120325120326120327120328120329120330120331120332120333120334120335120336120337120338120339120340120341120342120343120344120345120346120347120348120349120350120351120352120353120354120355120356120357120358120359120360120361120362120363120364120365120366120367120368120369120370120371120372120373120374120375120376120377120378120379120380120381120382120383120384120385120386120387120388120389120390120391120392120393120394120395120396120397120398120399120400120401120402120403120404120405120406120407120408120409120410120411120412120413120414120415120416120417120418120419120420120421120422120423120424120425120426120427120428120429120430120431120432120433120434120435120436120437120438120439120440120441120442120443120444120445120446120447120448120449120450120451120452120453120454120455120456120457120458120459120460120461120462120463120464120465120466120467120468120469120470120471120472120473120474120475120476120477120478120479120480120481120482120483120484120485120486120487120488120489120490120491120492120493120494120495120496120497120498120499120500120501120502120503120504120505120506120507120508120509120510120511120512120513120514120515120516120517120518120519120520120521120522120523120524120525120526120527120528120529120530120531120532120533120534120535120536120537120538120539120540120541120542120543120544120545120546120547120548120549120550120551120552120553120554120555120556120557120558120559120560120561120562120563120564120565120566120567120568120569120570120571120572120573120574120575120576120577120578120579120580120581120582120583120584120585120586120587120588120589120590120591120592120593120594120595120596120597120598120599120600120601120602120603120604120605120606120607120608120609120610120611120612120613120614120615120616120617120618120619120620120621120622120623120624120625120626120627120628120629120630120631120632120633120634120635120636120637120638120639120640120641120642120643120644120645120646120647120648120649120650120651120652120653120654120655120656120657120658120659120660120661120662120663120664120665120666120667120668120669120670120671120672120673120674120675120676120677120678120679120680120681120682120683120684120685120686120687120688120689120690120691120692120693120694120695120696120697120698120699120700120701120702120703120704120705120706120707120708120709120710120711120712120713120714120715120716120717120718120719120720120721120722120723120724120725120726120727120728120729120730120731120732120733120734120735120736120737120738120739120740120741120742120743120744120745120746120747120748120749120750120751120752120753120754120755120756120757120758120759120760120761120762120763120764120765120766120767120768120769120770120771120772120773120774120775120776120777120778120779120780120781120782120783120784120785120786120787120788120789120790120791120792120793120794120795120796120797120798120799120800120801120802120803120804120805120806120807120808120809120810120811120812120813120814120815120816120817120818120819120820120821120822120823120824120825120826120827120828120829120830120831120832120833120834120835120836120837120838120839120840120841120842120843120844120845120846120847120848120849120850120851120852120853120854120855120856120857120858120859120860120861120862120863120864120865120866120867120868120869120870120871120872120873120874120875120876120877120878120879120880120881120882120883120884120885120886120887120888120889120890120891120892120893120894120895120896120897120898120899120900120901120902120903120904120905120906120907120908120909120910120911120912120913120914120915120916120917120918120919120920120921120922120923120924120925120926120927120928120929120930120931120932120933120934120935120936120937120938120939120940120941120942120943120944120945120946120947120948120949120950120951120952120953120954120955120956120957120958120959120960120961120962120963120964120965120966120967120968120969120970120971120972120973120974120975120976120977120978120979120980120981120982120983120984120985120986120987120988120989120990120991120992120993120994120995120996120997120998120999121000121001121002121003121004121005121006121007121008121009121010121011121012121013121014121015121016121017121018121019121020121021121022121023121024121025121026121027121028121029121030121031121032121033121034121035121036121037121038121039121040121041121042121043121044121045121046121047121048121049121050121051121052121053121054121055121056121057121058121059121060121061121062121063121064121065121066121067121068121069121070121071121072121073121074121075121076121077121078121079121080121081121082121083121084121085121086121087121088121089121090121091121092121093121094121095121096121097121098121099121100121101121102121103121104121105121106121107121108121109121110121111121112121113121114121115121116121117121118121119121120121121121122121123121124121125121126121127121128121129121130121131121132121133121134121135121136121137121138121139121140121141121142121143121144121145121146121147121148121149121150121151121152121153121154121155121156121157121158121159121160121161121162121163121164121165121166121167121168121169121170121171121172121173121174121175121176121177121178121179121180121181121182121183121184121185121186121187121188121189121190121191121192121193121194121195121196121197121198121199121200121201121202121203121204121205121206121207121208121209121210121211121212121213121214121215121216121217121218121219121220121221121222121223121224121225121226121227121228121229121230121231121232121233121234121235121236121237121238121239121240121241121242121243121244121245121246121247121248121249121250121251121252121253121254121255121256121257121258121259121260121261121262121263121264121265121266121267121268121269121270121271121272121273121274121275121276121277121278121279121280121281121282121283121284121285121286121287121288121289121290121291121292121293121294121295121296121297121298121299121300121301121302121303121304121305121306121307121308121309121310121311121312121313121314121315121316121317121318121319121320121321121322121323121324121325121326121327121328121329121330121331121332121333121334121335121336121337121338121339121340121341121342121343121344121345121346121347121348121349121350121351121352121353121354121355121356121357121358121359121360121361121362121363121364121365121366121367121368121369121370121371121372121373121374121375121376121377121378121379121380121381121382121383121384121385121386121387121388121389121390121391121392121393121394121395121396121397121398121399121400121401121402121403121404121405121406121407121408121409121410121411121412121413121414121415121416121417121418121419121420121421121422121423121424121425121426121427121428121429121430121431121432121433121434121435121436121437121438121439121440121441121442121443121444121445121446121447121448121449121450121451121452121453121454121455121456121457121458121459121460121461121462121463121464121465121466121467121468121469121470121471121472121473121474121475121476121477121478121479121480121481121482121483121484121485121486121487121488121489121490121491121492121493121494121495121496121497121498121499121500121501121502121503121504121505121506121507121508121509121510121511121512121513121514121515121516121517121518121519121520121521121522121523121524121525121526121527121528121529121530121531121532121533121534121535121536121537121538121539121540121541121542121543121544121545121546121547121548121549121550121551121552121553121554121555121556121557121558121559121560121561121562121563121564121565121566121567121568121569121570121571121572121573121574121575121576121577121578121579121580121581121582121583121584121585121586121587121588121589121590121591121592121593121594121595121596121597121598121599121600121601121602121603121604121605121606121607121608121609121610121611121612121613121614121615121616121617121618121619121620121621121622121623121624121625121626121627121628121629121630121631121632121633121634121635121636121637121638121639121640121641121642121643121644121645121646121647121648121649121650121651121652121653121654121655121656121657121658121659121660121661121662121663121664121665121666121667121668121669121670121671121672121673121674121675121676121677121678121679121680121681121682121683121684121685121686121687121688121689121690121691121692121693121694121695121696121697121698121699121700121701121702121703121704121705121706121707121708121709121710121711121712121713121714121715121716121717121718121719121720121721121722121723121724121725121726121727121728121729121730121731121732121733121734121735121736121737121738121739121740121741121742121743121744121745121746121747121748121749121750121751121752121753121754121755121756121757121758121759121760121761121762121763121764121765121766121767121768121769121770121771121772121773121774121775121776121777121778121779121780121781121782121783121784121785121786121787121788121789121790121791121792121793121794121795121796121797121798121799121800121801121802121803121804121805121806121807121808121809121810121811121812121813121814121815121816121817121818121819121820121821121822121823121824121825121826121827121828121829121830121831121832121833121834121835121836121837121838121839121840121841121842121843121844121845121846121847121848121849121850121851121852121853121854121855121856121857121858121859121860121861121862121863121864121865121866121867121868121869121870121871121872121873121874121875121876121877121878121879121880121881121882121883121884121885121886121887121888121889121890121891121892121893121894121895121896121897121898121899121900121901121902121903121904121905121906121907121908121909121910121911121912121913121914121915121916121917121918121919121920121921121922121923121924121925121926121927121928121929121930121931121932121933121934121935121936121937121938121939121940121941121942121943121944121945121946121947121948121949121950121951121952121953121954121955121956121957121958121959121960121961121962121963121964121965121966121967121968121969121970121971121972121973121974121975121976121977121978121979121980121981121982121983121984121985121986121987121988121989121990121991121992121993121994121995121996121997121998121999122000122001122002122003122004122005122006122007122008122009122010122011122012122013122014122015122016122017122018122019122020122021122022122023122024122025122026122027122028122029122030122031122032122033122034122035122036122037122038122039122040122041122042122043122044122045122046122047122048122049122050122051122052122053122054122055122056122057122058122059122060122061122062122063122064122065122066122067122068122069122070122071122072122073122074122075122076122077122078122079122080122081122082122083122084122085122086122087122088122089122090122091122092122093122094122095122096122097122098122099122100122101122102122103122104122105122106122107122108122109122110122111122112122113122114122115122116122117122118122119122120122121122122122123122124122125122126122127122128122129122130122131122132122133122134122135122136122137122138122139122140122141122142122143122144122145122146122147122148122149122150122151122152122153122154122155122156122157122158122159122160122161122162122163122164122165122166122167122168122169122170122171122172122173122174122175122176122177122178122179122180122181122182122183122184122185122186122187122188122189122190122191122192122193122194122195122196122197122198122199122200122201122202122203122204122205122206122207122208122209122210122211122212122213122214122215122216122217122218122219122220122221122222122223122224122225122226122227122228122229122230122231122232122233122234122235122236122237122238122239122240122241122242122243122244122245122246122247122248122249122250122251122252122253122254122255122256122257122258122259122260122261122262122263122264122265122266122267122268122269122270122271122272122273122274122275122276122277122278122279122280122281122282122283122284122285122286122287122288122289122290122291122292122293122294122295122296122297122298122299122300122301122302122303122304122305122306122307122308122309122310122311122312122313122314122315122316122317122318122319122320122321122322122323122324122325122326122327122328122329122330122331122332122333122334122335122336122337122338122339122340122341122342122343122344122345122346122347122348122349122350122351122352122353122354122355122356122357122358122359122360122361122362122363122364122365122366122367122368122369122370122371122372122373122374122375122376122377122378122379122380122381122382122383122384122385122386122387122388122389122390122391122392122393122394122395122396122397122398122399122400122401122402122403122404122405122406122407122408122409122410122411122412122413122414122415122416122417122418122419122420122421122422122423122424122425122426122427122428122429122430122431122432122433122434122435122436122437122438122439122440122441122442122443122444122445122446122447122448122449122450122451122452122453122454122455122456122457122458122459122460122461122462122463122464122465122466122467122468122469122470122471122472122473122474122475122476122477122478122479122480122481122482122483122484122485122486122487122488122489122490122491122492122493122494122495122496122497122498122499122500122501122502122503122504122505122506122507122508122509122510122511122512122513122514122515122516122517122518122519122520122521122522122523122524122525122526122527122528122529122530122531122532122533122534122535122536122537122538122539122540122541122542122543122544122545122546122547122548122549122550122551122552122553122554122555122556122557122558122559122560122561122562122563122564122565122566122567122568122569122570122571122572122573122574122575122576122577122578122579122580122581122582122583122584122585122586122587122588122589122590122591122592122593122594122595122596122597122598122599122600122601122602122603122604122605122606122607122608122609122610122611122612122613122614122615122616122617122618122619122620122621122622122623122624122625122626122627122628122629122630122631122632122633122634122635122636122637122638122639122640122641122642122643122644122645122646122647122648122649122650122651122652122653122654122655122656122657122658122659122660122661122662122663122664122665122666122667122668122669122670122671122672122673122674122675122676122677122678122679122680122681122682122683122684122685122686122687122688122689122690122691122692122693122694122695122696122697122698122699122700122701122702122703122704122705122706122707122708122709122710122711122712122713122714122715122716122717122718122719122720122721122722122723122724122725122726122727122728122729122730122731122732122733122734122735122736122737122738122739122740122741122742122743122744122745122746122747122748122749122750122751122752122753122754122755122756122757122758122759122760122761122762122763122764122765122766122767122768122769122770122771122772122773122774122775122776122777122778122779122780122781122782122783122784122785122786122787122788122789122790122791122792122793122794122795122796122797122798122799122800122801122802122803122804122805122806122807122808122809122810122811122812122813122814122815122816122817122818122819122820122821122822122823122824122825122826122827122828122829122830122831122832122833122834122835122836122837122838122839122840122841122842122843122844122845122846122847122848122849122850122851122852122853122854122855122856122857122858122859122860122861122862122863122864122865122866122867122868122869122870122871122872122873122874122875122876122877122878122879122880122881122882122883122884122885122886122887122888122889122890122891122892122893122894122895122896122897122898122899122900122901122902122903122904122905122906122907122908122909122910122911122912122913122914122915122916122917122918122919122920122921122922122923122924122925122926122927122928122929122930122931122932122933122934122935122936122937122938122939122940122941122942122943122944122945122946122947122948122949122950122951122952122953122954122955122956122957122958122959122960122961122962122963122964122965122966122967122968122969122970122971122972122973122974122975122976122977122978122979122980122981122982122983122984122985122986122987122988122989122990122991122992122993122994122995122996122997122998122999123000123001123002123003123004123005123006123007123008123009123010123011123012123013123014123015123016123017123018123019123020123021123022123023123024123025123026123027123028123029123030123031123032123033123034123035123036123037123038123039123040123041123042123043123044123045123046123047123048123049123050123051123052123053123054123055123056123057123058123059123060123061123062123063123064123065123066123067123068123069123070123071123072123073123074123075123076123077123078123079123080123081123082123083123084123085123086123087123088123089123090123091123092
  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 = 16);
  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__(19); } catch(e) {}
  90. try { OIMO = OIMO || __webpack_require__(20); } catch(e) {}
  91. try { earcut = earcut || __webpack_require__(21); } catch(e) {}
  92. module.exports = factory(CANNON,OIMO,earcut);
  93. } else if(typeof define === 'function' && define.amd) {
  94. if(require.specified && require.specified("cannon")) amdDependencies.push("cannon");
  95. if(require.specified && require.specified("oimo")) amdDependencies.push("oimo");
  96. if(require.specified && require.specified("earcut")) amdDependencies.push("earcut");
  97. define("babylonjs", amdDependencies, factory);
  98. } else if(typeof exports === 'object') {
  99. try { CANNON = CANNON || require("cannon"); } catch(e) {}
  100. try { OIMO = OIMO || require("oimo"); } catch(e) {}
  101. try { earcut = earcut || require("earcut"); } catch(e) {}
  102. exports["babylonjs"] = factory(CANNON,OIMO,earcut);
  103. } else {
  104. root["BABYLON"] = factory(CANNON,OIMO,earcut);
  105. }
  106. })(this, function(CANNON,OIMO,earcut) {
  107. CANNON = CANNON || this.CANNON;
  108. OIMO = OIMO || this.OIMO;
  109. earcut = earcut || this.earcut;
  110. var __decorate=this&&this.__decorate||function(e,t,r,c){var o,f=arguments.length,n=f<3?t:null===c?c=Object.getOwnPropertyDescriptor(t,r):c;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)n=Reflect.decorate(e,t,r,c);else for(var l=e.length-1;l>=0;l--)(o=e[l])&&(n=(f<3?o(n):f>3?o(t,r,n):o(t,r))||n);return f>3&&n&&Object.defineProperty(t,r,n),n};
  111. var __extends=this&&this.__extends||function(){var t=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,o){t.__proto__=o}||function(t,o){for(var n in o)o.hasOwnProperty(n)&&(t[n]=o[n])};return function(o,n){function r(){this.constructor=o}t(o,n),o.prototype=null===n?Object.create(n):(r.prototype=n.prototype,new r)}}();
  112. var BABYLON;
  113. (function (BABYLON) {
  114. /**
  115. * EffectFallbacks can be used to add fallbacks (properties to disable) to certain properties when desired to improve performance.
  116. * (Eg. Start at high quality with reflection and fog, if fps is low, remove reflection, if still low remove fog)
  117. */
  118. var EffectFallbacks = /** @class */ (function () {
  119. function EffectFallbacks() {
  120. this._defines = {};
  121. this._currentRank = 32;
  122. this._maxRank = -1;
  123. }
  124. /**
  125. * Removes the fallback from the bound mesh.
  126. */
  127. EffectFallbacks.prototype.unBindMesh = function () {
  128. this._mesh = null;
  129. };
  130. /**
  131. * Adds a fallback on the specified property.
  132. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  133. * @param define The name of the define in the shader
  134. */
  135. EffectFallbacks.prototype.addFallback = function (rank, define) {
  136. if (!this._defines[rank]) {
  137. if (rank < this._currentRank) {
  138. this._currentRank = rank;
  139. }
  140. if (rank > this._maxRank) {
  141. this._maxRank = rank;
  142. }
  143. this._defines[rank] = new Array();
  144. }
  145. this._defines[rank].push(define);
  146. };
  147. /**
  148. * Sets the mesh to use CPU skinning when needing to fallback.
  149. * @param rank The rank of the fallback (Lower ranks will be fallbacked to first)
  150. * @param mesh The mesh to use the fallbacks.
  151. */
  152. EffectFallbacks.prototype.addCPUSkinningFallback = function (rank, mesh) {
  153. this._mesh = mesh;
  154. if (rank < this._currentRank) {
  155. this._currentRank = rank;
  156. }
  157. if (rank > this._maxRank) {
  158. this._maxRank = rank;
  159. }
  160. };
  161. Object.defineProperty(EffectFallbacks.prototype, "isMoreFallbacks", {
  162. /**
  163. * Checks to see if more fallbacks are still availible.
  164. */
  165. get: function () {
  166. return this._currentRank <= this._maxRank;
  167. },
  168. enumerable: true,
  169. configurable: true
  170. });
  171. /**
  172. * Removes the defines that shoould be removed when falling back.
  173. * @param currentDefines defines the current define statements for the shader.
  174. * @param effect defines the current effect we try to compile
  175. * @returns The resulting defines with defines of the current rank removed.
  176. */
  177. EffectFallbacks.prototype.reduce = function (currentDefines, effect) {
  178. // First we try to switch to CPU skinning
  179. if (this._mesh && this._mesh.computeBonesUsingShaders && this._mesh.numBoneInfluencers > 0 && this._mesh.material) {
  180. this._mesh.computeBonesUsingShaders = false;
  181. currentDefines = currentDefines.replace("#define NUM_BONE_INFLUENCERS " + this._mesh.numBoneInfluencers, "#define NUM_BONE_INFLUENCERS 0");
  182. effect._bonesComputationForcedToCPU = true;
  183. var scene = this._mesh.getScene();
  184. for (var index = 0; index < scene.meshes.length; index++) {
  185. var otherMesh = scene.meshes[index];
  186. if (!otherMesh.material) {
  187. continue;
  188. }
  189. if (!otherMesh.computeBonesUsingShaders || otherMesh.numBoneInfluencers === 0) {
  190. continue;
  191. }
  192. if (otherMesh.material.getEffect() === effect) {
  193. otherMesh.computeBonesUsingShaders = false;
  194. }
  195. else if (otherMesh.subMeshes) {
  196. for (var _i = 0, _a = otherMesh.subMeshes; _i < _a.length; _i++) {
  197. var subMesh = _a[_i];
  198. var subMeshEffect = subMesh.effect;
  199. if (subMeshEffect === effect) {
  200. otherMesh.computeBonesUsingShaders = false;
  201. break;
  202. }
  203. }
  204. }
  205. }
  206. }
  207. else {
  208. var currentFallbacks = this._defines[this._currentRank];
  209. if (currentFallbacks) {
  210. for (var index = 0; index < currentFallbacks.length; index++) {
  211. currentDefines = currentDefines.replace("#define " + currentFallbacks[index], "");
  212. }
  213. }
  214. this._currentRank++;
  215. }
  216. return currentDefines;
  217. };
  218. return EffectFallbacks;
  219. }());
  220. BABYLON.EffectFallbacks = EffectFallbacks;
  221. /**
  222. * Options to be used when creating an effect.
  223. */
  224. var EffectCreationOptions = /** @class */ (function () {
  225. function EffectCreationOptions() {
  226. }
  227. return EffectCreationOptions;
  228. }());
  229. BABYLON.EffectCreationOptions = EffectCreationOptions;
  230. /**
  231. * Effect containing vertex and fragment shader that can be executed on an object.
  232. */
  233. var Effect = /** @class */ (function () {
  234. /**
  235. * Instantiates an effect.
  236. * An effect can be used to create/manage/execute vertex and fragment shaders.
  237. * @param baseName Name of the effect.
  238. * @param attributesNamesOrOptions List of attribute names that will be passed to the shader or set of all options to create the effect.
  239. * @param uniformsNamesOrEngine List of uniform variable names that will be passed to the shader or the engine that will be used to render effect.
  240. * @param samplers List of sampler variables that will be passed to the shader.
  241. * @param engine Engine to be used to render the effect
  242. * @param defines Define statements to be added to the shader.
  243. * @param fallbacks Possible fallbacks for this effect to improve performance when needed.
  244. * @param onCompiled Callback that will be called when the shader is compiled.
  245. * @param onError Callback that will be called if an error occurs during shader compilation.
  246. * @param indexParameters Parameters to be used with Babylons include syntax to iterate over an array (eg. {lights: 10})
  247. */
  248. function Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, engine, defines, fallbacks, onCompiled, onError, indexParameters) {
  249. if (samplers === void 0) { samplers = null; }
  250. if (defines === void 0) { defines = null; }
  251. if (fallbacks === void 0) { fallbacks = null; }
  252. if (onCompiled === void 0) { onCompiled = null; }
  253. if (onError === void 0) { onError = null; }
  254. var _this = this;
  255. /**
  256. * Unique ID of the effect.
  257. */
  258. this.uniqueId = 0;
  259. /**
  260. * Observable that will be called when the shader is compiled.
  261. */
  262. this.onCompileObservable = new BABYLON.Observable();
  263. /**
  264. * Observable that will be called if an error occurs during shader compilation.
  265. */
  266. this.onErrorObservable = new BABYLON.Observable();
  267. /**
  268. * Observable that will be called when effect is bound.
  269. */
  270. this.onBindObservable = new BABYLON.Observable();
  271. /** @hidden */
  272. this._bonesComputationForcedToCPU = false;
  273. this._uniformBuffersNames = {};
  274. this._isReady = false;
  275. this._compilationError = "";
  276. this.name = baseName;
  277. if (attributesNamesOrOptions.attributes) {
  278. var options = attributesNamesOrOptions;
  279. this._engine = uniformsNamesOrEngine;
  280. this._attributesNames = options.attributes;
  281. this._uniformsNames = options.uniformsNames.concat(options.samplers);
  282. this._samplers = options.samplers.slice();
  283. this.defines = options.defines;
  284. this.onError = options.onError;
  285. this.onCompiled = options.onCompiled;
  286. this._fallbacks = options.fallbacks;
  287. this._indexParameters = options.indexParameters;
  288. this._transformFeedbackVaryings = options.transformFeedbackVaryings;
  289. if (options.uniformBuffersNames) {
  290. for (var i = 0; i < options.uniformBuffersNames.length; i++) {
  291. this._uniformBuffersNames[options.uniformBuffersNames[i]] = i;
  292. }
  293. }
  294. }
  295. else {
  296. this._engine = engine;
  297. this.defines = defines;
  298. this._uniformsNames = uniformsNamesOrEngine.concat(samplers);
  299. this._samplers = samplers ? samplers.slice() : [];
  300. this._attributesNames = attributesNamesOrOptions;
  301. this.onError = onError;
  302. this.onCompiled = onCompiled;
  303. this._indexParameters = indexParameters;
  304. this._fallbacks = fallbacks;
  305. }
  306. this.uniqueId = Effect._uniqueIdSeed++;
  307. var vertexSource;
  308. var fragmentSource;
  309. if (baseName.vertexElement) {
  310. vertexSource = document.getElementById(baseName.vertexElement);
  311. if (!vertexSource) {
  312. vertexSource = baseName.vertexElement;
  313. }
  314. }
  315. else {
  316. vertexSource = baseName.vertex || baseName;
  317. }
  318. if (baseName.fragmentElement) {
  319. fragmentSource = document.getElementById(baseName.fragmentElement);
  320. if (!fragmentSource) {
  321. fragmentSource = baseName.fragmentElement;
  322. }
  323. }
  324. else {
  325. fragmentSource = baseName.fragment || baseName;
  326. }
  327. this._loadVertexShader(vertexSource, function (vertexCode) {
  328. _this._processIncludes(vertexCode, function (vertexCodeWithIncludes) {
  329. _this._processShaderConversion(vertexCodeWithIncludes, false, function (migratedVertexCode) {
  330. _this._loadFragmentShader(fragmentSource, function (fragmentCode) {
  331. _this._processIncludes(fragmentCode, function (fragmentCodeWithIncludes) {
  332. _this._processShaderConversion(fragmentCodeWithIncludes, true, function (migratedFragmentCode) {
  333. if (baseName) {
  334. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  335. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  336. _this._vertexSourceCode = "#define SHADER_NAME vertex:" + vertex + "\n" + migratedVertexCode;
  337. _this._fragmentSourceCode = "#define SHADER_NAME fragment:" + fragment + "\n" + migratedFragmentCode;
  338. }
  339. else {
  340. _this._vertexSourceCode = migratedVertexCode;
  341. _this._fragmentSourceCode = migratedFragmentCode;
  342. }
  343. _this._prepareEffect();
  344. });
  345. });
  346. });
  347. });
  348. });
  349. });
  350. }
  351. Object.defineProperty(Effect.prototype, "key", {
  352. /**
  353. * Unique key for this effect
  354. */
  355. get: function () {
  356. return this._key;
  357. },
  358. enumerable: true,
  359. configurable: true
  360. });
  361. /**
  362. * If the effect has been compiled and prepared.
  363. * @returns if the effect is compiled and prepared.
  364. */
  365. Effect.prototype.isReady = function () {
  366. return this._isReady;
  367. };
  368. /**
  369. * The engine the effect was initialized with.
  370. * @returns the engine.
  371. */
  372. Effect.prototype.getEngine = function () {
  373. return this._engine;
  374. };
  375. /**
  376. * The compiled webGL program for the effect
  377. * @returns the webGL program.
  378. */
  379. Effect.prototype.getProgram = function () {
  380. return this._program;
  381. };
  382. /**
  383. * The set of names of attribute variables for the shader.
  384. * @returns An array of attribute names.
  385. */
  386. Effect.prototype.getAttributesNames = function () {
  387. return this._attributesNames;
  388. };
  389. /**
  390. * Returns the attribute at the given index.
  391. * @param index The index of the attribute.
  392. * @returns The location of the attribute.
  393. */
  394. Effect.prototype.getAttributeLocation = function (index) {
  395. return this._attributes[index];
  396. };
  397. /**
  398. * Returns the attribute based on the name of the variable.
  399. * @param name of the attribute to look up.
  400. * @returns the attribute location.
  401. */
  402. Effect.prototype.getAttributeLocationByName = function (name) {
  403. var index = this._attributesNames.indexOf(name);
  404. return this._attributes[index];
  405. };
  406. /**
  407. * The number of attributes.
  408. * @returns the numnber of attributes.
  409. */
  410. Effect.prototype.getAttributesCount = function () {
  411. return this._attributes.length;
  412. };
  413. /**
  414. * Gets the index of a uniform variable.
  415. * @param uniformName of the uniform to look up.
  416. * @returns the index.
  417. */
  418. Effect.prototype.getUniformIndex = function (uniformName) {
  419. return this._uniformsNames.indexOf(uniformName);
  420. };
  421. /**
  422. * Returns the attribute based on the name of the variable.
  423. * @param uniformName of the uniform to look up.
  424. * @returns the location of the uniform.
  425. */
  426. Effect.prototype.getUniform = function (uniformName) {
  427. return this._uniforms[this._uniformsNames.indexOf(uniformName)];
  428. };
  429. /**
  430. * Returns an array of sampler variable names
  431. * @returns The array of sampler variable neames.
  432. */
  433. Effect.prototype.getSamplers = function () {
  434. return this._samplers;
  435. };
  436. /**
  437. * The error from the last compilation.
  438. * @returns the error string.
  439. */
  440. Effect.prototype.getCompilationError = function () {
  441. return this._compilationError;
  442. };
  443. /**
  444. * Adds a callback to the onCompiled observable and call the callback imediatly if already ready.
  445. * @param func The callback to be used.
  446. */
  447. Effect.prototype.executeWhenCompiled = function (func) {
  448. if (this.isReady()) {
  449. func(this);
  450. return;
  451. }
  452. this.onCompileObservable.add(function (effect) {
  453. func(effect);
  454. });
  455. };
  456. /** @hidden */
  457. Effect.prototype._loadVertexShader = function (vertex, callback) {
  458. if (BABYLON.Tools.IsWindowObjectExist()) {
  459. // DOM element ?
  460. if (vertex instanceof HTMLElement) {
  461. var vertexCode = BABYLON.Tools.GetDOMTextContent(vertex);
  462. callback(vertexCode);
  463. return;
  464. }
  465. }
  466. // Base64 encoded ?
  467. if (vertex.substr(0, 7) === "base64:") {
  468. var vertexBinary = window.atob(vertex.substr(7));
  469. callback(vertexBinary);
  470. return;
  471. }
  472. // Is in local store ?
  473. if (Effect.ShadersStore[vertex + "VertexShader"]) {
  474. callback(Effect.ShadersStore[vertex + "VertexShader"]);
  475. return;
  476. }
  477. var vertexShaderUrl;
  478. if (vertex[0] === "." || vertex[0] === "/" || vertex.indexOf("http") > -1) {
  479. vertexShaderUrl = vertex;
  480. }
  481. else {
  482. vertexShaderUrl = BABYLON.Engine.ShadersRepository + vertex;
  483. }
  484. // Vertex shader
  485. this._engine._loadFile(vertexShaderUrl + ".vertex.fx", callback);
  486. };
  487. /** @hidden */
  488. Effect.prototype._loadFragmentShader = function (fragment, callback) {
  489. if (BABYLON.Tools.IsWindowObjectExist()) {
  490. // DOM element ?
  491. if (fragment instanceof HTMLElement) {
  492. var fragmentCode = BABYLON.Tools.GetDOMTextContent(fragment);
  493. callback(fragmentCode);
  494. return;
  495. }
  496. }
  497. // Base64 encoded ?
  498. if (fragment.substr(0, 7) === "base64:") {
  499. var fragmentBinary = window.atob(fragment.substr(7));
  500. callback(fragmentBinary);
  501. return;
  502. }
  503. // Is in local store ?
  504. if (Effect.ShadersStore[fragment + "PixelShader"]) {
  505. callback(Effect.ShadersStore[fragment + "PixelShader"]);
  506. return;
  507. }
  508. if (Effect.ShadersStore[fragment + "FragmentShader"]) {
  509. callback(Effect.ShadersStore[fragment + "FragmentShader"]);
  510. return;
  511. }
  512. var fragmentShaderUrl;
  513. if (fragment[0] === "." || fragment[0] === "/" || fragment.indexOf("http") > -1) {
  514. fragmentShaderUrl = fragment;
  515. }
  516. else {
  517. fragmentShaderUrl = BABYLON.Engine.ShadersRepository + fragment;
  518. }
  519. // Fragment shader
  520. this._engine._loadFile(fragmentShaderUrl + ".fragment.fx", callback);
  521. };
  522. Effect.prototype._dumpShadersSource = function (vertexCode, fragmentCode, defines) {
  523. // Rebuild shaders source code
  524. var shaderVersion = (this._engine.webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  525. var prefix = shaderVersion + (defines ? defines + "\n" : "");
  526. vertexCode = prefix + vertexCode;
  527. fragmentCode = prefix + fragmentCode;
  528. // Number lines of shaders source code
  529. var i = 2;
  530. var regex = /\n/gm;
  531. var formattedVertexCode = "\n1\t" + vertexCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  532. i = 2;
  533. var formattedFragmentCode = "\n1\t" + fragmentCode.replace(regex, function () { return "\n" + (i++) + "\t"; });
  534. // Dump shaders name and formatted source code
  535. if (this.name.vertexElement) {
  536. BABYLON.Tools.Error("Vertex shader: " + this.name.vertexElement + formattedVertexCode);
  537. BABYLON.Tools.Error("Fragment shader: " + this.name.fragmentElement + formattedFragmentCode);
  538. }
  539. else if (this.name.vertex) {
  540. BABYLON.Tools.Error("Vertex shader: " + this.name.vertex + formattedVertexCode);
  541. BABYLON.Tools.Error("Fragment shader: " + this.name.fragment + formattedFragmentCode);
  542. }
  543. else {
  544. BABYLON.Tools.Error("Vertex shader: " + this.name + formattedVertexCode);
  545. BABYLON.Tools.Error("Fragment shader: " + this.name + formattedFragmentCode);
  546. }
  547. };
  548. ;
  549. Effect.prototype._processShaderConversion = function (sourceCode, isFragment, callback) {
  550. var preparedSourceCode = this._processPrecision(sourceCode);
  551. if (this._engine.webGLVersion == 1) {
  552. callback(preparedSourceCode);
  553. return;
  554. }
  555. // Already converted
  556. if (preparedSourceCode.indexOf("#version 3") !== -1) {
  557. callback(preparedSourceCode.replace("#version 300 es", ""));
  558. return;
  559. }
  560. var hasDrawBuffersExtension = preparedSourceCode.search(/#extension.+GL_EXT_draw_buffers.+require/) !== -1;
  561. // Remove extensions
  562. // #extension GL_OES_standard_derivatives : enable
  563. // #extension GL_EXT_shader_texture_lod : enable
  564. // #extension GL_EXT_frag_depth : enable
  565. // #extension GL_EXT_draw_buffers : require
  566. var regex = /#extension.+(GL_OES_standard_derivatives|GL_EXT_shader_texture_lod|GL_EXT_frag_depth|GL_EXT_draw_buffers).+(enable|require)/g;
  567. var result = preparedSourceCode.replace(regex, "");
  568. // Migrate to GLSL v300
  569. result = result.replace(/varying(?![\n\r])\s/g, isFragment ? "in " : "out ");
  570. result = result.replace(/attribute[ \t]/g, "in ");
  571. result = result.replace(/[ \t]attribute/g, " in");
  572. if (isFragment) {
  573. result = result.replace(/texture2DLodEXT\s*\(/g, "textureLod(");
  574. result = result.replace(/textureCubeLodEXT\s*\(/g, "textureLod(");
  575. result = result.replace(/texture2D\s*\(/g, "texture(");
  576. result = result.replace(/textureCube\s*\(/g, "texture(");
  577. result = result.replace(/gl_FragDepthEXT/g, "gl_FragDepth");
  578. result = result.replace(/gl_FragColor/g, "glFragColor");
  579. result = result.replace(/gl_FragData/g, "glFragData");
  580. result = result.replace(/void\s+?main\s*\(/g, (hasDrawBuffersExtension ? "" : "out vec4 glFragColor;\n") + "void main(");
  581. }
  582. callback(result);
  583. };
  584. Effect.prototype._processIncludes = function (sourceCode, callback) {
  585. var _this = this;
  586. var regex = /#include<(.+)>(\((.*)\))*(\[(.*)\])*/g;
  587. var match = regex.exec(sourceCode);
  588. var returnValue = new String(sourceCode);
  589. while (match != null) {
  590. var includeFile = match[1];
  591. // Uniform declaration
  592. if (includeFile.indexOf("__decl__") !== -1) {
  593. includeFile = includeFile.replace(/__decl__/, "");
  594. if (this._engine.supportsUniformBuffers) {
  595. includeFile = includeFile.replace(/Vertex/, "Ubo");
  596. includeFile = includeFile.replace(/Fragment/, "Ubo");
  597. }
  598. includeFile = includeFile + "Declaration";
  599. }
  600. if (Effect.IncludesShadersStore[includeFile]) {
  601. // Substitution
  602. var includeContent = Effect.IncludesShadersStore[includeFile];
  603. if (match[2]) {
  604. var splits = match[3].split(",");
  605. for (var index = 0; index < splits.length; index += 2) {
  606. var source = new RegExp(splits[index], "g");
  607. var dest = splits[index + 1];
  608. includeContent = includeContent.replace(source, dest);
  609. }
  610. }
  611. if (match[4]) {
  612. var indexString = match[5];
  613. if (indexString.indexOf("..") !== -1) {
  614. var indexSplits = indexString.split("..");
  615. var minIndex = parseInt(indexSplits[0]);
  616. var maxIndex = parseInt(indexSplits[1]);
  617. var sourceIncludeContent = includeContent.slice(0);
  618. includeContent = "";
  619. if (isNaN(maxIndex)) {
  620. maxIndex = this._indexParameters[indexSplits[1]];
  621. }
  622. for (var i = minIndex; i < maxIndex; i++) {
  623. if (!this._engine.supportsUniformBuffers) {
  624. // Ubo replacement
  625. sourceIncludeContent = sourceIncludeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  626. return p1 + "{X}";
  627. });
  628. }
  629. includeContent += sourceIncludeContent.replace(/\{X\}/g, i.toString()) + "\n";
  630. }
  631. }
  632. else {
  633. if (!this._engine.supportsUniformBuffers) {
  634. // Ubo replacement
  635. includeContent = includeContent.replace(/light\{X\}.(\w*)/g, function (str, p1) {
  636. return p1 + "{X}";
  637. });
  638. }
  639. includeContent = includeContent.replace(/\{X\}/g, indexString);
  640. }
  641. }
  642. // Replace
  643. returnValue = returnValue.replace(match[0], includeContent);
  644. }
  645. else {
  646. var includeShaderUrl = BABYLON.Engine.ShadersRepository + "ShadersInclude/" + includeFile + ".fx";
  647. this._engine._loadFile(includeShaderUrl, function (fileContent) {
  648. Effect.IncludesShadersStore[includeFile] = fileContent;
  649. _this._processIncludes(returnValue, callback);
  650. });
  651. return;
  652. }
  653. match = regex.exec(sourceCode);
  654. }
  655. callback(returnValue);
  656. };
  657. Effect.prototype._processPrecision = function (source) {
  658. if (source.indexOf("precision highp float") === -1) {
  659. if (!this._engine.getCaps().highPrecisionShaderSupported) {
  660. source = "precision mediump float;\n" + source;
  661. }
  662. else {
  663. source = "precision highp float;\n" + source;
  664. }
  665. }
  666. else {
  667. if (!this._engine.getCaps().highPrecisionShaderSupported) { // Moving highp to mediump
  668. source = source.replace("precision highp float", "precision mediump float");
  669. }
  670. }
  671. return source;
  672. };
  673. /**
  674. * Recompiles the webGL program
  675. * @param vertexSourceCode The source code for the vertex shader.
  676. * @param fragmentSourceCode The source code for the fragment shader.
  677. * @param onCompiled Callback called when completed.
  678. * @param onError Callback called on error.
  679. */
  680. Effect.prototype._rebuildProgram = function (vertexSourceCode, fragmentSourceCode, onCompiled, onError) {
  681. var _this = this;
  682. this._isReady = false;
  683. this._vertexSourceCodeOverride = vertexSourceCode;
  684. this._fragmentSourceCodeOverride = fragmentSourceCode;
  685. this.onError = function (effect, error) {
  686. if (onError) {
  687. onError(error);
  688. }
  689. };
  690. this.onCompiled = function () {
  691. var scenes = _this.getEngine().scenes;
  692. for (var i = 0; i < scenes.length; i++) {
  693. scenes[i].markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  694. }
  695. if (onCompiled) {
  696. onCompiled(_this._program);
  697. }
  698. };
  699. this._fallbacks = null;
  700. this._prepareEffect();
  701. };
  702. /**
  703. * Gets the uniform locations of the the specified variable names
  704. * @param names THe names of the variables to lookup.
  705. * @returns Array of locations in the same order as variable names.
  706. */
  707. Effect.prototype.getSpecificUniformLocations = function (names) {
  708. var engine = this._engine;
  709. return engine.getUniforms(this._program, names);
  710. };
  711. /**
  712. * Prepares the effect
  713. */
  714. Effect.prototype._prepareEffect = function () {
  715. var attributesNames = this._attributesNames;
  716. var defines = this.defines;
  717. var fallbacks = this._fallbacks;
  718. this._valueCache = {};
  719. var previousProgram = this._program;
  720. try {
  721. var engine = this._engine;
  722. if (this._vertexSourceCodeOverride && this._fragmentSourceCodeOverride) {
  723. this._program = engine.createRawShaderProgram(this._vertexSourceCodeOverride, this._fragmentSourceCodeOverride, undefined, this._transformFeedbackVaryings);
  724. }
  725. else {
  726. this._program = engine.createShaderProgram(this._vertexSourceCode, this._fragmentSourceCode, defines, undefined, this._transformFeedbackVaryings);
  727. }
  728. this._program.__SPECTOR_rebuildProgram = this._rebuildProgram.bind(this);
  729. if (engine.supportsUniformBuffers) {
  730. for (var name in this._uniformBuffersNames) {
  731. this.bindUniformBlock(name, this._uniformBuffersNames[name]);
  732. }
  733. }
  734. this._uniforms = engine.getUniforms(this._program, this._uniformsNames);
  735. this._attributes = engine.getAttributes(this._program, attributesNames);
  736. var index;
  737. for (index = 0; index < this._samplers.length; index++) {
  738. var sampler = this.getUniform(this._samplers[index]);
  739. if (sampler == null) {
  740. this._samplers.splice(index, 1);
  741. index--;
  742. }
  743. }
  744. engine.bindSamplers(this);
  745. this._compilationError = "";
  746. this._isReady = true;
  747. if (this.onCompiled) {
  748. this.onCompiled(this);
  749. }
  750. this.onCompileObservable.notifyObservers(this);
  751. this.onCompileObservable.clear();
  752. // Unbind mesh reference in fallbacks
  753. if (this._fallbacks) {
  754. this._fallbacks.unBindMesh();
  755. }
  756. if (previousProgram) {
  757. this.getEngine()._deleteProgram(previousProgram);
  758. }
  759. }
  760. catch (e) {
  761. this._compilationError = e.message;
  762. // Let's go through fallbacks then
  763. BABYLON.Tools.Error("Unable to compile effect:");
  764. BABYLON.Tools.Error("Uniforms: " + this._uniformsNames.map(function (uniform) {
  765. return " " + uniform;
  766. }));
  767. BABYLON.Tools.Error("Attributes: " + attributesNames.map(function (attribute) {
  768. return " " + attribute;
  769. }));
  770. this._dumpShadersSource(this._vertexSourceCode, this._fragmentSourceCode, defines);
  771. BABYLON.Tools.Error("Error: " + this._compilationError);
  772. if (previousProgram) {
  773. this._program = previousProgram;
  774. this._isReady = true;
  775. if (this.onError) {
  776. this.onError(this, this._compilationError);
  777. }
  778. this.onErrorObservable.notifyObservers(this);
  779. }
  780. if (fallbacks && fallbacks.isMoreFallbacks) {
  781. BABYLON.Tools.Error("Trying next fallback.");
  782. this.defines = fallbacks.reduce(this.defines, this);
  783. this._prepareEffect();
  784. }
  785. else { // Sorry we did everything we can
  786. if (this.onError) {
  787. this.onError(this, this._compilationError);
  788. }
  789. this.onErrorObservable.notifyObservers(this);
  790. this.onErrorObservable.clear();
  791. // Unbind mesh reference in fallbacks
  792. if (this._fallbacks) {
  793. this._fallbacks.unBindMesh();
  794. }
  795. }
  796. }
  797. };
  798. Object.defineProperty(Effect.prototype, "isSupported", {
  799. /**
  800. * Checks if the effect is supported. (Must be called after compilation)
  801. */
  802. get: function () {
  803. return this._compilationError === "";
  804. },
  805. enumerable: true,
  806. configurable: true
  807. });
  808. /**
  809. * Binds a texture to the engine to be used as output of the shader.
  810. * @param channel Name of the output variable.
  811. * @param texture Texture to bind.
  812. */
  813. Effect.prototype._bindTexture = function (channel, texture) {
  814. this._engine._bindTexture(this._samplers.indexOf(channel), texture);
  815. };
  816. /**
  817. * Sets a texture on the engine to be used in the shader.
  818. * @param channel Name of the sampler variable.
  819. * @param texture Texture to set.
  820. */
  821. Effect.prototype.setTexture = function (channel, texture) {
  822. this._engine.setTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  823. };
  824. /**
  825. * Sets a depth stencil texture from a render target on the engine to be used in the shader.
  826. * @param channel Name of the sampler variable.
  827. * @param texture Texture to set.
  828. */
  829. Effect.prototype.setDepthStencilTexture = function (channel, texture) {
  830. this._engine.setDepthStencilTexture(this._samplers.indexOf(channel), this.getUniform(channel), texture);
  831. };
  832. /**
  833. * Sets an array of textures on the engine to be used in the shader.
  834. * @param channel Name of the variable.
  835. * @param textures Textures to set.
  836. */
  837. Effect.prototype.setTextureArray = function (channel, textures) {
  838. if (this._samplers.indexOf(channel + "Ex") === -1) {
  839. var initialPos = this._samplers.indexOf(channel);
  840. for (var index = 1; index < textures.length; index++) {
  841. this._samplers.splice(initialPos + index, 0, channel + "Ex");
  842. }
  843. }
  844. this._engine.setTextureArray(this._samplers.indexOf(channel), this.getUniform(channel), textures);
  845. };
  846. /**
  847. * Sets a texture to be the input of the specified post process. (To use the output, pass in the next post process in the pipeline)
  848. * @param channel Name of the sampler variable.
  849. * @param postProcess Post process to get the input texture from.
  850. */
  851. Effect.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  852. this._engine.setTextureFromPostProcess(this._samplers.indexOf(channel), postProcess);
  853. };
  854. /**
  855. * (Warning! setTextureFromPostProcessOutput may be desired instead)
  856. * Sets the input texture of the passed in post process to be input of this effect. (To use the output of the passed in post process use setTextureFromPostProcessOutput)
  857. * @param channel Name of the sampler variable.
  858. * @param postProcess Post process to get the output texture from.
  859. */
  860. Effect.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  861. this._engine.setTextureFromPostProcessOutput(this._samplers.indexOf(channel), postProcess);
  862. };
  863. /** @hidden */
  864. Effect.prototype._cacheMatrix = function (uniformName, matrix) {
  865. var cache = this._valueCache[uniformName];
  866. var flag = matrix.updateFlag;
  867. if (cache !== undefined && cache === flag) {
  868. return false;
  869. }
  870. this._valueCache[uniformName] = flag;
  871. return true;
  872. };
  873. /** @hidden */
  874. Effect.prototype._cacheFloat2 = function (uniformName, x, y) {
  875. var cache = this._valueCache[uniformName];
  876. if (!cache) {
  877. cache = [x, y];
  878. this._valueCache[uniformName] = cache;
  879. return true;
  880. }
  881. var changed = false;
  882. if (cache[0] !== x) {
  883. cache[0] = x;
  884. changed = true;
  885. }
  886. if (cache[1] !== y) {
  887. cache[1] = y;
  888. changed = true;
  889. }
  890. return changed;
  891. };
  892. /** @hidden */
  893. Effect.prototype._cacheFloat3 = function (uniformName, x, y, z) {
  894. var cache = this._valueCache[uniformName];
  895. if (!cache) {
  896. cache = [x, y, z];
  897. this._valueCache[uniformName] = cache;
  898. return true;
  899. }
  900. var changed = false;
  901. if (cache[0] !== x) {
  902. cache[0] = x;
  903. changed = true;
  904. }
  905. if (cache[1] !== y) {
  906. cache[1] = y;
  907. changed = true;
  908. }
  909. if (cache[2] !== z) {
  910. cache[2] = z;
  911. changed = true;
  912. }
  913. return changed;
  914. };
  915. /** @hidden */
  916. Effect.prototype._cacheFloat4 = function (uniformName, x, y, z, w) {
  917. var cache = this._valueCache[uniformName];
  918. if (!cache) {
  919. cache = [x, y, z, w];
  920. this._valueCache[uniformName] = cache;
  921. return true;
  922. }
  923. var changed = false;
  924. if (cache[0] !== x) {
  925. cache[0] = x;
  926. changed = true;
  927. }
  928. if (cache[1] !== y) {
  929. cache[1] = y;
  930. changed = true;
  931. }
  932. if (cache[2] !== z) {
  933. cache[2] = z;
  934. changed = true;
  935. }
  936. if (cache[3] !== w) {
  937. cache[3] = w;
  938. changed = true;
  939. }
  940. return changed;
  941. };
  942. /**
  943. * Binds a buffer to a uniform.
  944. * @param buffer Buffer to bind.
  945. * @param name Name of the uniform variable to bind to.
  946. */
  947. Effect.prototype.bindUniformBuffer = function (buffer, name) {
  948. var bufferName = this._uniformBuffersNames[name];
  949. if (bufferName === undefined || Effect._baseCache[bufferName] === buffer) {
  950. return;
  951. }
  952. Effect._baseCache[bufferName] = buffer;
  953. this._engine.bindUniformBufferBase(buffer, bufferName);
  954. };
  955. /**
  956. * Binds block to a uniform.
  957. * @param blockName Name of the block to bind.
  958. * @param index Index to bind.
  959. */
  960. Effect.prototype.bindUniformBlock = function (blockName, index) {
  961. this._engine.bindUniformBlock(this._program, blockName, index);
  962. };
  963. /**
  964. * Sets an interger value on a uniform variable.
  965. * @param uniformName Name of the variable.
  966. * @param value Value to be set.
  967. * @returns this effect.
  968. */
  969. Effect.prototype.setInt = function (uniformName, value) {
  970. var cache = this._valueCache[uniformName];
  971. if (cache !== undefined && cache === value)
  972. return this;
  973. this._valueCache[uniformName] = value;
  974. this._engine.setInt(this.getUniform(uniformName), value);
  975. return this;
  976. };
  977. /**
  978. * Sets an int array on a uniform variable.
  979. * @param uniformName Name of the variable.
  980. * @param array array to be set.
  981. * @returns this effect.
  982. */
  983. Effect.prototype.setIntArray = function (uniformName, array) {
  984. this._valueCache[uniformName] = null;
  985. this._engine.setIntArray(this.getUniform(uniformName), array);
  986. return this;
  987. };
  988. /**
  989. * Sets an int array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  990. * @param uniformName Name of the variable.
  991. * @param array array to be set.
  992. * @returns this effect.
  993. */
  994. Effect.prototype.setIntArray2 = function (uniformName, array) {
  995. this._valueCache[uniformName] = null;
  996. this._engine.setIntArray2(this.getUniform(uniformName), array);
  997. return this;
  998. };
  999. /**
  1000. * Sets an int array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1001. * @param uniformName Name of the variable.
  1002. * @param array array to be set.
  1003. * @returns this effect.
  1004. */
  1005. Effect.prototype.setIntArray3 = function (uniformName, array) {
  1006. this._valueCache[uniformName] = null;
  1007. this._engine.setIntArray3(this.getUniform(uniformName), array);
  1008. return this;
  1009. };
  1010. /**
  1011. * Sets an int array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1012. * @param uniformName Name of the variable.
  1013. * @param array array to be set.
  1014. * @returns this effect.
  1015. */
  1016. Effect.prototype.setIntArray4 = function (uniformName, array) {
  1017. this._valueCache[uniformName] = null;
  1018. this._engine.setIntArray4(this.getUniform(uniformName), array);
  1019. return this;
  1020. };
  1021. /**
  1022. * Sets an float array on a uniform variable.
  1023. * @param uniformName Name of the variable.
  1024. * @param array array to be set.
  1025. * @returns this effect.
  1026. */
  1027. Effect.prototype.setFloatArray = function (uniformName, array) {
  1028. this._valueCache[uniformName] = null;
  1029. this._engine.setFloatArray(this.getUniform(uniformName), array);
  1030. return this;
  1031. };
  1032. /**
  1033. * Sets an float array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1034. * @param uniformName Name of the variable.
  1035. * @param array array to be set.
  1036. * @returns this effect.
  1037. */
  1038. Effect.prototype.setFloatArray2 = function (uniformName, array) {
  1039. this._valueCache[uniformName] = null;
  1040. this._engine.setFloatArray2(this.getUniform(uniformName), array);
  1041. return this;
  1042. };
  1043. /**
  1044. * Sets an float array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1045. * @param uniformName Name of the variable.
  1046. * @param array array to be set.
  1047. * @returns this effect.
  1048. */
  1049. Effect.prototype.setFloatArray3 = function (uniformName, array) {
  1050. this._valueCache[uniformName] = null;
  1051. this._engine.setFloatArray3(this.getUniform(uniformName), array);
  1052. return this;
  1053. };
  1054. /**
  1055. * Sets an float array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1056. * @param uniformName Name of the variable.
  1057. * @param array array to be set.
  1058. * @returns this effect.
  1059. */
  1060. Effect.prototype.setFloatArray4 = function (uniformName, array) {
  1061. this._valueCache[uniformName] = null;
  1062. this._engine.setFloatArray4(this.getUniform(uniformName), array);
  1063. return this;
  1064. };
  1065. /**
  1066. * Sets an array on a uniform variable.
  1067. * @param uniformName Name of the variable.
  1068. * @param array array to be set.
  1069. * @returns this effect.
  1070. */
  1071. Effect.prototype.setArray = function (uniformName, array) {
  1072. this._valueCache[uniformName] = null;
  1073. this._engine.setArray(this.getUniform(uniformName), array);
  1074. return this;
  1075. };
  1076. /**
  1077. * Sets an array 2 on a uniform variable. (Array is specified as single array eg. [1,2,3,4] will result in [[1,2],[3,4]] in the shader)
  1078. * @param uniformName Name of the variable.
  1079. * @param array array to be set.
  1080. * @returns this effect.
  1081. */
  1082. Effect.prototype.setArray2 = function (uniformName, array) {
  1083. this._valueCache[uniformName] = null;
  1084. this._engine.setArray2(this.getUniform(uniformName), array);
  1085. return this;
  1086. };
  1087. /**
  1088. * Sets an array 3 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6] will result in [[1,2,3],[4,5,6]] in the shader)
  1089. * @param uniformName Name of the variable.
  1090. * @param array array to be set.
  1091. * @returns this effect.
  1092. */
  1093. Effect.prototype.setArray3 = function (uniformName, array) {
  1094. this._valueCache[uniformName] = null;
  1095. this._engine.setArray3(this.getUniform(uniformName), array);
  1096. return this;
  1097. };
  1098. /**
  1099. * Sets an array 4 on a uniform variable. (Array is specified as single array eg. [1,2,3,4,5,6,7,8] will result in [[1,2,3,4],[5,6,7,8]] in the shader)
  1100. * @param uniformName Name of the variable.
  1101. * @param array array to be set.
  1102. * @returns this effect.
  1103. */
  1104. Effect.prototype.setArray4 = function (uniformName, array) {
  1105. this._valueCache[uniformName] = null;
  1106. this._engine.setArray4(this.getUniform(uniformName), array);
  1107. return this;
  1108. };
  1109. /**
  1110. * Sets matrices on a uniform variable.
  1111. * @param uniformName Name of the variable.
  1112. * @param matrices matrices to be set.
  1113. * @returns this effect.
  1114. */
  1115. Effect.prototype.setMatrices = function (uniformName, matrices) {
  1116. if (!matrices) {
  1117. return this;
  1118. }
  1119. this._valueCache[uniformName] = null;
  1120. this._engine.setMatrices(this.getUniform(uniformName), matrices);
  1121. return this;
  1122. };
  1123. /**
  1124. * Sets matrix on a uniform variable.
  1125. * @param uniformName Name of the variable.
  1126. * @param matrix matrix to be set.
  1127. * @returns this effect.
  1128. */
  1129. Effect.prototype.setMatrix = function (uniformName, matrix) {
  1130. if (this._cacheMatrix(uniformName, matrix)) {
  1131. this._engine.setMatrix(this.getUniform(uniformName), matrix);
  1132. }
  1133. return this;
  1134. };
  1135. /**
  1136. * Sets a 3x3 matrix on a uniform variable. (Speicified as [1,2,3,4,5,6,7,8,9] will result in [1,2,3][4,5,6][7,8,9] matrix)
  1137. * @param uniformName Name of the variable.
  1138. * @param matrix matrix to be set.
  1139. * @returns this effect.
  1140. */
  1141. Effect.prototype.setMatrix3x3 = function (uniformName, matrix) {
  1142. this._valueCache[uniformName] = null;
  1143. this._engine.setMatrix3x3(this.getUniform(uniformName), matrix);
  1144. return this;
  1145. };
  1146. /**
  1147. * Sets a 2x2 matrix on a uniform variable. (Speicified as [1,2,3,4] will result in [1,2][3,4] matrix)
  1148. * @param uniformName Name of the variable.
  1149. * @param matrix matrix to be set.
  1150. * @returns this effect.
  1151. */
  1152. Effect.prototype.setMatrix2x2 = function (uniformName, matrix) {
  1153. this._valueCache[uniformName] = null;
  1154. this._engine.setMatrix2x2(this.getUniform(uniformName), matrix);
  1155. return this;
  1156. };
  1157. /**
  1158. * Sets a float on a uniform variable.
  1159. * @param uniformName Name of the variable.
  1160. * @param value value to be set.
  1161. * @returns this effect.
  1162. */
  1163. Effect.prototype.setFloat = function (uniformName, value) {
  1164. var cache = this._valueCache[uniformName];
  1165. if (cache !== undefined && cache === value)
  1166. return this;
  1167. this._valueCache[uniformName] = value;
  1168. this._engine.setFloat(this.getUniform(uniformName), value);
  1169. return this;
  1170. };
  1171. /**
  1172. * Sets a boolean on a uniform variable.
  1173. * @param uniformName Name of the variable.
  1174. * @param bool value to be set.
  1175. * @returns this effect.
  1176. */
  1177. Effect.prototype.setBool = function (uniformName, bool) {
  1178. var cache = this._valueCache[uniformName];
  1179. if (cache !== undefined && cache === bool)
  1180. return this;
  1181. this._valueCache[uniformName] = bool;
  1182. this._engine.setBool(this.getUniform(uniformName), bool ? 1 : 0);
  1183. return this;
  1184. };
  1185. /**
  1186. * Sets a Vector2 on a uniform variable.
  1187. * @param uniformName Name of the variable.
  1188. * @param vector2 vector2 to be set.
  1189. * @returns this effect.
  1190. */
  1191. Effect.prototype.setVector2 = function (uniformName, vector2) {
  1192. if (this._cacheFloat2(uniformName, vector2.x, vector2.y)) {
  1193. this._engine.setFloat2(this.getUniform(uniformName), vector2.x, vector2.y);
  1194. }
  1195. return this;
  1196. };
  1197. /**
  1198. * Sets a float2 on a uniform variable.
  1199. * @param uniformName Name of the variable.
  1200. * @param x First float in float2.
  1201. * @param y Second float in float2.
  1202. * @returns this effect.
  1203. */
  1204. Effect.prototype.setFloat2 = function (uniformName, x, y) {
  1205. if (this._cacheFloat2(uniformName, x, y)) {
  1206. this._engine.setFloat2(this.getUniform(uniformName), x, y);
  1207. }
  1208. return this;
  1209. };
  1210. /**
  1211. * Sets a Vector3 on a uniform variable.
  1212. * @param uniformName Name of the variable.
  1213. * @param vector3 Value to be set.
  1214. * @returns this effect.
  1215. */
  1216. Effect.prototype.setVector3 = function (uniformName, vector3) {
  1217. if (this._cacheFloat3(uniformName, vector3.x, vector3.y, vector3.z)) {
  1218. this._engine.setFloat3(this.getUniform(uniformName), vector3.x, vector3.y, vector3.z);
  1219. }
  1220. return this;
  1221. };
  1222. /**
  1223. * Sets a float3 on a uniform variable.
  1224. * @param uniformName Name of the variable.
  1225. * @param x First float in float3.
  1226. * @param y Second float in float3.
  1227. * @param z Third float in float3.
  1228. * @returns this effect.
  1229. */
  1230. Effect.prototype.setFloat3 = function (uniformName, x, y, z) {
  1231. if (this._cacheFloat3(uniformName, x, y, z)) {
  1232. this._engine.setFloat3(this.getUniform(uniformName), x, y, z);
  1233. }
  1234. return this;
  1235. };
  1236. /**
  1237. * Sets a Vector4 on a uniform variable.
  1238. * @param uniformName Name of the variable.
  1239. * @param vector4 Value to be set.
  1240. * @returns this effect.
  1241. */
  1242. Effect.prototype.setVector4 = function (uniformName, vector4) {
  1243. if (this._cacheFloat4(uniformName, vector4.x, vector4.y, vector4.z, vector4.w)) {
  1244. this._engine.setFloat4(this.getUniform(uniformName), vector4.x, vector4.y, vector4.z, vector4.w);
  1245. }
  1246. return this;
  1247. };
  1248. /**
  1249. * Sets a float4 on a uniform variable.
  1250. * @param uniformName Name of the variable.
  1251. * @param x First float in float4.
  1252. * @param y Second float in float4.
  1253. * @param z Third float in float4.
  1254. * @param w Fourth float in float4.
  1255. * @returns this effect.
  1256. */
  1257. Effect.prototype.setFloat4 = function (uniformName, x, y, z, w) {
  1258. if (this._cacheFloat4(uniformName, x, y, z, w)) {
  1259. this._engine.setFloat4(this.getUniform(uniformName), x, y, z, w);
  1260. }
  1261. return this;
  1262. };
  1263. /**
  1264. * Sets a Color3 on a uniform variable.
  1265. * @param uniformName Name of the variable.
  1266. * @param color3 Value to be set.
  1267. * @returns this effect.
  1268. */
  1269. Effect.prototype.setColor3 = function (uniformName, color3) {
  1270. if (this._cacheFloat3(uniformName, color3.r, color3.g, color3.b)) {
  1271. this._engine.setColor3(this.getUniform(uniformName), color3);
  1272. }
  1273. return this;
  1274. };
  1275. /**
  1276. * Sets a Color4 on a uniform variable.
  1277. * @param uniformName Name of the variable.
  1278. * @param color3 Value to be set.
  1279. * @param alpha Alpha value to be set.
  1280. * @returns this effect.
  1281. */
  1282. Effect.prototype.setColor4 = function (uniformName, color3, alpha) {
  1283. if (this._cacheFloat4(uniformName, color3.r, color3.g, color3.b, alpha)) {
  1284. this._engine.setColor4(this.getUniform(uniformName), color3, alpha);
  1285. }
  1286. return this;
  1287. };
  1288. /**
  1289. * Sets a Color4 on a uniform variable
  1290. * @param uniformName defines the name of the variable
  1291. * @param color4 defines the value to be set
  1292. * @returns this effect.
  1293. */
  1294. Effect.prototype.setDirectColor4 = function (uniformName, color4) {
  1295. if (this._cacheFloat4(uniformName, color4.r, color4.g, color4.b, color4.a)) {
  1296. this._engine.setDirectColor4(this.getUniform(uniformName), color4);
  1297. }
  1298. return this;
  1299. };
  1300. /**
  1301. * Resets the cache of effects.
  1302. */
  1303. Effect.ResetCache = function () {
  1304. Effect._baseCache = {};
  1305. };
  1306. Effect._uniqueIdSeed = 0;
  1307. Effect._baseCache = {};
  1308. /**
  1309. * Store of each shader (The can be looked up using effect.key)
  1310. */
  1311. Effect.ShadersStore = {};
  1312. /**
  1313. * Store of each included file for a shader (The can be looked up using effect.key)
  1314. */
  1315. Effect.IncludesShadersStore = {};
  1316. return Effect;
  1317. }());
  1318. BABYLON.Effect = Effect;
  1319. })(BABYLON || (BABYLON = {}));
  1320. //# sourceMappingURL=babylon.effect.js.map
  1321. //# sourceMappingURL=babylon.types.js.map
  1322. var BABYLON;
  1323. (function (BABYLON) {
  1324. var KeyboardEventTypes = /** @class */ (function () {
  1325. function KeyboardEventTypes() {
  1326. }
  1327. Object.defineProperty(KeyboardEventTypes, "KEYDOWN", {
  1328. get: function () {
  1329. return KeyboardEventTypes._KEYDOWN;
  1330. },
  1331. enumerable: true,
  1332. configurable: true
  1333. });
  1334. Object.defineProperty(KeyboardEventTypes, "KEYUP", {
  1335. get: function () {
  1336. return KeyboardEventTypes._KEYUP;
  1337. },
  1338. enumerable: true,
  1339. configurable: true
  1340. });
  1341. KeyboardEventTypes._KEYDOWN = 0x01;
  1342. KeyboardEventTypes._KEYUP = 0x02;
  1343. return KeyboardEventTypes;
  1344. }());
  1345. BABYLON.KeyboardEventTypes = KeyboardEventTypes;
  1346. var KeyboardInfo = /** @class */ (function () {
  1347. function KeyboardInfo(type, event) {
  1348. this.type = type;
  1349. this.event = event;
  1350. }
  1351. return KeyboardInfo;
  1352. }());
  1353. BABYLON.KeyboardInfo = KeyboardInfo;
  1354. /**
  1355. * This class is used to store keyboard related info for the onPreKeyboardObservable event.
  1356. * Set the skipOnKeyboardObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onKeyboardObservable
  1357. */
  1358. var KeyboardInfoPre = /** @class */ (function (_super) {
  1359. __extends(KeyboardInfoPre, _super);
  1360. function KeyboardInfoPre(type, event) {
  1361. var _this = _super.call(this, type, event) || this;
  1362. _this.skipOnPointerObservable = false;
  1363. return _this;
  1364. }
  1365. return KeyboardInfoPre;
  1366. }(KeyboardInfo));
  1367. BABYLON.KeyboardInfoPre = KeyboardInfoPre;
  1368. })(BABYLON || (BABYLON = {}));
  1369. //# sourceMappingURL=babylon.keyboardEvents.js.map
  1370. var BABYLON;
  1371. (function (BABYLON) {
  1372. var PointerEventTypes = /** @class */ (function () {
  1373. function PointerEventTypes() {
  1374. }
  1375. Object.defineProperty(PointerEventTypes, "POINTERDOWN", {
  1376. get: function () {
  1377. return PointerEventTypes._POINTERDOWN;
  1378. },
  1379. enumerable: true,
  1380. configurable: true
  1381. });
  1382. Object.defineProperty(PointerEventTypes, "POINTERUP", {
  1383. get: function () {
  1384. return PointerEventTypes._POINTERUP;
  1385. },
  1386. enumerable: true,
  1387. configurable: true
  1388. });
  1389. Object.defineProperty(PointerEventTypes, "POINTERMOVE", {
  1390. get: function () {
  1391. return PointerEventTypes._POINTERMOVE;
  1392. },
  1393. enumerable: true,
  1394. configurable: true
  1395. });
  1396. Object.defineProperty(PointerEventTypes, "POINTERWHEEL", {
  1397. get: function () {
  1398. return PointerEventTypes._POINTERWHEEL;
  1399. },
  1400. enumerable: true,
  1401. configurable: true
  1402. });
  1403. Object.defineProperty(PointerEventTypes, "POINTERPICK", {
  1404. get: function () {
  1405. return PointerEventTypes._POINTERPICK;
  1406. },
  1407. enumerable: true,
  1408. configurable: true
  1409. });
  1410. Object.defineProperty(PointerEventTypes, "POINTERTAP", {
  1411. get: function () {
  1412. return PointerEventTypes._POINTERTAP;
  1413. },
  1414. enumerable: true,
  1415. configurable: true
  1416. });
  1417. Object.defineProperty(PointerEventTypes, "POINTERDOUBLETAP", {
  1418. get: function () {
  1419. return PointerEventTypes._POINTERDOUBLETAP;
  1420. },
  1421. enumerable: true,
  1422. configurable: true
  1423. });
  1424. PointerEventTypes._POINTERDOWN = 0x01;
  1425. PointerEventTypes._POINTERUP = 0x02;
  1426. PointerEventTypes._POINTERMOVE = 0x04;
  1427. PointerEventTypes._POINTERWHEEL = 0x08;
  1428. PointerEventTypes._POINTERPICK = 0x10;
  1429. PointerEventTypes._POINTERTAP = 0x20;
  1430. PointerEventTypes._POINTERDOUBLETAP = 0x40;
  1431. return PointerEventTypes;
  1432. }());
  1433. BABYLON.PointerEventTypes = PointerEventTypes;
  1434. var PointerInfoBase = /** @class */ (function () {
  1435. function PointerInfoBase(type, event) {
  1436. this.type = type;
  1437. this.event = event;
  1438. }
  1439. return PointerInfoBase;
  1440. }());
  1441. BABYLON.PointerInfoBase = PointerInfoBase;
  1442. /**
  1443. * This class is used to store pointer related info for the onPrePointerObservable event.
  1444. * Set the skipOnPointerObservable property to true if you want the engine to stop any process after this event is triggered, even not calling onPointerObservable
  1445. */
  1446. var PointerInfoPre = /** @class */ (function (_super) {
  1447. __extends(PointerInfoPre, _super);
  1448. function PointerInfoPre(type, event, localX, localY) {
  1449. var _this = _super.call(this, type, event) || this;
  1450. /**
  1451. * Ray from a pointer if availible (eg. 6dof controller)
  1452. */
  1453. _this.ray = null;
  1454. _this.skipOnPointerObservable = false;
  1455. _this.localPosition = new BABYLON.Vector2(localX, localY);
  1456. return _this;
  1457. }
  1458. return PointerInfoPre;
  1459. }(PointerInfoBase));
  1460. BABYLON.PointerInfoPre = PointerInfoPre;
  1461. /**
  1462. * This type contains all the data related to a pointer event in Babylon.js.
  1463. * The event member is an instance of PointerEvent for all types except PointerWheel and is of type MouseWheelEvent when type equals PointerWheel. The different event types can be found in the PointerEventTypes class.
  1464. */
  1465. var PointerInfo = /** @class */ (function (_super) {
  1466. __extends(PointerInfo, _super);
  1467. function PointerInfo(type, event, pickInfo) {
  1468. var _this = _super.call(this, type, event) || this;
  1469. _this.pickInfo = pickInfo;
  1470. return _this;
  1471. }
  1472. return PointerInfo;
  1473. }(PointerInfoBase));
  1474. BABYLON.PointerInfo = PointerInfo;
  1475. })(BABYLON || (BABYLON = {}));
  1476. //# sourceMappingURL=babylon.pointerEvents.js.map
  1477. var BABYLON;
  1478. (function (BABYLON) {
  1479. BABYLON.ToGammaSpace = 1 / 2.2;
  1480. BABYLON.ToLinearSpace = 2.2;
  1481. BABYLON.Epsilon = 0.001;
  1482. /**
  1483. * Class used to hold a RBG color
  1484. */
  1485. var Color3 = /** @class */ (function () {
  1486. /**
  1487. * Creates a new Color3 object from red, green, blue values, all between 0 and 1
  1488. * @param r defines the red component (between 0 and 1, default is 0)
  1489. * @param g defines the green component (between 0 and 1, default is 0)
  1490. * @param b defines the blue component (between 0 and 1, default is 0)
  1491. */
  1492. function Color3(
  1493. /**
  1494. * Defines the red component (between 0 and 1, default is 0)
  1495. */
  1496. r,
  1497. /**
  1498. * Defines the green component (between 0 and 1, default is 0)
  1499. */
  1500. g,
  1501. /**
  1502. * Defines the blue component (between 0 and 1, default is 0)
  1503. */
  1504. b) {
  1505. if (r === void 0) { r = 0; }
  1506. if (g === void 0) { g = 0; }
  1507. if (b === void 0) { b = 0; }
  1508. this.r = r;
  1509. this.g = g;
  1510. this.b = b;
  1511. }
  1512. /**
  1513. * Creates a string with the Color3 current values
  1514. * @returns the string representation of the Color3 object
  1515. */
  1516. Color3.prototype.toString = function () {
  1517. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + "}";
  1518. };
  1519. /**
  1520. * Returns the string "Color3"
  1521. * @returns "Color3"
  1522. */
  1523. Color3.prototype.getClassName = function () {
  1524. return "Color3";
  1525. };
  1526. /**
  1527. * Compute the Color3 hash code
  1528. * @returns an unique number that can be used to hash Color3 objects
  1529. */
  1530. Color3.prototype.getHashCode = function () {
  1531. var hash = this.r || 0;
  1532. hash = (hash * 397) ^ (this.g || 0);
  1533. hash = (hash * 397) ^ (this.b || 0);
  1534. return hash;
  1535. };
  1536. // Operators
  1537. /**
  1538. * Stores in the given array from the given starting index the red, green, blue values as successive elements
  1539. * @param array defines the array where to store the r,g,b components
  1540. * @param index defines an optional index in the target array to define where to start storing values
  1541. * @returns the current Color3 object
  1542. */
  1543. Color3.prototype.toArray = function (array, index) {
  1544. if (index === undefined) {
  1545. index = 0;
  1546. }
  1547. array[index] = this.r;
  1548. array[index + 1] = this.g;
  1549. array[index + 2] = this.b;
  1550. return this;
  1551. };
  1552. /**
  1553. * Returns a new {BABYLON.Color4} object from the current Color3 and the given alpha
  1554. * @param alpha defines the alpha component on the new {BABYLON.Color4} object (default is 1)
  1555. * @returns a new {BABYLON.Color4} object
  1556. */
  1557. Color3.prototype.toColor4 = function (alpha) {
  1558. if (alpha === void 0) { alpha = 1; }
  1559. return new Color4(this.r, this.g, this.b, alpha);
  1560. };
  1561. /**
  1562. * Returns a new array populated with 3 numeric elements : red, green and blue values
  1563. * @returns the new array
  1564. */
  1565. Color3.prototype.asArray = function () {
  1566. var result = new Array();
  1567. this.toArray(result, 0);
  1568. return result;
  1569. };
  1570. /**
  1571. * Returns the luminance value
  1572. * @returns a float value
  1573. */
  1574. Color3.prototype.toLuminance = function () {
  1575. return this.r * 0.3 + this.g * 0.59 + this.b * 0.11;
  1576. };
  1577. /**
  1578. * Multiply each Color3 rgb values by the given Color3 rgb values in a new Color3 object
  1579. * @param otherColor defines the second operand
  1580. * @returns the new Color3 object
  1581. */
  1582. Color3.prototype.multiply = function (otherColor) {
  1583. return new Color3(this.r * otherColor.r, this.g * otherColor.g, this.b * otherColor.b);
  1584. };
  1585. /**
  1586. * Multiply the rgb values of the Color3 and the given Color3 and stores the result in the object "result"
  1587. * @param otherColor defines the second operand
  1588. * @param result defines the Color3 object where to store the result
  1589. * @returns the current Color3
  1590. */
  1591. Color3.prototype.multiplyToRef = function (otherColor, result) {
  1592. result.r = this.r * otherColor.r;
  1593. result.g = this.g * otherColor.g;
  1594. result.b = this.b * otherColor.b;
  1595. return this;
  1596. };
  1597. /**
  1598. * Determines equality between Color3 objects
  1599. * @param otherColor defines the second operand
  1600. * @returns true if the rgb values are equal to the given ones
  1601. */
  1602. Color3.prototype.equals = function (otherColor) {
  1603. return otherColor && this.r === otherColor.r && this.g === otherColor.g && this.b === otherColor.b;
  1604. };
  1605. /**
  1606. * Determines equality between the current Color3 object and a set of r,b,g values
  1607. * @param r defines the red component to check
  1608. * @param g defines the green component to check
  1609. * @param b defines the blue component to check
  1610. * @returns true if the rgb values are equal to the given ones
  1611. */
  1612. Color3.prototype.equalsFloats = function (r, g, b) {
  1613. return this.r === r && this.g === g && this.b === b;
  1614. };
  1615. /**
  1616. * Multiplies in place each rgb value by scale
  1617. * @param scale defines the scaling factor
  1618. * @returns the updated Color3
  1619. */
  1620. Color3.prototype.scale = function (scale) {
  1621. return new Color3(this.r * scale, this.g * scale, this.b * scale);
  1622. };
  1623. /**
  1624. * Multiplies the rgb values by scale and stores the result into "result"
  1625. * @param scale defines the scaling factor
  1626. * @param result defines the Color3 object where to store the result
  1627. * @returns the unmodified current Color3
  1628. */
  1629. Color3.prototype.scaleToRef = function (scale, result) {
  1630. result.r = this.r * scale;
  1631. result.g = this.g * scale;
  1632. result.b = this.b * scale;
  1633. return this;
  1634. };
  1635. /**
  1636. * Scale the current Color3 values by a factor and add the result to a given Color3
  1637. * @param scale defines the scale factor
  1638. * @param result defines color to store the result into
  1639. * @returns the unmodified current Color3
  1640. */
  1641. Color3.prototype.scaleAndAddToRef = function (scale, result) {
  1642. result.r += this.r * scale;
  1643. result.g += this.g * scale;
  1644. result.b += this.b * scale;
  1645. return this;
  1646. };
  1647. /**
  1648. * Clamps the rgb values by the min and max values and stores the result into "result"
  1649. * @param min defines minimum clamping value (default is 0)
  1650. * @param max defines maximum clamping value (default is 1)
  1651. * @param result defines color to store the result into
  1652. * @returns the original Color3
  1653. */
  1654. Color3.prototype.clampToRef = function (min, max, result) {
  1655. if (min === void 0) { min = 0; }
  1656. if (max === void 0) { max = 1; }
  1657. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  1658. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  1659. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  1660. return this;
  1661. };
  1662. /**
  1663. * Creates a new Color3 set with the added values of the current Color3 and of the given one
  1664. * @param otherColor defines the second operand
  1665. * @returns the new Color3
  1666. */
  1667. Color3.prototype.add = function (otherColor) {
  1668. return new Color3(this.r + otherColor.r, this.g + otherColor.g, this.b + otherColor.b);
  1669. };
  1670. /**
  1671. * Stores the result of the addition of the current Color3 and given one rgb values into "result"
  1672. * @param otherColor defines the second operand
  1673. * @param result defines Color3 object to store the result into
  1674. * @returns the unmodified current Color3
  1675. */
  1676. Color3.prototype.addToRef = function (otherColor, result) {
  1677. result.r = this.r + otherColor.r;
  1678. result.g = this.g + otherColor.g;
  1679. result.b = this.b + otherColor.b;
  1680. return this;
  1681. };
  1682. /**
  1683. * Returns a new Color3 set with the subtracted values of the given one from the current Color3
  1684. * @param otherColor defines the second operand
  1685. * @returns the new Color3
  1686. */
  1687. Color3.prototype.subtract = function (otherColor) {
  1688. return new Color3(this.r - otherColor.r, this.g - otherColor.g, this.b - otherColor.b);
  1689. };
  1690. /**
  1691. * Stores the result of the subtraction of given one from the current Color3 rgb values into "result"
  1692. * @param otherColor defines the second operand
  1693. * @param result defines Color3 object to store the result into
  1694. * @returns the unmodified current Color3
  1695. */
  1696. Color3.prototype.subtractToRef = function (otherColor, result) {
  1697. result.r = this.r - otherColor.r;
  1698. result.g = this.g - otherColor.g;
  1699. result.b = this.b - otherColor.b;
  1700. return this;
  1701. };
  1702. /**
  1703. * Copy the current object
  1704. * @returns a new Color3 copied the current one
  1705. */
  1706. Color3.prototype.clone = function () {
  1707. return new Color3(this.r, this.g, this.b);
  1708. };
  1709. /**
  1710. * Copies the rgb values from the source in the current Color3
  1711. * @param source defines the source Color3 object
  1712. * @returns the updated Color3 object
  1713. */
  1714. Color3.prototype.copyFrom = function (source) {
  1715. this.r = source.r;
  1716. this.g = source.g;
  1717. this.b = source.b;
  1718. return this;
  1719. };
  1720. /**
  1721. * Updates the Color3 rgb values from the given floats
  1722. * @param r defines the red component to read from
  1723. * @param g defines the green component to read from
  1724. * @param b defines the blue component to read from
  1725. * @returns the current Color3 object
  1726. */
  1727. Color3.prototype.copyFromFloats = function (r, g, b) {
  1728. this.r = r;
  1729. this.g = g;
  1730. this.b = b;
  1731. return this;
  1732. };
  1733. /**
  1734. * Updates the Color3 rgb values from the given floats
  1735. * @param r defines the red component to read from
  1736. * @param g defines the green component to read from
  1737. * @param b defines the blue component to read from
  1738. * @returns the current Color3 object
  1739. */
  1740. Color3.prototype.set = function (r, g, b) {
  1741. return this.copyFromFloats(r, g, b);
  1742. };
  1743. /**
  1744. * Compute the Color3 hexadecimal code as a string
  1745. * @returns a string containing the hexadecimal representation of the Color3 object
  1746. */
  1747. Color3.prototype.toHexString = function () {
  1748. var intR = (this.r * 255) | 0;
  1749. var intG = (this.g * 255) | 0;
  1750. var intB = (this.b * 255) | 0;
  1751. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB);
  1752. };
  1753. /**
  1754. * Computes a new Color3 converted from the current one to linear space
  1755. * @returns a new Color3 object
  1756. */
  1757. Color3.prototype.toLinearSpace = function () {
  1758. var convertedColor = new Color3();
  1759. this.toLinearSpaceToRef(convertedColor);
  1760. return convertedColor;
  1761. };
  1762. /**
  1763. * Converts the Color3 values to linear space and stores the result in "convertedColor"
  1764. * @param convertedColor defines the Color3 object where to store the linear space version
  1765. * @returns the unmodified Color3
  1766. */
  1767. Color3.prototype.toLinearSpaceToRef = function (convertedColor) {
  1768. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  1769. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  1770. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  1771. return this;
  1772. };
  1773. /**
  1774. * Computes a new Color3 converted from the current one to gamma space
  1775. * @returns a new Color3 object
  1776. */
  1777. Color3.prototype.toGammaSpace = function () {
  1778. var convertedColor = new Color3();
  1779. this.toGammaSpaceToRef(convertedColor);
  1780. return convertedColor;
  1781. };
  1782. /**
  1783. * Converts the Color3 values to gamma space and stores the result in "convertedColor"
  1784. * @param convertedColor defines the Color3 object where to store the gamma space version
  1785. * @returns the unmodified Color3
  1786. */
  1787. Color3.prototype.toGammaSpaceToRef = function (convertedColor) {
  1788. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  1789. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  1790. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  1791. return this;
  1792. };
  1793. // Statics
  1794. /**
  1795. * Creates a new Color3 from the string containing valid hexadecimal values
  1796. * @param hex defines a string containing valid hexadecimal values
  1797. * @returns a new Color3 object
  1798. */
  1799. Color3.FromHexString = function (hex) {
  1800. if (hex.substring(0, 1) !== "#" || hex.length !== 7) {
  1801. return new Color3(0, 0, 0);
  1802. }
  1803. var r = parseInt(hex.substring(1, 3), 16);
  1804. var g = parseInt(hex.substring(3, 5), 16);
  1805. var b = parseInt(hex.substring(5, 7), 16);
  1806. return Color3.FromInts(r, g, b);
  1807. };
  1808. /**
  1809. * Creates a new Vector3 from the starting index of the given array
  1810. * @param array defines the source array
  1811. * @param offset defines an offset in the source array
  1812. * @returns a new Color3 object
  1813. */
  1814. Color3.FromArray = function (array, offset) {
  1815. if (offset === void 0) { offset = 0; }
  1816. return new Color3(array[offset], array[offset + 1], array[offset + 2]);
  1817. };
  1818. /**
  1819. * Creates a new Color3 from integer values (< 256)
  1820. * @param r defines the red component to read from (value between 0 and 255)
  1821. * @param g defines the green component to read from (value between 0 and 255)
  1822. * @param b defines the blue component to read from (value between 0 and 255)
  1823. * @returns a new Color3 object
  1824. */
  1825. Color3.FromInts = function (r, g, b) {
  1826. return new Color3(r / 255.0, g / 255.0, b / 255.0);
  1827. };
  1828. /**
  1829. * Creates a new Color3 with values linearly interpolated of "amount" between the start Color3 and the end Color3
  1830. * @param start defines the start Color3 value
  1831. * @param end defines the end Color3 value
  1832. * @param amount defines the gradient value between start and end
  1833. * @returns a new Color3 object
  1834. */
  1835. Color3.Lerp = function (start, end, amount) {
  1836. var r = start.r + ((end.r - start.r) * amount);
  1837. var g = start.g + ((end.g - start.g) * amount);
  1838. var b = start.b + ((end.b - start.b) * amount);
  1839. return new Color3(r, g, b);
  1840. };
  1841. /**
  1842. * Returns a Color3 value containing a red color
  1843. * @returns a new Color3 object
  1844. */
  1845. Color3.Red = function () { return new Color3(1, 0, 0); };
  1846. /**
  1847. * Returns a Color3 value containing a green color
  1848. * @returns a new Color3 object
  1849. */
  1850. Color3.Green = function () { return new Color3(0, 1, 0); };
  1851. /**
  1852. * Returns a Color3 value containing a blue color
  1853. * @returns a new Color3 object
  1854. */
  1855. Color3.Blue = function () { return new Color3(0, 0, 1); };
  1856. /**
  1857. * Returns a Color3 value containing a black color
  1858. * @returns a new Color3 object
  1859. */
  1860. Color3.Black = function () { return new Color3(0, 0, 0); };
  1861. /**
  1862. * Returns a Color3 value containing a white color
  1863. * @returns a new Color3 object
  1864. */
  1865. Color3.White = function () { return new Color3(1, 1, 1); };
  1866. /**
  1867. * Returns a Color3 value containing a purple color
  1868. * @returns a new Color3 object
  1869. */
  1870. Color3.Purple = function () { return new Color3(0.5, 0, 0.5); };
  1871. /**
  1872. * Returns a Color3 value containing a magenta color
  1873. * @returns a new Color3 object
  1874. */
  1875. Color3.Magenta = function () { return new Color3(1, 0, 1); };
  1876. /**
  1877. * Returns a Color3 value containing a yellow color
  1878. * @returns a new Color3 object
  1879. */
  1880. Color3.Yellow = function () { return new Color3(1, 1, 0); };
  1881. /**
  1882. * Returns a Color3 value containing a gray color
  1883. * @returns a new Color3 object
  1884. */
  1885. Color3.Gray = function () { return new Color3(0.5, 0.5, 0.5); };
  1886. /**
  1887. * Returns a Color3 value containing a teal color
  1888. * @returns a new Color3 object
  1889. */
  1890. Color3.Teal = function () { return new Color3(0, 1.0, 1.0); };
  1891. /**
  1892. * Returns a Color3 value containing a random color
  1893. * @returns a new Color3 object
  1894. */
  1895. Color3.Random = function () { return new Color3(Math.random(), Math.random(), Math.random()); };
  1896. return Color3;
  1897. }());
  1898. BABYLON.Color3 = Color3;
  1899. /**
  1900. * Class used to hold a RBGA color
  1901. */
  1902. var Color4 = /** @class */ (function () {
  1903. /**
  1904. * Creates a new Color4 object from red, green, blue values, all between 0 and 1
  1905. * @param r defines the red component (between 0 and 1, default is 0)
  1906. * @param g defines the green component (between 0 and 1, default is 0)
  1907. * @param b defines the blue component (between 0 and 1, default is 0)
  1908. * @param a defines the alpha component (between 0 and 1, default is 1)
  1909. */
  1910. function Color4(
  1911. /**
  1912. * Defines the red component (between 0 and 1, default is 0)
  1913. */
  1914. r,
  1915. /**
  1916. * Defines the green component (between 0 and 1, default is 0)
  1917. */
  1918. g,
  1919. /**
  1920. * Defines the blue component (between 0 and 1, default is 0)
  1921. */
  1922. b,
  1923. /**
  1924. * Defines the alpha component (between 0 and 1, default is 1)
  1925. */
  1926. a) {
  1927. if (r === void 0) { r = 0; }
  1928. if (g === void 0) { g = 0; }
  1929. if (b === void 0) { b = 0; }
  1930. if (a === void 0) { a = 1; }
  1931. this.r = r;
  1932. this.g = g;
  1933. this.b = b;
  1934. this.a = a;
  1935. }
  1936. // Operators
  1937. /**
  1938. * Adds in place the given Color4 values to the current Color4 object
  1939. * @param right defines the second operand
  1940. * @returns the current updated Color4 object
  1941. */
  1942. Color4.prototype.addInPlace = function (right) {
  1943. this.r += right.r;
  1944. this.g += right.g;
  1945. this.b += right.b;
  1946. this.a += right.a;
  1947. return this;
  1948. };
  1949. /**
  1950. * Creates a new array populated with 4 numeric elements : red, green, blue, alpha values
  1951. * @returns the new array
  1952. */
  1953. Color4.prototype.asArray = function () {
  1954. var result = new Array();
  1955. this.toArray(result, 0);
  1956. return result;
  1957. };
  1958. /**
  1959. * Stores from the starting index in the given array the Color4 successive values
  1960. * @param array defines the array where to store the r,g,b components
  1961. * @param index defines an optional index in the target array to define where to start storing values
  1962. * @returns the current Color4 object
  1963. */
  1964. Color4.prototype.toArray = function (array, index) {
  1965. if (index === undefined) {
  1966. index = 0;
  1967. }
  1968. array[index] = this.r;
  1969. array[index + 1] = this.g;
  1970. array[index + 2] = this.b;
  1971. array[index + 3] = this.a;
  1972. return this;
  1973. };
  1974. /**
  1975. * Creates a new Color4 set with the added values of the current Color4 and of the given one
  1976. * @param right defines the second operand
  1977. * @returns a new Color4 object
  1978. */
  1979. Color4.prototype.add = function (right) {
  1980. return new Color4(this.r + right.r, this.g + right.g, this.b + right.b, this.a + right.a);
  1981. };
  1982. /**
  1983. * Creates a new Color4 set with the subtracted values of the given one from the current Color4
  1984. * @param right defines the second operand
  1985. * @returns a new Color4 object
  1986. */
  1987. Color4.prototype.subtract = function (right) {
  1988. return new Color4(this.r - right.r, this.g - right.g, this.b - right.b, this.a - right.a);
  1989. };
  1990. /**
  1991. * Subtracts the given ones from the current Color4 values and stores the results in "result"
  1992. * @param right defines the second operand
  1993. * @param result defines the Color4 object where to store the result
  1994. * @returns the current Color4 object
  1995. */
  1996. Color4.prototype.subtractToRef = function (right, result) {
  1997. result.r = this.r - right.r;
  1998. result.g = this.g - right.g;
  1999. result.b = this.b - right.b;
  2000. result.a = this.a - right.a;
  2001. return this;
  2002. };
  2003. /**
  2004. * Creates a new Color4 with the current Color4 values multiplied by scale
  2005. * @param scale defines the scaling factor to apply
  2006. * @returns a new Color4 object
  2007. */
  2008. Color4.prototype.scale = function (scale) {
  2009. return new Color4(this.r * scale, this.g * scale, this.b * scale, this.a * scale);
  2010. };
  2011. /**
  2012. * Multiplies the current Color4 values by scale and stores the result in "result"
  2013. * @param scale defines the scaling factor to apply
  2014. * @param result defines the Color4 object where to store the result
  2015. * @returns the current unmodified Color4
  2016. */
  2017. Color4.prototype.scaleToRef = function (scale, result) {
  2018. result.r = this.r * scale;
  2019. result.g = this.g * scale;
  2020. result.b = this.b * scale;
  2021. result.a = this.a * scale;
  2022. return this;
  2023. };
  2024. /**
  2025. * Scale the current Color4 values by a factor and add the result to a given Color4
  2026. * @param scale defines the scale factor
  2027. * @param result defines the Color4 object where to store the result
  2028. * @returns the unmodified current Color4
  2029. */
  2030. Color4.prototype.scaleAndAddToRef = function (scale, result) {
  2031. result.r += this.r * scale;
  2032. result.g += this.g * scale;
  2033. result.b += this.b * scale;
  2034. result.a += this.a * scale;
  2035. return this;
  2036. };
  2037. /**
  2038. * Clamps the rgb values by the min and max values and stores the result into "result"
  2039. * @param min defines minimum clamping value (default is 0)
  2040. * @param max defines maximum clamping value (default is 1)
  2041. * @param result defines color to store the result into.
  2042. * @returns the cuurent Color4
  2043. */
  2044. Color4.prototype.clampToRef = function (min, max, result) {
  2045. if (min === void 0) { min = 0; }
  2046. if (max === void 0) { max = 1; }
  2047. result.r = BABYLON.Scalar.Clamp(this.r, min, max);
  2048. result.g = BABYLON.Scalar.Clamp(this.g, min, max);
  2049. result.b = BABYLON.Scalar.Clamp(this.b, min, max);
  2050. result.a = BABYLON.Scalar.Clamp(this.a, min, max);
  2051. return this;
  2052. };
  2053. /**
  2054. * Multipy an Color4 value by another and return a new Color4 object
  2055. * @param color defines the Color4 value to multiply by
  2056. * @returns a new Color4 object
  2057. */
  2058. Color4.prototype.multiply = function (color) {
  2059. return new Color4(this.r * color.r, this.g * color.g, this.b * color.b, this.a * color.a);
  2060. };
  2061. /**
  2062. * Multipy a Color4 value by another and push the result in a reference value
  2063. * @param color defines the Color4 value to multiply by
  2064. * @param result defines the Color4 to fill the result in
  2065. * @returns the result Color4
  2066. */
  2067. Color4.prototype.multiplyToRef = function (color, result) {
  2068. result.r = this.r * color.r;
  2069. result.g = this.g * color.g;
  2070. result.b = this.b * color.b;
  2071. result.a = this.a * color.a;
  2072. return result;
  2073. };
  2074. /**
  2075. * Creates a string with the Color4 current values
  2076. * @returns the string representation of the Color4 object
  2077. */
  2078. Color4.prototype.toString = function () {
  2079. return "{R: " + this.r + " G:" + this.g + " B:" + this.b + " A:" + this.a + "}";
  2080. };
  2081. /**
  2082. * Returns the string "Color4"
  2083. * @returns "Color4"
  2084. */
  2085. Color4.prototype.getClassName = function () {
  2086. return "Color4";
  2087. };
  2088. /**
  2089. * Compute the Color4 hash code
  2090. * @returns an unique number that can be used to hash Color4 objects
  2091. */
  2092. Color4.prototype.getHashCode = function () {
  2093. var hash = this.r || 0;
  2094. hash = (hash * 397) ^ (this.g || 0);
  2095. hash = (hash * 397) ^ (this.b || 0);
  2096. hash = (hash * 397) ^ (this.a || 0);
  2097. return hash;
  2098. };
  2099. /**
  2100. * Creates a new Color4 copied from the current one
  2101. * @returns a new Color4 object
  2102. */
  2103. Color4.prototype.clone = function () {
  2104. return new Color4(this.r, this.g, this.b, this.a);
  2105. };
  2106. /**
  2107. * Copies the given Color4 values into the current one
  2108. * @param source defines the source Color4 object
  2109. * @returns the current updated Color4 object
  2110. */
  2111. Color4.prototype.copyFrom = function (source) {
  2112. this.r = source.r;
  2113. this.g = source.g;
  2114. this.b = source.b;
  2115. this.a = source.a;
  2116. return this;
  2117. };
  2118. /**
  2119. * Copies the given float values into the current one
  2120. * @param r defines the red component to read from
  2121. * @param g defines the green component to read from
  2122. * @param b defines the blue component to read from
  2123. * @param a defines the alpha component to read from
  2124. * @returns the current updated Color4 object
  2125. */
  2126. Color4.prototype.copyFromFloats = function (r, g, b, a) {
  2127. this.r = r;
  2128. this.g = g;
  2129. this.b = b;
  2130. this.a = a;
  2131. return this;
  2132. };
  2133. /**
  2134. * Copies the given float values into the current one
  2135. * @param r defines the red component to read from
  2136. * @param g defines the green component to read from
  2137. * @param b defines the blue component to read from
  2138. * @param a defines the alpha component to read from
  2139. * @returns the current updated Color4 object
  2140. */
  2141. Color4.prototype.set = function (r, g, b, a) {
  2142. return this.copyFromFloats(r, g, b, a);
  2143. };
  2144. /**
  2145. * Compute the Color4 hexadecimal code as a string
  2146. * @returns a string containing the hexadecimal representation of the Color4 object
  2147. */
  2148. Color4.prototype.toHexString = function () {
  2149. var intR = (this.r * 255) | 0;
  2150. var intG = (this.g * 255) | 0;
  2151. var intB = (this.b * 255) | 0;
  2152. var intA = (this.a * 255) | 0;
  2153. return "#" + BABYLON.Scalar.ToHex(intR) + BABYLON.Scalar.ToHex(intG) + BABYLON.Scalar.ToHex(intB) + BABYLON.Scalar.ToHex(intA);
  2154. };
  2155. /**
  2156. * Computes a new Color4 converted from the current one to linear space
  2157. * @returns a new Color4 object
  2158. */
  2159. Color4.prototype.toLinearSpace = function () {
  2160. var convertedColor = new Color4();
  2161. this.toLinearSpaceToRef(convertedColor);
  2162. return convertedColor;
  2163. };
  2164. /**
  2165. * Converts the Color4 values to linear space and stores the result in "convertedColor"
  2166. * @param convertedColor defines the Color4 object where to store the linear space version
  2167. * @returns the unmodified Color4
  2168. */
  2169. Color4.prototype.toLinearSpaceToRef = function (convertedColor) {
  2170. convertedColor.r = Math.pow(this.r, BABYLON.ToLinearSpace);
  2171. convertedColor.g = Math.pow(this.g, BABYLON.ToLinearSpace);
  2172. convertedColor.b = Math.pow(this.b, BABYLON.ToLinearSpace);
  2173. convertedColor.a = this.a;
  2174. return this;
  2175. };
  2176. /**
  2177. * Computes a new Color4 converted from the current one to gamma space
  2178. * @returns a new Color4 object
  2179. */
  2180. Color4.prototype.toGammaSpace = function () {
  2181. var convertedColor = new Color4();
  2182. this.toGammaSpaceToRef(convertedColor);
  2183. return convertedColor;
  2184. };
  2185. /**
  2186. * Converts the Color4 values to gamma space and stores the result in "convertedColor"
  2187. * @param convertedColor defines the Color4 object where to store the gamma space version
  2188. * @returns the unmodified Color4
  2189. */
  2190. Color4.prototype.toGammaSpaceToRef = function (convertedColor) {
  2191. convertedColor.r = Math.pow(this.r, BABYLON.ToGammaSpace);
  2192. convertedColor.g = Math.pow(this.g, BABYLON.ToGammaSpace);
  2193. convertedColor.b = Math.pow(this.b, BABYLON.ToGammaSpace);
  2194. convertedColor.a = this.a;
  2195. return this;
  2196. };
  2197. // Statics
  2198. /**
  2199. * Creates a new Color4 from the string containing valid hexadecimal values
  2200. * @param hex defines a string containing valid hexadecimal values
  2201. * @returns a new Color4 object
  2202. */
  2203. Color4.FromHexString = function (hex) {
  2204. if (hex.substring(0, 1) !== "#" || hex.length !== 9) {
  2205. return new Color4(0.0, 0.0, 0.0, 0.0);
  2206. }
  2207. var r = parseInt(hex.substring(1, 3), 16);
  2208. var g = parseInt(hex.substring(3, 5), 16);
  2209. var b = parseInt(hex.substring(5, 7), 16);
  2210. var a = parseInt(hex.substring(7, 9), 16);
  2211. return Color4.FromInts(r, g, b, a);
  2212. };
  2213. /**
  2214. * Creates a new Color4 object set with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2215. * @param left defines the start value
  2216. * @param right defines the end value
  2217. * @param amount defines the gradient factor
  2218. * @returns a new Color4 object
  2219. */
  2220. Color4.Lerp = function (left, right, amount) {
  2221. var result = new Color4(0.0, 0.0, 0.0, 0.0);
  2222. Color4.LerpToRef(left, right, amount, result);
  2223. return result;
  2224. };
  2225. /**
  2226. * Set the given "result" with the linearly interpolated values of "amount" between the left Color4 object and the right Color4 object
  2227. * @param left defines the start value
  2228. * @param right defines the end value
  2229. * @param amount defines the gradient factor
  2230. * @param result defines the Color4 object where to store data
  2231. */
  2232. Color4.LerpToRef = function (left, right, amount, result) {
  2233. result.r = left.r + (right.r - left.r) * amount;
  2234. result.g = left.g + (right.g - left.g) * amount;
  2235. result.b = left.b + (right.b - left.b) * amount;
  2236. result.a = left.a + (right.a - left.a) * amount;
  2237. };
  2238. /**
  2239. * Creates a new Color4 from the starting index element of the given array
  2240. * @param array defines the source array to read from
  2241. * @param offset defines the offset in the source array
  2242. * @returns a new Color4 object
  2243. */
  2244. Color4.FromArray = function (array, offset) {
  2245. if (offset === void 0) { offset = 0; }
  2246. return new Color4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  2247. };
  2248. /**
  2249. * Creates a new Color3 from integer values (< 256)
  2250. * @param r defines the red component to read from (value between 0 and 255)
  2251. * @param g defines the green component to read from (value between 0 and 255)
  2252. * @param b defines the blue component to read from (value between 0 and 255)
  2253. * @param a defines the alpha component to read from (value between 0 and 255)
  2254. * @returns a new Color3 object
  2255. */
  2256. Color4.FromInts = function (r, g, b, a) {
  2257. return new Color4(r / 255.0, g / 255.0, b / 255.0, a / 255.0);
  2258. };
  2259. /**
  2260. * Check the content of a given array and convert it to an array containing RGBA data
  2261. * If the original array was already containing count * 4 values then it is returned directly
  2262. * @param colors defines the array to check
  2263. * @param count defines the number of RGBA data to expect
  2264. * @returns an array containing count * 4 values (RGBA)
  2265. */
  2266. Color4.CheckColors4 = function (colors, count) {
  2267. // Check if color3 was used
  2268. if (colors.length === count * 3) {
  2269. var colors4 = [];
  2270. for (var index = 0; index < colors.length; index += 3) {
  2271. var newIndex = (index / 3) * 4;
  2272. colors4[newIndex] = colors[index];
  2273. colors4[newIndex + 1] = colors[index + 1];
  2274. colors4[newIndex + 2] = colors[index + 2];
  2275. colors4[newIndex + 3] = 1.0;
  2276. }
  2277. return colors4;
  2278. }
  2279. return colors;
  2280. };
  2281. return Color4;
  2282. }());
  2283. BABYLON.Color4 = Color4;
  2284. /**
  2285. * Class representing a vector containing 2 coordinates
  2286. */
  2287. var Vector2 = /** @class */ (function () {
  2288. /**
  2289. * Creates a new Vector2 from the given x and y coordinates
  2290. * @param x defines the first coordinate
  2291. * @param y defines the second coordinate
  2292. */
  2293. function Vector2(
  2294. /** defines the first coordinate */
  2295. x,
  2296. /** defines the second coordinate */
  2297. y) {
  2298. if (x === void 0) { x = 0; }
  2299. if (y === void 0) { y = 0; }
  2300. this.x = x;
  2301. this.y = y;
  2302. }
  2303. /**
  2304. * Gets a string with the Vector2 coordinates
  2305. * @returns a string with the Vector2 coordinates
  2306. */
  2307. Vector2.prototype.toString = function () {
  2308. return "{X: " + this.x + " Y:" + this.y + "}";
  2309. };
  2310. /**
  2311. * Gets class name
  2312. * @returns the string "Vector2"
  2313. */
  2314. Vector2.prototype.getClassName = function () {
  2315. return "Vector2";
  2316. };
  2317. /**
  2318. * Gets current vector hash code
  2319. * @returns the Vector2 hash code as a number
  2320. */
  2321. Vector2.prototype.getHashCode = function () {
  2322. var hash = this.x || 0;
  2323. hash = (hash * 397) ^ (this.y || 0);
  2324. return hash;
  2325. };
  2326. // Operators
  2327. /**
  2328. * Sets the Vector2 coordinates in the given array or Float32Array from the given index.
  2329. * @param array defines the source array
  2330. * @param index defines the offset in source array
  2331. * @returns the current Vector2
  2332. */
  2333. Vector2.prototype.toArray = function (array, index) {
  2334. if (index === void 0) { index = 0; }
  2335. array[index] = this.x;
  2336. array[index + 1] = this.y;
  2337. return this;
  2338. };
  2339. /**
  2340. * Copy the current vector to an array
  2341. * @returns a new array with 2 elements: the Vector2 coordinates.
  2342. */
  2343. Vector2.prototype.asArray = function () {
  2344. var result = new Array();
  2345. this.toArray(result, 0);
  2346. return result;
  2347. };
  2348. /**
  2349. * Sets the Vector2 coordinates with the given Vector2 coordinates
  2350. * @param source defines the source Vector2
  2351. * @returns the current updated Vector2
  2352. */
  2353. Vector2.prototype.copyFrom = function (source) {
  2354. this.x = source.x;
  2355. this.y = source.y;
  2356. return this;
  2357. };
  2358. /**
  2359. * Sets the Vector2 coordinates with the given floats
  2360. * @param x defines the first coordinate
  2361. * @param y defines the second coordinate
  2362. * @returns the current updated Vector2
  2363. */
  2364. Vector2.prototype.copyFromFloats = function (x, y) {
  2365. this.x = x;
  2366. this.y = y;
  2367. return this;
  2368. };
  2369. /**
  2370. * Sets the Vector2 coordinates with the given floats
  2371. * @param x defines the first coordinate
  2372. * @param y defines the second coordinate
  2373. * @returns the current updated Vector2
  2374. */
  2375. Vector2.prototype.set = function (x, y) {
  2376. return this.copyFromFloats(x, y);
  2377. };
  2378. /**
  2379. * Add another vector with the current one
  2380. * @param otherVector defines the other vector
  2381. * @returns a new Vector2 set with the addition of the current Vector2 and the given one coordinates
  2382. */
  2383. Vector2.prototype.add = function (otherVector) {
  2384. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2385. };
  2386. /**
  2387. * Sets the "result" coordinates with the addition of the current Vector2 and the given one coordinates
  2388. * @param otherVector defines the other vector
  2389. * @param result defines the target vector
  2390. * @returns the unmodified current Vector2
  2391. */
  2392. Vector2.prototype.addToRef = function (otherVector, result) {
  2393. result.x = this.x + otherVector.x;
  2394. result.y = this.y + otherVector.y;
  2395. return this;
  2396. };
  2397. /**
  2398. * Set the Vector2 coordinates by adding the given Vector2 coordinates
  2399. * @param otherVector defines the other vector
  2400. * @returns the current updated Vector2
  2401. */
  2402. Vector2.prototype.addInPlace = function (otherVector) {
  2403. this.x += otherVector.x;
  2404. this.y += otherVector.y;
  2405. return this;
  2406. };
  2407. /**
  2408. * Gets a new Vector2 by adding the current Vector2 coordinates to the given Vector3 x, y coordinates
  2409. * @param otherVector defines the other vector
  2410. * @returns a new Vector2
  2411. */
  2412. Vector2.prototype.addVector3 = function (otherVector) {
  2413. return new Vector2(this.x + otherVector.x, this.y + otherVector.y);
  2414. };
  2415. /**
  2416. * Gets a new Vector2 set with the subtracted coordinates of the given one from the current Vector2
  2417. * @param otherVector defines the other vector
  2418. * @returns a new Vector2
  2419. */
  2420. Vector2.prototype.subtract = function (otherVector) {
  2421. return new Vector2(this.x - otherVector.x, this.y - otherVector.y);
  2422. };
  2423. /**
  2424. * Sets the "result" coordinates with the subtraction of the given one from the current Vector2 coordinates.
  2425. * @param otherVector defines the other vector
  2426. * @param result defines the target vector
  2427. * @returns the unmodified current Vector2
  2428. */
  2429. Vector2.prototype.subtractToRef = function (otherVector, result) {
  2430. result.x = this.x - otherVector.x;
  2431. result.y = this.y - otherVector.y;
  2432. return this;
  2433. };
  2434. /**
  2435. * Sets the current Vector2 coordinates by subtracting from it the given one coordinates
  2436. * @param otherVector defines the other vector
  2437. * @returns the current updated Vector2
  2438. */
  2439. Vector2.prototype.subtractInPlace = function (otherVector) {
  2440. this.x -= otherVector.x;
  2441. this.y -= otherVector.y;
  2442. return this;
  2443. };
  2444. /**
  2445. * Multiplies in place the current Vector2 coordinates by the given ones
  2446. * @param otherVector defines the other vector
  2447. * @returns the current updated Vector2
  2448. */
  2449. Vector2.prototype.multiplyInPlace = function (otherVector) {
  2450. this.x *= otherVector.x;
  2451. this.y *= otherVector.y;
  2452. return this;
  2453. };
  2454. /**
  2455. * Returns a new Vector2 set with the multiplication of the current Vector2 and the given one coordinates
  2456. * @param otherVector defines the other vector
  2457. * @returns a new Vector2
  2458. */
  2459. Vector2.prototype.multiply = function (otherVector) {
  2460. return new Vector2(this.x * otherVector.x, this.y * otherVector.y);
  2461. };
  2462. /**
  2463. * Sets "result" coordinates with the multiplication of the current Vector2 and the given one coordinates
  2464. * @param otherVector defines the other vector
  2465. * @param result defines the target vector
  2466. * @returns the unmodified current Vector2
  2467. */
  2468. Vector2.prototype.multiplyToRef = function (otherVector, result) {
  2469. result.x = this.x * otherVector.x;
  2470. result.y = this.y * otherVector.y;
  2471. return this;
  2472. };
  2473. /**
  2474. * Gets a new Vector2 set with the Vector2 coordinates multiplied by the given floats
  2475. * @param x defines the first coordinate
  2476. * @param y defines the second coordinate
  2477. * @returns a new Vector2
  2478. */
  2479. Vector2.prototype.multiplyByFloats = function (x, y) {
  2480. return new Vector2(this.x * x, this.y * y);
  2481. };
  2482. /**
  2483. * Returns a new Vector2 set with the Vector2 coordinates divided by the given one coordinates
  2484. * @param otherVector defines the other vector
  2485. * @returns a new Vector2
  2486. */
  2487. Vector2.prototype.divide = function (otherVector) {
  2488. return new Vector2(this.x / otherVector.x, this.y / otherVector.y);
  2489. };
  2490. /**
  2491. * Sets the "result" coordinates with the Vector2 divided by the given one coordinates
  2492. * @param otherVector defines the other vector
  2493. * @param result defines the target vector
  2494. * @returns the unmodified current Vector2
  2495. */
  2496. Vector2.prototype.divideToRef = function (otherVector, result) {
  2497. result.x = this.x / otherVector.x;
  2498. result.y = this.y / otherVector.y;
  2499. return this;
  2500. };
  2501. /**
  2502. * Divides the current Vector3 coordinates by the given ones
  2503. * @param otherVector defines the other vector
  2504. * @returns the current updated Vector2
  2505. */
  2506. Vector2.prototype.divideInPlace = function (otherVector) {
  2507. return this.divideToRef(otherVector, this);
  2508. };
  2509. /**
  2510. * Gets a new Vector2 with current Vector2 negated coordinates
  2511. * @returns a new Vector2
  2512. */
  2513. Vector2.prototype.negate = function () {
  2514. return new Vector2(-this.x, -this.y);
  2515. };
  2516. /**
  2517. * Multiply the Vector2 coordinates by scale
  2518. * @param scale defines the scaling factor
  2519. * @returns the current updated Vector2
  2520. */
  2521. Vector2.prototype.scaleInPlace = function (scale) {
  2522. this.x *= scale;
  2523. this.y *= scale;
  2524. return this;
  2525. };
  2526. /**
  2527. * Returns a new Vector2 scaled by "scale" from the current Vector2
  2528. * @param scale defines the scaling factor
  2529. * @returns a new Vector2
  2530. */
  2531. Vector2.prototype.scale = function (scale) {
  2532. var result = new Vector2(0, 0);
  2533. this.scaleToRef(scale, result);
  2534. return result;
  2535. };
  2536. /**
  2537. * Scale the current Vector2 values by a factor to a given Vector2
  2538. * @param scale defines the scale factor
  2539. * @param result defines the Vector2 object where to store the result
  2540. * @returns the unmodified current Vector2
  2541. */
  2542. Vector2.prototype.scaleToRef = function (scale, result) {
  2543. result.x = this.x * scale;
  2544. result.y = this.y * scale;
  2545. return this;
  2546. };
  2547. /**
  2548. * Scale the current Vector2 values by a factor and add the result to a given Vector2
  2549. * @param scale defines the scale factor
  2550. * @param result defines the Vector2 object where to store the result
  2551. * @returns the unmodified current Vector2
  2552. */
  2553. Vector2.prototype.scaleAndAddToRef = function (scale, result) {
  2554. result.x += this.x * scale;
  2555. result.y += this.y * scale;
  2556. return this;
  2557. };
  2558. /**
  2559. * Gets a boolean if two vectors are equals
  2560. * @param otherVector defines the other vector
  2561. * @returns true if the given vector coordinates strictly equal the current Vector2 ones
  2562. */
  2563. Vector2.prototype.equals = function (otherVector) {
  2564. return otherVector && this.x === otherVector.x && this.y === otherVector.y;
  2565. };
  2566. /**
  2567. * Gets a boolean if two vectors are equals (using an epsilon value)
  2568. * @param otherVector defines the other vector
  2569. * @param epsilon defines the minimal distance to consider equality
  2570. * @returns true if the given vector coordinates are close to the current ones by a distance of epsilon.
  2571. */
  2572. Vector2.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  2573. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  2574. return otherVector && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon) && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon);
  2575. };
  2576. // Properties
  2577. /**
  2578. * Gets the length of the vector
  2579. * @returns the vector length (float)
  2580. */
  2581. Vector2.prototype.length = function () {
  2582. return Math.sqrt(this.x * this.x + this.y * this.y);
  2583. };
  2584. /**
  2585. * Gets the vector squared length
  2586. * @returns the vector squared length (float)
  2587. */
  2588. Vector2.prototype.lengthSquared = function () {
  2589. return (this.x * this.x + this.y * this.y);
  2590. };
  2591. // Methods
  2592. /**
  2593. * Normalize the vector
  2594. * @returns the current updated Vector2
  2595. */
  2596. Vector2.prototype.normalize = function () {
  2597. var len = this.length();
  2598. if (len === 0)
  2599. return this;
  2600. var num = 1.0 / len;
  2601. this.x *= num;
  2602. this.y *= num;
  2603. return this;
  2604. };
  2605. /**
  2606. * Gets a new Vector2 copied from the Vector2
  2607. * @returns a new Vector2
  2608. */
  2609. Vector2.prototype.clone = function () {
  2610. return new Vector2(this.x, this.y);
  2611. };
  2612. // Statics
  2613. /**
  2614. * Gets a new Vector2(0, 0)
  2615. * @returns a new Vector2
  2616. */
  2617. Vector2.Zero = function () {
  2618. return new Vector2(0, 0);
  2619. };
  2620. /**
  2621. * Gets a new Vector2(1, 1)
  2622. * @returns a new Vector2
  2623. */
  2624. Vector2.One = function () {
  2625. return new Vector2(1, 1);
  2626. };
  2627. /**
  2628. * Gets a new Vector2 set from the given index element of the given array
  2629. * @param array defines the data source
  2630. * @param offset defines the offset in the data source
  2631. * @returns a new Vector2
  2632. */
  2633. Vector2.FromArray = function (array, offset) {
  2634. if (offset === void 0) { offset = 0; }
  2635. return new Vector2(array[offset], array[offset + 1]);
  2636. };
  2637. /**
  2638. * Sets "result" from the given index element of the given array
  2639. * @param array defines the data source
  2640. * @param offset defines the offset in the data source
  2641. * @param result defines the target vector
  2642. */
  2643. Vector2.FromArrayToRef = function (array, offset, result) {
  2644. result.x = array[offset];
  2645. result.y = array[offset + 1];
  2646. };
  2647. /**
  2648. * Gets a new Vector2 located for "amount" (float) on the CatmullRom spline defined by the given four Vector2
  2649. * @param value1 defines 1st point of control
  2650. * @param value2 defines 2nd point of control
  2651. * @param value3 defines 3rd point of control
  2652. * @param value4 defines 4th point of control
  2653. * @param amount defines the interpolation factor
  2654. * @returns a new Vector2
  2655. */
  2656. Vector2.CatmullRom = function (value1, value2, value3, value4, amount) {
  2657. var squared = amount * amount;
  2658. var cubed = amount * squared;
  2659. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  2660. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  2661. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  2662. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  2663. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  2664. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  2665. return new Vector2(x, y);
  2666. };
  2667. /**
  2668. * 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".
  2669. * If a coordinate of "value" is lower than "min" coordinates, the returned Vector2 is given this "min" coordinate.
  2670. * If a coordinate of "value" is greater than "max" coordinates, the returned Vector2 is given this "max" coordinate
  2671. * @param value defines the value to clamp
  2672. * @param min defines the lower limit
  2673. * @param max defines the upper limit
  2674. * @returns a new Vector2
  2675. */
  2676. Vector2.Clamp = function (value, min, max) {
  2677. var x = value.x;
  2678. x = (x > max.x) ? max.x : x;
  2679. x = (x < min.x) ? min.x : x;
  2680. var y = value.y;
  2681. y = (y > max.y) ? max.y : y;
  2682. y = (y < min.y) ? min.y : y;
  2683. return new Vector2(x, y);
  2684. };
  2685. /**
  2686. * Returns a new Vector2 located for "amount" (float) on the Hermite spline defined by the vectors "value1", "value3", "tangent1", "tangent2"
  2687. * @param value1 defines the 1st control point
  2688. * @param tangent1 defines the outgoing tangent
  2689. * @param value2 defines the 2nd control point
  2690. * @param tangent2 defines the incoming tangent
  2691. * @param amount defines the interpolation factor
  2692. * @returns a new Vector2
  2693. */
  2694. Vector2.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  2695. var squared = amount * amount;
  2696. var cubed = amount * squared;
  2697. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  2698. var part2 = (-2.0 * cubed) + (3.0 * squared);
  2699. var part3 = (cubed - (2.0 * squared)) + amount;
  2700. var part4 = cubed - squared;
  2701. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  2702. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  2703. return new Vector2(x, y);
  2704. };
  2705. /**
  2706. * Returns a new Vector2 located for "amount" (float) on the linear interpolation between the vector "start" adn the vector "end".
  2707. * @param start defines the start vector
  2708. * @param end defines the end vector
  2709. * @param amount defines the interpolation factor
  2710. * @returns a new Vector2
  2711. */
  2712. Vector2.Lerp = function (start, end, amount) {
  2713. var x = start.x + ((end.x - start.x) * amount);
  2714. var y = start.y + ((end.y - start.y) * amount);
  2715. return new Vector2(x, y);
  2716. };
  2717. /**
  2718. * Gets the dot product of the vector "left" and the vector "right"
  2719. * @param left defines first vector
  2720. * @param right defines second vector
  2721. * @returns the dot product (float)
  2722. */
  2723. Vector2.Dot = function (left, right) {
  2724. return left.x * right.x + left.y * right.y;
  2725. };
  2726. /**
  2727. * Returns a new Vector2 equal to the normalized given vector
  2728. * @param vector defines the vector to normalize
  2729. * @returns a new Vector2
  2730. */
  2731. Vector2.Normalize = function (vector) {
  2732. var newVector = vector.clone();
  2733. newVector.normalize();
  2734. return newVector;
  2735. };
  2736. /**
  2737. * Gets a new Vector2 set with the minimal coordinate values from the "left" and "right" vectors
  2738. * @param left defines 1st vector
  2739. * @param right defines 2nd vector
  2740. * @returns a new Vector2
  2741. */
  2742. Vector2.Minimize = function (left, right) {
  2743. var x = (left.x < right.x) ? left.x : right.x;
  2744. var y = (left.y < right.y) ? left.y : right.y;
  2745. return new Vector2(x, y);
  2746. };
  2747. /**
  2748. * Gets a new Vecto2 set with the maximal coordinate values from the "left" and "right" vectors
  2749. * @param left defines 1st vector
  2750. * @param right defines 2nd vector
  2751. * @returns a new Vector2
  2752. */
  2753. Vector2.Maximize = function (left, right) {
  2754. var x = (left.x > right.x) ? left.x : right.x;
  2755. var y = (left.y > right.y) ? left.y : right.y;
  2756. return new Vector2(x, y);
  2757. };
  2758. /**
  2759. * Gets a new Vector2 set with the transformed coordinates of the given vector by the given transformation matrix
  2760. * @param vector defines the vector to transform
  2761. * @param transformation defines the matrix to apply
  2762. * @returns a new Vector2
  2763. */
  2764. Vector2.Transform = function (vector, transformation) {
  2765. var r = Vector2.Zero();
  2766. Vector2.TransformToRef(vector, transformation, r);
  2767. return r;
  2768. };
  2769. /**
  2770. * Transforms the given vector coordinates by the given transformation matrix and stores the result in the vector "result" coordinates
  2771. * @param vector defines the vector to transform
  2772. * @param transformation defines the matrix to apply
  2773. * @param result defines the target vector
  2774. */
  2775. Vector2.TransformToRef = function (vector, transformation, result) {
  2776. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + transformation.m[12];
  2777. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + transformation.m[13];
  2778. result.x = x;
  2779. result.y = y;
  2780. };
  2781. /**
  2782. * Determines if a given vector is included in a triangle
  2783. * @param p defines the vector to test
  2784. * @param p0 defines 1st triangle point
  2785. * @param p1 defines 2nd triangle point
  2786. * @param p2 defines 3rd triangle point
  2787. * @returns true if the point "p" is in the triangle defined by the vertors "p0", "p1", "p2"
  2788. */
  2789. Vector2.PointInTriangle = function (p, p0, p1, p2) {
  2790. var a = 1 / 2 * (-p1.y * p2.x + p0.y * (-p1.x + p2.x) + p0.x * (p1.y - p2.y) + p1.x * p2.y);
  2791. var sign = a < 0 ? -1 : 1;
  2792. var s = (p0.y * p2.x - p0.x * p2.y + (p2.y - p0.y) * p.x + (p0.x - p2.x) * p.y) * sign;
  2793. var t = (p0.x * p1.y - p0.y * p1.x + (p0.y - p1.y) * p.x + (p1.x - p0.x) * p.y) * sign;
  2794. return s > 0 && t > 0 && (s + t) < 2 * a * sign;
  2795. };
  2796. /**
  2797. * Gets the distance between the vectors "value1" and "value2"
  2798. * @param value1 defines first vector
  2799. * @param value2 defines second vector
  2800. * @returns the distance between vectors
  2801. */
  2802. Vector2.Distance = function (value1, value2) {
  2803. return Math.sqrt(Vector2.DistanceSquared(value1, value2));
  2804. };
  2805. /**
  2806. * Returns the squared distance between the vectors "value1" and "value2"
  2807. * @param value1 defines first vector
  2808. * @param value2 defines second vector
  2809. * @returns the squared distance between vectors
  2810. */
  2811. Vector2.DistanceSquared = function (value1, value2) {
  2812. var x = value1.x - value2.x;
  2813. var y = value1.y - value2.y;
  2814. return (x * x) + (y * y);
  2815. };
  2816. /**
  2817. * Gets a new Vector2 located at the center of the vectors "value1" and "value2"
  2818. * @param value1 defines first vector
  2819. * @param value2 defines second vector
  2820. * @returns a new Vector2
  2821. */
  2822. Vector2.Center = function (value1, value2) {
  2823. var center = value1.add(value2);
  2824. center.scaleInPlace(0.5);
  2825. return center;
  2826. };
  2827. /**
  2828. * Gets the shortest distance (float) between the point "p" and the segment defined by the two points "segA" and "segB".
  2829. * @param p defines the middle point
  2830. * @param segA defines one point of the segment
  2831. * @param segB defines the other point of the segment
  2832. * @returns the shortest distance
  2833. */
  2834. Vector2.DistanceOfPointFromSegment = function (p, segA, segB) {
  2835. var l2 = Vector2.DistanceSquared(segA, segB);
  2836. if (l2 === 0.0) {
  2837. return Vector2.Distance(p, segA);
  2838. }
  2839. var v = segB.subtract(segA);
  2840. var t = Math.max(0, Math.min(1, Vector2.Dot(p.subtract(segA), v) / l2));
  2841. var proj = segA.add(v.multiplyByFloats(t, t));
  2842. return Vector2.Distance(p, proj);
  2843. };
  2844. return Vector2;
  2845. }());
  2846. BABYLON.Vector2 = Vector2;
  2847. /**
  2848. * Classed used to store (x,y,z) vector representation
  2849. * A Vector3 is the main object used in 3D geometry
  2850. * It can represent etiher the coordinates of a point the space, either a direction
  2851. * Reminder: Babylon.js uses a left handed forward facing system
  2852. */
  2853. var Vector3 = /** @class */ (function () {
  2854. /**
  2855. * Creates a new Vector3 object from the given x, y, z (floats) coordinates.
  2856. * @param x defines the first coordinates (on X axis)
  2857. * @param y defines the second coordinates (on Y axis)
  2858. * @param z defines the third coordinates (on Z axis)
  2859. */
  2860. function Vector3(
  2861. /**
  2862. * Defines the first coordinates (on X axis)
  2863. */
  2864. x,
  2865. /**
  2866. * Defines the second coordinates (on Y axis)
  2867. */
  2868. y,
  2869. /**
  2870. * Defines the third coordinates (on Z axis)
  2871. */
  2872. z) {
  2873. if (x === void 0) { x = 0; }
  2874. if (y === void 0) { y = 0; }
  2875. if (z === void 0) { z = 0; }
  2876. this.x = x;
  2877. this.y = y;
  2878. this.z = z;
  2879. }
  2880. /**
  2881. * Creates a string representation of the Vector3
  2882. * @returns a string with the Vector3 coordinates.
  2883. */
  2884. Vector3.prototype.toString = function () {
  2885. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + "}";
  2886. };
  2887. /**
  2888. * Gets the class name
  2889. * @returns the string "Vector3"
  2890. */
  2891. Vector3.prototype.getClassName = function () {
  2892. return "Vector3";
  2893. };
  2894. /**
  2895. * Creates the Vector3 hash code
  2896. * @returns a number which tends to be unique between Vector3 instances
  2897. */
  2898. Vector3.prototype.getHashCode = function () {
  2899. var hash = this.x || 0;
  2900. hash = (hash * 397) ^ (this.y || 0);
  2901. hash = (hash * 397) ^ (this.z || 0);
  2902. return hash;
  2903. };
  2904. // Operators
  2905. /**
  2906. * Creates an array containing three elements : the coordinates of the Vector3
  2907. * @returns a new array of numbers
  2908. */
  2909. Vector3.prototype.asArray = function () {
  2910. var result = [];
  2911. this.toArray(result, 0);
  2912. return result;
  2913. };
  2914. /**
  2915. * Populates the given array or Float32Array from the given index with the successive coordinates of the Vector3
  2916. * @param array defines the destination array
  2917. * @param index defines the offset in the destination array
  2918. * @returns the current Vector3
  2919. */
  2920. Vector3.prototype.toArray = function (array, index) {
  2921. if (index === void 0) { index = 0; }
  2922. array[index] = this.x;
  2923. array[index + 1] = this.y;
  2924. array[index + 2] = this.z;
  2925. return this;
  2926. };
  2927. /**
  2928. * Converts the current Vector3 into a quaternion (considering that the Vector3 contains Euler angles representation of a rotation)
  2929. * @returns a new Quaternion object, computed from the Vector3 coordinates
  2930. */
  2931. Vector3.prototype.toQuaternion = function () {
  2932. return BABYLON.Quaternion.RotationYawPitchRoll(this.x, this.y, this.z);
  2933. };
  2934. /**
  2935. * Adds the given vector to the current Vector3
  2936. * @param otherVector defines the second operand
  2937. * @returns the current updated Vector3
  2938. */
  2939. Vector3.prototype.addInPlace = function (otherVector) {
  2940. this.x += otherVector.x;
  2941. this.y += otherVector.y;
  2942. this.z += otherVector.z;
  2943. return this;
  2944. };
  2945. /**
  2946. * Gets a new Vector3, result of the addition the current Vector3 and the given vector
  2947. * @param otherVector defines the second operand
  2948. * @returns the resulting Vector3
  2949. */
  2950. Vector3.prototype.add = function (otherVector) {
  2951. return new Vector3(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z);
  2952. };
  2953. /**
  2954. * Adds the current Vector3 to the given one and stores the result in the vector "result"
  2955. * @param otherVector defines the second operand
  2956. * @param result defines the Vector3 object where to store the result
  2957. * @returns the current Vector3
  2958. */
  2959. Vector3.prototype.addToRef = function (otherVector, result) {
  2960. result.x = this.x + otherVector.x;
  2961. result.y = this.y + otherVector.y;
  2962. result.z = this.z + otherVector.z;
  2963. return this;
  2964. };
  2965. /**
  2966. * Subtract the given vector from the current Vector3
  2967. * @param otherVector defines the second operand
  2968. * @returns the current updated Vector3
  2969. */
  2970. Vector3.prototype.subtractInPlace = function (otherVector) {
  2971. this.x -= otherVector.x;
  2972. this.y -= otherVector.y;
  2973. this.z -= otherVector.z;
  2974. return this;
  2975. };
  2976. /**
  2977. * Returns a new Vector3, result of the subtraction of the given vector from the current Vector3
  2978. * @param otherVector defines the second operand
  2979. * @returns the resulting Vector3
  2980. */
  2981. Vector3.prototype.subtract = function (otherVector) {
  2982. return new Vector3(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z);
  2983. };
  2984. /**
  2985. * Subtracts the given vector from the current Vector3 and stores the result in the vector "result".
  2986. * @param otherVector defines the second operand
  2987. * @param result defines the Vector3 object where to store the result
  2988. * @returns the current Vector3
  2989. */
  2990. Vector3.prototype.subtractToRef = function (otherVector, result) {
  2991. result.x = this.x - otherVector.x;
  2992. result.y = this.y - otherVector.y;
  2993. result.z = this.z - otherVector.z;
  2994. return this;
  2995. };
  2996. /**
  2997. * Returns a new Vector3 set with the subtraction of the given floats from the current Vector3 coordinates
  2998. * @param x defines the x coordinate of the operand
  2999. * @param y defines the y coordinate of the operand
  3000. * @param z defines the z coordinate of the operand
  3001. * @returns the resulting Vector3
  3002. */
  3003. Vector3.prototype.subtractFromFloats = function (x, y, z) {
  3004. return new Vector3(this.x - x, this.y - y, this.z - z);
  3005. };
  3006. /**
  3007. * Subtracts the given floats from the current Vector3 coordinates and set the given vector "result" with this result
  3008. * @param x defines the x coordinate of the operand
  3009. * @param y defines the y coordinate of the operand
  3010. * @param z defines the z coordinate of the operand
  3011. * @param result defines the Vector3 object where to store the result
  3012. * @returns the current Vector3
  3013. */
  3014. Vector3.prototype.subtractFromFloatsToRef = function (x, y, z, result) {
  3015. result.x = this.x - x;
  3016. result.y = this.y - y;
  3017. result.z = this.z - z;
  3018. return this;
  3019. };
  3020. /**
  3021. * Gets a new Vector3 set with the current Vector3 negated coordinates
  3022. * @returns a new Vector3
  3023. */
  3024. Vector3.prototype.negate = function () {
  3025. return new Vector3(-this.x, -this.y, -this.z);
  3026. };
  3027. /**
  3028. * Multiplies the Vector3 coordinates by the float "scale"
  3029. * @param scale defines the multiplier factor
  3030. * @returns the current updated Vector3
  3031. */
  3032. Vector3.prototype.scaleInPlace = function (scale) {
  3033. this.x *= scale;
  3034. this.y *= scale;
  3035. this.z *= scale;
  3036. return this;
  3037. };
  3038. /**
  3039. * Returns a new Vector3 set with the current Vector3 coordinates multiplied by the float "scale"
  3040. * @param scale defines the multiplier factor
  3041. * @returns a new Vector3
  3042. */
  3043. Vector3.prototype.scale = function (scale) {
  3044. return new Vector3(this.x * scale, this.y * scale, this.z * scale);
  3045. };
  3046. /**
  3047. * Multiplies the current Vector3 coordinates by the float "scale" and stores the result in the given vector "result" coordinates
  3048. * @param scale defines the multiplier factor
  3049. * @param result defines the Vector3 object where to store the result
  3050. * @returns the current Vector3
  3051. */
  3052. Vector3.prototype.scaleToRef = function (scale, result) {
  3053. result.x = this.x * scale;
  3054. result.y = this.y * scale;
  3055. result.z = this.z * scale;
  3056. return this;
  3057. };
  3058. /**
  3059. * Scale the current Vector3 values by a factor and add the result to a given Vector3
  3060. * @param scale defines the scale factor
  3061. * @param result defines the Vector3 object where to store the result
  3062. * @returns the unmodified current Vector3
  3063. */
  3064. Vector3.prototype.scaleAndAddToRef = function (scale, result) {
  3065. result.x += this.x * scale;
  3066. result.y += this.y * scale;
  3067. result.z += this.z * scale;
  3068. return this;
  3069. };
  3070. /**
  3071. * Returns true if the current Vector3 and the given vector coordinates are strictly equal
  3072. * @param otherVector defines the second operand
  3073. * @returns true if both vectors are equals
  3074. */
  3075. Vector3.prototype.equals = function (otherVector) {
  3076. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z;
  3077. };
  3078. /**
  3079. * Returns true if the current Vector3 and the given vector coordinates are distant less than epsilon
  3080. * @param otherVector defines the second operand
  3081. * @param epsilon defines the minimal distance to define values as equals
  3082. * @returns true if both vectors are distant less than epsilon
  3083. */
  3084. Vector3.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  3085. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  3086. 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);
  3087. };
  3088. /**
  3089. * Returns true if the current Vector3 coordinates equals the given floats
  3090. * @param x defines the x coordinate of the operand
  3091. * @param y defines the y coordinate of the operand
  3092. * @param z defines the z coordinate of the operand
  3093. * @returns true if both vectors are equals
  3094. */
  3095. Vector3.prototype.equalsToFloats = function (x, y, z) {
  3096. return this.x === x && this.y === y && this.z === z;
  3097. };
  3098. /**
  3099. * Multiplies the current Vector3 coordinates by the given ones
  3100. * @param otherVector defines the second operand
  3101. * @returns the current updated Vector3
  3102. */
  3103. Vector3.prototype.multiplyInPlace = function (otherVector) {
  3104. this.x *= otherVector.x;
  3105. this.y *= otherVector.y;
  3106. this.z *= otherVector.z;
  3107. return this;
  3108. };
  3109. /**
  3110. * Returns a new Vector3, result of the multiplication of the current Vector3 by the given vector
  3111. * @param otherVector defines the second operand
  3112. * @returns the new Vector3
  3113. */
  3114. Vector3.prototype.multiply = function (otherVector) {
  3115. return new Vector3(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z);
  3116. };
  3117. /**
  3118. * Multiplies the current Vector3 by the given one and stores the result in the given vector "result"
  3119. * @param otherVector defines the second operand
  3120. * @param result defines the Vector3 object where to store the result
  3121. * @returns the current Vector3
  3122. */
  3123. Vector3.prototype.multiplyToRef = function (otherVector, result) {
  3124. result.x = this.x * otherVector.x;
  3125. result.y = this.y * otherVector.y;
  3126. result.z = this.z * otherVector.z;
  3127. return this;
  3128. };
  3129. /**
  3130. * Returns a new Vector3 set with the result of the mulliplication of the current Vector3 coordinates by the given floats
  3131. * @param x defines the x coordinate of the operand
  3132. * @param y defines the y coordinate of the operand
  3133. * @param z defines the z coordinate of the operand
  3134. * @returns the new Vector3
  3135. */
  3136. Vector3.prototype.multiplyByFloats = function (x, y, z) {
  3137. return new Vector3(this.x * x, this.y * y, this.z * z);
  3138. };
  3139. /**
  3140. * Returns a new Vector3 set with the result of the division of the current Vector3 coordinates by the given ones
  3141. * @param otherVector defines the second operand
  3142. * @returns the new Vector3
  3143. */
  3144. Vector3.prototype.divide = function (otherVector) {
  3145. return new Vector3(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z);
  3146. };
  3147. /**
  3148. * Divides the current Vector3 coordinates by the given ones and stores the result in the given vector "result"
  3149. * @param otherVector defines the second operand
  3150. * @param result defines the Vector3 object where to store the result
  3151. * @returns the current Vector3
  3152. */
  3153. Vector3.prototype.divideToRef = function (otherVector, result) {
  3154. result.x = this.x / otherVector.x;
  3155. result.y = this.y / otherVector.y;
  3156. result.z = this.z / otherVector.z;
  3157. return this;
  3158. };
  3159. /**
  3160. * Divides the current Vector3 coordinates by the given ones.
  3161. * @param otherVector defines the second operand
  3162. * @returns the current updated Vector3
  3163. */
  3164. Vector3.prototype.divideInPlace = function (otherVector) {
  3165. return this.divideToRef(otherVector, this);
  3166. };
  3167. /**
  3168. * Updates the current Vector3 with the minimal coordinate values between its and the given vector ones
  3169. * @param other defines the second operand
  3170. * @returns the current updated Vector3
  3171. */
  3172. Vector3.prototype.minimizeInPlace = function (other) {
  3173. if (other.x < this.x)
  3174. this.x = other.x;
  3175. if (other.y < this.y)
  3176. this.y = other.y;
  3177. if (other.z < this.z)
  3178. this.z = other.z;
  3179. return this;
  3180. };
  3181. /**
  3182. * Updates the current Vector3 with the maximal coordinate values between its and the given vector ones.
  3183. * @param other defines the second operand
  3184. * @returns the current updated Vector3
  3185. */
  3186. Vector3.prototype.maximizeInPlace = function (other) {
  3187. if (other.x > this.x)
  3188. this.x = other.x;
  3189. if (other.y > this.y)
  3190. this.y = other.y;
  3191. if (other.z > this.z)
  3192. this.z = other.z;
  3193. return this;
  3194. };
  3195. Object.defineProperty(Vector3.prototype, "isNonUniform", {
  3196. /**
  3197. * Gets a boolean indicating that the vector is non uniform meaning x, y or z are not all the same
  3198. */
  3199. get: function () {
  3200. var absX = Math.abs(this.x);
  3201. var absY = Math.abs(this.y);
  3202. if (absX !== absY) {
  3203. return true;
  3204. }
  3205. var absZ = Math.abs(this.z);
  3206. if (absX !== absZ) {
  3207. return true;
  3208. }
  3209. if (absY !== absZ) {
  3210. return true;
  3211. }
  3212. return false;
  3213. },
  3214. enumerable: true,
  3215. configurable: true
  3216. });
  3217. // Properties
  3218. /**
  3219. * Gets the length of the Vector3
  3220. * @returns the length of the Vecto3
  3221. */
  3222. Vector3.prototype.length = function () {
  3223. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z);
  3224. };
  3225. /**
  3226. * Gets the squared length of the Vector3
  3227. * @returns squared length of the Vector3
  3228. */
  3229. Vector3.prototype.lengthSquared = function () {
  3230. return (this.x * this.x + this.y * this.y + this.z * this.z);
  3231. };
  3232. /**
  3233. * Normalize the current Vector3.
  3234. * Please note that this is an in place operation.
  3235. * @returns the current updated Vector3
  3236. */
  3237. Vector3.prototype.normalize = function () {
  3238. var len = this.length();
  3239. if (len === 0 || len === 1.0)
  3240. return this;
  3241. var num = 1.0 / len;
  3242. this.x *= num;
  3243. this.y *= num;
  3244. this.z *= num;
  3245. return this;
  3246. };
  3247. /**
  3248. * Normalize the current Vector3 to a new vector
  3249. * @returns the new Vector3
  3250. */
  3251. Vector3.prototype.normalizeToNew = function () {
  3252. var normalized = new Vector3(0, 0, 0);
  3253. this.normalizeToRef(normalized);
  3254. return normalized;
  3255. };
  3256. /**
  3257. * Normalize the current Vector3 to the reference
  3258. * @param reference define the Vector3 to update
  3259. * @returns the updated Vector3
  3260. */
  3261. Vector3.prototype.normalizeToRef = function (reference) {
  3262. var len = this.length();
  3263. if (len === 0 || len === 1.0) {
  3264. reference.set(this.x, this.y, this.z);
  3265. return reference;
  3266. }
  3267. var scale = 1.0 / len;
  3268. this.scaleToRef(scale, reference);
  3269. return reference;
  3270. };
  3271. /**
  3272. * Creates a new Vector3 copied from the current Vector3
  3273. * @returns the new Vector3
  3274. */
  3275. Vector3.prototype.clone = function () {
  3276. return new Vector3(this.x, this.y, this.z);
  3277. };
  3278. /**
  3279. * Copies the given vector coordinates to the current Vector3 ones
  3280. * @param source defines the source Vector3
  3281. * @returns the current updated Vector3
  3282. */
  3283. Vector3.prototype.copyFrom = function (source) {
  3284. this.x = source.x;
  3285. this.y = source.y;
  3286. this.z = source.z;
  3287. return this;
  3288. };
  3289. /**
  3290. * Copies the given floats to the current Vector3 coordinates
  3291. * @param x defines the x coordinate of the operand
  3292. * @param y defines the y coordinate of the operand
  3293. * @param z defines the z coordinate of the operand
  3294. * @returns the current updated Vector3
  3295. */
  3296. Vector3.prototype.copyFromFloats = function (x, y, z) {
  3297. this.x = x;
  3298. this.y = y;
  3299. this.z = z;
  3300. return this;
  3301. };
  3302. /**
  3303. * Copies the given floats to the current Vector3 coordinates
  3304. * @param x defines the x coordinate of the operand
  3305. * @param y defines the y coordinate of the operand
  3306. * @param z defines the z coordinate of the operand
  3307. * @returns the current updated Vector3
  3308. */
  3309. Vector3.prototype.set = function (x, y, z) {
  3310. return this.copyFromFloats(x, y, z);
  3311. };
  3312. // Statics
  3313. /**
  3314. * Get the clip factor between two vectors
  3315. * @param vector0 defines the first operand
  3316. * @param vector1 defines the second operand
  3317. * @param axis defines the axis to use
  3318. * @param size defines the size along the axis
  3319. * @returns the clip factor
  3320. */
  3321. Vector3.GetClipFactor = function (vector0, vector1, axis, size) {
  3322. var d0 = Vector3.Dot(vector0, axis) - size;
  3323. var d1 = Vector3.Dot(vector1, axis) - size;
  3324. var s = d0 / (d0 - d1);
  3325. return s;
  3326. };
  3327. /**
  3328. * Get angle between two vectors
  3329. * @param vector0 angle between vector0 and vector1
  3330. * @param vector1 angle between vector0 and vector1
  3331. * @param normal direction of the normal
  3332. * @return the angle between vector0 and vector1
  3333. */
  3334. Vector3.GetAngleBetweenVectors = function (vector0, vector1, normal) {
  3335. var v0 = vector0.clone().normalize();
  3336. var v1 = vector1.clone().normalize();
  3337. var dot = Vector3.Dot(v0, v1);
  3338. var n = Vector3.Cross(v0, v1);
  3339. if (Vector3.Dot(n, normal) > 0) {
  3340. return Math.acos(dot);
  3341. }
  3342. return -Math.acos(dot);
  3343. };
  3344. /**
  3345. * Returns a new Vector3 set from the index "offset" of the given array
  3346. * @param array defines the source array
  3347. * @param offset defines the offset in the source array
  3348. * @returns the new Vector3
  3349. */
  3350. Vector3.FromArray = function (array, offset) {
  3351. if (!offset) {
  3352. offset = 0;
  3353. }
  3354. return new Vector3(array[offset], array[offset + 1], array[offset + 2]);
  3355. };
  3356. /**
  3357. * Returns a new Vector3 set from the index "offset" of the given Float32Array
  3358. * This function is deprecated. Use FromArray instead
  3359. * @param array defines the source array
  3360. * @param offset defines the offset in the source array
  3361. * @returns the new Vector3
  3362. */
  3363. Vector3.FromFloatArray = function (array, offset) {
  3364. return Vector3.FromArray(array, offset);
  3365. };
  3366. /**
  3367. * Sets the given vector "result" with the element values from the index "offset" of the given array
  3368. * @param array defines the source array
  3369. * @param offset defines the offset in the source array
  3370. * @param result defines the Vector3 where to store the result
  3371. */
  3372. Vector3.FromArrayToRef = function (array, offset, result) {
  3373. result.x = array[offset];
  3374. result.y = array[offset + 1];
  3375. result.z = array[offset + 2];
  3376. };
  3377. /**
  3378. * Sets the given vector "result" with the element values from the index "offset" of the given Float32Array
  3379. * This function is deprecated. Use FromArrayToRef instead.
  3380. * @param array defines the source array
  3381. * @param offset defines the offset in the source array
  3382. * @param result defines the Vector3 where to store the result
  3383. */
  3384. Vector3.FromFloatArrayToRef = function (array, offset, result) {
  3385. return Vector3.FromArrayToRef(array, offset, result);
  3386. };
  3387. /**
  3388. * Sets the given vector "result" with the given floats.
  3389. * @param x defines the x coordinate of the source
  3390. * @param y defines the y coordinate of the source
  3391. * @param z defines the z coordinate of the source
  3392. * @param result defines the Vector3 where to store the result
  3393. */
  3394. Vector3.FromFloatsToRef = function (x, y, z, result) {
  3395. result.x = x;
  3396. result.y = y;
  3397. result.z = z;
  3398. };
  3399. /**
  3400. * Returns a new Vector3 set to (0.0, 0.0, 0.0)
  3401. * @returns a new empty Vector3
  3402. */
  3403. Vector3.Zero = function () {
  3404. return new Vector3(0.0, 0.0, 0.0);
  3405. };
  3406. /**
  3407. * Returns a new Vector3 set to (1.0, 1.0, 1.0)
  3408. * @returns a new unit Vector3
  3409. */
  3410. Vector3.One = function () {
  3411. return new Vector3(1.0, 1.0, 1.0);
  3412. };
  3413. /**
  3414. * Returns a new Vector3 set to (0.0, 1.0, 0.0)
  3415. * @returns a new up Vector3
  3416. */
  3417. Vector3.Up = function () {
  3418. return new Vector3(0.0, 1.0, 0.0);
  3419. };
  3420. /**
  3421. * Returns a new Vector3 set to (0.0, -1.0, 0.0)
  3422. * @returns a new down Vector3
  3423. */
  3424. Vector3.Down = function () {
  3425. return new Vector3(0.0, -1.0, 0.0);
  3426. };
  3427. /**
  3428. * Returns a new Vector3 set to (0.0, 0.0, 1.0)
  3429. * @returns a new forward Vector3
  3430. */
  3431. Vector3.Forward = function () {
  3432. return new Vector3(0.0, 0.0, 1.0);
  3433. };
  3434. /**
  3435. * Returns a new Vector3 set to (1.0, 0.0, 0.0)
  3436. * @returns a new right Vector3
  3437. */
  3438. Vector3.Right = function () {
  3439. return new Vector3(1.0, 0.0, 0.0);
  3440. };
  3441. /**
  3442. * Returns a new Vector3 set to (-1.0, 0.0, 0.0)
  3443. * @returns a new left Vector3
  3444. */
  3445. Vector3.Left = function () {
  3446. return new Vector3(-1.0, 0.0, 0.0);
  3447. };
  3448. /**
  3449. * Returns a new Vector3 set with the result of the transformation by the given matrix of the given vector.
  3450. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3451. * @param vector defines the Vector3 to transform
  3452. * @param transformation defines the transformation matrix
  3453. * @returns the transformed Vector3
  3454. */
  3455. Vector3.TransformCoordinates = function (vector, transformation) {
  3456. var result = Vector3.Zero();
  3457. Vector3.TransformCoordinatesToRef(vector, transformation, result);
  3458. return result;
  3459. };
  3460. /**
  3461. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given vector
  3462. * This method computes tranformed coordinates only, not transformed direction vectors (ie. it takes translation in account)
  3463. * @param vector defines the Vector3 to transform
  3464. * @param transformation defines the transformation matrix
  3465. * @param result defines the Vector3 where to store the result
  3466. */
  3467. Vector3.TransformCoordinatesToRef = function (vector, transformation, result) {
  3468. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]) + transformation.m[12];
  3469. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]) + transformation.m[13];
  3470. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]) + transformation.m[14];
  3471. var w = (vector.x * transformation.m[3]) + (vector.y * transformation.m[7]) + (vector.z * transformation.m[11]) + transformation.m[15];
  3472. result.x = x / w;
  3473. result.y = y / w;
  3474. result.z = z / w;
  3475. };
  3476. /**
  3477. * Sets the given vector "result" coordinates with the result of the transformation by the given matrix of the given floats (x, y, z)
  3478. * This method computes tranformed coordinates only, not transformed direction vectors
  3479. * @param x define the x coordinate of the source vector
  3480. * @param y define the y coordinate of the source vector
  3481. * @param z define the z coordinate of the source vector
  3482. * @param transformation defines the transformation matrix
  3483. * @param result defines the Vector3 where to store the result
  3484. */
  3485. Vector3.TransformCoordinatesFromFloatsToRef = function (x, y, z, transformation, result) {
  3486. var rx = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]) + transformation.m[12];
  3487. var ry = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]) + transformation.m[13];
  3488. var rz = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]) + transformation.m[14];
  3489. var rw = (x * transformation.m[3]) + (y * transformation.m[7]) + (z * transformation.m[11]) + transformation.m[15];
  3490. result.x = rx / rw;
  3491. result.y = ry / rw;
  3492. result.z = rz / rw;
  3493. };
  3494. /**
  3495. * Returns a new Vector3 set with the result of the normal transformation by the given matrix of the given vector
  3496. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3497. * @param vector defines the Vector3 to transform
  3498. * @param transformation defines the transformation matrix
  3499. * @returns the new Vector3
  3500. */
  3501. Vector3.TransformNormal = function (vector, transformation) {
  3502. var result = Vector3.Zero();
  3503. Vector3.TransformNormalToRef(vector, transformation, result);
  3504. return result;
  3505. };
  3506. /**
  3507. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector
  3508. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3509. * @param vector defines the Vector3 to transform
  3510. * @param transformation defines the transformation matrix
  3511. * @param result defines the Vector3 where to store the result
  3512. */
  3513. Vector3.TransformNormalToRef = function (vector, transformation, result) {
  3514. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  3515. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  3516. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  3517. result.x = x;
  3518. result.y = y;
  3519. result.z = z;
  3520. };
  3521. /**
  3522. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z)
  3523. * This methods computes transformed normalized direction vectors only (ie. it does not apply translation)
  3524. * @param x define the x coordinate of the source vector
  3525. * @param y define the y coordinate of the source vector
  3526. * @param z define the z coordinate of the source vector
  3527. * @param transformation defines the transformation matrix
  3528. * @param result defines the Vector3 where to store the result
  3529. */
  3530. Vector3.TransformNormalFromFloatsToRef = function (x, y, z, transformation, result) {
  3531. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  3532. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  3533. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  3534. };
  3535. /**
  3536. * Returns a new Vector3 located for "amount" on the CatmullRom interpolation spline defined by the vectors "value1", "value2", "value3", "value4"
  3537. * @param value1 defines the first control point
  3538. * @param value2 defines the second control point
  3539. * @param value3 defines the third control point
  3540. * @param value4 defines the fourth control point
  3541. * @param amount defines the amount on the spline to use
  3542. * @returns the new Vector3
  3543. */
  3544. Vector3.CatmullRom = function (value1, value2, value3, value4, amount) {
  3545. var squared = amount * amount;
  3546. var cubed = amount * squared;
  3547. var x = 0.5 * ((((2.0 * value2.x) + ((-value1.x + value3.x) * amount)) +
  3548. (((((2.0 * value1.x) - (5.0 * value2.x)) + (4.0 * value3.x)) - value4.x) * squared)) +
  3549. ((((-value1.x + (3.0 * value2.x)) - (3.0 * value3.x)) + value4.x) * cubed));
  3550. var y = 0.5 * ((((2.0 * value2.y) + ((-value1.y + value3.y) * amount)) +
  3551. (((((2.0 * value1.y) - (5.0 * value2.y)) + (4.0 * value3.y)) - value4.y) * squared)) +
  3552. ((((-value1.y + (3.0 * value2.y)) - (3.0 * value3.y)) + value4.y) * cubed));
  3553. var z = 0.5 * ((((2.0 * value2.z) + ((-value1.z + value3.z) * amount)) +
  3554. (((((2.0 * value1.z) - (5.0 * value2.z)) + (4.0 * value3.z)) - value4.z) * squared)) +
  3555. ((((-value1.z + (3.0 * value2.z)) - (3.0 * value3.z)) + value4.z) * cubed));
  3556. return new Vector3(x, y, z);
  3557. };
  3558. /**
  3559. * 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"
  3560. * If a coordinate value of "value" is lower than one of the "min" coordinate, then this "value" coordinate is set with the "min" one
  3561. * If a coordinate value of "value" is greater than one of the "max" coordinate, then this "value" coordinate is set with the "max" one
  3562. * @param value defines the current value
  3563. * @param min defines the lower range value
  3564. * @param max defines the upper range value
  3565. * @returns the new Vector3
  3566. */
  3567. Vector3.Clamp = function (value, min, max) {
  3568. var x = value.x;
  3569. x = (x > max.x) ? max.x : x;
  3570. x = (x < min.x) ? min.x : x;
  3571. var y = value.y;
  3572. y = (y > max.y) ? max.y : y;
  3573. y = (y < min.y) ? min.y : y;
  3574. var z = value.z;
  3575. z = (z > max.z) ? max.z : z;
  3576. z = (z < min.z) ? min.z : z;
  3577. return new Vector3(x, y, z);
  3578. };
  3579. /**
  3580. * Returns a new Vector3 located for "amount" (float) on the Hermite interpolation spline defined by the vectors "value1", "tangent1", "value2", "tangent2"
  3581. * @param value1 defines the first control point
  3582. * @param tangent1 defines the first tangent vector
  3583. * @param value2 defines the second control point
  3584. * @param tangent2 defines the second tangent vector
  3585. * @param amount defines the amount on the interpolation spline (between 0 and 1)
  3586. * @returns the new Vector3
  3587. */
  3588. Vector3.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  3589. var squared = amount * amount;
  3590. var cubed = amount * squared;
  3591. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  3592. var part2 = (-2.0 * cubed) + (3.0 * squared);
  3593. var part3 = (cubed - (2.0 * squared)) + amount;
  3594. var part4 = cubed - squared;
  3595. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  3596. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  3597. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  3598. return new Vector3(x, y, z);
  3599. };
  3600. /**
  3601. * Returns a new Vector3 located for "amount" (float) on the linear interpolation between the vectors "start" and "end"
  3602. * @param start defines the start value
  3603. * @param end defines the end value
  3604. * @param amount max defines amount between both (between 0 and 1)
  3605. * @returns the new Vector3
  3606. */
  3607. Vector3.Lerp = function (start, end, amount) {
  3608. var result = new Vector3(0, 0, 0);
  3609. Vector3.LerpToRef(start, end, amount, result);
  3610. return result;
  3611. };
  3612. /**
  3613. * Sets the given vector "result" with the result of the linear interpolation from the vector "start" for "amount" to the vector "end"
  3614. * @param start defines the start value
  3615. * @param end defines the end value
  3616. * @param amount max defines amount between both (between 0 and 1)
  3617. * @param result defines the Vector3 where to store the result
  3618. */
  3619. Vector3.LerpToRef = function (start, end, amount, result) {
  3620. result.x = start.x + ((end.x - start.x) * amount);
  3621. result.y = start.y + ((end.y - start.y) * amount);
  3622. result.z = start.z + ((end.z - start.z) * amount);
  3623. };
  3624. /**
  3625. * Returns the dot product (float) between the vectors "left" and "right"
  3626. * @param left defines the left operand
  3627. * @param right defines the right operand
  3628. * @returns the dot product
  3629. */
  3630. Vector3.Dot = function (left, right) {
  3631. return (left.x * right.x + left.y * right.y + left.z * right.z);
  3632. };
  3633. /**
  3634. * Returns a new Vector3 as the cross product of the vectors "left" and "right"
  3635. * The cross product is then orthogonal to both "left" and "right"
  3636. * @param left defines the left operand
  3637. * @param right defines the right operand
  3638. * @returns the cross product
  3639. */
  3640. Vector3.Cross = function (left, right) {
  3641. var result = Vector3.Zero();
  3642. Vector3.CrossToRef(left, right, result);
  3643. return result;
  3644. };
  3645. /**
  3646. * Sets the given vector "result" with the cross product of "left" and "right"
  3647. * The cross product is then orthogonal to both "left" and "right"
  3648. * @param left defines the left operand
  3649. * @param right defines the right operand
  3650. * @param result defines the Vector3 where to store the result
  3651. */
  3652. Vector3.CrossToRef = function (left, right, result) {
  3653. MathTmp.Vector3[0].x = left.y * right.z - left.z * right.y;
  3654. MathTmp.Vector3[0].y = left.z * right.x - left.x * right.z;
  3655. MathTmp.Vector3[0].z = left.x * right.y - left.y * right.x;
  3656. result.copyFrom(MathTmp.Vector3[0]);
  3657. };
  3658. /**
  3659. * Returns a new Vector3 as the normalization of the given vector
  3660. * @param vector defines the Vector3 to normalize
  3661. * @returns the new Vector3
  3662. */
  3663. Vector3.Normalize = function (vector) {
  3664. var result = Vector3.Zero();
  3665. Vector3.NormalizeToRef(vector, result);
  3666. return result;
  3667. };
  3668. /**
  3669. * Sets the given vector "result" with the normalization of the given first vector
  3670. * @param vector defines the Vector3 to normalize
  3671. * @param result defines the Vector3 where to store the result
  3672. */
  3673. Vector3.NormalizeToRef = function (vector, result) {
  3674. result.copyFrom(vector);
  3675. result.normalize();
  3676. };
  3677. /**
  3678. * Project a Vector3 onto screen space
  3679. * @param vector defines the Vector3 to project
  3680. * @param world defines the world matrix to use
  3681. * @param transform defines the transform (view x projection) matrix to use
  3682. * @param viewport defines the screen viewport to use
  3683. * @returns the new Vector3
  3684. */
  3685. Vector3.Project = function (vector, world, transform, viewport) {
  3686. var cw = viewport.width;
  3687. var ch = viewport.height;
  3688. var cx = viewport.x;
  3689. var cy = viewport.y;
  3690. var viewportMatrix = Vector3._viewportMatrixCache ? Vector3._viewportMatrixCache : (Vector3._viewportMatrixCache = new Matrix());
  3691. 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);
  3692. var matrix = MathTmp.Matrix[0];
  3693. world.multiplyToRef(transform, matrix);
  3694. matrix.multiplyToRef(viewportMatrix, matrix);
  3695. return Vector3.TransformCoordinates(vector, matrix);
  3696. };
  3697. /**
  3698. * Unproject from screen space to object space
  3699. * @param source defines the screen space Vector3 to use
  3700. * @param viewportWidth defines the current width of the viewport
  3701. * @param viewportHeight defines the current height of the viewport
  3702. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3703. * @param transform defines the transform (view x projection) matrix to use
  3704. * @returns the new Vector3
  3705. */
  3706. Vector3.UnprojectFromTransform = function (source, viewportWidth, viewportHeight, world, transform) {
  3707. var matrix = MathTmp.Matrix[0];
  3708. world.multiplyToRef(transform, matrix);
  3709. matrix.invert();
  3710. source.x = source.x / viewportWidth * 2 - 1;
  3711. source.y = -(source.y / viewportHeight * 2 - 1);
  3712. var vector = Vector3.TransformCoordinates(source, matrix);
  3713. var num = source.x * matrix.m[3] + source.y * matrix.m[7] + source.z * matrix.m[11] + matrix.m[15];
  3714. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3715. vector = vector.scale(1.0 / num);
  3716. }
  3717. return vector;
  3718. };
  3719. /**
  3720. * Unproject from screen space to object space
  3721. * @param source defines the screen space Vector3 to use
  3722. * @param viewportWidth defines the current width of the viewport
  3723. * @param viewportHeight defines the current height of the viewport
  3724. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3725. * @param view defines the view matrix to use
  3726. * @param projection defines the projection matrix to use
  3727. * @returns the new Vector3
  3728. */
  3729. Vector3.Unproject = function (source, viewportWidth, viewportHeight, world, view, projection) {
  3730. var result = Vector3.Zero();
  3731. Vector3.UnprojectToRef(source, viewportWidth, viewportHeight, world, view, projection, result);
  3732. return result;
  3733. };
  3734. /**
  3735. * Unproject from screen space to object space
  3736. * @param source defines the screen space Vector3 to use
  3737. * @param viewportWidth defines the current width of the viewport
  3738. * @param viewportHeight defines the current height of the viewport
  3739. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3740. * @param view defines the view matrix to use
  3741. * @param projection defines the projection matrix to use
  3742. * @param result defines the Vector3 where to store the result
  3743. */
  3744. Vector3.UnprojectToRef = function (source, viewportWidth, viewportHeight, world, view, projection, result) {
  3745. Vector3.UnprojectFloatsToRef(source.x, source.y, source.z, viewportWidth, viewportHeight, world, view, projection, result);
  3746. };
  3747. /**
  3748. * Unproject from screen space to object space
  3749. * @param sourceX defines the screen space x coordinate to use
  3750. * @param sourceY defines the screen space y coordinate to use
  3751. * @param sourceZ defines the screen space z coordinate to use
  3752. * @param viewportWidth defines the current width of the viewport
  3753. * @param viewportHeight defines the current height of the viewport
  3754. * @param world defines the world matrix to use (can be set to Identity to go to world space)
  3755. * @param view defines the view matrix to use
  3756. * @param projection defines the projection matrix to use
  3757. * @param result defines the Vector3 where to store the result
  3758. */
  3759. Vector3.UnprojectFloatsToRef = function (sourceX, sourceY, sourceZ, viewportWidth, viewportHeight, world, view, projection, result) {
  3760. var matrix = MathTmp.Matrix[0];
  3761. world.multiplyToRef(view, matrix);
  3762. matrix.multiplyToRef(projection, matrix);
  3763. matrix.invert();
  3764. var screenSource = MathTmp.Vector3[0];
  3765. screenSource.x = sourceX / viewportWidth * 2 - 1;
  3766. screenSource.y = -(sourceY / viewportHeight * 2 - 1);
  3767. screenSource.z = 2 * sourceZ - 1.0;
  3768. Vector3.TransformCoordinatesToRef(screenSource, matrix, result);
  3769. var num = screenSource.x * matrix.m[3] + screenSource.y * matrix.m[7] + screenSource.z * matrix.m[11] + matrix.m[15];
  3770. if (BABYLON.Scalar.WithinEpsilon(num, 1.0)) {
  3771. result.scaleInPlace(1.0 / num);
  3772. }
  3773. };
  3774. /**
  3775. * Gets the minimal coordinate values between two Vector3
  3776. * @param left defines the first operand
  3777. * @param right defines the second operand
  3778. * @returns the new Vector3
  3779. */
  3780. Vector3.Minimize = function (left, right) {
  3781. var min = left.clone();
  3782. min.minimizeInPlace(right);
  3783. return min;
  3784. };
  3785. /**
  3786. * Gets the maximal coordinate values between two Vector3
  3787. * @param left defines the first operand
  3788. * @param right defines the second operand
  3789. * @returns the new Vector3
  3790. */
  3791. Vector3.Maximize = function (left, right) {
  3792. var max = left.clone();
  3793. max.maximizeInPlace(right);
  3794. return max;
  3795. };
  3796. /**
  3797. * Returns the distance between the vectors "value1" and "value2"
  3798. * @param value1 defines the first operand
  3799. * @param value2 defines the second operand
  3800. * @returns the distance
  3801. */
  3802. Vector3.Distance = function (value1, value2) {
  3803. return Math.sqrt(Vector3.DistanceSquared(value1, value2));
  3804. };
  3805. /**
  3806. * Returns the squared distance between the vectors "value1" and "value2"
  3807. * @param value1 defines the first operand
  3808. * @param value2 defines the second operand
  3809. * @returns the squared distance
  3810. */
  3811. Vector3.DistanceSquared = function (value1, value2) {
  3812. var x = value1.x - value2.x;
  3813. var y = value1.y - value2.y;
  3814. var z = value1.z - value2.z;
  3815. return (x * x) + (y * y) + (z * z);
  3816. };
  3817. /**
  3818. * Returns a new Vector3 located at the center between "value1" and "value2"
  3819. * @param value1 defines the first operand
  3820. * @param value2 defines the second operand
  3821. * @returns the new Vector3
  3822. */
  3823. Vector3.Center = function (value1, value2) {
  3824. var center = value1.add(value2);
  3825. center.scaleInPlace(0.5);
  3826. return center;
  3827. };
  3828. /**
  3829. * Given three orthogonal normalized left-handed oriented Vector3 axis in space (target system),
  3830. * RotationFromAxis() returns the rotation Euler angles (ex : rotation.x, rotation.y, rotation.z) to apply
  3831. * to something in order to rotate it from its local system to the given target system
  3832. * Note: axis1, axis2 and axis3 are normalized during this operation
  3833. * @param axis1 defines the first axis
  3834. * @param axis2 defines the second axis
  3835. * @param axis3 defines the third axis
  3836. * @returns a new Vector3
  3837. */
  3838. Vector3.RotationFromAxis = function (axis1, axis2, axis3) {
  3839. var rotation = Vector3.Zero();
  3840. Vector3.RotationFromAxisToRef(axis1, axis2, axis3, rotation);
  3841. return rotation;
  3842. };
  3843. /**
  3844. * The same than RotationFromAxis but updates the given ref Vector3 parameter instead of returning a new Vector3
  3845. * @param axis1 defines the first axis
  3846. * @param axis2 defines the second axis
  3847. * @param axis3 defines the third axis
  3848. * @param ref defines the Vector3 where to store the result
  3849. */
  3850. Vector3.RotationFromAxisToRef = function (axis1, axis2, axis3, ref) {
  3851. var quat = MathTmp.Quaternion[0];
  3852. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  3853. quat.toEulerAnglesToRef(ref);
  3854. };
  3855. return Vector3;
  3856. }());
  3857. BABYLON.Vector3 = Vector3;
  3858. //Vector4 class created for EulerAngle class conversion to Quaternion
  3859. var Vector4 = /** @class */ (function () {
  3860. /**
  3861. * Creates a Vector4 object from the given floats.
  3862. */
  3863. function Vector4(x, y, z, w) {
  3864. this.x = x;
  3865. this.y = y;
  3866. this.z = z;
  3867. this.w = w;
  3868. }
  3869. /**
  3870. * Returns the string with the Vector4 coordinates.
  3871. */
  3872. Vector4.prototype.toString = function () {
  3873. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  3874. };
  3875. /**
  3876. * Returns the string "Vector4".
  3877. */
  3878. Vector4.prototype.getClassName = function () {
  3879. return "Vector4";
  3880. };
  3881. /**
  3882. * Returns the Vector4 hash code.
  3883. */
  3884. Vector4.prototype.getHashCode = function () {
  3885. var hash = this.x || 0;
  3886. hash = (hash * 397) ^ (this.y || 0);
  3887. hash = (hash * 397) ^ (this.z || 0);
  3888. hash = (hash * 397) ^ (this.w || 0);
  3889. return hash;
  3890. };
  3891. // Operators
  3892. /**
  3893. * Returns a new array populated with 4 elements : the Vector4 coordinates.
  3894. */
  3895. Vector4.prototype.asArray = function () {
  3896. var result = new Array();
  3897. this.toArray(result, 0);
  3898. return result;
  3899. };
  3900. /**
  3901. * Populates the given array from the given index with the Vector4 coordinates.
  3902. * Returns the Vector4.
  3903. */
  3904. Vector4.prototype.toArray = function (array, index) {
  3905. if (index === undefined) {
  3906. index = 0;
  3907. }
  3908. array[index] = this.x;
  3909. array[index + 1] = this.y;
  3910. array[index + 2] = this.z;
  3911. array[index + 3] = this.w;
  3912. return this;
  3913. };
  3914. /**
  3915. * Adds the given vector to the current Vector4.
  3916. * Returns the updated Vector4.
  3917. */
  3918. Vector4.prototype.addInPlace = function (otherVector) {
  3919. this.x += otherVector.x;
  3920. this.y += otherVector.y;
  3921. this.z += otherVector.z;
  3922. this.w += otherVector.w;
  3923. return this;
  3924. };
  3925. /**
  3926. * Returns a new Vector4 as the result of the addition of the current Vector4 and the given one.
  3927. */
  3928. Vector4.prototype.add = function (otherVector) {
  3929. return new Vector4(this.x + otherVector.x, this.y + otherVector.y, this.z + otherVector.z, this.w + otherVector.w);
  3930. };
  3931. /**
  3932. * Updates the given vector "result" with the result of the addition of the current Vector4 and the given one.
  3933. * Returns the current Vector4.
  3934. */
  3935. Vector4.prototype.addToRef = function (otherVector, result) {
  3936. result.x = this.x + otherVector.x;
  3937. result.y = this.y + otherVector.y;
  3938. result.z = this.z + otherVector.z;
  3939. result.w = this.w + otherVector.w;
  3940. return this;
  3941. };
  3942. /**
  3943. * Subtract in place the given vector from the current Vector4.
  3944. * Returns the updated Vector4.
  3945. */
  3946. Vector4.prototype.subtractInPlace = function (otherVector) {
  3947. this.x -= otherVector.x;
  3948. this.y -= otherVector.y;
  3949. this.z -= otherVector.z;
  3950. this.w -= otherVector.w;
  3951. return this;
  3952. };
  3953. /**
  3954. * Returns a new Vector4 with the result of the subtraction of the given vector from the current Vector4.
  3955. */
  3956. Vector4.prototype.subtract = function (otherVector) {
  3957. return new Vector4(this.x - otherVector.x, this.y - otherVector.y, this.z - otherVector.z, this.w - otherVector.w);
  3958. };
  3959. /**
  3960. * Sets the given vector "result" with the result of the subtraction of the given vector from the current Vector4.
  3961. * Returns the current Vector4.
  3962. */
  3963. Vector4.prototype.subtractToRef = function (otherVector, result) {
  3964. result.x = this.x - otherVector.x;
  3965. result.y = this.y - otherVector.y;
  3966. result.z = this.z - otherVector.z;
  3967. result.w = this.w - otherVector.w;
  3968. return this;
  3969. };
  3970. /**
  3971. * Returns a new Vector4 set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3972. */
  3973. Vector4.prototype.subtractFromFloats = function (x, y, z, w) {
  3974. return new Vector4(this.x - x, this.y - y, this.z - z, this.w - w);
  3975. };
  3976. /**
  3977. * Sets the given vector "result" set with the result of the subtraction of the given floats from the current Vector4 coordinates.
  3978. * Returns the current Vector4.
  3979. */
  3980. Vector4.prototype.subtractFromFloatsToRef = function (x, y, z, w, result) {
  3981. result.x = this.x - x;
  3982. result.y = this.y - y;
  3983. result.z = this.z - z;
  3984. result.w = this.w - w;
  3985. return this;
  3986. };
  3987. /**
  3988. * Returns a new Vector4 set with the current Vector4 negated coordinates.
  3989. */
  3990. Vector4.prototype.negate = function () {
  3991. return new Vector4(-this.x, -this.y, -this.z, -this.w);
  3992. };
  3993. /**
  3994. * Multiplies the current Vector4 coordinates by scale (float).
  3995. * Returns the updated Vector4.
  3996. */
  3997. Vector4.prototype.scaleInPlace = function (scale) {
  3998. this.x *= scale;
  3999. this.y *= scale;
  4000. this.z *= scale;
  4001. this.w *= scale;
  4002. return this;
  4003. };
  4004. /**
  4005. * Returns a new Vector4 set with the current Vector4 coordinates multiplied by scale (float).
  4006. */
  4007. Vector4.prototype.scale = function (scale) {
  4008. return new Vector4(this.x * scale, this.y * scale, this.z * scale, this.w * scale);
  4009. };
  4010. /**
  4011. * Sets the given vector "result" with the current Vector4 coordinates multiplied by scale (float).
  4012. * Returns the current Vector4.
  4013. */
  4014. Vector4.prototype.scaleToRef = function (scale, result) {
  4015. result.x = this.x * scale;
  4016. result.y = this.y * scale;
  4017. result.z = this.z * scale;
  4018. result.w = this.w * scale;
  4019. return this;
  4020. };
  4021. /**
  4022. * Scale the current Vector4 values by a factor and add the result to a given Vector4
  4023. * @param scale defines the scale factor
  4024. * @param result defines the Vector4 object where to store the result
  4025. * @returns the unmodified current Vector4
  4026. */
  4027. Vector4.prototype.scaleAndAddToRef = function (scale, result) {
  4028. result.x += this.x * scale;
  4029. result.y += this.y * scale;
  4030. result.z += this.z * scale;
  4031. result.w += this.w * scale;
  4032. return this;
  4033. };
  4034. /**
  4035. * Boolean : True if the current Vector4 coordinates are stricly equal to the given ones.
  4036. */
  4037. Vector4.prototype.equals = function (otherVector) {
  4038. return otherVector && this.x === otherVector.x && this.y === otherVector.y && this.z === otherVector.z && this.w === otherVector.w;
  4039. };
  4040. /**
  4041. * Boolean : True if the current Vector4 coordinates are each beneath the distance "epsilon" from the given vector ones.
  4042. */
  4043. Vector4.prototype.equalsWithEpsilon = function (otherVector, epsilon) {
  4044. if (epsilon === void 0) { epsilon = BABYLON.Epsilon; }
  4045. return otherVector
  4046. && BABYLON.Scalar.WithinEpsilon(this.x, otherVector.x, epsilon)
  4047. && BABYLON.Scalar.WithinEpsilon(this.y, otherVector.y, epsilon)
  4048. && BABYLON.Scalar.WithinEpsilon(this.z, otherVector.z, epsilon)
  4049. && BABYLON.Scalar.WithinEpsilon(this.w, otherVector.w, epsilon);
  4050. };
  4051. /**
  4052. * Boolean : True if the given floats are strictly equal to the current Vector4 coordinates.
  4053. */
  4054. Vector4.prototype.equalsToFloats = function (x, y, z, w) {
  4055. return this.x === x && this.y === y && this.z === z && this.w === w;
  4056. };
  4057. /**
  4058. * Multiplies in place the current Vector4 by the given one.
  4059. * Returns the updated Vector4.
  4060. */
  4061. Vector4.prototype.multiplyInPlace = function (otherVector) {
  4062. this.x *= otherVector.x;
  4063. this.y *= otherVector.y;
  4064. this.z *= otherVector.z;
  4065. this.w *= otherVector.w;
  4066. return this;
  4067. };
  4068. /**
  4069. * Returns a new Vector4 set with the multiplication result of the current Vector4 and the given one.
  4070. */
  4071. Vector4.prototype.multiply = function (otherVector) {
  4072. return new Vector4(this.x * otherVector.x, this.y * otherVector.y, this.z * otherVector.z, this.w * otherVector.w);
  4073. };
  4074. /**
  4075. * Updates the given vector "result" with the multiplication result of the current Vector4 and the given one.
  4076. * Returns the current Vector4.
  4077. */
  4078. Vector4.prototype.multiplyToRef = function (otherVector, result) {
  4079. result.x = this.x * otherVector.x;
  4080. result.y = this.y * otherVector.y;
  4081. result.z = this.z * otherVector.z;
  4082. result.w = this.w * otherVector.w;
  4083. return this;
  4084. };
  4085. /**
  4086. * Returns a new Vector4 set with the multiplication result of the given floats and the current Vector4 coordinates.
  4087. */
  4088. Vector4.prototype.multiplyByFloats = function (x, y, z, w) {
  4089. return new Vector4(this.x * x, this.y * y, this.z * z, this.w * w);
  4090. };
  4091. /**
  4092. * Returns a new Vector4 set with the division result of the current Vector4 by the given one.
  4093. */
  4094. Vector4.prototype.divide = function (otherVector) {
  4095. return new Vector4(this.x / otherVector.x, this.y / otherVector.y, this.z / otherVector.z, this.w / otherVector.w);
  4096. };
  4097. /**
  4098. * Updates the given vector "result" with the division result of the current Vector4 by the given one.
  4099. * Returns the current Vector4.
  4100. */
  4101. Vector4.prototype.divideToRef = function (otherVector, result) {
  4102. result.x = this.x / otherVector.x;
  4103. result.y = this.y / otherVector.y;
  4104. result.z = this.z / otherVector.z;
  4105. result.w = this.w / otherVector.w;
  4106. return this;
  4107. };
  4108. /**
  4109. * Divides the current Vector3 coordinates by the given ones.
  4110. * @returns the updated Vector3.
  4111. */
  4112. Vector4.prototype.divideInPlace = function (otherVector) {
  4113. return this.divideToRef(otherVector, this);
  4114. };
  4115. /**
  4116. * Updates the Vector4 coordinates with the minimum values between its own and the given vector ones
  4117. * @param other defines the second operand
  4118. * @returns the current updated Vector4
  4119. */
  4120. Vector4.prototype.minimizeInPlace = function (other) {
  4121. if (other.x < this.x)
  4122. this.x = other.x;
  4123. if (other.y < this.y)
  4124. this.y = other.y;
  4125. if (other.z < this.z)
  4126. this.z = other.z;
  4127. if (other.w < this.w)
  4128. this.w = other.w;
  4129. return this;
  4130. };
  4131. /**
  4132. * Updates the Vector4 coordinates with the maximum values between its own and the given vector ones
  4133. * @param other defines the second operand
  4134. * @returns the current updated Vector4
  4135. */
  4136. Vector4.prototype.maximizeInPlace = function (other) {
  4137. if (other.x > this.x)
  4138. this.x = other.x;
  4139. if (other.y > this.y)
  4140. this.y = other.y;
  4141. if (other.z > this.z)
  4142. this.z = other.z;
  4143. if (other.w > this.w)
  4144. this.w = other.w;
  4145. return this;
  4146. };
  4147. // Properties
  4148. /**
  4149. * Returns the Vector4 length (float).
  4150. */
  4151. Vector4.prototype.length = function () {
  4152. return Math.sqrt(this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4153. };
  4154. /**
  4155. * Returns the Vector4 squared length (float).
  4156. */
  4157. Vector4.prototype.lengthSquared = function () {
  4158. return (this.x * this.x + this.y * this.y + this.z * this.z + this.w * this.w);
  4159. };
  4160. // Methods
  4161. /**
  4162. * Normalizes in place the Vector4.
  4163. * Returns the updated Vector4.
  4164. */
  4165. Vector4.prototype.normalize = function () {
  4166. var len = this.length();
  4167. if (len === 0)
  4168. return this;
  4169. var num = 1.0 / len;
  4170. this.x *= num;
  4171. this.y *= num;
  4172. this.z *= num;
  4173. this.w *= num;
  4174. return this;
  4175. };
  4176. /**
  4177. * Returns a new Vector3 from the Vector4 (x, y, z) coordinates.
  4178. */
  4179. Vector4.prototype.toVector3 = function () {
  4180. return new Vector3(this.x, this.y, this.z);
  4181. };
  4182. /**
  4183. * Returns a new Vector4 copied from the current one.
  4184. */
  4185. Vector4.prototype.clone = function () {
  4186. return new Vector4(this.x, this.y, this.z, this.w);
  4187. };
  4188. /**
  4189. * Updates the current Vector4 with the given one coordinates.
  4190. * Returns the updated Vector4.
  4191. */
  4192. Vector4.prototype.copyFrom = function (source) {
  4193. this.x = source.x;
  4194. this.y = source.y;
  4195. this.z = source.z;
  4196. this.w = source.w;
  4197. return this;
  4198. };
  4199. /**
  4200. * Updates the current Vector4 coordinates with the given floats.
  4201. * Returns the updated Vector4.
  4202. */
  4203. Vector4.prototype.copyFromFloats = function (x, y, z, w) {
  4204. this.x = x;
  4205. this.y = y;
  4206. this.z = z;
  4207. this.w = w;
  4208. return this;
  4209. };
  4210. /**
  4211. * Updates the current Vector4 coordinates with the given floats.
  4212. * Returns the updated Vector4.
  4213. */
  4214. Vector4.prototype.set = function (x, y, z, w) {
  4215. return this.copyFromFloats(x, y, z, w);
  4216. };
  4217. // Statics
  4218. /**
  4219. * Returns a new Vector4 set from the starting index of the given array.
  4220. */
  4221. Vector4.FromArray = function (array, offset) {
  4222. if (!offset) {
  4223. offset = 0;
  4224. }
  4225. return new Vector4(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4226. };
  4227. /**
  4228. * Updates the given vector "result" from the starting index of the given array.
  4229. */
  4230. Vector4.FromArrayToRef = function (array, offset, result) {
  4231. result.x = array[offset];
  4232. result.y = array[offset + 1];
  4233. result.z = array[offset + 2];
  4234. result.w = array[offset + 3];
  4235. };
  4236. /**
  4237. * Updates the given vector "result" from the starting index of the given Float32Array.
  4238. */
  4239. Vector4.FromFloatArrayToRef = function (array, offset, result) {
  4240. Vector4.FromArrayToRef(array, offset, result);
  4241. };
  4242. /**
  4243. * Updates the given vector "result" coordinates from the given floats.
  4244. */
  4245. Vector4.FromFloatsToRef = function (x, y, z, w, result) {
  4246. result.x = x;
  4247. result.y = y;
  4248. result.z = z;
  4249. result.w = w;
  4250. };
  4251. /**
  4252. * Returns a new Vector4 set to (0.0, 0.0, 0.0, 0.0)
  4253. */
  4254. Vector4.Zero = function () {
  4255. return new Vector4(0.0, 0.0, 0.0, 0.0);
  4256. };
  4257. /**
  4258. * Returns a new Vector4 set to (1.0, 1.0, 1.0, 1.0)
  4259. */
  4260. Vector4.One = function () {
  4261. return new Vector4(1.0, 1.0, 1.0, 1.0);
  4262. };
  4263. /**
  4264. * Returns a new normalized Vector4 from the given one.
  4265. */
  4266. Vector4.Normalize = function (vector) {
  4267. var result = Vector4.Zero();
  4268. Vector4.NormalizeToRef(vector, result);
  4269. return result;
  4270. };
  4271. /**
  4272. * Updates the given vector "result" from the normalization of the given one.
  4273. */
  4274. Vector4.NormalizeToRef = function (vector, result) {
  4275. result.copyFrom(vector);
  4276. result.normalize();
  4277. };
  4278. Vector4.Minimize = function (left, right) {
  4279. var min = left.clone();
  4280. min.minimizeInPlace(right);
  4281. return min;
  4282. };
  4283. Vector4.Maximize = function (left, right) {
  4284. var max = left.clone();
  4285. max.maximizeInPlace(right);
  4286. return max;
  4287. };
  4288. /**
  4289. * Returns the distance (float) between the vectors "value1" and "value2".
  4290. */
  4291. Vector4.Distance = function (value1, value2) {
  4292. return Math.sqrt(Vector4.DistanceSquared(value1, value2));
  4293. };
  4294. /**
  4295. * Returns the squared distance (float) between the vectors "value1" and "value2".
  4296. */
  4297. Vector4.DistanceSquared = function (value1, value2) {
  4298. var x = value1.x - value2.x;
  4299. var y = value1.y - value2.y;
  4300. var z = value1.z - value2.z;
  4301. var w = value1.w - value2.w;
  4302. return (x * x) + (y * y) + (z * z) + (w * w);
  4303. };
  4304. /**
  4305. * Returns a new Vector4 located at the center between the vectors "value1" and "value2".
  4306. */
  4307. Vector4.Center = function (value1, value2) {
  4308. var center = value1.add(value2);
  4309. center.scaleInPlace(0.5);
  4310. return center;
  4311. };
  4312. /**
  4313. * Returns a new Vector4 set with the result of the normal transformation by the given matrix of the given vector.
  4314. * This methods computes transformed normalized direction vectors only.
  4315. */
  4316. Vector4.TransformNormal = function (vector, transformation) {
  4317. var result = Vector4.Zero();
  4318. Vector4.TransformNormalToRef(vector, transformation, result);
  4319. return result;
  4320. };
  4321. /**
  4322. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given vector.
  4323. * This methods computes transformed normalized direction vectors only.
  4324. */
  4325. Vector4.TransformNormalToRef = function (vector, transformation, result) {
  4326. var x = (vector.x * transformation.m[0]) + (vector.y * transformation.m[4]) + (vector.z * transformation.m[8]);
  4327. var y = (vector.x * transformation.m[1]) + (vector.y * transformation.m[5]) + (vector.z * transformation.m[9]);
  4328. var z = (vector.x * transformation.m[2]) + (vector.y * transformation.m[6]) + (vector.z * transformation.m[10]);
  4329. result.x = x;
  4330. result.y = y;
  4331. result.z = z;
  4332. result.w = vector.w;
  4333. };
  4334. /**
  4335. * Sets the given vector "result" with the result of the normal transformation by the given matrix of the given floats (x, y, z, w).
  4336. * This methods computes transformed normalized direction vectors only.
  4337. */
  4338. Vector4.TransformNormalFromFloatsToRef = function (x, y, z, w, transformation, result) {
  4339. result.x = (x * transformation.m[0]) + (y * transformation.m[4]) + (z * transformation.m[8]);
  4340. result.y = (x * transformation.m[1]) + (y * transformation.m[5]) + (z * transformation.m[9]);
  4341. result.z = (x * transformation.m[2]) + (y * transformation.m[6]) + (z * transformation.m[10]);
  4342. result.w = w;
  4343. };
  4344. return Vector4;
  4345. }());
  4346. BABYLON.Vector4 = Vector4;
  4347. var Size = /** @class */ (function () {
  4348. /**
  4349. * Creates a Size object from the given width and height (floats).
  4350. */
  4351. function Size(width, height) {
  4352. this.width = width;
  4353. this.height = height;
  4354. }
  4355. // Returns a string with the Size width and height.
  4356. Size.prototype.toString = function () {
  4357. return "{W: " + this.width + ", H: " + this.height + "}";
  4358. };
  4359. /**
  4360. * Returns the string "Size"
  4361. */
  4362. Size.prototype.getClassName = function () {
  4363. return "Size";
  4364. };
  4365. /**
  4366. * Returns the Size hash code.
  4367. */
  4368. Size.prototype.getHashCode = function () {
  4369. var hash = this.width || 0;
  4370. hash = (hash * 397) ^ (this.height || 0);
  4371. return hash;
  4372. };
  4373. /**
  4374. * Updates the current size from the given one.
  4375. * Returns the updated Size.
  4376. */
  4377. Size.prototype.copyFrom = function (src) {
  4378. this.width = src.width;
  4379. this.height = src.height;
  4380. };
  4381. /**
  4382. * Updates in place the current Size from the given floats.
  4383. * Returns the updated Size.
  4384. */
  4385. Size.prototype.copyFromFloats = function (width, height) {
  4386. this.width = width;
  4387. this.height = height;
  4388. return this;
  4389. };
  4390. /**
  4391. * Updates in place the current Size from the given floats.
  4392. * Returns the updated Size.
  4393. */
  4394. Size.prototype.set = function (width, height) {
  4395. return this.copyFromFloats(width, height);
  4396. };
  4397. /**
  4398. * Returns a new Size set with the multiplication result of the current Size and the given floats.
  4399. */
  4400. Size.prototype.multiplyByFloats = function (w, h) {
  4401. return new Size(this.width * w, this.height * h);
  4402. };
  4403. /**
  4404. * Returns a new Size copied from the given one.
  4405. */
  4406. Size.prototype.clone = function () {
  4407. return new Size(this.width, this.height);
  4408. };
  4409. /**
  4410. * Boolean : True if the current Size and the given one width and height are strictly equal.
  4411. */
  4412. Size.prototype.equals = function (other) {
  4413. if (!other) {
  4414. return false;
  4415. }
  4416. return (this.width === other.width) && (this.height === other.height);
  4417. };
  4418. Object.defineProperty(Size.prototype, "surface", {
  4419. /**
  4420. * Returns the surface of the Size : width * height (float).
  4421. */
  4422. get: function () {
  4423. return this.width * this.height;
  4424. },
  4425. enumerable: true,
  4426. configurable: true
  4427. });
  4428. /**
  4429. * Returns a new Size set to (0.0, 0.0)
  4430. */
  4431. Size.Zero = function () {
  4432. return new Size(0.0, 0.0);
  4433. };
  4434. /**
  4435. * Returns a new Size set as the addition result of the current Size and the given one.
  4436. */
  4437. Size.prototype.add = function (otherSize) {
  4438. var r = new Size(this.width + otherSize.width, this.height + otherSize.height);
  4439. return r;
  4440. };
  4441. /**
  4442. * Returns a new Size set as the subtraction result of the given one from the current Size.
  4443. */
  4444. Size.prototype.subtract = function (otherSize) {
  4445. var r = new Size(this.width - otherSize.width, this.height - otherSize.height);
  4446. return r;
  4447. };
  4448. /**
  4449. * Returns a new Size set at the linear interpolation "amount" between "start" and "end".
  4450. */
  4451. Size.Lerp = function (start, end, amount) {
  4452. var w = start.width + ((end.width - start.width) * amount);
  4453. var h = start.height + ((end.height - start.height) * amount);
  4454. return new Size(w, h);
  4455. };
  4456. return Size;
  4457. }());
  4458. BABYLON.Size = Size;
  4459. /**
  4460. * Class used to store quaternion data
  4461. * @see https://en.wikipedia.org/wiki/Quaternion
  4462. * @see http://doc.babylonjs.com/features/position,_rotation,_scaling
  4463. */
  4464. var Quaternion = /** @class */ (function () {
  4465. /**
  4466. * Creates a new Quaternion from the given floats
  4467. * @param x defines the first component (0 by default)
  4468. * @param y defines the second component (0 by default)
  4469. * @param z defines the third component (0 by default)
  4470. * @param w defines the fourth component (1.0 by default)
  4471. */
  4472. function Quaternion(
  4473. /** defines the first component (0 by default) */
  4474. x,
  4475. /** defines the second component (0 by default) */
  4476. y,
  4477. /** defines the third component (0 by default) */
  4478. z,
  4479. /** defines the fourth component (1.0 by default) */
  4480. w) {
  4481. if (x === void 0) { x = 0.0; }
  4482. if (y === void 0) { y = 0.0; }
  4483. if (z === void 0) { z = 0.0; }
  4484. if (w === void 0) { w = 1.0; }
  4485. this.x = x;
  4486. this.y = y;
  4487. this.z = z;
  4488. this.w = w;
  4489. }
  4490. /**
  4491. * Gets a string representation for the current quaternion
  4492. * @returns a string with the Quaternion coordinates
  4493. */
  4494. Quaternion.prototype.toString = function () {
  4495. return "{X: " + this.x + " Y:" + this.y + " Z:" + this.z + " W:" + this.w + "}";
  4496. };
  4497. /**
  4498. * Gets the class name of the quaternion
  4499. * @returns the string "Quaternion"
  4500. */
  4501. Quaternion.prototype.getClassName = function () {
  4502. return "Quaternion";
  4503. };
  4504. /**
  4505. * Gets a hash code for this quaternion
  4506. * @returns the quaternion hash code
  4507. */
  4508. Quaternion.prototype.getHashCode = function () {
  4509. var hash = this.x || 0;
  4510. hash = (hash * 397) ^ (this.y || 0);
  4511. hash = (hash * 397) ^ (this.z || 0);
  4512. hash = (hash * 397) ^ (this.w || 0);
  4513. return hash;
  4514. };
  4515. /**
  4516. * Copy the quaternion to an array
  4517. * @returns a new array populated with 4 elements from the quaternion coordinates
  4518. */
  4519. Quaternion.prototype.asArray = function () {
  4520. return [this.x, this.y, this.z, this.w];
  4521. };
  4522. /**
  4523. * Check if two quaternions are equals
  4524. * @param otherQuaternion defines the second operand
  4525. * @return true if the current quaternion and the given one coordinates are strictly equals
  4526. */
  4527. Quaternion.prototype.equals = function (otherQuaternion) {
  4528. return otherQuaternion && this.x === otherQuaternion.x && this.y === otherQuaternion.y && this.z === otherQuaternion.z && this.w === otherQuaternion.w;
  4529. };
  4530. /**
  4531. * Clone the current quaternion
  4532. * @returns a new quaternion copied from the current one
  4533. */
  4534. Quaternion.prototype.clone = function () {
  4535. return new Quaternion(this.x, this.y, this.z, this.w);
  4536. };
  4537. /**
  4538. * Copy a quaternion to the current one
  4539. * @param other defines the other quaternion
  4540. * @returns the updated current quaternion
  4541. */
  4542. Quaternion.prototype.copyFrom = function (other) {
  4543. this.x = other.x;
  4544. this.y = other.y;
  4545. this.z = other.z;
  4546. this.w = other.w;
  4547. return this;
  4548. };
  4549. /**
  4550. * Updates the current quaternion with the given float coordinates
  4551. * @param x defines the x coordinate
  4552. * @param y defines the y coordinate
  4553. * @param z defines the z coordinate
  4554. * @param w defines the w coordinate
  4555. * @returns the updated current quaternion
  4556. */
  4557. Quaternion.prototype.copyFromFloats = function (x, y, z, w) {
  4558. this.x = x;
  4559. this.y = y;
  4560. this.z = z;
  4561. this.w = w;
  4562. return this;
  4563. };
  4564. /**
  4565. * Updates the current quaternion from the given float coordinates
  4566. * @param x defines the x coordinate
  4567. * @param y defines the y coordinate
  4568. * @param z defines the z coordinate
  4569. * @param w defines the w coordinate
  4570. * @returns the updated current quaternion
  4571. */
  4572. Quaternion.prototype.set = function (x, y, z, w) {
  4573. return this.copyFromFloats(x, y, z, w);
  4574. };
  4575. /**
  4576. * Adds two quaternions
  4577. * @param other defines the second operand
  4578. * @returns a new quaternion as the addition result of the given one and the current quaternion
  4579. */
  4580. Quaternion.prototype.add = function (other) {
  4581. return new Quaternion(this.x + other.x, this.y + other.y, this.z + other.z, this.w + other.w);
  4582. };
  4583. /**
  4584. * Add a quaternion to the current one
  4585. * @param other defines the quaternion to add
  4586. * @returns the current quaternion
  4587. */
  4588. Quaternion.prototype.addInPlace = function (other) {
  4589. this.x += other.x;
  4590. this.y += other.y;
  4591. this.z += other.z;
  4592. this.w += other.w;
  4593. return this;
  4594. };
  4595. /**
  4596. * Subtract two quaternions
  4597. * @param other defines the second operand
  4598. * @returns a new quaternion as the subtraction result of the given one from the current one
  4599. */
  4600. Quaternion.prototype.subtract = function (other) {
  4601. return new Quaternion(this.x - other.x, this.y - other.y, this.z - other.z, this.w - other.w);
  4602. };
  4603. /**
  4604. * Multiplies the current quaternion by a scale factor
  4605. * @param value defines the scale factor
  4606. * @returns a new quaternion set by multiplying the current quaternion coordinates by the float "scale"
  4607. */
  4608. Quaternion.prototype.scale = function (value) {
  4609. return new Quaternion(this.x * value, this.y * value, this.z * value, this.w * value);
  4610. };
  4611. /**
  4612. * Scale the current quaternion values by a factor and stores the result to a given quaternion
  4613. * @param scale defines the scale factor
  4614. * @param result defines the Quaternion object where to store the result
  4615. * @returns the unmodified current quaternion
  4616. */
  4617. Quaternion.prototype.scaleToRef = function (scale, result) {
  4618. result.x = this.x * scale;
  4619. result.y = this.y * scale;
  4620. result.z = this.z * scale;
  4621. result.w = this.w * scale;
  4622. return this;
  4623. };
  4624. /**
  4625. * Multiplies in place the current quaternion by a scale factor
  4626. * @param value defines the scale factor
  4627. * @returns the current modified quaternion
  4628. */
  4629. Quaternion.prototype.scaleInPlace = function (value) {
  4630. this.x *= value;
  4631. this.y *= value;
  4632. this.z *= value;
  4633. this.w *= value;
  4634. return this;
  4635. };
  4636. /**
  4637. * Scale the current quaternion values by a factor and add the result to a given quaternion
  4638. * @param scale defines the scale factor
  4639. * @param result defines the Quaternion object where to store the result
  4640. * @returns the unmodified current quaternion
  4641. */
  4642. Quaternion.prototype.scaleAndAddToRef = function (scale, result) {
  4643. result.x += this.x * scale;
  4644. result.y += this.y * scale;
  4645. result.z += this.z * scale;
  4646. result.w += this.w * scale;
  4647. return this;
  4648. };
  4649. /**
  4650. * Multiplies two quaternions
  4651. * @param q1 defines the second operand
  4652. * @returns a new quaternion set as the multiplication result of the current one with the given one "q1"
  4653. */
  4654. Quaternion.prototype.multiply = function (q1) {
  4655. var result = new Quaternion(0, 0, 0, 1.0);
  4656. this.multiplyToRef(q1, result);
  4657. return result;
  4658. };
  4659. /**
  4660. * Sets the given "result" as the the multiplication result of the current one with the given one "q1"
  4661. * @param q1 defines the second operand
  4662. * @param result defines the target quaternion
  4663. * @returns the current quaternion
  4664. */
  4665. Quaternion.prototype.multiplyToRef = function (q1, result) {
  4666. var x = this.x * q1.w + this.y * q1.z - this.z * q1.y + this.w * q1.x;
  4667. var y = -this.x * q1.z + this.y * q1.w + this.z * q1.x + this.w * q1.y;
  4668. var z = this.x * q1.y - this.y * q1.x + this.z * q1.w + this.w * q1.z;
  4669. var w = -this.x * q1.x - this.y * q1.y - this.z * q1.z + this.w * q1.w;
  4670. result.copyFromFloats(x, y, z, w);
  4671. return this;
  4672. };
  4673. /**
  4674. * Updates the current quaternion with the multiplication of itself with the given one "q1"
  4675. * @param q1 defines the second operand
  4676. * @returns the currentupdated quaternion
  4677. */
  4678. Quaternion.prototype.multiplyInPlace = function (q1) {
  4679. this.multiplyToRef(q1, this);
  4680. return this;
  4681. };
  4682. /**
  4683. * Conjugates (1-q) the current quaternion and stores the result in the given quaternion
  4684. * @param ref defines the target quaternion
  4685. * @returns the current quaternion
  4686. */
  4687. Quaternion.prototype.conjugateToRef = function (ref) {
  4688. ref.copyFromFloats(-this.x, -this.y, -this.z, this.w);
  4689. return this;
  4690. };
  4691. /**
  4692. * Conjugates in place (1-q) the current quaternion
  4693. * @returns the current updated quaternion
  4694. */
  4695. Quaternion.prototype.conjugateInPlace = function () {
  4696. this.x *= -1;
  4697. this.y *= -1;
  4698. this.z *= -1;
  4699. return this;
  4700. };
  4701. /**
  4702. * Conjugates in place (1-q) the current quaternion
  4703. * @returns a new quaternion
  4704. */
  4705. Quaternion.prototype.conjugate = function () {
  4706. var result = new Quaternion(-this.x, -this.y, -this.z, this.w);
  4707. return result;
  4708. };
  4709. /**
  4710. * Gets length of current quaternion
  4711. * @returns the quaternion length (float)
  4712. */
  4713. Quaternion.prototype.length = function () {
  4714. return Math.sqrt((this.x * this.x) + (this.y * this.y) + (this.z * this.z) + (this.w * this.w));
  4715. };
  4716. /**
  4717. * Normalize in place the current quaternion
  4718. * @returns the current updated quaternion
  4719. */
  4720. Quaternion.prototype.normalize = function () {
  4721. var length = 1.0 / this.length();
  4722. this.x *= length;
  4723. this.y *= length;
  4724. this.z *= length;
  4725. this.w *= length;
  4726. return this;
  4727. };
  4728. /**
  4729. * Returns a new Vector3 set with the Euler angles translated from the current quaternion
  4730. * @param order is a reserved parameter and is ignore for now
  4731. * @returns a new Vector3 containing the Euler angles
  4732. */
  4733. Quaternion.prototype.toEulerAngles = function (order) {
  4734. if (order === void 0) { order = "YZX"; }
  4735. var result = Vector3.Zero();
  4736. this.toEulerAnglesToRef(result, order);
  4737. return result;
  4738. };
  4739. /**
  4740. * Sets the given vector3 "result" with the Euler angles translated from the current quaternion
  4741. * @param result defines the vector which will be filled with the Euler angles
  4742. * @param order is a reserved parameter and is ignore for now
  4743. * @returns the current unchanged quaternion
  4744. */
  4745. Quaternion.prototype.toEulerAnglesToRef = function (result, order) {
  4746. if (order === void 0) { order = "YZX"; }
  4747. var qz = this.z;
  4748. var qx = this.x;
  4749. var qy = this.y;
  4750. var qw = this.w;
  4751. var sqw = qw * qw;
  4752. var sqz = qz * qz;
  4753. var sqx = qx * qx;
  4754. var sqy = qy * qy;
  4755. var zAxisY = qy * qz - qx * qw;
  4756. var limit = .4999999;
  4757. if (zAxisY < -limit) {
  4758. result.y = 2 * Math.atan2(qy, qw);
  4759. result.x = Math.PI / 2;
  4760. result.z = 0;
  4761. }
  4762. else if (zAxisY > limit) {
  4763. result.y = 2 * Math.atan2(qy, qw);
  4764. result.x = -Math.PI / 2;
  4765. result.z = 0;
  4766. }
  4767. else {
  4768. result.z = Math.atan2(2.0 * (qx * qy + qz * qw), (-sqz - sqx + sqy + sqw));
  4769. result.x = Math.asin(-2.0 * (qz * qy - qx * qw));
  4770. result.y = Math.atan2(2.0 * (qz * qx + qy * qw), (sqz - sqx - sqy + sqw));
  4771. }
  4772. return this;
  4773. };
  4774. /**
  4775. * Updates the given rotation matrix with the current quaternion values
  4776. * @param result defines the target matrix
  4777. * @returns the current unchanged quaternion
  4778. */
  4779. Quaternion.prototype.toRotationMatrix = function (result) {
  4780. var xx = this.x * this.x;
  4781. var yy = this.y * this.y;
  4782. var zz = this.z * this.z;
  4783. var xy = this.x * this.y;
  4784. var zw = this.z * this.w;
  4785. var zx = this.z * this.x;
  4786. var yw = this.y * this.w;
  4787. var yz = this.y * this.z;
  4788. var xw = this.x * this.w;
  4789. result.m[0] = 1.0 - (2.0 * (yy + zz));
  4790. result.m[1] = 2.0 * (xy + zw);
  4791. result.m[2] = 2.0 * (zx - yw);
  4792. result.m[3] = 0;
  4793. result.m[4] = 2.0 * (xy - zw);
  4794. result.m[5] = 1.0 - (2.0 * (zz + xx));
  4795. result.m[6] = 2.0 * (yz + xw);
  4796. result.m[7] = 0;
  4797. result.m[8] = 2.0 * (zx + yw);
  4798. result.m[9] = 2.0 * (yz - xw);
  4799. result.m[10] = 1.0 - (2.0 * (yy + xx));
  4800. result.m[11] = 0;
  4801. result.m[12] = 0;
  4802. result.m[13] = 0;
  4803. result.m[14] = 0;
  4804. result.m[15] = 1.0;
  4805. result._markAsUpdated();
  4806. return this;
  4807. };
  4808. /**
  4809. * Updates the current quaternion from the given rotation matrix values
  4810. * @param matrix defines the source matrix
  4811. * @returns the current updated quaternion
  4812. */
  4813. Quaternion.prototype.fromRotationMatrix = function (matrix) {
  4814. Quaternion.FromRotationMatrixToRef(matrix, this);
  4815. return this;
  4816. };
  4817. // Statics
  4818. /**
  4819. * Creates a new quaternion from a rotation matrix
  4820. * @param matrix defines the source matrix
  4821. * @returns a new quaternion created from the given rotation matrix values
  4822. */
  4823. Quaternion.FromRotationMatrix = function (matrix) {
  4824. var result = new Quaternion();
  4825. Quaternion.FromRotationMatrixToRef(matrix, result);
  4826. return result;
  4827. };
  4828. /**
  4829. * Updates the given quaternion with the given rotation matrix values
  4830. * @param matrix defines the source matrix
  4831. * @param result defines the target quaternion
  4832. */
  4833. Quaternion.FromRotationMatrixToRef = function (matrix, result) {
  4834. var data = matrix.m;
  4835. var m11 = data[0], m12 = data[4], m13 = data[8];
  4836. var m21 = data[1], m22 = data[5], m23 = data[9];
  4837. var m31 = data[2], m32 = data[6], m33 = data[10];
  4838. var trace = m11 + m22 + m33;
  4839. var s;
  4840. if (trace > 0) {
  4841. s = 0.5 / Math.sqrt(trace + 1.0);
  4842. result.w = 0.25 / s;
  4843. result.x = (m32 - m23) * s;
  4844. result.y = (m13 - m31) * s;
  4845. result.z = (m21 - m12) * s;
  4846. }
  4847. else if (m11 > m22 && m11 > m33) {
  4848. s = 2.0 * Math.sqrt(1.0 + m11 - m22 - m33);
  4849. result.w = (m32 - m23) / s;
  4850. result.x = 0.25 * s;
  4851. result.y = (m12 + m21) / s;
  4852. result.z = (m13 + m31) / s;
  4853. }
  4854. else if (m22 > m33) {
  4855. s = 2.0 * Math.sqrt(1.0 + m22 - m11 - m33);
  4856. result.w = (m13 - m31) / s;
  4857. result.x = (m12 + m21) / s;
  4858. result.y = 0.25 * s;
  4859. result.z = (m23 + m32) / s;
  4860. }
  4861. else {
  4862. s = 2.0 * Math.sqrt(1.0 + m33 - m11 - m22);
  4863. result.w = (m21 - m12) / s;
  4864. result.x = (m13 + m31) / s;
  4865. result.y = (m23 + m32) / s;
  4866. result.z = 0.25 * s;
  4867. }
  4868. };
  4869. /**
  4870. * Returns the dot product (float) between the quaternions "left" and "right"
  4871. * @param left defines the left operand
  4872. * @param right defines the right operand
  4873. * @returns the dot product
  4874. */
  4875. Quaternion.Dot = function (left, right) {
  4876. return (left.x * right.x + left.y * right.y + left.z * right.z + left.w * right.w);
  4877. };
  4878. /**
  4879. * Checks if the two quaternions are close to each other
  4880. * @param quat0 defines the first quaternion to check
  4881. * @param quat1 defines the second quaternion to check
  4882. * @returns true if the two quaternions are close to each other
  4883. */
  4884. Quaternion.AreClose = function (quat0, quat1) {
  4885. var dot = Quaternion.Dot(quat0, quat1);
  4886. return dot >= 0;
  4887. };
  4888. /**
  4889. * Creates an empty quaternion
  4890. * @returns a new quaternion set to (0.0, 0.0, 0.0)
  4891. */
  4892. Quaternion.Zero = function () {
  4893. return new Quaternion(0.0, 0.0, 0.0, 0.0);
  4894. };
  4895. /**
  4896. * Inverse a given quaternion
  4897. * @param q defines the source quaternion
  4898. * @returns a new quaternion as the inverted current quaternion
  4899. */
  4900. Quaternion.Inverse = function (q) {
  4901. return new Quaternion(-q.x, -q.y, -q.z, q.w);
  4902. };
  4903. /**
  4904. * Creates an identity quaternion
  4905. * @returns the identity quaternion
  4906. */
  4907. Quaternion.Identity = function () {
  4908. return new Quaternion(0.0, 0.0, 0.0, 1.0);
  4909. };
  4910. /**
  4911. * Gets a boolean indicating if the given quaternion is identity
  4912. * @param quaternion defines the quaternion to check
  4913. * @returns true if the quaternion is identity
  4914. */
  4915. Quaternion.IsIdentity = function (quaternion) {
  4916. return quaternion && quaternion.x === 0 && quaternion.y === 0 && quaternion.z === 0 && quaternion.w === 1;
  4917. };
  4918. /**
  4919. * Creates a quaternion from a rotation around an axis
  4920. * @param axis defines the axis to use
  4921. * @param angle defines the angle to use
  4922. * @returns a new quaternion created from the given axis (Vector3) and angle in radians (float)
  4923. */
  4924. Quaternion.RotationAxis = function (axis, angle) {
  4925. return Quaternion.RotationAxisToRef(axis, angle, new Quaternion());
  4926. };
  4927. /**
  4928. * Creates a rotation around an axis and stores it into the given quaternion
  4929. * @param axis defines the axis to use
  4930. * @param angle defines the angle to use
  4931. * @param result defines the target quaternion
  4932. * @returns the target quaternion
  4933. */
  4934. Quaternion.RotationAxisToRef = function (axis, angle, result) {
  4935. var sin = Math.sin(angle / 2);
  4936. axis.normalize();
  4937. result.w = Math.cos(angle / 2);
  4938. result.x = axis.x * sin;
  4939. result.y = axis.y * sin;
  4940. result.z = axis.z * sin;
  4941. return result;
  4942. };
  4943. /**
  4944. * Creates a new quaternion from data stored into an array
  4945. * @param array defines the data source
  4946. * @param offset defines the offset in the source array where the data starts
  4947. * @returns a new quaternion
  4948. */
  4949. Quaternion.FromArray = function (array, offset) {
  4950. if (!offset) {
  4951. offset = 0;
  4952. }
  4953. return new Quaternion(array[offset], array[offset + 1], array[offset + 2], array[offset + 3]);
  4954. };
  4955. /**
  4956. * Creates a new quaternion from the given Euler float angles (y, x, z)
  4957. * @param yaw defines the rotation around Y axis
  4958. * @param pitch defines the rotation around X axis
  4959. * @param roll defines the rotation around Z axis
  4960. * @returns the new quaternion
  4961. */
  4962. Quaternion.RotationYawPitchRoll = function (yaw, pitch, roll) {
  4963. var q = new Quaternion();
  4964. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, q);
  4965. return q;
  4966. };
  4967. /**
  4968. * Creates a new rotation from the given Euler float angles (y, x, z) and stores it in the target quaternion
  4969. * @param yaw defines the rotation around Y axis
  4970. * @param pitch defines the rotation around X axis
  4971. * @param roll defines the rotation around Z axis
  4972. * @param result defines the target quaternion
  4973. */
  4974. Quaternion.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  4975. // Produces a quaternion from Euler angles in the z-y-x orientation (Tait-Bryan angles)
  4976. var halfRoll = roll * 0.5;
  4977. var halfPitch = pitch * 0.5;
  4978. var halfYaw = yaw * 0.5;
  4979. var sinRoll = Math.sin(halfRoll);
  4980. var cosRoll = Math.cos(halfRoll);
  4981. var sinPitch = Math.sin(halfPitch);
  4982. var cosPitch = Math.cos(halfPitch);
  4983. var sinYaw = Math.sin(halfYaw);
  4984. var cosYaw = Math.cos(halfYaw);
  4985. result.x = (cosYaw * sinPitch * cosRoll) + (sinYaw * cosPitch * sinRoll);
  4986. result.y = (sinYaw * cosPitch * cosRoll) - (cosYaw * sinPitch * sinRoll);
  4987. result.z = (cosYaw * cosPitch * sinRoll) - (sinYaw * sinPitch * cosRoll);
  4988. result.w = (cosYaw * cosPitch * cosRoll) + (sinYaw * sinPitch * sinRoll);
  4989. };
  4990. /**
  4991. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation
  4992. * @param alpha defines the rotation around first axis
  4993. * @param beta defines the rotation around second axis
  4994. * @param gamma defines the rotation around third axis
  4995. * @returns the new quaternion
  4996. */
  4997. Quaternion.RotationAlphaBetaGamma = function (alpha, beta, gamma) {
  4998. var result = new Quaternion();
  4999. Quaternion.RotationAlphaBetaGammaToRef(alpha, beta, gamma, result);
  5000. return result;
  5001. };
  5002. /**
  5003. * Creates a new quaternion from the given Euler float angles expressed in z-x-z orientation and stores it in the target quaternion
  5004. * @param alpha defines the rotation around first axis
  5005. * @param beta defines the rotation around second axis
  5006. * @param gamma defines the rotation around third axis
  5007. * @param result defines the target quaternion
  5008. */
  5009. Quaternion.RotationAlphaBetaGammaToRef = function (alpha, beta, gamma, result) {
  5010. // Produces a quaternion from Euler angles in the z-x-z orientation
  5011. var halfGammaPlusAlpha = (gamma + alpha) * 0.5;
  5012. var halfGammaMinusAlpha = (gamma - alpha) * 0.5;
  5013. var halfBeta = beta * 0.5;
  5014. result.x = Math.cos(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5015. result.y = Math.sin(halfGammaMinusAlpha) * Math.sin(halfBeta);
  5016. result.z = Math.sin(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5017. result.w = Math.cos(halfGammaPlusAlpha) * Math.cos(halfBeta);
  5018. };
  5019. /**
  5020. * 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)
  5021. * @param axis1 defines the first axis
  5022. * @param axis2 defines the second axis
  5023. * @param axis3 defines the third axis
  5024. * @returns the new quaternion
  5025. */
  5026. Quaternion.RotationQuaternionFromAxis = function (axis1, axis2, axis3) {
  5027. var quat = new Quaternion(0.0, 0.0, 0.0, 0.0);
  5028. Quaternion.RotationQuaternionFromAxisToRef(axis1, axis2, axis3, quat);
  5029. return quat;
  5030. };
  5031. /**
  5032. * 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
  5033. * @param axis1 defines the first axis
  5034. * @param axis2 defines the second axis
  5035. * @param axis3 defines the third axis
  5036. * @param ref defines the target quaternion
  5037. */
  5038. Quaternion.RotationQuaternionFromAxisToRef = function (axis1, axis2, axis3, ref) {
  5039. var rotMat = MathTmp.Matrix[0];
  5040. Matrix.FromXYZAxesToRef(axis1.normalize(), axis2.normalize(), axis3.normalize(), rotMat);
  5041. Quaternion.FromRotationMatrixToRef(rotMat, ref);
  5042. };
  5043. /**
  5044. * Interpolates between two quaternions
  5045. * @param left defines first quaternion
  5046. * @param right defines second quaternion
  5047. * @param amount defines the gradient to use
  5048. * @returns the new interpolated quaternion
  5049. */
  5050. Quaternion.Slerp = function (left, right, amount) {
  5051. var result = Quaternion.Identity();
  5052. Quaternion.SlerpToRef(left, right, amount, result);
  5053. return result;
  5054. };
  5055. /**
  5056. * Interpolates between two quaternions and stores it into a target quaternion
  5057. * @param left defines first quaternion
  5058. * @param right defines second quaternion
  5059. * @param amount defines the gradient to use
  5060. * @param result defines the target quaternion
  5061. */
  5062. Quaternion.SlerpToRef = function (left, right, amount, result) {
  5063. var num2;
  5064. var num3;
  5065. var num4 = (((left.x * right.x) + (left.y * right.y)) + (left.z * right.z)) + (left.w * right.w);
  5066. var flag = false;
  5067. if (num4 < 0) {
  5068. flag = true;
  5069. num4 = -num4;
  5070. }
  5071. if (num4 > 0.999999) {
  5072. num3 = 1 - amount;
  5073. num2 = flag ? -amount : amount;
  5074. }
  5075. else {
  5076. var num5 = Math.acos(num4);
  5077. var num6 = (1.0 / Math.sin(num5));
  5078. num3 = (Math.sin((1.0 - amount) * num5)) * num6;
  5079. num2 = flag ? ((-Math.sin(amount * num5)) * num6) : ((Math.sin(amount * num5)) * num6);
  5080. }
  5081. result.x = (num3 * left.x) + (num2 * right.x);
  5082. result.y = (num3 * left.y) + (num2 * right.y);
  5083. result.z = (num3 * left.z) + (num2 * right.z);
  5084. result.w = (num3 * left.w) + (num2 * right.w);
  5085. };
  5086. /**
  5087. * Interpolate between two quaternions using Hermite interpolation
  5088. * @param value1 defines first quaternion
  5089. * @param tangent1 defines the incoming tangent
  5090. * @param value2 defines second quaternion
  5091. * @param tangent2 defines the outgoing tangent
  5092. * @param amount defines the target quaternion
  5093. * @returns the new interpolated quaternion
  5094. */
  5095. Quaternion.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  5096. var squared = amount * amount;
  5097. var cubed = amount * squared;
  5098. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  5099. var part2 = (-2.0 * cubed) + (3.0 * squared);
  5100. var part3 = (cubed - (2.0 * squared)) + amount;
  5101. var part4 = cubed - squared;
  5102. var x = (((value1.x * part1) + (value2.x * part2)) + (tangent1.x * part3)) + (tangent2.x * part4);
  5103. var y = (((value1.y * part1) + (value2.y * part2)) + (tangent1.y * part3)) + (tangent2.y * part4);
  5104. var z = (((value1.z * part1) + (value2.z * part2)) + (tangent1.z * part3)) + (tangent2.z * part4);
  5105. var w = (((value1.w * part1) + (value2.w * part2)) + (tangent1.w * part3)) + (tangent2.w * part4);
  5106. return new Quaternion(x, y, z, w);
  5107. };
  5108. return Quaternion;
  5109. }());
  5110. BABYLON.Quaternion = Quaternion;
  5111. /**
  5112. * Class used to store matrix data (4x4)
  5113. */
  5114. var Matrix = /** @class */ (function () {
  5115. /**
  5116. * Creates an empty matrix (filled with zeros)
  5117. */
  5118. function Matrix() {
  5119. this._isIdentity = false;
  5120. this._isIdentityDirty = true;
  5121. /**
  5122. * Gets or sets the internal data of the matrix
  5123. */
  5124. this.m = new Float32Array(16);
  5125. this._markAsUpdated();
  5126. }
  5127. /** @hidden */
  5128. Matrix.prototype._markAsUpdated = function () {
  5129. this.updateFlag = Matrix._updateFlagSeed++;
  5130. this._isIdentityDirty = true;
  5131. };
  5132. // Properties
  5133. /**
  5134. * Check if the current matrix is indentity
  5135. * @param considerAsTextureMatrix defines if the current matrix must be considered as a texture matrix (3x2)
  5136. * @returns true is the matrix is the identity matrix
  5137. */
  5138. Matrix.prototype.isIdentity = function (considerAsTextureMatrix) {
  5139. if (considerAsTextureMatrix === void 0) { considerAsTextureMatrix = false; }
  5140. if (this._isIdentityDirty) {
  5141. this._isIdentityDirty = false;
  5142. if (this.m[0] !== 1.0 || this.m[5] !== 1.0 || this.m[15] !== 1.0) {
  5143. this._isIdentity = false;
  5144. }
  5145. else if (this.m[1] !== 0.0 || this.m[2] !== 0.0 || this.m[3] !== 0.0 ||
  5146. this.m[4] !== 0.0 || this.m[6] !== 0.0 || this.m[7] !== 0.0 ||
  5147. this.m[8] !== 0.0 || this.m[9] !== 0.0 || this.m[11] !== 0.0 ||
  5148. this.m[12] !== 0.0 || this.m[13] !== 0.0 || this.m[14] !== 0.0) {
  5149. this._isIdentity = false;
  5150. }
  5151. else {
  5152. this._isIdentity = true;
  5153. }
  5154. if (!considerAsTextureMatrix && this.m[10] !== 1.0) {
  5155. this._isIdentity = false;
  5156. }
  5157. }
  5158. return this._isIdentity;
  5159. };
  5160. /**
  5161. * Gets the determinant of the matrix
  5162. * @returns the matrix determinant
  5163. */
  5164. Matrix.prototype.determinant = function () {
  5165. var temp1 = (this.m[10] * this.m[15]) - (this.m[11] * this.m[14]);
  5166. var temp2 = (this.m[9] * this.m[15]) - (this.m[11] * this.m[13]);
  5167. var temp3 = (this.m[9] * this.m[14]) - (this.m[10] * this.m[13]);
  5168. var temp4 = (this.m[8] * this.m[15]) - (this.m[11] * this.m[12]);
  5169. var temp5 = (this.m[8] * this.m[14]) - (this.m[10] * this.m[12]);
  5170. var temp6 = (this.m[8] * this.m[13]) - (this.m[9] * this.m[12]);
  5171. return ((((this.m[0] * (((this.m[5] * temp1) - (this.m[6] * temp2)) + (this.m[7] * temp3))) - (this.m[1] * (((this.m[4] * temp1) -
  5172. (this.m[6] * temp4)) + (this.m[7] * temp5)))) + (this.m[2] * (((this.m[4] * temp2) - (this.m[5] * temp4)) + (this.m[7] * temp6)))) -
  5173. (this.m[3] * (((this.m[4] * temp3) - (this.m[5] * temp5)) + (this.m[6] * temp6))));
  5174. };
  5175. // Methods
  5176. /**
  5177. * Returns the matrix as a Float32Array
  5178. * @returns the matrix underlying array
  5179. */
  5180. Matrix.prototype.toArray = function () {
  5181. return this.m;
  5182. };
  5183. /**
  5184. * Returns the matrix as a Float32Array
  5185. * @returns the matrix underlying array.
  5186. */
  5187. Matrix.prototype.asArray = function () {
  5188. return this.toArray();
  5189. };
  5190. /**
  5191. * Inverts the current matrix in place
  5192. * @returns the current inverted matrix
  5193. */
  5194. Matrix.prototype.invert = function () {
  5195. this.invertToRef(this);
  5196. return this;
  5197. };
  5198. /**
  5199. * Sets all the matrix elements to zero
  5200. * @returns the current matrix
  5201. */
  5202. Matrix.prototype.reset = function () {
  5203. for (var index = 0; index < 16; index++) {
  5204. this.m[index] = 0.0;
  5205. }
  5206. this._markAsUpdated();
  5207. return this;
  5208. };
  5209. /**
  5210. * Adds the current matrix with a second one
  5211. * @param other defines the matrix to add
  5212. * @returns a new matrix as the addition of the current matrix and the given one
  5213. */
  5214. Matrix.prototype.add = function (other) {
  5215. var result = new Matrix();
  5216. this.addToRef(other, result);
  5217. return result;
  5218. };
  5219. /**
  5220. * Sets the given matrix "result" to the addition of the current matrix and the given one
  5221. * @param other defines the matrix to add
  5222. * @param result defines the target matrix
  5223. * @returns the current matrix
  5224. */
  5225. Matrix.prototype.addToRef = function (other, result) {
  5226. for (var index = 0; index < 16; index++) {
  5227. result.m[index] = this.m[index] + other.m[index];
  5228. }
  5229. result._markAsUpdated();
  5230. return this;
  5231. };
  5232. /**
  5233. * Adds in place the given matrix to the current matrix
  5234. * @param other defines the second operand
  5235. * @returns the current updated matrix
  5236. */
  5237. Matrix.prototype.addToSelf = function (other) {
  5238. for (var index = 0; index < 16; index++) {
  5239. this.m[index] += other.m[index];
  5240. }
  5241. this._markAsUpdated();
  5242. return this;
  5243. };
  5244. /**
  5245. * Sets the given matrix to the current inverted Matrix
  5246. * @param other defines the target matrix
  5247. * @returns the unmodified current matrix
  5248. */
  5249. Matrix.prototype.invertToRef = function (other) {
  5250. var l1 = this.m[0];
  5251. var l2 = this.m[1];
  5252. var l3 = this.m[2];
  5253. var l4 = this.m[3];
  5254. var l5 = this.m[4];
  5255. var l6 = this.m[5];
  5256. var l7 = this.m[6];
  5257. var l8 = this.m[7];
  5258. var l9 = this.m[8];
  5259. var l10 = this.m[9];
  5260. var l11 = this.m[10];
  5261. var l12 = this.m[11];
  5262. var l13 = this.m[12];
  5263. var l14 = this.m[13];
  5264. var l15 = this.m[14];
  5265. var l16 = this.m[15];
  5266. var l17 = (l11 * l16) - (l12 * l15);
  5267. var l18 = (l10 * l16) - (l12 * l14);
  5268. var l19 = (l10 * l15) - (l11 * l14);
  5269. var l20 = (l9 * l16) - (l12 * l13);
  5270. var l21 = (l9 * l15) - (l11 * l13);
  5271. var l22 = (l9 * l14) - (l10 * l13);
  5272. var l23 = ((l6 * l17) - (l7 * l18)) + (l8 * l19);
  5273. var l24 = -(((l5 * l17) - (l7 * l20)) + (l8 * l21));
  5274. var l25 = ((l5 * l18) - (l6 * l20)) + (l8 * l22);
  5275. var l26 = -(((l5 * l19) - (l6 * l21)) + (l7 * l22));
  5276. var l27 = 1.0 / ((((l1 * l23) + (l2 * l24)) + (l3 * l25)) + (l4 * l26));
  5277. var l28 = (l7 * l16) - (l8 * l15);
  5278. var l29 = (l6 * l16) - (l8 * l14);
  5279. var l30 = (l6 * l15) - (l7 * l14);
  5280. var l31 = (l5 * l16) - (l8 * l13);
  5281. var l32 = (l5 * l15) - (l7 * l13);
  5282. var l33 = (l5 * l14) - (l6 * l13);
  5283. var l34 = (l7 * l12) - (l8 * l11);
  5284. var l35 = (l6 * l12) - (l8 * l10);
  5285. var l36 = (l6 * l11) - (l7 * l10);
  5286. var l37 = (l5 * l12) - (l8 * l9);
  5287. var l38 = (l5 * l11) - (l7 * l9);
  5288. var l39 = (l5 * l10) - (l6 * l9);
  5289. other.m[0] = l23 * l27;
  5290. other.m[4] = l24 * l27;
  5291. other.m[8] = l25 * l27;
  5292. other.m[12] = l26 * l27;
  5293. other.m[1] = -(((l2 * l17) - (l3 * l18)) + (l4 * l19)) * l27;
  5294. other.m[5] = (((l1 * l17) - (l3 * l20)) + (l4 * l21)) * l27;
  5295. other.m[9] = -(((l1 * l18) - (l2 * l20)) + (l4 * l22)) * l27;
  5296. other.m[13] = (((l1 * l19) - (l2 * l21)) + (l3 * l22)) * l27;
  5297. other.m[2] = (((l2 * l28) - (l3 * l29)) + (l4 * l30)) * l27;
  5298. other.m[6] = -(((l1 * l28) - (l3 * l31)) + (l4 * l32)) * l27;
  5299. other.m[10] = (((l1 * l29) - (l2 * l31)) + (l4 * l33)) * l27;
  5300. other.m[14] = -(((l1 * l30) - (l2 * l32)) + (l3 * l33)) * l27;
  5301. other.m[3] = -(((l2 * l34) - (l3 * l35)) + (l4 * l36)) * l27;
  5302. other.m[7] = (((l1 * l34) - (l3 * l37)) + (l4 * l38)) * l27;
  5303. other.m[11] = -(((l1 * l35) - (l2 * l37)) + (l4 * l39)) * l27;
  5304. other.m[15] = (((l1 * l36) - (l2 * l38)) + (l3 * l39)) * l27;
  5305. other._markAsUpdated();
  5306. return this;
  5307. };
  5308. /**
  5309. * Inserts the translation vector (using 3 floats) in the current matrix
  5310. * @param x defines the 1st component of the translation
  5311. * @param y defines the 2nd component of the translation
  5312. * @param z defines the 3rd component of the translation
  5313. * @returns the current updated matrix
  5314. */
  5315. Matrix.prototype.setTranslationFromFloats = function (x, y, z) {
  5316. this.m[12] = x;
  5317. this.m[13] = y;
  5318. this.m[14] = z;
  5319. this._markAsUpdated();
  5320. return this;
  5321. };
  5322. /**
  5323. * Inserts the translation vector in the current matrix
  5324. * @param vector3 defines the translation to insert
  5325. * @returns the current updated matrix
  5326. */
  5327. Matrix.prototype.setTranslation = function (vector3) {
  5328. this.m[12] = vector3.x;
  5329. this.m[13] = vector3.y;
  5330. this.m[14] = vector3.z;
  5331. this._markAsUpdated();
  5332. return this;
  5333. };
  5334. /**
  5335. * Gets the translation value of the current matrix
  5336. * @returns a new Vector3 as the extracted translation from the matrix
  5337. */
  5338. Matrix.prototype.getTranslation = function () {
  5339. return new Vector3(this.m[12], this.m[13], this.m[14]);
  5340. };
  5341. /**
  5342. * Fill a Vector3 with the extracted translation from the matrix
  5343. * @param result defines the Vector3 where to store the translation
  5344. * @returns the current matrix
  5345. */
  5346. Matrix.prototype.getTranslationToRef = function (result) {
  5347. result.x = this.m[12];
  5348. result.y = this.m[13];
  5349. result.z = this.m[14];
  5350. return this;
  5351. };
  5352. /**
  5353. * Remove rotation and scaling part from the matrix
  5354. * @returns the updated matrix
  5355. */
  5356. Matrix.prototype.removeRotationAndScaling = function () {
  5357. this.setRowFromFloats(0, 1, 0, 0, 0);
  5358. this.setRowFromFloats(1, 0, 1, 0, 0);
  5359. this.setRowFromFloats(2, 0, 0, 1, 0);
  5360. return this;
  5361. };
  5362. /**
  5363. * Multiply two matrices
  5364. * @param other defines the second operand
  5365. * @returns a new matrix set with the multiplication result of the current Matrix and the given one
  5366. */
  5367. Matrix.prototype.multiply = function (other) {
  5368. var result = new Matrix();
  5369. this.multiplyToRef(other, result);
  5370. return result;
  5371. };
  5372. /**
  5373. * Copy the current matrix from the given one
  5374. * @param other defines the source matrix
  5375. * @returns the current updated matrix
  5376. */
  5377. Matrix.prototype.copyFrom = function (other) {
  5378. for (var index = 0; index < 16; index++) {
  5379. this.m[index] = other.m[index];
  5380. }
  5381. this._markAsUpdated();
  5382. return this;
  5383. };
  5384. /**
  5385. * Populates the given array from the starting index with the current matrix values
  5386. * @param array defines the target array
  5387. * @param offset defines the offset in the target array where to start storing values
  5388. * @returns the current matrix
  5389. */
  5390. Matrix.prototype.copyToArray = function (array, offset) {
  5391. if (offset === void 0) { offset = 0; }
  5392. for (var index = 0; index < 16; index++) {
  5393. array[offset + index] = this.m[index];
  5394. }
  5395. return this;
  5396. };
  5397. /**
  5398. * Sets the given matrix "result" with the multiplication result of the current Matrix and the given one
  5399. * @param other defines the second operand
  5400. * @param result defines the matrix where to store the multiplication
  5401. * @returns the current matrix
  5402. */
  5403. Matrix.prototype.multiplyToRef = function (other, result) {
  5404. this.multiplyToArray(other, result.m, 0);
  5405. result._markAsUpdated();
  5406. return this;
  5407. };
  5408. /**
  5409. * Sets the Float32Array "result" from the given index "offset" with the multiplication of the current matrix and the given one
  5410. * @param other defines the second operand
  5411. * @param result defines the array where to store the multiplication
  5412. * @param offset defines the offset in the target array where to start storing values
  5413. * @returns the current matrix
  5414. */
  5415. Matrix.prototype.multiplyToArray = function (other, result, offset) {
  5416. var tm0 = this.m[0];
  5417. var tm1 = this.m[1];
  5418. var tm2 = this.m[2];
  5419. var tm3 = this.m[3];
  5420. var tm4 = this.m[4];
  5421. var tm5 = this.m[5];
  5422. var tm6 = this.m[6];
  5423. var tm7 = this.m[7];
  5424. var tm8 = this.m[8];
  5425. var tm9 = this.m[9];
  5426. var tm10 = this.m[10];
  5427. var tm11 = this.m[11];
  5428. var tm12 = this.m[12];
  5429. var tm13 = this.m[13];
  5430. var tm14 = this.m[14];
  5431. var tm15 = this.m[15];
  5432. var om0 = other.m[0];
  5433. var om1 = other.m[1];
  5434. var om2 = other.m[2];
  5435. var om3 = other.m[3];
  5436. var om4 = other.m[4];
  5437. var om5 = other.m[5];
  5438. var om6 = other.m[6];
  5439. var om7 = other.m[7];
  5440. var om8 = other.m[8];
  5441. var om9 = other.m[9];
  5442. var om10 = other.m[10];
  5443. var om11 = other.m[11];
  5444. var om12 = other.m[12];
  5445. var om13 = other.m[13];
  5446. var om14 = other.m[14];
  5447. var om15 = other.m[15];
  5448. result[offset] = tm0 * om0 + tm1 * om4 + tm2 * om8 + tm3 * om12;
  5449. result[offset + 1] = tm0 * om1 + tm1 * om5 + tm2 * om9 + tm3 * om13;
  5450. result[offset + 2] = tm0 * om2 + tm1 * om6 + tm2 * om10 + tm3 * om14;
  5451. result[offset + 3] = tm0 * om3 + tm1 * om7 + tm2 * om11 + tm3 * om15;
  5452. result[offset + 4] = tm4 * om0 + tm5 * om4 + tm6 * om8 + tm7 * om12;
  5453. result[offset + 5] = tm4 * om1 + tm5 * om5 + tm6 * om9 + tm7 * om13;
  5454. result[offset + 6] = tm4 * om2 + tm5 * om6 + tm6 * om10 + tm7 * om14;
  5455. result[offset + 7] = tm4 * om3 + tm5 * om7 + tm6 * om11 + tm7 * om15;
  5456. result[offset + 8] = tm8 * om0 + tm9 * om4 + tm10 * om8 + tm11 * om12;
  5457. result[offset + 9] = tm8 * om1 + tm9 * om5 + tm10 * om9 + tm11 * om13;
  5458. result[offset + 10] = tm8 * om2 + tm9 * om6 + tm10 * om10 + tm11 * om14;
  5459. result[offset + 11] = tm8 * om3 + tm9 * om7 + tm10 * om11 + tm11 * om15;
  5460. result[offset + 12] = tm12 * om0 + tm13 * om4 + tm14 * om8 + tm15 * om12;
  5461. result[offset + 13] = tm12 * om1 + tm13 * om5 + tm14 * om9 + tm15 * om13;
  5462. result[offset + 14] = tm12 * om2 + tm13 * om6 + tm14 * om10 + tm15 * om14;
  5463. result[offset + 15] = tm12 * om3 + tm13 * om7 + tm14 * om11 + tm15 * om15;
  5464. return this;
  5465. };
  5466. /**
  5467. * Check equality between this matrix and a second one
  5468. * @param value defines the second matrix to compare
  5469. * @returns true is the current matrix and the given one values are strictly equal
  5470. */
  5471. Matrix.prototype.equals = function (value) {
  5472. return value &&
  5473. (this.m[0] === value.m[0] && this.m[1] === value.m[1] && this.m[2] === value.m[2] && this.m[3] === value.m[3] &&
  5474. this.m[4] === value.m[4] && this.m[5] === value.m[5] && this.m[6] === value.m[6] && this.m[7] === value.m[7] &&
  5475. this.m[8] === value.m[8] && this.m[9] === value.m[9] && this.m[10] === value.m[10] && this.m[11] === value.m[11] &&
  5476. this.m[12] === value.m[12] && this.m[13] === value.m[13] && this.m[14] === value.m[14] && this.m[15] === value.m[15]);
  5477. };
  5478. /**
  5479. * Clone the current matrix
  5480. * @returns a new matrix from the current matrix
  5481. */
  5482. Matrix.prototype.clone = function () {
  5483. 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]);
  5484. };
  5485. /**
  5486. * Returns the name of the current matrix class
  5487. * @returns the string "Matrix"
  5488. */
  5489. Matrix.prototype.getClassName = function () {
  5490. return "Matrix";
  5491. };
  5492. /**
  5493. * Gets the hash code of the current matrix
  5494. * @returns the hash code
  5495. */
  5496. Matrix.prototype.getHashCode = function () {
  5497. var hash = this.m[0] || 0;
  5498. for (var i = 1; i < 16; i++) {
  5499. hash = (hash * 397) ^ (this.m[i] || 0);
  5500. }
  5501. return hash;
  5502. };
  5503. /**
  5504. * Decomposes the current Matrix into a translation, rotation and scaling components
  5505. * @param scale defines the scale vector3 given as a reference to update
  5506. * @param rotation defines the rotation quaternion given as a reference to update
  5507. * @param translation defines the translation vector3 given as a reference to update
  5508. * @returns true if operation was successful
  5509. */
  5510. Matrix.prototype.decompose = function (scale, rotation, translation) {
  5511. if (translation) {
  5512. translation.x = this.m[12];
  5513. translation.y = this.m[13];
  5514. translation.z = this.m[14];
  5515. }
  5516. scale = scale || MathTmp.Vector3[0];
  5517. scale.x = Math.sqrt(this.m[0] * this.m[0] + this.m[1] * this.m[1] + this.m[2] * this.m[2]);
  5518. scale.y = Math.sqrt(this.m[4] * this.m[4] + this.m[5] * this.m[5] + this.m[6] * this.m[6]);
  5519. scale.z = Math.sqrt(this.m[8] * this.m[8] + this.m[9] * this.m[9] + this.m[10] * this.m[10]);
  5520. if (this.determinant() <= 0) {
  5521. scale.y *= -1;
  5522. }
  5523. if (scale.x === 0 || scale.y === 0 || scale.z === 0) {
  5524. if (rotation) {
  5525. rotation.x = 0;
  5526. rotation.y = 0;
  5527. rotation.z = 0;
  5528. rotation.w = 1;
  5529. }
  5530. return false;
  5531. }
  5532. if (rotation) {
  5533. 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]);
  5534. Quaternion.FromRotationMatrixToRef(MathTmp.Matrix[0], rotation);
  5535. }
  5536. return true;
  5537. };
  5538. /**
  5539. * Gets specific row of the matrix
  5540. * @param index defines the number of the row to get
  5541. * @returns the index-th row of the current matrix as a new Vector4
  5542. */
  5543. Matrix.prototype.getRow = function (index) {
  5544. if (index < 0 || index > 3) {
  5545. return null;
  5546. }
  5547. var i = index * 4;
  5548. return new Vector4(this.m[i + 0], this.m[i + 1], this.m[i + 2], this.m[i + 3]);
  5549. };
  5550. /**
  5551. * Sets the index-th row of the current matrix to the vector4 values
  5552. * @param index defines the number of the row to set
  5553. * @param row defines the target vector4
  5554. * @returns the updated current matrix
  5555. */
  5556. Matrix.prototype.setRow = function (index, row) {
  5557. if (index < 0 || index > 3) {
  5558. return this;
  5559. }
  5560. var i = index * 4;
  5561. this.m[i + 0] = row.x;
  5562. this.m[i + 1] = row.y;
  5563. this.m[i + 2] = row.z;
  5564. this.m[i + 3] = row.w;
  5565. this._markAsUpdated();
  5566. return this;
  5567. };
  5568. /**
  5569. * Compute the transpose of the matrix
  5570. * @returns the new transposed matrix
  5571. */
  5572. Matrix.prototype.transpose = function () {
  5573. return Matrix.Transpose(this);
  5574. };
  5575. /**
  5576. * Compute the transpose of the matrix and store it in a given matrix
  5577. * @param result defines the target matrix
  5578. * @returns the current matrix
  5579. */
  5580. Matrix.prototype.transposeToRef = function (result) {
  5581. Matrix.TransposeToRef(this, result);
  5582. return this;
  5583. };
  5584. /**
  5585. * Sets the index-th row of the current matrix with the given 4 x float values
  5586. * @param index defines the row index
  5587. * @param x defines the x component to set
  5588. * @param y defines the y component to set
  5589. * @param z defines the z component to set
  5590. * @param w defines the w component to set
  5591. * @returns the updated current matrix
  5592. */
  5593. Matrix.prototype.setRowFromFloats = function (index, x, y, z, w) {
  5594. if (index < 0 || index > 3) {
  5595. return this;
  5596. }
  5597. var i = index * 4;
  5598. this.m[i + 0] = x;
  5599. this.m[i + 1] = y;
  5600. this.m[i + 2] = z;
  5601. this.m[i + 3] = w;
  5602. this._markAsUpdated();
  5603. return this;
  5604. };
  5605. /**
  5606. * Compute a new matrix set with the current matrix values multiplied by scale (float)
  5607. * @param scale defines the scale factor
  5608. * @returns a new matrix
  5609. */
  5610. Matrix.prototype.scale = function (scale) {
  5611. var result = new Matrix();
  5612. this.scaleToRef(scale, result);
  5613. return result;
  5614. };
  5615. /**
  5616. * Scale the current matrix values by a factor to a given result matrix
  5617. * @param scale defines the scale factor
  5618. * @param result defines the matrix to store the result
  5619. * @returns the current matrix
  5620. */
  5621. Matrix.prototype.scaleToRef = function (scale, result) {
  5622. for (var index = 0; index < 16; index++) {
  5623. result.m[index] = this.m[index] * scale;
  5624. }
  5625. result._markAsUpdated();
  5626. return this;
  5627. };
  5628. /**
  5629. * Scale the current matrix values by a factor and add the result to a given matrix
  5630. * @param scale defines the scale factor
  5631. * @param result defines the Matrix to store the result
  5632. * @returns the current matrix
  5633. */
  5634. Matrix.prototype.scaleAndAddToRef = function (scale, result) {
  5635. for (var index = 0; index < 16; index++) {
  5636. result.m[index] += this.m[index] * scale;
  5637. }
  5638. result._markAsUpdated();
  5639. return this;
  5640. };
  5641. /**
  5642. * Writes to the given matrix a normal matrix, computed from this one (using values from identity matrix for fourth row and column).
  5643. * @param ref matrix to store the result
  5644. */
  5645. Matrix.prototype.toNormalMatrix = function (ref) {
  5646. this.invertToRef(ref);
  5647. ref.transpose();
  5648. var m = ref.m;
  5649. 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);
  5650. };
  5651. /**
  5652. * Gets only rotation part of the current matrix
  5653. * @returns a new matrix sets to the extracted rotation matrix from the current one
  5654. */
  5655. Matrix.prototype.getRotationMatrix = function () {
  5656. var result = Matrix.Identity();
  5657. this.getRotationMatrixToRef(result);
  5658. return result;
  5659. };
  5660. /**
  5661. * Extracts the rotation matrix from the current one and sets it as the given "result"
  5662. * @param result defines the target matrix to store data to
  5663. * @returns the current matrix
  5664. */
  5665. Matrix.prototype.getRotationMatrixToRef = function (result) {
  5666. var m = this.m;
  5667. var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1] + m[2] * m[2]);
  5668. var sy = Math.sqrt(m[4] * m[4] + m[5] * m[5] + m[6] * m[6]);
  5669. var sz = Math.sqrt(m[8] * m[8] + m[9] * m[9] + m[10] * m[10]);
  5670. if (this.determinant() <= 0) {
  5671. sy *= -1;
  5672. }
  5673. if (sx === 0 || sy === 0 || sz === 0) {
  5674. Matrix.IdentityToRef(result);
  5675. }
  5676. else {
  5677. 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);
  5678. }
  5679. return this;
  5680. };
  5681. // Statics
  5682. /**
  5683. * Creates a matrix from an array
  5684. * @param array defines the source array
  5685. * @param offset defines an offset in the source array
  5686. * @returns a new Matrix set from the starting index of the given array
  5687. */
  5688. Matrix.FromArray = function (array, offset) {
  5689. var result = new Matrix();
  5690. if (!offset) {
  5691. offset = 0;
  5692. }
  5693. Matrix.FromArrayToRef(array, offset, result);
  5694. return result;
  5695. };
  5696. /**
  5697. * Copy the content of an array into a given matrix
  5698. * @param array defines the source array
  5699. * @param offset defines an offset in the source array
  5700. * @param result defines the target matrix
  5701. */
  5702. Matrix.FromArrayToRef = function (array, offset, result) {
  5703. for (var index = 0; index < 16; index++) {
  5704. result.m[index] = array[index + offset];
  5705. }
  5706. result._markAsUpdated();
  5707. };
  5708. /**
  5709. * Stores an array into a matrix after having multiplied each component by a given factor
  5710. * @param array defines the source array
  5711. * @param offset defines the offset in the source array
  5712. * @param scale defines the scaling factor
  5713. * @param result defines the target matrix
  5714. */
  5715. Matrix.FromFloat32ArrayToRefScaled = function (array, offset, scale, result) {
  5716. for (var index = 0; index < 16; index++) {
  5717. result.m[index] = array[index + offset] * scale;
  5718. }
  5719. result._markAsUpdated();
  5720. };
  5721. /**
  5722. * Stores a list of values (16) inside a given matrix
  5723. * @param initialM11 defines 1st value of 1st row
  5724. * @param initialM12 defines 2nd value of 1st row
  5725. * @param initialM13 defines 3rd value of 1st row
  5726. * @param initialM14 defines 4th value of 1st row
  5727. * @param initialM21 defines 1st value of 2nd row
  5728. * @param initialM22 defines 2nd value of 2nd row
  5729. * @param initialM23 defines 3rd value of 2nd row
  5730. * @param initialM24 defines 4th value of 2nd row
  5731. * @param initialM31 defines 1st value of 3rd row
  5732. * @param initialM32 defines 2nd value of 3rd row
  5733. * @param initialM33 defines 3rd value of 3rd row
  5734. * @param initialM34 defines 4th value of 3rd row
  5735. * @param initialM41 defines 1st value of 4th row
  5736. * @param initialM42 defines 2nd value of 4th row
  5737. * @param initialM43 defines 3rd value of 4th row
  5738. * @param initialM44 defines 4th value of 4th row
  5739. * @param result defines the target matrix
  5740. */
  5741. Matrix.FromValuesToRef = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44, result) {
  5742. result.m[0] = initialM11;
  5743. result.m[1] = initialM12;
  5744. result.m[2] = initialM13;
  5745. result.m[3] = initialM14;
  5746. result.m[4] = initialM21;
  5747. result.m[5] = initialM22;
  5748. result.m[6] = initialM23;
  5749. result.m[7] = initialM24;
  5750. result.m[8] = initialM31;
  5751. result.m[9] = initialM32;
  5752. result.m[10] = initialM33;
  5753. result.m[11] = initialM34;
  5754. result.m[12] = initialM41;
  5755. result.m[13] = initialM42;
  5756. result.m[14] = initialM43;
  5757. result.m[15] = initialM44;
  5758. result._markAsUpdated();
  5759. };
  5760. Object.defineProperty(Matrix, "IdentityReadOnly", {
  5761. /**
  5762. * Gets an identity matrix that must not be updated
  5763. */
  5764. get: function () {
  5765. return Matrix._identityReadOnly;
  5766. },
  5767. enumerable: true,
  5768. configurable: true
  5769. });
  5770. /**
  5771. * Creates new matrix from a list of values (16)
  5772. * @param initialM11 defines 1st value of 1st row
  5773. * @param initialM12 defines 2nd value of 1st row
  5774. * @param initialM13 defines 3rd value of 1st row
  5775. * @param initialM14 defines 4th value of 1st row
  5776. * @param initialM21 defines 1st value of 2nd row
  5777. * @param initialM22 defines 2nd value of 2nd row
  5778. * @param initialM23 defines 3rd value of 2nd row
  5779. * @param initialM24 defines 4th value of 2nd row
  5780. * @param initialM31 defines 1st value of 3rd row
  5781. * @param initialM32 defines 2nd value of 3rd row
  5782. * @param initialM33 defines 3rd value of 3rd row
  5783. * @param initialM34 defines 4th value of 3rd row
  5784. * @param initialM41 defines 1st value of 4th row
  5785. * @param initialM42 defines 2nd value of 4th row
  5786. * @param initialM43 defines 3rd value of 4th row
  5787. * @param initialM44 defines 4th value of 4th row
  5788. * @returns the new matrix
  5789. */
  5790. Matrix.FromValues = function (initialM11, initialM12, initialM13, initialM14, initialM21, initialM22, initialM23, initialM24, initialM31, initialM32, initialM33, initialM34, initialM41, initialM42, initialM43, initialM44) {
  5791. var result = new Matrix();
  5792. result.m[0] = initialM11;
  5793. result.m[1] = initialM12;
  5794. result.m[2] = initialM13;
  5795. result.m[3] = initialM14;
  5796. result.m[4] = initialM21;
  5797. result.m[5] = initialM22;
  5798. result.m[6] = initialM23;
  5799. result.m[7] = initialM24;
  5800. result.m[8] = initialM31;
  5801. result.m[9] = initialM32;
  5802. result.m[10] = initialM33;
  5803. result.m[11] = initialM34;
  5804. result.m[12] = initialM41;
  5805. result.m[13] = initialM42;
  5806. result.m[14] = initialM43;
  5807. result.m[15] = initialM44;
  5808. return result;
  5809. };
  5810. /**
  5811. * Creates a new matrix composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5812. * @param scale defines the scale vector3
  5813. * @param rotation defines the rotation quaternion
  5814. * @param translation defines the translation vector3
  5815. * @returns a new matrix
  5816. */
  5817. Matrix.Compose = function (scale, rotation, translation) {
  5818. var result = Matrix.Identity();
  5819. Matrix.ComposeToRef(scale, rotation, translation, result);
  5820. return result;
  5821. };
  5822. /**
  5823. * Sets a matrix to a value composed by merging scale (vector3), rotation (quaternion) and translation (vector3)
  5824. * @param scale defines the scale vector3
  5825. * @param rotation defines the rotation quaternion
  5826. * @param translation defines the translation vector3
  5827. * @param result defines the target matrix
  5828. */
  5829. Matrix.ComposeToRef = function (scale, rotation, translation, result) {
  5830. Matrix.FromValuesToRef(scale.x, 0, 0, 0, 0, scale.y, 0, 0, 0, 0, scale.z, 0, 0, 0, 0, 1, MathTmp.Matrix[1]);
  5831. rotation.toRotationMatrix(MathTmp.Matrix[0]);
  5832. MathTmp.Matrix[1].multiplyToRef(MathTmp.Matrix[0], result);
  5833. result.setTranslation(translation);
  5834. };
  5835. /**
  5836. * Creates a new identity matrix
  5837. * @returns a new identity matrix
  5838. */
  5839. Matrix.Identity = function () {
  5840. 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);
  5841. };
  5842. /**
  5843. * Creates a new identity matrix and stores the result in a given matrix
  5844. * @param result defines the target matrix
  5845. */
  5846. Matrix.IdentityToRef = function (result) {
  5847. 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);
  5848. };
  5849. /**
  5850. * Creates a new zero matrix
  5851. * @returns a new zero matrix
  5852. */
  5853. Matrix.Zero = function () {
  5854. 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);
  5855. };
  5856. /**
  5857. * Creates a new rotation matrix for "angle" radians around the X axis
  5858. * @param angle defines the angle (in radians) to use
  5859. * @return the new matrix
  5860. */
  5861. Matrix.RotationX = function (angle) {
  5862. var result = new Matrix();
  5863. Matrix.RotationXToRef(angle, result);
  5864. return result;
  5865. };
  5866. /**
  5867. * Creates a new matrix as the invert of a given matrix
  5868. * @param source defines the source matrix
  5869. * @returns the new matrix
  5870. */
  5871. Matrix.Invert = function (source) {
  5872. var result = new Matrix();
  5873. source.invertToRef(result);
  5874. return result;
  5875. };
  5876. /**
  5877. * Creates a new rotation matrix for "angle" radians around the X axis and stores it in a given matrix
  5878. * @param angle defines the angle (in radians) to use
  5879. * @param result defines the target matrix
  5880. */
  5881. Matrix.RotationXToRef = function (angle, result) {
  5882. var s = Math.sin(angle);
  5883. var c = Math.cos(angle);
  5884. result.m[0] = 1.0;
  5885. result.m[15] = 1.0;
  5886. result.m[5] = c;
  5887. result.m[10] = c;
  5888. result.m[9] = -s;
  5889. result.m[6] = s;
  5890. result.m[1] = 0.0;
  5891. result.m[2] = 0.0;
  5892. result.m[3] = 0.0;
  5893. result.m[4] = 0.0;
  5894. result.m[7] = 0.0;
  5895. result.m[8] = 0.0;
  5896. result.m[11] = 0.0;
  5897. result.m[12] = 0.0;
  5898. result.m[13] = 0.0;
  5899. result.m[14] = 0.0;
  5900. result._markAsUpdated();
  5901. };
  5902. /**
  5903. * Creates a new rotation matrix for "angle" radians around the Y axis
  5904. * @param angle defines the angle (in radians) to use
  5905. * @return the new matrix
  5906. */
  5907. Matrix.RotationY = function (angle) {
  5908. var result = new Matrix();
  5909. Matrix.RotationYToRef(angle, result);
  5910. return result;
  5911. };
  5912. /**
  5913. * Creates a new rotation matrix for "angle" radians around the Y axis and stores it in a given matrix
  5914. * @param angle defines the angle (in radians) to use
  5915. * @param result defines the target matrix
  5916. */
  5917. Matrix.RotationYToRef = function (angle, result) {
  5918. var s = Math.sin(angle);
  5919. var c = Math.cos(angle);
  5920. result.m[5] = 1.0;
  5921. result.m[15] = 1.0;
  5922. result.m[0] = c;
  5923. result.m[2] = -s;
  5924. result.m[8] = s;
  5925. result.m[10] = c;
  5926. result.m[1] = 0.0;
  5927. result.m[3] = 0.0;
  5928. result.m[4] = 0.0;
  5929. result.m[6] = 0.0;
  5930. result.m[7] = 0.0;
  5931. result.m[9] = 0.0;
  5932. result.m[11] = 0.0;
  5933. result.m[12] = 0.0;
  5934. result.m[13] = 0.0;
  5935. result.m[14] = 0.0;
  5936. result._markAsUpdated();
  5937. };
  5938. /**
  5939. * Creates a new rotation matrix for "angle" radians around the Z axis
  5940. * @param angle defines the angle (in radians) to use
  5941. * @return the new matrix
  5942. */
  5943. Matrix.RotationZ = function (angle) {
  5944. var result = new Matrix();
  5945. Matrix.RotationZToRef(angle, result);
  5946. return result;
  5947. };
  5948. /**
  5949. * Creates a new rotation matrix for "angle" radians around the Z axis and stores it in a given matrix
  5950. * @param angle defines the angle (in radians) to use
  5951. * @param result defines the target matrix
  5952. */
  5953. Matrix.RotationZToRef = function (angle, result) {
  5954. var s = Math.sin(angle);
  5955. var c = Math.cos(angle);
  5956. result.m[10] = 1.0;
  5957. result.m[15] = 1.0;
  5958. result.m[0] = c;
  5959. result.m[1] = s;
  5960. result.m[4] = -s;
  5961. result.m[5] = c;
  5962. result.m[2] = 0.0;
  5963. result.m[3] = 0.0;
  5964. result.m[6] = 0.0;
  5965. result.m[7] = 0.0;
  5966. result.m[8] = 0.0;
  5967. result.m[9] = 0.0;
  5968. result.m[11] = 0.0;
  5969. result.m[12] = 0.0;
  5970. result.m[13] = 0.0;
  5971. result.m[14] = 0.0;
  5972. result._markAsUpdated();
  5973. };
  5974. /**
  5975. * Creates a new rotation matrix for "angle" radians around the given axis
  5976. * @param axis defines the axis to use
  5977. * @param angle defines the angle (in radians) to use
  5978. * @return the new matrix
  5979. */
  5980. Matrix.RotationAxis = function (axis, angle) {
  5981. var result = Matrix.Zero();
  5982. Matrix.RotationAxisToRef(axis, angle, result);
  5983. return result;
  5984. };
  5985. /**
  5986. * Creates a new rotation matrix for "angle" radians around the given axis and stores it in a given matrix
  5987. * @param axis defines the axis to use
  5988. * @param angle defines the angle (in radians) to use
  5989. * @param result defines the target matrix
  5990. */
  5991. Matrix.RotationAxisToRef = function (axis, angle, result) {
  5992. var s = Math.sin(-angle);
  5993. var c = Math.cos(-angle);
  5994. var c1 = 1 - c;
  5995. axis.normalize();
  5996. result.m[0] = (axis.x * axis.x) * c1 + c;
  5997. result.m[1] = (axis.x * axis.y) * c1 - (axis.z * s);
  5998. result.m[2] = (axis.x * axis.z) * c1 + (axis.y * s);
  5999. result.m[3] = 0.0;
  6000. result.m[4] = (axis.y * axis.x) * c1 + (axis.z * s);
  6001. result.m[5] = (axis.y * axis.y) * c1 + c;
  6002. result.m[6] = (axis.y * axis.z) * c1 - (axis.x * s);
  6003. result.m[7] = 0.0;
  6004. result.m[8] = (axis.z * axis.x) * c1 - (axis.y * s);
  6005. result.m[9] = (axis.z * axis.y) * c1 + (axis.x * s);
  6006. result.m[10] = (axis.z * axis.z) * c1 + c;
  6007. result.m[11] = 0.0;
  6008. result.m[15] = 1.0;
  6009. result._markAsUpdated();
  6010. };
  6011. /**
  6012. * Creates a rotation matrix
  6013. * @param yaw defines the yaw angle in radians (Y axis)
  6014. * @param pitch defines the pitch angle in radians (X axis)
  6015. * @param roll defines the roll angle in radians (X axis)
  6016. * @returns the new rotation matrix
  6017. */
  6018. Matrix.RotationYawPitchRoll = function (yaw, pitch, roll) {
  6019. var result = new Matrix();
  6020. Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, result);
  6021. return result;
  6022. };
  6023. /**
  6024. * Creates a rotation matrix and stores it in a given matrix
  6025. * @param yaw defines the yaw angle in radians (Y axis)
  6026. * @param pitch defines the pitch angle in radians (X axis)
  6027. * @param roll defines the roll angle in radians (X axis)
  6028. * @param result defines the target matrix
  6029. */
  6030. Matrix.RotationYawPitchRollToRef = function (yaw, pitch, roll, result) {
  6031. Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, this._tempQuaternion);
  6032. this._tempQuaternion.toRotationMatrix(result);
  6033. };
  6034. /**
  6035. * Creates a scaling matrix
  6036. * @param x defines the scale factor on X axis
  6037. * @param y defines the scale factor on Y axis
  6038. * @param z defines the scale factor on Z axis
  6039. * @returns the new matrix
  6040. */
  6041. Matrix.Scaling = function (x, y, z) {
  6042. var result = Matrix.Zero();
  6043. Matrix.ScalingToRef(x, y, z, result);
  6044. return result;
  6045. };
  6046. /**
  6047. * Creates a scaling matrix and stores it in a given matrix
  6048. * @param x defines the scale factor on X axis
  6049. * @param y defines the scale factor on Y axis
  6050. * @param z defines the scale factor on Z axis
  6051. * @param result defines the target matrix
  6052. */
  6053. Matrix.ScalingToRef = function (x, y, z, result) {
  6054. result.m[0] = x;
  6055. result.m[1] = 0.0;
  6056. result.m[2] = 0.0;
  6057. result.m[3] = 0.0;
  6058. result.m[4] = 0.0;
  6059. result.m[5] = y;
  6060. result.m[6] = 0.0;
  6061. result.m[7] = 0.0;
  6062. result.m[8] = 0.0;
  6063. result.m[9] = 0.0;
  6064. result.m[10] = z;
  6065. result.m[11] = 0.0;
  6066. result.m[12] = 0.0;
  6067. result.m[13] = 0.0;
  6068. result.m[14] = 0.0;
  6069. result.m[15] = 1.0;
  6070. result._markAsUpdated();
  6071. };
  6072. /**
  6073. * Creates a translation matrix
  6074. * @param x defines the translation on X axis
  6075. * @param y defines the translation on Y axis
  6076. * @param z defines the translationon Z axis
  6077. * @returns the new matrix
  6078. */
  6079. Matrix.Translation = function (x, y, z) {
  6080. var result = Matrix.Identity();
  6081. Matrix.TranslationToRef(x, y, z, result);
  6082. return result;
  6083. };
  6084. /**
  6085. * Creates a translation matrix and stores it in a given matrix
  6086. * @param x defines the translation on X axis
  6087. * @param y defines the translation on Y axis
  6088. * @param z defines the translationon Z axis
  6089. * @param result defines the target matrix
  6090. */
  6091. Matrix.TranslationToRef = function (x, y, z, result) {
  6092. 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);
  6093. };
  6094. /**
  6095. * Returns a new Matrix whose values are the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6096. * @param startValue defines the start value
  6097. * @param endValue defines the end value
  6098. * @param gradient defines the gradient factor
  6099. * @returns the new matrix
  6100. */
  6101. Matrix.Lerp = function (startValue, endValue, gradient) {
  6102. var result = Matrix.Zero();
  6103. Matrix.LerpToRef(startValue, endValue, gradient, result);
  6104. return result;
  6105. };
  6106. /**
  6107. * Set the given matrix "result" as the interpolated values for "gradient" (float) between the ones of the matrices "startValue" and "endValue".
  6108. * @param startValue defines the start value
  6109. * @param endValue defines the end value
  6110. * @param gradient defines the gradient factor
  6111. * @param result defines the Matrix object where to store data
  6112. */
  6113. Matrix.LerpToRef = function (startValue, endValue, gradient, result) {
  6114. for (var index = 0; index < 16; index++) {
  6115. result.m[index] = startValue.m[index] * (1.0 - gradient) + endValue.m[index] * gradient;
  6116. }
  6117. result._markAsUpdated();
  6118. };
  6119. /**
  6120. * Builds a new matrix whose values are computed by:
  6121. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6122. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6123. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6124. * @param startValue defines the first matrix
  6125. * @param endValue defines the second matrix
  6126. * @param gradient defines the gradient between the two matrices
  6127. * @returns the new matrix
  6128. */
  6129. Matrix.DecomposeLerp = function (startValue, endValue, gradient) {
  6130. var result = Matrix.Zero();
  6131. Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  6132. return result;
  6133. };
  6134. /**
  6135. * Update a matrix to values which are computed by:
  6136. * * decomposing the the "startValue" and "endValue" matrices into their respective scale, rotation and translation matrices
  6137. * * interpolating for "gradient" (float) the values between each of these decomposed matrices between the start and the end
  6138. * * recomposing a new matrix from these 3 interpolated scale, rotation and translation matrices
  6139. * @param startValue defines the first matrix
  6140. * @param endValue defines the second matrix
  6141. * @param gradient defines the gradient between the two matrices
  6142. * @param result defines the target matrix
  6143. */
  6144. Matrix.DecomposeLerpToRef = function (startValue, endValue, gradient, result) {
  6145. var startScale = MathTmp.Vector3[0];
  6146. var startRotation = MathTmp.Quaternion[0];
  6147. var startTranslation = MathTmp.Vector3[1];
  6148. startValue.decompose(startScale, startRotation, startTranslation);
  6149. var endScale = MathTmp.Vector3[2];
  6150. var endRotation = MathTmp.Quaternion[1];
  6151. var endTranslation = MathTmp.Vector3[3];
  6152. endValue.decompose(endScale, endRotation, endTranslation);
  6153. var resultScale = MathTmp.Vector3[4];
  6154. Vector3.LerpToRef(startScale, endScale, gradient, resultScale);
  6155. var resultRotation = MathTmp.Quaternion[2];
  6156. Quaternion.SlerpToRef(startRotation, endRotation, gradient, resultRotation);
  6157. var resultTranslation = MathTmp.Vector3[5];
  6158. Vector3.LerpToRef(startTranslation, endTranslation, gradient, resultTranslation);
  6159. Matrix.ComposeToRef(resultScale, resultRotation, resultTranslation, result);
  6160. };
  6161. /**
  6162. * 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"
  6163. * This function works in left handed mode
  6164. * @param eye defines the final position of the entity
  6165. * @param target defines where the entity should look at
  6166. * @param up defines the up vector for the entity
  6167. * @returns the new matrix
  6168. */
  6169. Matrix.LookAtLH = function (eye, target, up) {
  6170. var result = Matrix.Zero();
  6171. Matrix.LookAtLHToRef(eye, target, up, result);
  6172. return result;
  6173. };
  6174. /**
  6175. * 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".
  6176. * This function works in left handed mode
  6177. * @param eye defines the final position of the entity
  6178. * @param target defines where the entity should look at
  6179. * @param up defines the up vector for the entity
  6180. * @param result defines the target matrix
  6181. */
  6182. Matrix.LookAtLHToRef = function (eye, target, up, result) {
  6183. // Z axis
  6184. target.subtractToRef(eye, this._zAxis);
  6185. this._zAxis.normalize();
  6186. // X axis
  6187. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6188. if (this._xAxis.lengthSquared() === 0) {
  6189. this._xAxis.x = 1.0;
  6190. }
  6191. else {
  6192. this._xAxis.normalize();
  6193. }
  6194. // Y axis
  6195. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6196. this._yAxis.normalize();
  6197. // Eye angles
  6198. var ex = -Vector3.Dot(this._xAxis, eye);
  6199. var ey = -Vector3.Dot(this._yAxis, eye);
  6200. var ez = -Vector3.Dot(this._zAxis, eye);
  6201. 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);
  6202. };
  6203. /**
  6204. * 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"
  6205. * This function works in right handed mode
  6206. * @param eye defines the final position of the entity
  6207. * @param target defines where the entity should look at
  6208. * @param up defines the up vector for the entity
  6209. * @returns the new matrix
  6210. */
  6211. Matrix.LookAtRH = function (eye, target, up) {
  6212. var result = Matrix.Zero();
  6213. Matrix.LookAtRHToRef(eye, target, up, result);
  6214. return result;
  6215. };
  6216. /**
  6217. * 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".
  6218. * This function works in right handed mode
  6219. * @param eye defines the final position of the entity
  6220. * @param target defines where the entity should look at
  6221. * @param up defines the up vector for the entity
  6222. * @param result defines the target matrix
  6223. */
  6224. Matrix.LookAtRHToRef = function (eye, target, up, result) {
  6225. // Z axis
  6226. eye.subtractToRef(target, this._zAxis);
  6227. this._zAxis.normalize();
  6228. // X axis
  6229. Vector3.CrossToRef(up, this._zAxis, this._xAxis);
  6230. if (this._xAxis.lengthSquared() === 0) {
  6231. this._xAxis.x = 1.0;
  6232. }
  6233. else {
  6234. this._xAxis.normalize();
  6235. }
  6236. // Y axis
  6237. Vector3.CrossToRef(this._zAxis, this._xAxis, this._yAxis);
  6238. this._yAxis.normalize();
  6239. // Eye angles
  6240. var ex = -Vector3.Dot(this._xAxis, eye);
  6241. var ey = -Vector3.Dot(this._yAxis, eye);
  6242. var ez = -Vector3.Dot(this._zAxis, eye);
  6243. 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);
  6244. };
  6245. /**
  6246. * Create a left-handed orthographic projection matrix
  6247. * @param width defines the viewport width
  6248. * @param height defines the viewport height
  6249. * @param znear defines the near clip plane
  6250. * @param zfar defines the far clip plane
  6251. * @returns a new matrix as a left-handed orthographic projection matrix
  6252. */
  6253. Matrix.OrthoLH = function (width, height, znear, zfar) {
  6254. var matrix = Matrix.Zero();
  6255. Matrix.OrthoLHToRef(width, height, znear, zfar, matrix);
  6256. return matrix;
  6257. };
  6258. /**
  6259. * Store a left-handed orthographic projection to a given matrix
  6260. * @param width defines the viewport width
  6261. * @param height defines the viewport height
  6262. * @param znear defines the near clip plane
  6263. * @param zfar defines the far clip plane
  6264. * @param result defines the target matrix
  6265. */
  6266. Matrix.OrthoLHToRef = function (width, height, znear, zfar, result) {
  6267. var n = znear;
  6268. var f = zfar;
  6269. var a = 2.0 / width;
  6270. var b = 2.0 / height;
  6271. var c = 2.0 / (f - n);
  6272. var d = -(f + n) / (f - n);
  6273. 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);
  6274. };
  6275. /**
  6276. * Create a left-handed orthographic projection matrix
  6277. * @param left defines the viewport left coordinate
  6278. * @param right defines the viewport right coordinate
  6279. * @param bottom defines the viewport bottom coordinate
  6280. * @param top defines the viewport top coordinate
  6281. * @param znear defines the near clip plane
  6282. * @param zfar defines the far clip plane
  6283. * @returns a new matrix as a left-handed orthographic projection matrix
  6284. */
  6285. Matrix.OrthoOffCenterLH = function (left, right, bottom, top, znear, zfar) {
  6286. var matrix = Matrix.Zero();
  6287. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, matrix);
  6288. return matrix;
  6289. };
  6290. /**
  6291. * Stores a left-handed orthographic projection into a given matrix
  6292. * @param left defines the viewport left coordinate
  6293. * @param right defines the viewport right coordinate
  6294. * @param bottom defines the viewport bottom coordinate
  6295. * @param top defines the viewport top coordinate
  6296. * @param znear defines the near clip plane
  6297. * @param zfar defines the far clip plane
  6298. * @param result defines the target matrix
  6299. */
  6300. Matrix.OrthoOffCenterLHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6301. var n = znear;
  6302. var f = zfar;
  6303. var a = 2.0 / (right - left);
  6304. var b = 2.0 / (top - bottom);
  6305. var c = 2.0 / (f - n);
  6306. var d = -(f + n) / (f - n);
  6307. var i0 = (left + right) / (left - right);
  6308. var i1 = (top + bottom) / (bottom - top);
  6309. 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);
  6310. };
  6311. /**
  6312. * Creates a right-handed orthographic projection matrix
  6313. * @param left defines the viewport left coordinate
  6314. * @param right defines the viewport right coordinate
  6315. * @param bottom defines the viewport bottom coordinate
  6316. * @param top defines the viewport top coordinate
  6317. * @param znear defines the near clip plane
  6318. * @param zfar defines the far clip plane
  6319. * @returns a new matrix as a right-handed orthographic projection matrix
  6320. */
  6321. Matrix.OrthoOffCenterRH = function (left, right, bottom, top, znear, zfar) {
  6322. var matrix = Matrix.Zero();
  6323. Matrix.OrthoOffCenterRHToRef(left, right, bottom, top, znear, zfar, matrix);
  6324. return matrix;
  6325. };
  6326. /**
  6327. * Stores a right-handed orthographic projection into a given matrix
  6328. * @param left defines the viewport left coordinate
  6329. * @param right defines the viewport right coordinate
  6330. * @param bottom defines the viewport bottom coordinate
  6331. * @param top defines the viewport top coordinate
  6332. * @param znear defines the near clip plane
  6333. * @param zfar defines the far clip plane
  6334. * @param result defines the target matrix
  6335. */
  6336. Matrix.OrthoOffCenterRHToRef = function (left, right, bottom, top, znear, zfar, result) {
  6337. Matrix.OrthoOffCenterLHToRef(left, right, bottom, top, znear, zfar, result);
  6338. result.m[10] *= -1.0;
  6339. };
  6340. /**
  6341. * Creates a left-handed perspective projection matrix
  6342. * @param width defines the viewport width
  6343. * @param height defines the viewport height
  6344. * @param znear defines the near clip plane
  6345. * @param zfar defines the far clip plane
  6346. * @returns a new matrix as a left-handed perspective projection matrix
  6347. */
  6348. Matrix.PerspectiveLH = function (width, height, znear, zfar) {
  6349. var matrix = Matrix.Zero();
  6350. var n = znear;
  6351. var f = zfar;
  6352. var a = 2.0 * n / width;
  6353. var b = 2.0 * n / height;
  6354. var c = (f + n) / (f - n);
  6355. var d = -2.0 * f * n / (f - n);
  6356. 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);
  6357. return matrix;
  6358. };
  6359. /**
  6360. * Creates a left-handed perspective projection matrix
  6361. * @param fov defines the horizontal field of view
  6362. * @param aspect defines the aspect ratio
  6363. * @param znear defines the near clip plane
  6364. * @param zfar defines the far clip plane
  6365. * @returns a new matrix as a left-handed perspective projection matrix
  6366. */
  6367. Matrix.PerspectiveFovLH = function (fov, aspect, znear, zfar) {
  6368. var matrix = Matrix.Zero();
  6369. Matrix.PerspectiveFovLHToRef(fov, aspect, znear, zfar, matrix);
  6370. return matrix;
  6371. };
  6372. /**
  6373. * Stores a left-handed perspective projection into a given matrix
  6374. * @param fov defines the horizontal field of view
  6375. * @param aspect defines the aspect ratio
  6376. * @param znear defines the near clip plane
  6377. * @param zfar defines the far clip plane
  6378. * @param result defines the target matrix
  6379. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6380. */
  6381. Matrix.PerspectiveFovLHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6382. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6383. var n = znear;
  6384. var f = zfar;
  6385. var t = 1.0 / (Math.tan(fov * 0.5));
  6386. var a = isVerticalFovFixed ? (t / aspect) : t;
  6387. var b = isVerticalFovFixed ? t : (t * aspect);
  6388. var c = (f + n) / (f - n);
  6389. var d = -2.0 * f * n / (f - n);
  6390. 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);
  6391. };
  6392. /**
  6393. * Creates a right-handed perspective projection matrix
  6394. * @param fov defines the horizontal field of view
  6395. * @param aspect defines the aspect ratio
  6396. * @param znear defines the near clip plane
  6397. * @param zfar defines the far clip plane
  6398. * @returns a new matrix as a right-handed perspective projection matrix
  6399. */
  6400. Matrix.PerspectiveFovRH = function (fov, aspect, znear, zfar) {
  6401. var matrix = Matrix.Zero();
  6402. Matrix.PerspectiveFovRHToRef(fov, aspect, znear, zfar, matrix);
  6403. return matrix;
  6404. };
  6405. /**
  6406. * Stores a right-handed perspective projection into a given matrix
  6407. * @param fov defines the horizontal field of view
  6408. * @param aspect defines the aspect ratio
  6409. * @param znear defines the near clip plane
  6410. * @param zfar defines the far clip plane
  6411. * @param result defines the target matrix
  6412. * @param isVerticalFovFixed defines it the fov is vertically fixed (default) or horizontally
  6413. */
  6414. Matrix.PerspectiveFovRHToRef = function (fov, aspect, znear, zfar, result, isVerticalFovFixed) {
  6415. //alternatively this could be expressed as:
  6416. // m = PerspectiveFovLHToRef
  6417. // m[10] *= -1.0;
  6418. // m[11] *= -1.0;
  6419. if (isVerticalFovFixed === void 0) { isVerticalFovFixed = true; }
  6420. var n = znear;
  6421. var f = zfar;
  6422. var t = 1.0 / (Math.tan(fov * 0.5));
  6423. var a = isVerticalFovFixed ? (t / aspect) : t;
  6424. var b = isVerticalFovFixed ? t : (t * aspect);
  6425. var c = -(f + n) / (f - n);
  6426. var d = -2 * f * n / (f - n);
  6427. 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);
  6428. };
  6429. /**
  6430. * Stores a perspective projection for WebVR info a given matrix
  6431. * @param fov defines the field of view
  6432. * @param znear defines the near clip plane
  6433. * @param zfar defines the far clip plane
  6434. * @param result defines the target matrix
  6435. * @param rightHanded defines if the matrix must be in right-handed mode (false by default)
  6436. */
  6437. Matrix.PerspectiveFovWebVRToRef = function (fov, znear, zfar, result, rightHanded) {
  6438. if (rightHanded === void 0) { rightHanded = false; }
  6439. var rightHandedFactor = rightHanded ? -1 : 1;
  6440. var upTan = Math.tan(fov.upDegrees * Math.PI / 180.0);
  6441. var downTan = Math.tan(fov.downDegrees * Math.PI / 180.0);
  6442. var leftTan = Math.tan(fov.leftDegrees * Math.PI / 180.0);
  6443. var rightTan = Math.tan(fov.rightDegrees * Math.PI / 180.0);
  6444. var xScale = 2.0 / (leftTan + rightTan);
  6445. var yScale = 2.0 / (upTan + downTan);
  6446. result.m[0] = xScale;
  6447. result.m[1] = result.m[2] = result.m[3] = result.m[4] = 0.0;
  6448. result.m[5] = yScale;
  6449. result.m[6] = result.m[7] = 0.0;
  6450. result.m[8] = ((leftTan - rightTan) * xScale * 0.5);
  6451. result.m[9] = -((upTan - downTan) * yScale * 0.5);
  6452. result.m[10] = -zfar / (znear - zfar);
  6453. result.m[11] = 1.0 * rightHandedFactor;
  6454. result.m[12] = result.m[13] = result.m[15] = 0.0;
  6455. result.m[14] = -(2.0 * zfar * znear) / (zfar - znear);
  6456. result._markAsUpdated();
  6457. };
  6458. /**
  6459. * Computes a complete transformation matrix
  6460. * @param viewport defines the viewport to use
  6461. * @param world defines the world matrix
  6462. * @param view defines the view matrix
  6463. * @param projection defines the projection matrix
  6464. * @param zmin defines the near clip plane
  6465. * @param zmax defines the far clip plane
  6466. * @returns the transformation matrix
  6467. */
  6468. Matrix.GetFinalMatrix = function (viewport, world, view, projection, zmin, zmax) {
  6469. var cw = viewport.width;
  6470. var ch = viewport.height;
  6471. var cx = viewport.x;
  6472. var cy = viewport.y;
  6473. 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);
  6474. return world.multiply(view).multiply(projection).multiply(viewportMatrix);
  6475. };
  6476. /**
  6477. * Extracts a 2x2 matrix from a given matrix and store the result in a Float32Array
  6478. * @param matrix defines the matrix to use
  6479. * @returns a new Float32Array array with 4 elements : the 2x2 matrix extracted from the given matrix
  6480. */
  6481. Matrix.GetAsMatrix2x2 = function (matrix) {
  6482. return new Float32Array([
  6483. matrix.m[0], matrix.m[1],
  6484. matrix.m[4], matrix.m[5]
  6485. ]);
  6486. };
  6487. /**
  6488. * Extracts a 3x3 matrix from a given matrix and store the result in a Float32Array
  6489. * @param matrix defines the matrix to use
  6490. * @returns a new Float32Array array with 9 elements : the 3x3 matrix extracted from the given matrix
  6491. */
  6492. Matrix.GetAsMatrix3x3 = function (matrix) {
  6493. return new Float32Array([
  6494. matrix.m[0], matrix.m[1], matrix.m[2],
  6495. matrix.m[4], matrix.m[5], matrix.m[6],
  6496. matrix.m[8], matrix.m[9], matrix.m[10]
  6497. ]);
  6498. };
  6499. /**
  6500. * Compute the transpose of a given matrix
  6501. * @param matrix defines the matrix to transpose
  6502. * @returns the new matrix
  6503. */
  6504. Matrix.Transpose = function (matrix) {
  6505. var result = new Matrix();
  6506. Matrix.TransposeToRef(matrix, result);
  6507. return result;
  6508. };
  6509. /**
  6510. * Compute the transpose of a matrix and store it in a target matrix
  6511. * @param matrix defines the matrix to transpose
  6512. * @param result defines the target matrix
  6513. */
  6514. Matrix.TransposeToRef = function (matrix, result) {
  6515. result.m[0] = matrix.m[0];
  6516. result.m[1] = matrix.m[4];
  6517. result.m[2] = matrix.m[8];
  6518. result.m[3] = matrix.m[12];
  6519. result.m[4] = matrix.m[1];
  6520. result.m[5] = matrix.m[5];
  6521. result.m[6] = matrix.m[9];
  6522. result.m[7] = matrix.m[13];
  6523. result.m[8] = matrix.m[2];
  6524. result.m[9] = matrix.m[6];
  6525. result.m[10] = matrix.m[10];
  6526. result.m[11] = matrix.m[14];
  6527. result.m[12] = matrix.m[3];
  6528. result.m[13] = matrix.m[7];
  6529. result.m[14] = matrix.m[11];
  6530. result.m[15] = matrix.m[15];
  6531. };
  6532. /**
  6533. * Computes a reflection matrix from a plane
  6534. * @param plane defines the reflection plane
  6535. * @returns a new matrix
  6536. */
  6537. Matrix.Reflection = function (plane) {
  6538. var matrix = new Matrix();
  6539. Matrix.ReflectionToRef(plane, matrix);
  6540. return matrix;
  6541. };
  6542. /**
  6543. * Computes a reflection matrix from a plane
  6544. * @param plane defines the reflection plane
  6545. * @param result defines the target matrix
  6546. */
  6547. Matrix.ReflectionToRef = function (plane, result) {
  6548. plane.normalize();
  6549. var x = plane.normal.x;
  6550. var y = plane.normal.y;
  6551. var z = plane.normal.z;
  6552. var temp = -2 * x;
  6553. var temp2 = -2 * y;
  6554. var temp3 = -2 * z;
  6555. result.m[0] = (temp * x) + 1;
  6556. result.m[1] = temp2 * x;
  6557. result.m[2] = temp3 * x;
  6558. result.m[3] = 0.0;
  6559. result.m[4] = temp * y;
  6560. result.m[5] = (temp2 * y) + 1;
  6561. result.m[6] = temp3 * y;
  6562. result.m[7] = 0.0;
  6563. result.m[8] = temp * z;
  6564. result.m[9] = temp2 * z;
  6565. result.m[10] = (temp3 * z) + 1;
  6566. result.m[11] = 0.0;
  6567. result.m[12] = temp * plane.d;
  6568. result.m[13] = temp2 * plane.d;
  6569. result.m[14] = temp3 * plane.d;
  6570. result.m[15] = 1.0;
  6571. result._markAsUpdated();
  6572. };
  6573. /**
  6574. * Sets the given matrix as a rotation matrix composed from the 3 left handed axes
  6575. * @param xaxis defines the value of the 1st axis
  6576. * @param yaxis defines the value of the 2nd axis
  6577. * @param zaxis defines the value of the 3rd axis
  6578. * @param result defines the target matrix
  6579. */
  6580. Matrix.FromXYZAxesToRef = function (xaxis, yaxis, zaxis, result) {
  6581. result.m[0] = xaxis.x;
  6582. result.m[1] = xaxis.y;
  6583. result.m[2] = xaxis.z;
  6584. result.m[3] = 0.0;
  6585. result.m[4] = yaxis.x;
  6586. result.m[5] = yaxis.y;
  6587. result.m[6] = yaxis.z;
  6588. result.m[7] = 0.0;
  6589. result.m[8] = zaxis.x;
  6590. result.m[9] = zaxis.y;
  6591. result.m[10] = zaxis.z;
  6592. result.m[11] = 0.0;
  6593. result.m[12] = 0.0;
  6594. result.m[13] = 0.0;
  6595. result.m[14] = 0.0;
  6596. result.m[15] = 1.0;
  6597. result._markAsUpdated();
  6598. };
  6599. /**
  6600. * Creates a rotation matrix from a quaternion and stores it in a target matrix
  6601. * @param quat defines the quaternion to use
  6602. * @param result defines the target matrix
  6603. */
  6604. Matrix.FromQuaternionToRef = function (quat, result) {
  6605. var xx = quat.x * quat.x;
  6606. var yy = quat.y * quat.y;
  6607. var zz = quat.z * quat.z;
  6608. var xy = quat.x * quat.y;
  6609. var zw = quat.z * quat.w;
  6610. var zx = quat.z * quat.x;
  6611. var yw = quat.y * quat.w;
  6612. var yz = quat.y * quat.z;
  6613. var xw = quat.x * quat.w;
  6614. result.m[0] = 1.0 - (2.0 * (yy + zz));
  6615. result.m[1] = 2.0 * (xy + zw);
  6616. result.m[2] = 2.0 * (zx - yw);
  6617. result.m[3] = 0.0;
  6618. result.m[4] = 2.0 * (xy - zw);
  6619. result.m[5] = 1.0 - (2.0 * (zz + xx));
  6620. result.m[6] = 2.0 * (yz + xw);
  6621. result.m[7] = 0.0;
  6622. result.m[8] = 2.0 * (zx + yw);
  6623. result.m[9] = 2.0 * (yz - xw);
  6624. result.m[10] = 1.0 - (2.0 * (yy + xx));
  6625. result.m[11] = 0.0;
  6626. result.m[12] = 0.0;
  6627. result.m[13] = 0.0;
  6628. result.m[14] = 0.0;
  6629. result.m[15] = 1.0;
  6630. result._markAsUpdated();
  6631. };
  6632. Matrix._tempQuaternion = new Quaternion();
  6633. Matrix._xAxis = Vector3.Zero();
  6634. Matrix._yAxis = Vector3.Zero();
  6635. Matrix._zAxis = Vector3.Zero();
  6636. Matrix._updateFlagSeed = 0;
  6637. Matrix._identityReadOnly = Matrix.Identity();
  6638. return Matrix;
  6639. }());
  6640. BABYLON.Matrix = Matrix;
  6641. var Plane = /** @class */ (function () {
  6642. /**
  6643. * Creates a Plane object according to the given floats a, b, c, d and the plane equation : ax + by + cz + d = 0
  6644. */
  6645. function Plane(a, b, c, d) {
  6646. this.normal = new Vector3(a, b, c);
  6647. this.d = d;
  6648. }
  6649. /**
  6650. * Returns the plane coordinates as a new array of 4 elements [a, b, c, d].
  6651. */
  6652. Plane.prototype.asArray = function () {
  6653. return [this.normal.x, this.normal.y, this.normal.z, this.d];
  6654. };
  6655. // Methods
  6656. /**
  6657. * Returns a new plane copied from the current Plane.
  6658. */
  6659. Plane.prototype.clone = function () {
  6660. return new Plane(this.normal.x, this.normal.y, this.normal.z, this.d);
  6661. };
  6662. /**
  6663. * Returns the string "Plane".
  6664. */
  6665. Plane.prototype.getClassName = function () {
  6666. return "Plane";
  6667. };
  6668. /**
  6669. * Returns the Plane hash code.
  6670. */
  6671. Plane.prototype.getHashCode = function () {
  6672. var hash = this.normal.getHashCode();
  6673. hash = (hash * 397) ^ (this.d || 0);
  6674. return hash;
  6675. };
  6676. /**
  6677. * Normalize the current Plane in place.
  6678. * Returns the updated Plane.
  6679. */
  6680. Plane.prototype.normalize = function () {
  6681. var norm = (Math.sqrt((this.normal.x * this.normal.x) + (this.normal.y * this.normal.y) + (this.normal.z * this.normal.z)));
  6682. var magnitude = 0.0;
  6683. if (norm !== 0) {
  6684. magnitude = 1.0 / norm;
  6685. }
  6686. this.normal.x *= magnitude;
  6687. this.normal.y *= magnitude;
  6688. this.normal.z *= magnitude;
  6689. this.d *= magnitude;
  6690. return this;
  6691. };
  6692. /**
  6693. * Returns a new Plane as the result of the transformation of the current Plane by the given matrix.
  6694. */
  6695. Plane.prototype.transform = function (transformation) {
  6696. var transposedMatrix = Matrix.Transpose(transformation);
  6697. var x = this.normal.x;
  6698. var y = this.normal.y;
  6699. var z = this.normal.z;
  6700. var d = this.d;
  6701. var normalX = (((x * transposedMatrix.m[0]) + (y * transposedMatrix.m[1])) + (z * transposedMatrix.m[2])) + (d * transposedMatrix.m[3]);
  6702. var normalY = (((x * transposedMatrix.m[4]) + (y * transposedMatrix.m[5])) + (z * transposedMatrix.m[6])) + (d * transposedMatrix.m[7]);
  6703. var normalZ = (((x * transposedMatrix.m[8]) + (y * transposedMatrix.m[9])) + (z * transposedMatrix.m[10])) + (d * transposedMatrix.m[11]);
  6704. var finalD = (((x * transposedMatrix.m[12]) + (y * transposedMatrix.m[13])) + (z * transposedMatrix.m[14])) + (d * transposedMatrix.m[15]);
  6705. return new Plane(normalX, normalY, normalZ, finalD);
  6706. };
  6707. /**
  6708. * Returns the dot product (float) of the point coordinates and the plane normal.
  6709. */
  6710. Plane.prototype.dotCoordinate = function (point) {
  6711. return ((((this.normal.x * point.x) + (this.normal.y * point.y)) + (this.normal.z * point.z)) + this.d);
  6712. };
  6713. /**
  6714. * Updates the current Plane from the plane defined by the three given points.
  6715. * Returns the updated Plane.
  6716. */
  6717. Plane.prototype.copyFromPoints = function (point1, point2, point3) {
  6718. var x1 = point2.x - point1.x;
  6719. var y1 = point2.y - point1.y;
  6720. var z1 = point2.z - point1.z;
  6721. var x2 = point3.x - point1.x;
  6722. var y2 = point3.y - point1.y;
  6723. var z2 = point3.z - point1.z;
  6724. var yz = (y1 * z2) - (z1 * y2);
  6725. var xz = (z1 * x2) - (x1 * z2);
  6726. var xy = (x1 * y2) - (y1 * x2);
  6727. var pyth = (Math.sqrt((yz * yz) + (xz * xz) + (xy * xy)));
  6728. var invPyth;
  6729. if (pyth !== 0) {
  6730. invPyth = 1.0 / pyth;
  6731. }
  6732. else {
  6733. invPyth = 0.0;
  6734. }
  6735. this.normal.x = yz * invPyth;
  6736. this.normal.y = xz * invPyth;
  6737. this.normal.z = xy * invPyth;
  6738. this.d = -((this.normal.x * point1.x) + (this.normal.y * point1.y) + (this.normal.z * point1.z));
  6739. return this;
  6740. };
  6741. /**
  6742. * Boolean : True is the vector "direction" is the same side than the plane normal.
  6743. */
  6744. Plane.prototype.isFrontFacingTo = function (direction, epsilon) {
  6745. var dot = Vector3.Dot(this.normal, direction);
  6746. return (dot <= epsilon);
  6747. };
  6748. /**
  6749. * Returns the signed distance (float) from the given point to the Plane.
  6750. */
  6751. Plane.prototype.signedDistanceTo = function (point) {
  6752. return Vector3.Dot(point, this.normal) + this.d;
  6753. };
  6754. // Statics
  6755. /**
  6756. * Returns a new Plane from the given array.
  6757. */
  6758. Plane.FromArray = function (array) {
  6759. return new Plane(array[0], array[1], array[2], array[3]);
  6760. };
  6761. /**
  6762. * Returns a new Plane defined by the three given points.
  6763. */
  6764. Plane.FromPoints = function (point1, point2, point3) {
  6765. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6766. result.copyFromPoints(point1, point2, point3);
  6767. return result;
  6768. };
  6769. /**
  6770. * Returns a new Plane the normal vector to this plane at the given origin point.
  6771. * Note : the vector "normal" is updated because normalized.
  6772. */
  6773. Plane.FromPositionAndNormal = function (origin, normal) {
  6774. var result = new Plane(0.0, 0.0, 0.0, 0.0);
  6775. normal.normalize();
  6776. result.normal = normal;
  6777. result.d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6778. return result;
  6779. };
  6780. /**
  6781. * Returns the signed distance between the plane defined by the normal vector at the "origin"" point and the given other point.
  6782. */
  6783. Plane.SignedDistanceToPlaneFromPositionAndNormal = function (origin, normal, point) {
  6784. var d = -(normal.x * origin.x + normal.y * origin.y + normal.z * origin.z);
  6785. return Vector3.Dot(point, normal) + d;
  6786. };
  6787. return Plane;
  6788. }());
  6789. BABYLON.Plane = Plane;
  6790. var Viewport = /** @class */ (function () {
  6791. /**
  6792. * Creates a Viewport object located at (x, y) and sized (width, height).
  6793. */
  6794. function Viewport(x, y, width, height) {
  6795. this.x = x;
  6796. this.y = y;
  6797. this.width = width;
  6798. this.height = height;
  6799. }
  6800. Viewport.prototype.toGlobal = function (renderWidthOrEngine, renderHeight) {
  6801. if (renderWidthOrEngine.getRenderWidth) {
  6802. var engine = renderWidthOrEngine;
  6803. return this.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  6804. }
  6805. var renderWidth = renderWidthOrEngine;
  6806. return new Viewport(this.x * renderWidth, this.y * renderHeight, this.width * renderWidth, this.height * renderHeight);
  6807. };
  6808. /**
  6809. * Returns a new Viewport copied from the current one.
  6810. */
  6811. Viewport.prototype.clone = function () {
  6812. return new Viewport(this.x, this.y, this.width, this.height);
  6813. };
  6814. return Viewport;
  6815. }());
  6816. BABYLON.Viewport = Viewport;
  6817. var Frustum = /** @class */ (function () {
  6818. function Frustum() {
  6819. }
  6820. /**
  6821. * Returns a new array of 6 Frustum planes computed by the given transformation matrix.
  6822. */
  6823. Frustum.GetPlanes = function (transform) {
  6824. var frustumPlanes = [];
  6825. for (var index = 0; index < 6; index++) {
  6826. frustumPlanes.push(new Plane(0.0, 0.0, 0.0, 0.0));
  6827. }
  6828. Frustum.GetPlanesToRef(transform, frustumPlanes);
  6829. return frustumPlanes;
  6830. };
  6831. Frustum.GetNearPlaneToRef = function (transform, frustumPlane) {
  6832. frustumPlane.normal.x = transform.m[3] + transform.m[2];
  6833. frustumPlane.normal.y = transform.m[7] + transform.m[6];
  6834. frustumPlane.normal.z = transform.m[11] + transform.m[10];
  6835. frustumPlane.d = transform.m[15] + transform.m[14];
  6836. frustumPlane.normalize();
  6837. };
  6838. Frustum.GetFarPlaneToRef = function (transform, frustumPlane) {
  6839. frustumPlane.normal.x = transform.m[3] - transform.m[2];
  6840. frustumPlane.normal.y = transform.m[7] - transform.m[6];
  6841. frustumPlane.normal.z = transform.m[11] - transform.m[10];
  6842. frustumPlane.d = transform.m[15] - transform.m[14];
  6843. frustumPlane.normalize();
  6844. };
  6845. Frustum.GetLeftPlaneToRef = function (transform, frustumPlane) {
  6846. frustumPlane.normal.x = transform.m[3] + transform.m[0];
  6847. frustumPlane.normal.y = transform.m[7] + transform.m[4];
  6848. frustumPlane.normal.z = transform.m[11] + transform.m[8];
  6849. frustumPlane.d = transform.m[15] + transform.m[12];
  6850. frustumPlane.normalize();
  6851. };
  6852. Frustum.GetRightPlaneToRef = function (transform, frustumPlane) {
  6853. frustumPlane.normal.x = transform.m[3] - transform.m[0];
  6854. frustumPlane.normal.y = transform.m[7] - transform.m[4];
  6855. frustumPlane.normal.z = transform.m[11] - transform.m[8];
  6856. frustumPlane.d = transform.m[15] - transform.m[12];
  6857. frustumPlane.normalize();
  6858. };
  6859. Frustum.GetTopPlaneToRef = function (transform, frustumPlane) {
  6860. frustumPlane.normal.x = transform.m[3] - transform.m[1];
  6861. frustumPlane.normal.y = transform.m[7] - transform.m[5];
  6862. frustumPlane.normal.z = transform.m[11] - transform.m[9];
  6863. frustumPlane.d = transform.m[15] - transform.m[13];
  6864. frustumPlane.normalize();
  6865. };
  6866. Frustum.GetBottomPlaneToRef = function (transform, frustumPlane) {
  6867. frustumPlane.normal.x = transform.m[3] + transform.m[1];
  6868. frustumPlane.normal.y = transform.m[7] + transform.m[5];
  6869. frustumPlane.normal.z = transform.m[11] + transform.m[9];
  6870. frustumPlane.d = transform.m[15] + transform.m[13];
  6871. frustumPlane.normalize();
  6872. };
  6873. /**
  6874. * Sets the given array "frustumPlanes" with the 6 Frustum planes computed by the given transformation matrix.
  6875. */
  6876. Frustum.GetPlanesToRef = function (transform, frustumPlanes) {
  6877. // Near
  6878. Frustum.GetNearPlaneToRef(transform, frustumPlanes[0]);
  6879. // Far
  6880. Frustum.GetFarPlaneToRef(transform, frustumPlanes[1]);
  6881. // Left
  6882. Frustum.GetLeftPlaneToRef(transform, frustumPlanes[2]);
  6883. // Right
  6884. Frustum.GetRightPlaneToRef(transform, frustumPlanes[3]);
  6885. // Top
  6886. Frustum.GetTopPlaneToRef(transform, frustumPlanes[4]);
  6887. // Bottom
  6888. Frustum.GetBottomPlaneToRef(transform, frustumPlanes[5]);
  6889. };
  6890. return Frustum;
  6891. }());
  6892. BABYLON.Frustum = Frustum;
  6893. /** Defines supported spaces */
  6894. var Space;
  6895. (function (Space) {
  6896. /** Local (object) space */
  6897. Space[Space["LOCAL"] = 0] = "LOCAL";
  6898. /** World space */
  6899. Space[Space["WORLD"] = 1] = "WORLD";
  6900. /** Bone space */
  6901. Space[Space["BONE"] = 2] = "BONE";
  6902. })(Space = BABYLON.Space || (BABYLON.Space = {}));
  6903. /** Defines the 3 main axes */
  6904. var Axis = /** @class */ (function () {
  6905. function Axis() {
  6906. }
  6907. /** X axis */
  6908. Axis.X = new Vector3(1.0, 0.0, 0.0);
  6909. /** Y axis */
  6910. Axis.Y = new Vector3(0.0, 1.0, 0.0);
  6911. /** Z axis */
  6912. Axis.Z = new Vector3(0.0, 0.0, 1.0);
  6913. return Axis;
  6914. }());
  6915. BABYLON.Axis = Axis;
  6916. ;
  6917. var BezierCurve = /** @class */ (function () {
  6918. function BezierCurve() {
  6919. }
  6920. /**
  6921. * Returns the cubic Bezier interpolated value (float) at "t" (float) from the given x1, y1, x2, y2 floats.
  6922. */
  6923. BezierCurve.interpolate = function (t, x1, y1, x2, y2) {
  6924. // Extract X (which is equal to time here)
  6925. var f0 = 1 - 3 * x2 + 3 * x1;
  6926. var f1 = 3 * x2 - 6 * x1;
  6927. var f2 = 3 * x1;
  6928. var refinedT = t;
  6929. for (var i = 0; i < 5; i++) {
  6930. var refinedT2 = refinedT * refinedT;
  6931. var refinedT3 = refinedT2 * refinedT;
  6932. var x = f0 * refinedT3 + f1 * refinedT2 + f2 * refinedT;
  6933. var slope = 1.0 / (3.0 * f0 * refinedT2 + 2.0 * f1 * refinedT + f2);
  6934. refinedT -= (x - t) * slope;
  6935. refinedT = Math.min(1, Math.max(0, refinedT));
  6936. }
  6937. // Resolve cubic bezier for the given x
  6938. return 3 * Math.pow(1 - refinedT, 2) * refinedT * y1 +
  6939. 3 * (1 - refinedT) * Math.pow(refinedT, 2) * y2 +
  6940. Math.pow(refinedT, 3);
  6941. };
  6942. return BezierCurve;
  6943. }());
  6944. BABYLON.BezierCurve = BezierCurve;
  6945. /**
  6946. * Defines potential orientation for back face culling
  6947. */
  6948. var Orientation;
  6949. (function (Orientation) {
  6950. /**
  6951. * Clockwise
  6952. */
  6953. Orientation[Orientation["CW"] = 0] = "CW";
  6954. /** Counter clockwise */
  6955. Orientation[Orientation["CCW"] = 1] = "CCW";
  6956. })(Orientation = BABYLON.Orientation || (BABYLON.Orientation = {}));
  6957. /**
  6958. * Defines angle representation
  6959. */
  6960. var Angle = /** @class */ (function () {
  6961. /**
  6962. * Creates an Angle object of "radians" radians (float).
  6963. */
  6964. function Angle(radians) {
  6965. this._radians = radians;
  6966. if (this._radians < 0.0)
  6967. this._radians += (2.0 * Math.PI);
  6968. }
  6969. /**
  6970. * Get value in degrees
  6971. * @returns the Angle value in degrees (float)
  6972. */
  6973. Angle.prototype.degrees = function () {
  6974. return this._radians * 180.0 / Math.PI;
  6975. };
  6976. /**
  6977. * Get value in radians
  6978. * @returns the Angle value in radians (float)
  6979. */
  6980. Angle.prototype.radians = function () {
  6981. return this._radians;
  6982. };
  6983. /**
  6984. * Gets a new Angle object valued with the angle value in radians between the two given vectors
  6985. * @param a defines first vector
  6986. * @param b defines second vector
  6987. * @returns a new Angle
  6988. */
  6989. Angle.BetweenTwoPoints = function (a, b) {
  6990. var delta = b.subtract(a);
  6991. var theta = Math.atan2(delta.y, delta.x);
  6992. return new Angle(theta);
  6993. };
  6994. /**
  6995. * Gets a new Angle object from the given float in radians
  6996. * @param radians defines the angle value in radians
  6997. * @returns a new Angle
  6998. */
  6999. Angle.FromRadians = function (radians) {
  7000. return new Angle(radians);
  7001. };
  7002. /**
  7003. * Gets a new Angle object from the given float in degrees
  7004. * @param degrees defines the angle value in degrees
  7005. * @returns a new Angle
  7006. */
  7007. Angle.FromDegrees = function (degrees) {
  7008. return new Angle(degrees * Math.PI / 180.0);
  7009. };
  7010. return Angle;
  7011. }());
  7012. BABYLON.Angle = Angle;
  7013. var Arc2 = /** @class */ (function () {
  7014. /**
  7015. * Creates an Arc object from the three given points : start, middle and end.
  7016. */
  7017. function Arc2(startPoint, midPoint, endPoint) {
  7018. this.startPoint = startPoint;
  7019. this.midPoint = midPoint;
  7020. this.endPoint = endPoint;
  7021. var temp = Math.pow(midPoint.x, 2) + Math.pow(midPoint.y, 2);
  7022. var startToMid = (Math.pow(startPoint.x, 2) + Math.pow(startPoint.y, 2) - temp) / 2.;
  7023. var midToEnd = (temp - Math.pow(endPoint.x, 2) - Math.pow(endPoint.y, 2)) / 2.;
  7024. var det = (startPoint.x - midPoint.x) * (midPoint.y - endPoint.y) - (midPoint.x - endPoint.x) * (startPoint.y - midPoint.y);
  7025. 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);
  7026. this.radius = this.centerPoint.subtract(this.startPoint).length();
  7027. this.startAngle = Angle.BetweenTwoPoints(this.centerPoint, this.startPoint);
  7028. var a1 = this.startAngle.degrees();
  7029. var a2 = Angle.BetweenTwoPoints(this.centerPoint, this.midPoint).degrees();
  7030. var a3 = Angle.BetweenTwoPoints(this.centerPoint, this.endPoint).degrees();
  7031. // angles correction
  7032. if (a2 - a1 > +180.0)
  7033. a2 -= 360.0;
  7034. if (a2 - a1 < -180.0)
  7035. a2 += 360.0;
  7036. if (a3 - a2 > +180.0)
  7037. a3 -= 360.0;
  7038. if (a3 - a2 < -180.0)
  7039. a3 += 360.0;
  7040. this.orientation = (a2 - a1) < 0 ? Orientation.CW : Orientation.CCW;
  7041. this.angle = Angle.FromDegrees(this.orientation === Orientation.CW ? a1 - a3 : a3 - a1);
  7042. }
  7043. return Arc2;
  7044. }());
  7045. BABYLON.Arc2 = Arc2;
  7046. var Path2 = /** @class */ (function () {
  7047. /**
  7048. * Creates a Path2 object from the starting 2D coordinates x and y.
  7049. */
  7050. function Path2(x, y) {
  7051. this._points = new Array();
  7052. this._length = 0.0;
  7053. this.closed = false;
  7054. this._points.push(new Vector2(x, y));
  7055. }
  7056. /**
  7057. * Adds a new segment until the given coordinates (x, y) to the current Path2.
  7058. * Returns the updated Path2.
  7059. */
  7060. Path2.prototype.addLineTo = function (x, y) {
  7061. if (this.closed) {
  7062. return this;
  7063. }
  7064. var newPoint = new Vector2(x, y);
  7065. var previousPoint = this._points[this._points.length - 1];
  7066. this._points.push(newPoint);
  7067. this._length += newPoint.subtract(previousPoint).length();
  7068. return this;
  7069. };
  7070. /**
  7071. * 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.
  7072. * Returns the updated Path2.
  7073. */
  7074. Path2.prototype.addArcTo = function (midX, midY, endX, endY, numberOfSegments) {
  7075. if (numberOfSegments === void 0) { numberOfSegments = 36; }
  7076. if (this.closed) {
  7077. return this;
  7078. }
  7079. var startPoint = this._points[this._points.length - 1];
  7080. var midPoint = new Vector2(midX, midY);
  7081. var endPoint = new Vector2(endX, endY);
  7082. var arc = new Arc2(startPoint, midPoint, endPoint);
  7083. var increment = arc.angle.radians() / numberOfSegments;
  7084. if (arc.orientation === Orientation.CW)
  7085. increment *= -1;
  7086. var currentAngle = arc.startAngle.radians() + increment;
  7087. for (var i = 0; i < numberOfSegments; i++) {
  7088. var x = Math.cos(currentAngle) * arc.radius + arc.centerPoint.x;
  7089. var y = Math.sin(currentAngle) * arc.radius + arc.centerPoint.y;
  7090. this.addLineTo(x, y);
  7091. currentAngle += increment;
  7092. }
  7093. return this;
  7094. };
  7095. /**
  7096. * Closes the Path2.
  7097. * Returns the Path2.
  7098. */
  7099. Path2.prototype.close = function () {
  7100. this.closed = true;
  7101. return this;
  7102. };
  7103. /**
  7104. * Returns the Path2 total length (float).
  7105. */
  7106. Path2.prototype.length = function () {
  7107. var result = this._length;
  7108. if (!this.closed) {
  7109. var lastPoint = this._points[this._points.length - 1];
  7110. var firstPoint = this._points[0];
  7111. result += (firstPoint.subtract(lastPoint).length());
  7112. }
  7113. return result;
  7114. };
  7115. /**
  7116. * Returns the Path2 internal array of points.
  7117. */
  7118. Path2.prototype.getPoints = function () {
  7119. return this._points;
  7120. };
  7121. /**
  7122. * Returns a new Vector2 located at a percentage of the Path2 total length on this path.
  7123. */
  7124. Path2.prototype.getPointAtLengthPosition = function (normalizedLengthPosition) {
  7125. if (normalizedLengthPosition < 0 || normalizedLengthPosition > 1) {
  7126. return Vector2.Zero();
  7127. }
  7128. var lengthPosition = normalizedLengthPosition * this.length();
  7129. var previousOffset = 0;
  7130. for (var i = 0; i < this._points.length; i++) {
  7131. var j = (i + 1) % this._points.length;
  7132. var a = this._points[i];
  7133. var b = this._points[j];
  7134. var bToA = b.subtract(a);
  7135. var nextOffset = (bToA.length() + previousOffset);
  7136. if (lengthPosition >= previousOffset && lengthPosition <= nextOffset) {
  7137. var dir = bToA.normalize();
  7138. var localOffset = lengthPosition - previousOffset;
  7139. return new Vector2(a.x + (dir.x * localOffset), a.y + (dir.y * localOffset));
  7140. }
  7141. previousOffset = nextOffset;
  7142. }
  7143. return Vector2.Zero();
  7144. };
  7145. /**
  7146. * Returns a new Path2 starting at the coordinates (x, y).
  7147. */
  7148. Path2.StartingAt = function (x, y) {
  7149. return new Path2(x, y);
  7150. };
  7151. return Path2;
  7152. }());
  7153. BABYLON.Path2 = Path2;
  7154. var Path3D = /** @class */ (function () {
  7155. /**
  7156. * new Path3D(path, normal, raw)
  7157. * Creates a Path3D. A Path3D is a logical math object, so not a mesh.
  7158. * please read the description in the tutorial : http://doc.babylonjs.com/tutorials/How_to_use_Path3D
  7159. * path : an array of Vector3, the curve axis of the Path3D
  7160. * normal (optional) : Vector3, the first wanted normal to the curve. Ex (0, 1, 0) for a vertical normal.
  7161. * raw (optional, default false) : boolean, if true the returned Path3D isn't normalized. Useful to depict path acceleration or speed.
  7162. */
  7163. function Path3D(path, firstNormal, raw) {
  7164. if (firstNormal === void 0) { firstNormal = null; }
  7165. this.path = path;
  7166. this._curve = new Array();
  7167. this._distances = new Array();
  7168. this._tangents = new Array();
  7169. this._normals = new Array();
  7170. this._binormals = new Array();
  7171. for (var p = 0; p < path.length; p++) {
  7172. this._curve[p] = path[p].clone(); // hard copy
  7173. }
  7174. this._raw = raw || false;
  7175. this._compute(firstNormal);
  7176. }
  7177. /**
  7178. * Returns the Path3D array of successive Vector3 designing its curve.
  7179. */
  7180. Path3D.prototype.getCurve = function () {
  7181. return this._curve;
  7182. };
  7183. /**
  7184. * Returns an array populated with tangent vectors on each Path3D curve point.
  7185. */
  7186. Path3D.prototype.getTangents = function () {
  7187. return this._tangents;
  7188. };
  7189. /**
  7190. * Returns an array populated with normal vectors on each Path3D curve point.
  7191. */
  7192. Path3D.prototype.getNormals = function () {
  7193. return this._normals;
  7194. };
  7195. /**
  7196. * Returns an array populated with binormal vectors on each Path3D curve point.
  7197. */
  7198. Path3D.prototype.getBinormals = function () {
  7199. return this._binormals;
  7200. };
  7201. /**
  7202. * Returns an array populated with distances (float) of the i-th point from the first curve point.
  7203. */
  7204. Path3D.prototype.getDistances = function () {
  7205. return this._distances;
  7206. };
  7207. /**
  7208. * Forces the Path3D tangent, normal, binormal and distance recomputation.
  7209. * Returns the same object updated.
  7210. */
  7211. Path3D.prototype.update = function (path, firstNormal) {
  7212. if (firstNormal === void 0) { firstNormal = null; }
  7213. for (var p = 0; p < path.length; p++) {
  7214. this._curve[p].x = path[p].x;
  7215. this._curve[p].y = path[p].y;
  7216. this._curve[p].z = path[p].z;
  7217. }
  7218. this._compute(firstNormal);
  7219. return this;
  7220. };
  7221. // private function compute() : computes tangents, normals and binormals
  7222. Path3D.prototype._compute = function (firstNormal) {
  7223. var l = this._curve.length;
  7224. // first and last tangents
  7225. this._tangents[0] = this._getFirstNonNullVector(0);
  7226. if (!this._raw) {
  7227. this._tangents[0].normalize();
  7228. }
  7229. this._tangents[l - 1] = this._curve[l - 1].subtract(this._curve[l - 2]);
  7230. if (!this._raw) {
  7231. this._tangents[l - 1].normalize();
  7232. }
  7233. // normals and binormals at first point : arbitrary vector with _normalVector()
  7234. var tg0 = this._tangents[0];
  7235. var pp0 = this._normalVector(this._curve[0], tg0, firstNormal);
  7236. this._normals[0] = pp0;
  7237. if (!this._raw) {
  7238. this._normals[0].normalize();
  7239. }
  7240. this._binormals[0] = Vector3.Cross(tg0, this._normals[0]);
  7241. if (!this._raw) {
  7242. this._binormals[0].normalize();
  7243. }
  7244. this._distances[0] = 0.0;
  7245. // normals and binormals : next points
  7246. var prev; // previous vector (segment)
  7247. var cur; // current vector (segment)
  7248. var curTang; // current tangent
  7249. // previous normal
  7250. var prevBinor; // previous binormal
  7251. for (var i = 1; i < l; i++) {
  7252. // tangents
  7253. prev = this._getLastNonNullVector(i);
  7254. if (i < l - 1) {
  7255. cur = this._getFirstNonNullVector(i);
  7256. this._tangents[i] = prev.add(cur);
  7257. this._tangents[i].normalize();
  7258. }
  7259. this._distances[i] = this._distances[i - 1] + prev.length();
  7260. // normals and binormals
  7261. // http://www.cs.cmu.edu/afs/andrew/scs/cs/15-462/web/old/asst2camera.html
  7262. curTang = this._tangents[i];
  7263. prevBinor = this._binormals[i - 1];
  7264. this._normals[i] = Vector3.Cross(prevBinor, curTang);
  7265. if (!this._raw) {
  7266. this._normals[i].normalize();
  7267. }
  7268. this._binormals[i] = Vector3.Cross(curTang, this._normals[i]);
  7269. if (!this._raw) {
  7270. this._binormals[i].normalize();
  7271. }
  7272. }
  7273. };
  7274. // private function getFirstNonNullVector(index)
  7275. // returns the first non null vector from index : curve[index + N].subtract(curve[index])
  7276. Path3D.prototype._getFirstNonNullVector = function (index) {
  7277. var i = 1;
  7278. var nNVector = this._curve[index + i].subtract(this._curve[index]);
  7279. while (nNVector.length() === 0 && index + i + 1 < this._curve.length) {
  7280. i++;
  7281. nNVector = this._curve[index + i].subtract(this._curve[index]);
  7282. }
  7283. return nNVector;
  7284. };
  7285. // private function getLastNonNullVector(index)
  7286. // returns the last non null vector from index : curve[index].subtract(curve[index - N])
  7287. Path3D.prototype._getLastNonNullVector = function (index) {
  7288. var i = 1;
  7289. var nLVector = this._curve[index].subtract(this._curve[index - i]);
  7290. while (nLVector.length() === 0 && index > i + 1) {
  7291. i++;
  7292. nLVector = this._curve[index].subtract(this._curve[index - i]);
  7293. }
  7294. return nLVector;
  7295. };
  7296. // private function normalVector(v0, vt, va) :
  7297. // returns an arbitrary point in the plane defined by the point v0 and the vector vt orthogonal to this plane
  7298. // if va is passed, it returns the va projection on the plane orthogonal to vt at the point v0
  7299. Path3D.prototype._normalVector = function (v0, vt, va) {
  7300. var normal0;
  7301. var tgl = vt.length();
  7302. if (tgl === 0.0) {
  7303. tgl = 1.0;
  7304. }
  7305. if (va === undefined || va === null) {
  7306. var point;
  7307. if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.y) / tgl, 1.0, BABYLON.Epsilon)) { // search for a point in the plane
  7308. point = new Vector3(0.0, -1.0, 0.0);
  7309. }
  7310. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.x) / tgl, 1.0, BABYLON.Epsilon)) {
  7311. point = new Vector3(1.0, 0.0, 0.0);
  7312. }
  7313. else if (!BABYLON.Scalar.WithinEpsilon(Math.abs(vt.z) / tgl, 1.0, BABYLON.Epsilon)) {
  7314. point = new Vector3(0.0, 0.0, 1.0);
  7315. }
  7316. else {
  7317. point = Vector3.Zero();
  7318. }
  7319. normal0 = Vector3.Cross(vt, point);
  7320. }
  7321. else {
  7322. normal0 = Vector3.Cross(vt, va);
  7323. Vector3.CrossToRef(normal0, vt, normal0);
  7324. }
  7325. normal0.normalize();
  7326. return normal0;
  7327. };
  7328. return Path3D;
  7329. }());
  7330. BABYLON.Path3D = Path3D;
  7331. var Curve3 = /** @class */ (function () {
  7332. /**
  7333. * A Curve3 object is a logical object, so not a mesh, to handle curves in the 3D geometric space.
  7334. * A Curve3 is designed from a series of successive Vector3.
  7335. * Tuto : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#curve3-object
  7336. */
  7337. function Curve3(points) {
  7338. this._length = 0.0;
  7339. this._points = points;
  7340. this._length = this._computeLength(points);
  7341. }
  7342. /**
  7343. * Returns a Curve3 object along a Quadratic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#quadratic-bezier-curve
  7344. * @param v0 (Vector3) the origin point of the Quadratic Bezier
  7345. * @param v1 (Vector3) the control point
  7346. * @param v2 (Vector3) the end point of the Quadratic Bezier
  7347. * @param nbPoints (integer) the wanted number of points in the curve
  7348. */
  7349. Curve3.CreateQuadraticBezier = function (v0, v1, v2, nbPoints) {
  7350. nbPoints = nbPoints > 2 ? nbPoints : 3;
  7351. var bez = new Array();
  7352. var equation = function (t, val0, val1, val2) {
  7353. var res = (1.0 - t) * (1.0 - t) * val0 + 2.0 * t * (1.0 - t) * val1 + t * t * val2;
  7354. return res;
  7355. };
  7356. for (var i = 0; i <= nbPoints; i++) {
  7357. 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)));
  7358. }
  7359. return new Curve3(bez);
  7360. };
  7361. /**
  7362. * Returns a Curve3 object along a Cubic Bezier curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#cubic-bezier-curve
  7363. * @param v0 (Vector3) the origin point of the Cubic Bezier
  7364. * @param v1 (Vector3) the first control point
  7365. * @param v2 (Vector3) the second control point
  7366. * @param v3 (Vector3) the end point of the Cubic Bezier
  7367. * @param nbPoints (integer) the wanted number of points in the curve
  7368. */
  7369. Curve3.CreateCubicBezier = function (v0, v1, v2, v3, nbPoints) {
  7370. nbPoints = nbPoints > 3 ? nbPoints : 4;
  7371. var bez = new Array();
  7372. var equation = function (t, val0, val1, val2, val3) {
  7373. 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;
  7374. return res;
  7375. };
  7376. for (var i = 0; i <= nbPoints; i++) {
  7377. 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)));
  7378. }
  7379. return new Curve3(bez);
  7380. };
  7381. /**
  7382. * Returns a Curve3 object along a Hermite Spline curve : http://doc.babylonjs.com/tutorials/How_to_use_Curve3#hermite-spline
  7383. * @param p1 (Vector3) the origin point of the Hermite Spline
  7384. * @param t1 (Vector3) the tangent vector at the origin point
  7385. * @param p2 (Vector3) the end point of the Hermite Spline
  7386. * @param t2 (Vector3) the tangent vector at the end point
  7387. * @param nbPoints (integer) the wanted number of points in the curve
  7388. */
  7389. Curve3.CreateHermiteSpline = function (p1, t1, p2, t2, nbPoints) {
  7390. var hermite = new Array();
  7391. var step = 1.0 / nbPoints;
  7392. for (var i = 0; i <= nbPoints; i++) {
  7393. hermite.push(Vector3.Hermite(p1, t1, p2, t2, i * step));
  7394. }
  7395. return new Curve3(hermite);
  7396. };
  7397. /**
  7398. * Returns a Curve3 object along a CatmullRom Spline curve :
  7399. * @param points (array of Vector3) the points the spline must pass through. At least, four points required
  7400. * @param nbPoints (integer) the wanted number of points between each curve control points
  7401. * @param closed (boolean) optional with default false, when true forms a closed loop from the points
  7402. */
  7403. Curve3.CreateCatmullRomSpline = function (points, nbPoints, closed) {
  7404. var catmullRom = new Array();
  7405. var step = 1.0 / nbPoints;
  7406. var amount = 0.0;
  7407. if (closed) {
  7408. var pointsCount = points.length;
  7409. for (var i = 0; i < pointsCount; i++) {
  7410. amount = 0;
  7411. for (var c = 0; c < nbPoints; c++) {
  7412. catmullRom.push(Vector3.CatmullRom(points[i % pointsCount], points[(i + 1) % pointsCount], points[(i + 2) % pointsCount], points[(i + 3) % pointsCount], amount));
  7413. amount += step;
  7414. }
  7415. }
  7416. catmullRom.push(catmullRom[0]);
  7417. }
  7418. else {
  7419. var totalPoints = new Array();
  7420. totalPoints.push(points[0].clone());
  7421. Array.prototype.push.apply(totalPoints, points);
  7422. totalPoints.push(points[points.length - 1].clone());
  7423. for (var i = 0; i < totalPoints.length - 3; i++) {
  7424. amount = 0;
  7425. for (var c = 0; c < nbPoints; c++) {
  7426. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7427. amount += step;
  7428. }
  7429. }
  7430. i--;
  7431. catmullRom.push(Vector3.CatmullRom(totalPoints[i], totalPoints[i + 1], totalPoints[i + 2], totalPoints[i + 3], amount));
  7432. }
  7433. return new Curve3(catmullRom);
  7434. };
  7435. /**
  7436. * Returns the Curve3 stored array of successive Vector3
  7437. */
  7438. Curve3.prototype.getPoints = function () {
  7439. return this._points;
  7440. };
  7441. /**
  7442. * Returns the computed length (float) of the curve.
  7443. */
  7444. Curve3.prototype.length = function () {
  7445. return this._length;
  7446. };
  7447. /**
  7448. * Returns a new instance of Curve3 object : var curve = curveA.continue(curveB);
  7449. * This new Curve3 is built by translating and sticking the curveB at the end of the curveA.
  7450. * curveA and curveB keep unchanged.
  7451. */
  7452. Curve3.prototype.continue = function (curve) {
  7453. var lastPoint = this._points[this._points.length - 1];
  7454. var continuedPoints = this._points.slice();
  7455. var curvePoints = curve.getPoints();
  7456. for (var i = 1; i < curvePoints.length; i++) {
  7457. continuedPoints.push(curvePoints[i].subtract(curvePoints[0]).add(lastPoint));
  7458. }
  7459. var continuedCurve = new Curve3(continuedPoints);
  7460. return continuedCurve;
  7461. };
  7462. Curve3.prototype._computeLength = function (path) {
  7463. var l = 0;
  7464. for (var i = 1; i < path.length; i++) {
  7465. l += (path[i].subtract(path[i - 1])).length();
  7466. }
  7467. return l;
  7468. };
  7469. return Curve3;
  7470. }());
  7471. BABYLON.Curve3 = Curve3;
  7472. // Vertex formats
  7473. var PositionNormalVertex = /** @class */ (function () {
  7474. function PositionNormalVertex(position, normal) {
  7475. if (position === void 0) { position = Vector3.Zero(); }
  7476. if (normal === void 0) { normal = Vector3.Up(); }
  7477. this.position = position;
  7478. this.normal = normal;
  7479. }
  7480. PositionNormalVertex.prototype.clone = function () {
  7481. return new PositionNormalVertex(this.position.clone(), this.normal.clone());
  7482. };
  7483. return PositionNormalVertex;
  7484. }());
  7485. BABYLON.PositionNormalVertex = PositionNormalVertex;
  7486. var PositionNormalTextureVertex = /** @class */ (function () {
  7487. function PositionNormalTextureVertex(position, normal, uv) {
  7488. if (position === void 0) { position = Vector3.Zero(); }
  7489. if (normal === void 0) { normal = Vector3.Up(); }
  7490. if (uv === void 0) { uv = Vector2.Zero(); }
  7491. this.position = position;
  7492. this.normal = normal;
  7493. this.uv = uv;
  7494. }
  7495. PositionNormalTextureVertex.prototype.clone = function () {
  7496. return new PositionNormalTextureVertex(this.position.clone(), this.normal.clone(), this.uv.clone());
  7497. };
  7498. return PositionNormalTextureVertex;
  7499. }());
  7500. BABYLON.PositionNormalTextureVertex = PositionNormalTextureVertex;
  7501. // Temporary pre-allocated objects for engine internal use
  7502. // usage in any internal function :
  7503. // var tmp = Tmp.Vector3[0]; <= gets access to the first pre-created Vector3
  7504. // There's a Tmp array per object type : int, float, Vector2, Vector3, Vector4, Quaternion, Matrix
  7505. var Tmp = /** @class */ (function () {
  7506. function Tmp() {
  7507. }
  7508. Tmp.Color3 = [Color3.Black(), Color3.Black(), Color3.Black()];
  7509. Tmp.Color4 = [new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 0)];
  7510. Tmp.Vector2 = [Vector2.Zero(), Vector2.Zero(), Vector2.Zero()]; // 3 temp Vector2 at once should be enough
  7511. Tmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(),
  7512. Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()]; // 9 temp Vector3 at once should be enough
  7513. Tmp.Vector4 = [Vector4.Zero(), Vector4.Zero(), Vector4.Zero()]; // 3 temp Vector4 at once should be enough
  7514. Tmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero()]; // 2 temp Quaternion at once should be enough
  7515. Tmp.Matrix = [Matrix.Zero(), Matrix.Zero(),
  7516. Matrix.Zero(), Matrix.Zero(),
  7517. Matrix.Zero(), Matrix.Zero(),
  7518. Matrix.Zero(), Matrix.Zero()]; // 6 temp Matrices at once should be enough
  7519. return Tmp;
  7520. }());
  7521. BABYLON.Tmp = Tmp;
  7522. // Same as Tmp but not exported to keep it only for math functions to avoid conflicts
  7523. var MathTmp = /** @class */ (function () {
  7524. function MathTmp() {
  7525. }
  7526. MathTmp.Vector3 = [Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero(), Vector3.Zero()];
  7527. MathTmp.Matrix = [Matrix.Zero(), Matrix.Zero()];
  7528. MathTmp.Quaternion = [Quaternion.Zero(), Quaternion.Zero(), Quaternion.Zero()];
  7529. return MathTmp;
  7530. }());
  7531. })(BABYLON || (BABYLON = {}));
  7532. //# sourceMappingURL=babylon.math.js.map
  7533. var BABYLON;
  7534. (function (BABYLON) {
  7535. var Scalar = /** @class */ (function () {
  7536. function Scalar() {
  7537. }
  7538. /**
  7539. * Boolean : true if the absolute difference between a and b is lower than epsilon (default = 1.401298E-45)
  7540. */
  7541. Scalar.WithinEpsilon = function (a, b, epsilon) {
  7542. if (epsilon === void 0) { epsilon = 1.401298E-45; }
  7543. var num = a - b;
  7544. return -epsilon <= num && num <= epsilon;
  7545. };
  7546. /**
  7547. * Returns a string : the upper case translation of the number i to hexadecimal.
  7548. */
  7549. Scalar.ToHex = function (i) {
  7550. var str = i.toString(16);
  7551. if (i <= 15) {
  7552. return ("0" + str).toUpperCase();
  7553. }
  7554. return str.toUpperCase();
  7555. };
  7556. /**
  7557. * Returns -1 if value is negative and +1 is value is positive.
  7558. * Returns the value itself if it's equal to zero.
  7559. */
  7560. Scalar.Sign = function (value) {
  7561. value = +value; // convert to a number
  7562. if (value === 0 || isNaN(value))
  7563. return value;
  7564. return value > 0 ? 1 : -1;
  7565. };
  7566. /**
  7567. * Returns the value itself if it's between min and max.
  7568. * Returns min if the value is lower than min.
  7569. * Returns max if the value is greater than max.
  7570. */
  7571. Scalar.Clamp = function (value, min, max) {
  7572. if (min === void 0) { min = 0; }
  7573. if (max === void 0) { max = 1; }
  7574. return Math.min(max, Math.max(min, value));
  7575. };
  7576. /**
  7577. * Returns the log2 of value.
  7578. */
  7579. Scalar.Log2 = function (value) {
  7580. return Math.log(value) * Math.LOG2E;
  7581. };
  7582. /**
  7583. * Loops the value, so that it is never larger than length and never smaller than 0.
  7584. *
  7585. * This is similar to the modulo operator but it works with floating point numbers.
  7586. * For example, using 3.0 for t and 2.5 for length, the result would be 0.5.
  7587. * With t = 5 and length = 2.5, the result would be 0.0.
  7588. * Note, however, that the behaviour is not defined for negative numbers as it is for the modulo operator
  7589. */
  7590. Scalar.Repeat = function (value, length) {
  7591. return value - Math.floor(value / length) * length;
  7592. };
  7593. /**
  7594. * Normalize the value between 0.0 and 1.0 using min and max values
  7595. */
  7596. Scalar.Normalize = function (value, min, max) {
  7597. return (value - min) / (max - min);
  7598. };
  7599. /**
  7600. * Denormalize the value from 0.0 and 1.0 using min and max values
  7601. */
  7602. Scalar.Denormalize = function (normalized, min, max) {
  7603. return (normalized * (max - min) + min);
  7604. };
  7605. /**
  7606. * Calculates the shortest difference between two given angles given in degrees.
  7607. */
  7608. Scalar.DeltaAngle = function (current, target) {
  7609. var num = Scalar.Repeat(target - current, 360.0);
  7610. if (num > 180.0) {
  7611. num -= 360.0;
  7612. }
  7613. return num;
  7614. };
  7615. /**
  7616. * PingPongs the value t, so that it is never larger than length and never smaller than 0.
  7617. *
  7618. * The returned value will move back and forth between 0 and length
  7619. */
  7620. Scalar.PingPong = function (tx, length) {
  7621. var t = Scalar.Repeat(tx, length * 2.0);
  7622. return length - Math.abs(t - length);
  7623. };
  7624. /**
  7625. * Interpolates between min and max with smoothing at the limits.
  7626. *
  7627. * This function interpolates between min and max in a similar way to Lerp. However, the interpolation will gradually speed up
  7628. * from the start and slow down toward the end. This is useful for creating natural-looking animation, fading and other transitions.
  7629. */
  7630. Scalar.SmoothStep = function (from, to, tx) {
  7631. var t = Scalar.Clamp(tx);
  7632. t = -2.0 * t * t * t + 3.0 * t * t;
  7633. return to * t + from * (1.0 - t);
  7634. };
  7635. /**
  7636. * Moves a value current towards target.
  7637. *
  7638. * This is essentially the same as Mathf.Lerp but instead the function will ensure that the speed never exceeds maxDelta.
  7639. * Negative values of maxDelta pushes the value away from target.
  7640. */
  7641. Scalar.MoveTowards = function (current, target, maxDelta) {
  7642. var result = 0;
  7643. if (Math.abs(target - current) <= maxDelta) {
  7644. result = target;
  7645. }
  7646. else {
  7647. result = current + Scalar.Sign(target - current) * maxDelta;
  7648. }
  7649. return result;
  7650. };
  7651. /**
  7652. * Same as MoveTowards but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7653. *
  7654. * Variables current and target are assumed to be in degrees. For optimization reasons, negative values of maxDelta
  7655. * are not supported and may cause oscillation. To push current away from a target angle, add 180 to that angle instead.
  7656. */
  7657. Scalar.MoveTowardsAngle = function (current, target, maxDelta) {
  7658. var num = Scalar.DeltaAngle(current, target);
  7659. var result = 0;
  7660. if (-maxDelta < num && num < maxDelta) {
  7661. result = target;
  7662. }
  7663. else {
  7664. target = current + num;
  7665. result = Scalar.MoveTowards(current, target, maxDelta);
  7666. }
  7667. return result;
  7668. };
  7669. /**
  7670. * Creates a new scalar with values linearly interpolated of "amount" between the start scalar and the end scalar.
  7671. */
  7672. Scalar.Lerp = function (start, end, amount) {
  7673. return start + ((end - start) * amount);
  7674. };
  7675. /**
  7676. * Same as Lerp but makes sure the values interpolate correctly when they wrap around 360 degrees.
  7677. * The parameter t is clamped to the range [0, 1]. Variables a and b are assumed to be in degrees.
  7678. */
  7679. Scalar.LerpAngle = function (start, end, amount) {
  7680. var num = Scalar.Repeat(end - start, 360.0);
  7681. if (num > 180.0) {
  7682. num -= 360.0;
  7683. }
  7684. return start + num * Scalar.Clamp(amount);
  7685. };
  7686. /**
  7687. * Calculates the linear parameter t that produces the interpolant value within the range [a, b].
  7688. */
  7689. Scalar.InverseLerp = function (a, b, value) {
  7690. var result = 0;
  7691. if (a != b) {
  7692. result = Scalar.Clamp((value - a) / (b - a));
  7693. }
  7694. else {
  7695. result = 0.0;
  7696. }
  7697. return result;
  7698. };
  7699. /**
  7700. * Returns a new scalar located for "amount" (float) on the Hermite spline defined by the scalars "value1", "value3", "tangent1", "tangent2".
  7701. */
  7702. Scalar.Hermite = function (value1, tangent1, value2, tangent2, amount) {
  7703. var squared = amount * amount;
  7704. var cubed = amount * squared;
  7705. var part1 = ((2.0 * cubed) - (3.0 * squared)) + 1.0;
  7706. var part2 = (-2.0 * cubed) + (3.0 * squared);
  7707. var part3 = (cubed - (2.0 * squared)) + amount;
  7708. var part4 = cubed - squared;
  7709. return (((value1 * part1) + (value2 * part2)) + (tangent1 * part3)) + (tangent2 * part4);
  7710. };
  7711. /**
  7712. * Returns a random float number between and min and max values
  7713. */
  7714. Scalar.RandomRange = function (min, max) {
  7715. if (min === max)
  7716. return min;
  7717. return ((Math.random() * (max - min)) + min);
  7718. };
  7719. /**
  7720. * This function returns percentage of a number in a given range.
  7721. *
  7722. * RangeToPercent(40,20,60) will return 0.5 (50%)
  7723. * RangeToPercent(34,0,100) will return 0.34 (34%)
  7724. */
  7725. Scalar.RangeToPercent = function (number, min, max) {
  7726. return ((number - min) / (max - min));
  7727. };
  7728. /**
  7729. * This function returns number that corresponds to the percentage in a given range.
  7730. *
  7731. * PercentToRange(0.34,0,100) will return 34.
  7732. */
  7733. Scalar.PercentToRange = function (percent, min, max) {
  7734. return ((max - min) * percent + min);
  7735. };
  7736. /**
  7737. * Returns the angle converted to equivalent value between -Math.PI and Math.PI radians.
  7738. * @param angle The angle to normalize in radian.
  7739. * @return The converted angle.
  7740. */
  7741. Scalar.NormalizeRadians = function (angle) {
  7742. // More precise but slower version kept for reference.
  7743. // angle = angle % Tools.TwoPi;
  7744. // angle = (angle + Tools.TwoPi) % Tools.TwoPi;
  7745. //if (angle > Math.PI) {
  7746. // angle -= Tools.TwoPi;
  7747. //}
  7748. angle -= (Scalar.TwoPi * Math.floor((angle + Math.PI) / Scalar.TwoPi));
  7749. return angle;
  7750. };
  7751. /**
  7752. * Two pi constants convenient for computation.
  7753. */
  7754. Scalar.TwoPi = Math.PI * 2;
  7755. return Scalar;
  7756. }());
  7757. BABYLON.Scalar = Scalar;
  7758. })(BABYLON || (BABYLON = {}));
  7759. //# sourceMappingURL=babylon.math.scalar.js.map
  7760. //# sourceMappingURL=babylon.mixins.js.map
  7761. // Type definitions for WebGL 2, Editor's Draft Fri Feb 24 16:10:18 2017 -0800
  7762. // Project: https://www.khronos.org/registry/webgl/specs/latest/2.0/
  7763. // Definitions by: Nico Kemnitz <https://github.com/nkemnitz/>
  7764. // Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
  7765. //# sourceMappingURL=babylon.webgl2.js.map
  7766. var BABYLON;
  7767. (function (BABYLON) {
  7768. var __decoratorInitialStore = {};
  7769. var __mergedStore = {};
  7770. var _copySource = function (creationFunction, source, instanciate) {
  7771. var destination = creationFunction();
  7772. // Tags
  7773. if (BABYLON.Tags) {
  7774. BABYLON.Tags.AddTagsTo(destination, source.tags);
  7775. }
  7776. var classStore = getMergedStore(destination);
  7777. // Properties
  7778. for (var property in classStore) {
  7779. var propertyDescriptor = classStore[property];
  7780. var sourceProperty = source[property];
  7781. var propertyType = propertyDescriptor.type;
  7782. if (sourceProperty !== undefined && sourceProperty !== null) {
  7783. switch (propertyType) {
  7784. case 0: // Value
  7785. case 6: // Mesh reference
  7786. case 11: // Camera reference
  7787. destination[property] = sourceProperty;
  7788. break;
  7789. case 1: // Texture
  7790. destination[property] = (instanciate || sourceProperty.isRenderTarget) ? sourceProperty : sourceProperty.clone();
  7791. break;
  7792. case 2: // Color3
  7793. case 3: // FresnelParameters
  7794. case 4: // Vector2
  7795. case 5: // Vector3
  7796. case 7: // Color Curves
  7797. case 10: // Quaternion
  7798. destination[property] = instanciate ? sourceProperty : sourceProperty.clone();
  7799. break;
  7800. }
  7801. }
  7802. }
  7803. return destination;
  7804. };
  7805. function getDirectStore(target) {
  7806. var classKey = target.getClassName();
  7807. if (!__decoratorInitialStore[classKey]) {
  7808. __decoratorInitialStore[classKey] = {};
  7809. }
  7810. return __decoratorInitialStore[classKey];
  7811. }
  7812. /**
  7813. * Return the list of properties flagged as serializable
  7814. * @param target: host object
  7815. */
  7816. function getMergedStore(target) {
  7817. var classKey = target.getClassName();
  7818. if (__mergedStore[classKey]) {
  7819. return __mergedStore[classKey];
  7820. }
  7821. __mergedStore[classKey] = {};
  7822. var store = __mergedStore[classKey];
  7823. var currentTarget = target;
  7824. var currentKey = classKey;
  7825. while (currentKey) {
  7826. var initialStore = __decoratorInitialStore[currentKey];
  7827. for (var property in initialStore) {
  7828. store[property] = initialStore[property];
  7829. }
  7830. var parent_1 = void 0;
  7831. var done = false;
  7832. do {
  7833. parent_1 = Object.getPrototypeOf(currentTarget);
  7834. if (!parent_1.getClassName) {
  7835. done = true;
  7836. break;
  7837. }
  7838. if (parent_1.getClassName() !== currentKey) {
  7839. break;
  7840. }
  7841. currentTarget = parent_1;
  7842. } while (parent_1);
  7843. if (done) {
  7844. break;
  7845. }
  7846. currentKey = parent_1.getClassName();
  7847. currentTarget = parent_1;
  7848. }
  7849. return store;
  7850. }
  7851. function generateSerializableMember(type, sourceName) {
  7852. return function (target, propertyKey) {
  7853. var classStore = getDirectStore(target);
  7854. if (!classStore[propertyKey]) {
  7855. classStore[propertyKey] = { type: type, sourceName: sourceName };
  7856. }
  7857. };
  7858. }
  7859. function generateExpandMember(setCallback, targetKey) {
  7860. if (targetKey === void 0) { targetKey = null; }
  7861. return function (target, propertyKey) {
  7862. var key = targetKey || ("_" + propertyKey);
  7863. Object.defineProperty(target, propertyKey, {
  7864. get: function () {
  7865. return this[key];
  7866. },
  7867. set: function (value) {
  7868. if (this[key] === value) {
  7869. return;
  7870. }
  7871. this[key] = value;
  7872. target[setCallback].apply(this);
  7873. },
  7874. enumerable: true,
  7875. configurable: true
  7876. });
  7877. };
  7878. }
  7879. function expandToProperty(callback, targetKey) {
  7880. if (targetKey === void 0) { targetKey = null; }
  7881. return generateExpandMember(callback, targetKey);
  7882. }
  7883. BABYLON.expandToProperty = expandToProperty;
  7884. function serialize(sourceName) {
  7885. return generateSerializableMember(0, sourceName); // value member
  7886. }
  7887. BABYLON.serialize = serialize;
  7888. function serializeAsTexture(sourceName) {
  7889. return generateSerializableMember(1, sourceName); // texture member
  7890. }
  7891. BABYLON.serializeAsTexture = serializeAsTexture;
  7892. function serializeAsColor3(sourceName) {
  7893. return generateSerializableMember(2, sourceName); // color3 member
  7894. }
  7895. BABYLON.serializeAsColor3 = serializeAsColor3;
  7896. function serializeAsFresnelParameters(sourceName) {
  7897. return generateSerializableMember(3, sourceName); // fresnel parameters member
  7898. }
  7899. BABYLON.serializeAsFresnelParameters = serializeAsFresnelParameters;
  7900. function serializeAsVector2(sourceName) {
  7901. return generateSerializableMember(4, sourceName); // vector2 member
  7902. }
  7903. BABYLON.serializeAsVector2 = serializeAsVector2;
  7904. function serializeAsVector3(sourceName) {
  7905. return generateSerializableMember(5, sourceName); // vector3 member
  7906. }
  7907. BABYLON.serializeAsVector3 = serializeAsVector3;
  7908. function serializeAsMeshReference(sourceName) {
  7909. return generateSerializableMember(6, sourceName); // mesh reference member
  7910. }
  7911. BABYLON.serializeAsMeshReference = serializeAsMeshReference;
  7912. function serializeAsColorCurves(sourceName) {
  7913. return generateSerializableMember(7, sourceName); // color curves
  7914. }
  7915. BABYLON.serializeAsColorCurves = serializeAsColorCurves;
  7916. function serializeAsColor4(sourceName) {
  7917. return generateSerializableMember(8, sourceName); // color 4
  7918. }
  7919. BABYLON.serializeAsColor4 = serializeAsColor4;
  7920. function serializeAsImageProcessingConfiguration(sourceName) {
  7921. return generateSerializableMember(9, sourceName); // image processing
  7922. }
  7923. BABYLON.serializeAsImageProcessingConfiguration = serializeAsImageProcessingConfiguration;
  7924. function serializeAsQuaternion(sourceName) {
  7925. return generateSerializableMember(10, sourceName); // quaternion member
  7926. }
  7927. BABYLON.serializeAsQuaternion = serializeAsQuaternion;
  7928. /**
  7929. * Decorator used to define property that can be serialized as reference to a camera
  7930. * @param sourceName defines the name of the property to decorate
  7931. */
  7932. function serializeAsCameraReference(sourceName) {
  7933. return generateSerializableMember(11, sourceName); // camera reference member
  7934. }
  7935. BABYLON.serializeAsCameraReference = serializeAsCameraReference;
  7936. var SerializationHelper = /** @class */ (function () {
  7937. function SerializationHelper() {
  7938. }
  7939. SerializationHelper.Serialize = function (entity, serializationObject) {
  7940. if (!serializationObject) {
  7941. serializationObject = {};
  7942. }
  7943. // Tags
  7944. if (BABYLON.Tags) {
  7945. serializationObject.tags = BABYLON.Tags.GetTags(entity);
  7946. }
  7947. var serializedProperties = getMergedStore(entity);
  7948. // Properties
  7949. for (var property in serializedProperties) {
  7950. var propertyDescriptor = serializedProperties[property];
  7951. var targetPropertyName = propertyDescriptor.sourceName || property;
  7952. var propertyType = propertyDescriptor.type;
  7953. var sourceProperty = entity[property];
  7954. if (sourceProperty !== undefined && sourceProperty !== null) {
  7955. switch (propertyType) {
  7956. case 0: // Value
  7957. serializationObject[targetPropertyName] = sourceProperty;
  7958. break;
  7959. case 1: // Texture
  7960. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7961. break;
  7962. case 2: // Color3
  7963. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7964. break;
  7965. case 3: // FresnelParameters
  7966. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7967. break;
  7968. case 4: // Vector2
  7969. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7970. break;
  7971. case 5: // Vector3
  7972. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7973. break;
  7974. case 6: // Mesh reference
  7975. serializationObject[targetPropertyName] = sourceProperty.id;
  7976. break;
  7977. case 7: // Color Curves
  7978. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7979. break;
  7980. case 8: // Color 4
  7981. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7982. break;
  7983. case 9: // Image Processing
  7984. serializationObject[targetPropertyName] = sourceProperty.serialize();
  7985. break;
  7986. case 10: // Quaternion
  7987. serializationObject[targetPropertyName] = sourceProperty.asArray();
  7988. break;
  7989. case 11: // Camera reference
  7990. serializationObject[targetPropertyName] = sourceProperty.id;
  7991. break;
  7992. }
  7993. }
  7994. }
  7995. return serializationObject;
  7996. };
  7997. SerializationHelper.Parse = function (creationFunction, source, scene, rootUrl) {
  7998. if (rootUrl === void 0) { rootUrl = null; }
  7999. var destination = creationFunction();
  8000. if (!rootUrl) {
  8001. rootUrl = "";
  8002. }
  8003. // Tags
  8004. if (BABYLON.Tags) {
  8005. BABYLON.Tags.AddTagsTo(destination, source.tags);
  8006. }
  8007. var classStore = getMergedStore(destination);
  8008. // Properties
  8009. for (var property in classStore) {
  8010. var propertyDescriptor = classStore[property];
  8011. var sourceProperty = source[propertyDescriptor.sourceName || property];
  8012. var propertyType = propertyDescriptor.type;
  8013. if (sourceProperty !== undefined && sourceProperty !== null) {
  8014. var dest = destination;
  8015. switch (propertyType) {
  8016. case 0: // Value
  8017. dest[property] = sourceProperty;
  8018. break;
  8019. case 1: // Texture
  8020. if (scene) {
  8021. dest[property] = BABYLON.Texture.Parse(sourceProperty, scene, rootUrl);
  8022. }
  8023. break;
  8024. case 2: // Color3
  8025. dest[property] = BABYLON.Color3.FromArray(sourceProperty);
  8026. break;
  8027. case 3: // FresnelParameters
  8028. dest[property] = BABYLON.FresnelParameters.Parse(sourceProperty);
  8029. break;
  8030. case 4: // Vector2
  8031. dest[property] = BABYLON.Vector2.FromArray(sourceProperty);
  8032. break;
  8033. case 5: // Vector3
  8034. dest[property] = BABYLON.Vector3.FromArray(sourceProperty);
  8035. break;
  8036. case 6: // Mesh reference
  8037. if (scene) {
  8038. dest[property] = scene.getLastMeshByID(sourceProperty);
  8039. }
  8040. break;
  8041. case 7: // Color Curves
  8042. dest[property] = BABYLON.ColorCurves.Parse(sourceProperty);
  8043. break;
  8044. case 8: // Color 4
  8045. dest[property] = BABYLON.Color4.FromArray(sourceProperty);
  8046. break;
  8047. case 9: // Image Processing
  8048. dest[property] = BABYLON.ImageProcessingConfiguration.Parse(sourceProperty);
  8049. break;
  8050. case 10: // Quaternion
  8051. dest[property] = BABYLON.Quaternion.FromArray(sourceProperty);
  8052. break;
  8053. case 11: // Camera reference
  8054. if (scene) {
  8055. dest[property] = scene.getCameraByID(sourceProperty);
  8056. }
  8057. break;
  8058. }
  8059. }
  8060. }
  8061. return destination;
  8062. };
  8063. SerializationHelper.Clone = function (creationFunction, source) {
  8064. return _copySource(creationFunction, source, false);
  8065. };
  8066. SerializationHelper.Instanciate = function (creationFunction, source) {
  8067. return _copySource(creationFunction, source, true);
  8068. };
  8069. return SerializationHelper;
  8070. }());
  8071. BABYLON.SerializationHelper = SerializationHelper;
  8072. })(BABYLON || (BABYLON = {}));
  8073. //# sourceMappingURL=babylon.decorators.js.map
  8074. var BABYLON;
  8075. (function (BABYLON) {
  8076. /**
  8077. * Wrapper class for promise with external resolve and reject.
  8078. */
  8079. var Deferred = /** @class */ (function () {
  8080. /**
  8081. * Constructor for this deferred object.
  8082. */
  8083. function Deferred() {
  8084. var _this = this;
  8085. this.promise = new Promise(function (resolve, reject) {
  8086. _this._resolve = resolve;
  8087. _this._reject = reject;
  8088. });
  8089. }
  8090. Object.defineProperty(Deferred.prototype, "resolve", {
  8091. /**
  8092. * The resolve method of the promise associated with this deferred object.
  8093. */
  8094. get: function () {
  8095. return this._resolve;
  8096. },
  8097. enumerable: true,
  8098. configurable: true
  8099. });
  8100. Object.defineProperty(Deferred.prototype, "reject", {
  8101. /**
  8102. * The reject method of the promise associated with this deferred object.
  8103. */
  8104. get: function () {
  8105. return this._reject;
  8106. },
  8107. enumerable: true,
  8108. configurable: true
  8109. });
  8110. return Deferred;
  8111. }());
  8112. BABYLON.Deferred = Deferred;
  8113. })(BABYLON || (BABYLON = {}));
  8114. //# sourceMappingURL=babylon.deferred.js.map
  8115. var BABYLON;
  8116. (function (BABYLON) {
  8117. /**
  8118. * A class serves as a medium between the observable and its observers
  8119. */
  8120. var EventState = /** @class */ (function () {
  8121. /**
  8122. * Create a new EventState
  8123. * @param mask defines the mask associated with this state
  8124. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8125. * @param target defines the original target of the state
  8126. * @param currentTarget defines the current target of the state
  8127. */
  8128. function EventState(mask, skipNextObservers, target, currentTarget) {
  8129. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8130. this.initalize(mask, skipNextObservers, target, currentTarget);
  8131. }
  8132. /**
  8133. * Initialize the current event state
  8134. * @param mask defines the mask associated with this state
  8135. * @param skipNextObservers defines a flag which will instruct the observable to skip following observers when set to true
  8136. * @param target defines the original target of the state
  8137. * @param currentTarget defines the current target of the state
  8138. * @returns the current event state
  8139. */
  8140. EventState.prototype.initalize = function (mask, skipNextObservers, target, currentTarget) {
  8141. if (skipNextObservers === void 0) { skipNextObservers = false; }
  8142. this.mask = mask;
  8143. this.skipNextObservers = skipNextObservers;
  8144. this.target = target;
  8145. this.currentTarget = currentTarget;
  8146. return this;
  8147. };
  8148. return EventState;
  8149. }());
  8150. BABYLON.EventState = EventState;
  8151. /**
  8152. * Represent an Observer registered to a given Observable object.
  8153. */
  8154. var Observer = /** @class */ (function () {
  8155. /**
  8156. * Creates a new observer
  8157. * @param callback defines the callback to call when the observer is notified
  8158. * @param mask defines the mask of the observer (used to filter notifications)
  8159. * @param scope defines the current scope used to restore the JS context
  8160. */
  8161. function Observer(
  8162. /**
  8163. * Defines the callback to call when the observer is notified
  8164. */
  8165. callback,
  8166. /**
  8167. * Defines the mask of the observer (used to filter notifications)
  8168. */
  8169. mask,
  8170. /**
  8171. * Defines the current scope used to restore the JS context
  8172. */
  8173. scope) {
  8174. if (scope === void 0) { scope = null; }
  8175. this.callback = callback;
  8176. this.mask = mask;
  8177. this.scope = scope;
  8178. /** @hidden */
  8179. this._willBeUnregistered = false;
  8180. /**
  8181. * Gets or sets a property defining that the observer as to be unregistered after the next notification
  8182. */
  8183. this.unregisterOnNextCall = false;
  8184. }
  8185. return Observer;
  8186. }());
  8187. BABYLON.Observer = Observer;
  8188. /**
  8189. * Represent a list of observers registered to multiple Observables object.
  8190. */
  8191. var MultiObserver = /** @class */ (function () {
  8192. function MultiObserver() {
  8193. }
  8194. /**
  8195. * Release associated resources
  8196. */
  8197. MultiObserver.prototype.dispose = function () {
  8198. if (this._observers && this._observables) {
  8199. for (var index = 0; index < this._observers.length; index++) {
  8200. this._observables[index].remove(this._observers[index]);
  8201. }
  8202. }
  8203. this._observers = null;
  8204. this._observables = null;
  8205. };
  8206. /**
  8207. * Raise a callback when one of the observable will notify
  8208. * @param observables defines a list of observables to watch
  8209. * @param callback defines the callback to call on notification
  8210. * @param mask defines the mask used to filter notifications
  8211. * @param scope defines the current scope used to restore the JS context
  8212. * @returns the new MultiObserver
  8213. */
  8214. MultiObserver.Watch = function (observables, callback, mask, scope) {
  8215. if (mask === void 0) { mask = -1; }
  8216. if (scope === void 0) { scope = null; }
  8217. var result = new MultiObserver();
  8218. result._observers = new Array();
  8219. result._observables = observables;
  8220. for (var _i = 0, observables_1 = observables; _i < observables_1.length; _i++) {
  8221. var observable = observables_1[_i];
  8222. var observer = observable.add(callback, mask, false, scope);
  8223. if (observer) {
  8224. result._observers.push(observer);
  8225. }
  8226. }
  8227. return result;
  8228. };
  8229. return MultiObserver;
  8230. }());
  8231. BABYLON.MultiObserver = MultiObserver;
  8232. /**
  8233. * The Observable class is a simple implementation of the Observable pattern.
  8234. *
  8235. * 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.
  8236. * This enable a more fine grained execution without having to rely on multiple different Observable objects.
  8237. * 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).
  8238. * 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.
  8239. */
  8240. var Observable = /** @class */ (function () {
  8241. /**
  8242. * Creates a new observable
  8243. * @param onObserverAdded defines a callback to call when a new observer is added
  8244. */
  8245. function Observable(onObserverAdded) {
  8246. this._observers = new Array();
  8247. this._eventState = new EventState(0);
  8248. if (onObserverAdded) {
  8249. this._onObserverAdded = onObserverAdded;
  8250. }
  8251. }
  8252. /**
  8253. * Create a new Observer with the specified callback
  8254. * @param callback the callback that will be executed for that Observer
  8255. * @param mask the mask used to filter observers
  8256. * @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.
  8257. * @param scope optional scope for the callback to be called from
  8258. * @param unregisterOnFirstCall defines if the observer as to be unregistered after the next notification
  8259. * @returns the new observer created for the callback
  8260. */
  8261. Observable.prototype.add = function (callback, mask, insertFirst, scope, unregisterOnFirstCall) {
  8262. if (mask === void 0) { mask = -1; }
  8263. if (insertFirst === void 0) { insertFirst = false; }
  8264. if (scope === void 0) { scope = null; }
  8265. if (unregisterOnFirstCall === void 0) { unregisterOnFirstCall = false; }
  8266. if (!callback) {
  8267. return null;
  8268. }
  8269. var observer = new Observer(callback, mask, scope);
  8270. observer.unregisterOnNextCall = unregisterOnFirstCall;
  8271. if (insertFirst) {
  8272. this._observers.unshift(observer);
  8273. }
  8274. else {
  8275. this._observers.push(observer);
  8276. }
  8277. if (this._onObserverAdded) {
  8278. this._onObserverAdded(observer);
  8279. }
  8280. return observer;
  8281. };
  8282. /**
  8283. * Create a new Observer with the specified callback and unregisters after the next notification
  8284. * @param callback the callback that will be executed for that Observer
  8285. * @returns the new observer created for the callback
  8286. */
  8287. Observable.prototype.addOnce = function (callback) {
  8288. return this.add(callback, undefined, undefined, undefined, true);
  8289. };
  8290. /**
  8291. * Remove an Observer from the Observable object
  8292. * @param observer the instance of the Observer to remove
  8293. * @returns false if it doesn't belong to this Observable
  8294. */
  8295. Observable.prototype.remove = function (observer) {
  8296. if (!observer) {
  8297. return false;
  8298. }
  8299. var index = this._observers.indexOf(observer);
  8300. if (index !== -1) {
  8301. this._observers.splice(index, 1);
  8302. return true;
  8303. }
  8304. return false;
  8305. };
  8306. /**
  8307. * Remove a callback from the Observable object
  8308. * @param callback the callback to remove
  8309. * @param scope optional scope. If used only the callbacks with this scope will be removed
  8310. * @returns false if it doesn't belong to this Observable
  8311. */
  8312. Observable.prototype.removeCallback = function (callback, scope) {
  8313. for (var index = 0; index < this._observers.length; index++) {
  8314. if (this._observers[index].callback === callback && (!scope || scope === this._observers[index].scope)) {
  8315. this._observers.splice(index, 1);
  8316. return true;
  8317. }
  8318. }
  8319. return false;
  8320. };
  8321. Observable.prototype._deferUnregister = function (observer) {
  8322. var _this = this;
  8323. observer.unregisterOnNextCall = false;
  8324. observer._willBeUnregistered = true;
  8325. BABYLON.Tools.SetImmediate(function () {
  8326. _this.remove(observer);
  8327. });
  8328. };
  8329. /**
  8330. * Notify all Observers by calling their respective callback with the given data
  8331. * Will return true if all observers were executed, false if an observer set skipNextObservers to true, then prevent the subsequent ones to execute
  8332. * @param eventData defines the data to send to all observers
  8333. * @param mask defines the mask of the current notification (observers with incompatible mask (ie mask & observer.mask === 0) will not be notified)
  8334. * @param target defines the original target of the state
  8335. * @param currentTarget defines the current target of the state
  8336. * @returns false if the complete observer chain was not processed (because one observer set the skipNextObservers to true)
  8337. */
  8338. Observable.prototype.notifyObservers = function (eventData, mask, target, currentTarget) {
  8339. if (mask === void 0) { mask = -1; }
  8340. if (!this._observers.length) {
  8341. return true;
  8342. }
  8343. var state = this._eventState;
  8344. state.mask = mask;
  8345. state.target = target;
  8346. state.currentTarget = currentTarget;
  8347. state.skipNextObservers = false;
  8348. state.lastReturnValue = eventData;
  8349. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8350. var obs = _a[_i];
  8351. if (obs._willBeUnregistered) {
  8352. continue;
  8353. }
  8354. if (obs.mask & mask) {
  8355. if (obs.scope) {
  8356. state.lastReturnValue = obs.callback.apply(obs.scope, [eventData, state]);
  8357. }
  8358. else {
  8359. state.lastReturnValue = obs.callback(eventData, state);
  8360. }
  8361. if (obs.unregisterOnNextCall) {
  8362. this._deferUnregister(obs);
  8363. }
  8364. }
  8365. if (state.skipNextObservers) {
  8366. return false;
  8367. }
  8368. }
  8369. return true;
  8370. };
  8371. /**
  8372. * Calling this will execute each callback, expecting it to be a promise or return a value.
  8373. * If at any point in the chain one function fails, the promise will fail and the execution will not continue.
  8374. * This is useful when a chain of events (sometimes async events) is needed to initialize a certain object
  8375. * and it is crucial that all callbacks will be executed.
  8376. * The order of the callbacks is kept, callbacks are not executed parallel.
  8377. *
  8378. * @param eventData The data to be sent to each callback
  8379. * @param mask is used to filter observers defaults to -1
  8380. * @param target defines the callback target (see EventState)
  8381. * @param currentTarget defines he current object in the bubbling phase
  8382. * @returns {Promise<T>} will return a Promise than resolves when all callbacks executed successfully.
  8383. */
  8384. Observable.prototype.notifyObserversWithPromise = function (eventData, mask, target, currentTarget) {
  8385. var _this = this;
  8386. if (mask === void 0) { mask = -1; }
  8387. // create an empty promise
  8388. var p = Promise.resolve(eventData);
  8389. // no observers? return this promise.
  8390. if (!this._observers.length) {
  8391. return p;
  8392. }
  8393. var state = this._eventState;
  8394. state.mask = mask;
  8395. state.target = target;
  8396. state.currentTarget = currentTarget;
  8397. state.skipNextObservers = false;
  8398. // execute one callback after another (not using Promise.all, the order is important)
  8399. this._observers.forEach(function (obs) {
  8400. if (state.skipNextObservers) {
  8401. return;
  8402. }
  8403. if (obs._willBeUnregistered) {
  8404. return;
  8405. }
  8406. if (obs.mask & mask) {
  8407. if (obs.scope) {
  8408. p = p.then(function (lastReturnedValue) {
  8409. state.lastReturnValue = lastReturnedValue;
  8410. return obs.callback.apply(obs.scope, [eventData, state]);
  8411. });
  8412. }
  8413. else {
  8414. p = p.then(function (lastReturnedValue) {
  8415. state.lastReturnValue = lastReturnedValue;
  8416. return obs.callback(eventData, state);
  8417. });
  8418. }
  8419. if (obs.unregisterOnNextCall) {
  8420. _this._deferUnregister(obs);
  8421. }
  8422. }
  8423. });
  8424. // return the eventData
  8425. return p.then(function () { return eventData; });
  8426. };
  8427. /**
  8428. * Notify a specific observer
  8429. * @param observer defines the observer to notify
  8430. * @param eventData defines the data to be sent to each callback
  8431. * @param mask is used to filter observers defaults to -1
  8432. */
  8433. Observable.prototype.notifyObserver = function (observer, eventData, mask) {
  8434. if (mask === void 0) { mask = -1; }
  8435. var state = this._eventState;
  8436. state.mask = mask;
  8437. state.skipNextObservers = false;
  8438. observer.callback(eventData, state);
  8439. };
  8440. /**
  8441. * Gets a boolean indicating if the observable has at least one observer
  8442. * @returns true is the Observable has at least one Observer registered
  8443. */
  8444. Observable.prototype.hasObservers = function () {
  8445. return this._observers.length > 0;
  8446. };
  8447. /**
  8448. * Clear the list of observers
  8449. */
  8450. Observable.prototype.clear = function () {
  8451. this._observers = new Array();
  8452. this._onObserverAdded = null;
  8453. };
  8454. /**
  8455. * Clone the current observable
  8456. * @returns a new observable
  8457. */
  8458. Observable.prototype.clone = function () {
  8459. var result = new Observable();
  8460. result._observers = this._observers.slice(0);
  8461. return result;
  8462. };
  8463. /**
  8464. * Does this observable handles observer registered with a given mask
  8465. * @param mask defines the mask to be tested
  8466. * @return whether or not one observer registered with the given mask is handeled
  8467. **/
  8468. Observable.prototype.hasSpecificMask = function (mask) {
  8469. if (mask === void 0) { mask = -1; }
  8470. for (var _i = 0, _a = this._observers; _i < _a.length; _i++) {
  8471. var obs = _a[_i];
  8472. if (obs.mask & mask || obs.mask === mask) {
  8473. return true;
  8474. }
  8475. }
  8476. return false;
  8477. };
  8478. return Observable;
  8479. }());
  8480. BABYLON.Observable = Observable;
  8481. })(BABYLON || (BABYLON = {}));
  8482. //# sourceMappingURL=babylon.observable.js.map
  8483. var BABYLON;
  8484. (function (BABYLON) {
  8485. var SmartArray = /** @class */ (function () {
  8486. function SmartArray(capacity) {
  8487. this.length = 0;
  8488. this.data = new Array(capacity);
  8489. this._id = SmartArray._GlobalId++;
  8490. }
  8491. SmartArray.prototype.push = function (value) {
  8492. this.data[this.length++] = value;
  8493. if (this.length > this.data.length) {
  8494. this.data.length *= 2;
  8495. }
  8496. };
  8497. SmartArray.prototype.forEach = function (func) {
  8498. for (var index = 0; index < this.length; index++) {
  8499. func(this.data[index]);
  8500. }
  8501. };
  8502. SmartArray.prototype.sort = function (compareFn) {
  8503. this.data.sort(compareFn);
  8504. };
  8505. SmartArray.prototype.reset = function () {
  8506. this.length = 0;
  8507. };
  8508. SmartArray.prototype.dispose = function () {
  8509. this.reset();
  8510. if (this.data) {
  8511. this.data.length = 0;
  8512. this.data = [];
  8513. }
  8514. };
  8515. SmartArray.prototype.concat = function (array) {
  8516. if (array.length === 0) {
  8517. return;
  8518. }
  8519. if (this.length + array.length > this.data.length) {
  8520. this.data.length = (this.length + array.length) * 2;
  8521. }
  8522. for (var index = 0; index < array.length; index++) {
  8523. this.data[this.length++] = (array.data || array)[index];
  8524. }
  8525. };
  8526. SmartArray.prototype.indexOf = function (value) {
  8527. var position = this.data.indexOf(value);
  8528. if (position >= this.length) {
  8529. return -1;
  8530. }
  8531. return position;
  8532. };
  8533. SmartArray.prototype.contains = function (value) {
  8534. return this.data.indexOf(value) !== -1;
  8535. };
  8536. // Statics
  8537. SmartArray._GlobalId = 0;
  8538. return SmartArray;
  8539. }());
  8540. BABYLON.SmartArray = SmartArray;
  8541. var SmartArrayNoDuplicate = /** @class */ (function (_super) {
  8542. __extends(SmartArrayNoDuplicate, _super);
  8543. function SmartArrayNoDuplicate() {
  8544. var _this = _super !== null && _super.apply(this, arguments) || this;
  8545. _this._duplicateId = 0;
  8546. return _this;
  8547. }
  8548. SmartArrayNoDuplicate.prototype.push = function (value) {
  8549. _super.prototype.push.call(this, value);
  8550. if (!value.__smartArrayFlags) {
  8551. value.__smartArrayFlags = {};
  8552. }
  8553. value.__smartArrayFlags[this._id] = this._duplicateId;
  8554. };
  8555. SmartArrayNoDuplicate.prototype.pushNoDuplicate = function (value) {
  8556. if (value.__smartArrayFlags && value.__smartArrayFlags[this._id] === this._duplicateId) {
  8557. return false;
  8558. }
  8559. this.push(value);
  8560. return true;
  8561. };
  8562. SmartArrayNoDuplicate.prototype.reset = function () {
  8563. _super.prototype.reset.call(this);
  8564. this._duplicateId++;
  8565. };
  8566. SmartArrayNoDuplicate.prototype.concatWithNoDuplicate = function (array) {
  8567. if (array.length === 0) {
  8568. return;
  8569. }
  8570. if (this.length + array.length > this.data.length) {
  8571. this.data.length = (this.length + array.length) * 2;
  8572. }
  8573. for (var index = 0; index < array.length; index++) {
  8574. var item = (array.data || array)[index];
  8575. this.pushNoDuplicate(item);
  8576. }
  8577. };
  8578. return SmartArrayNoDuplicate;
  8579. }(SmartArray));
  8580. BABYLON.SmartArrayNoDuplicate = SmartArrayNoDuplicate;
  8581. })(BABYLON || (BABYLON = {}));
  8582. //# sourceMappingURL=babylon.smartArray.js.map
  8583. var BABYLON;
  8584. (function (BABYLON) {
  8585. /** Class used to store color gradient */
  8586. var ColorGradient = /** @class */ (function () {
  8587. function ColorGradient() {
  8588. }
  8589. /**
  8590. * Will get a color picked randomly between color1 and color2.
  8591. * If color2 is undefined then color1 will be used
  8592. * @param result defines the target Color4 to store the result in
  8593. */
  8594. ColorGradient.prototype.getColorToRef = function (result) {
  8595. if (!this.color2) {
  8596. result.copyFrom(this.color1);
  8597. return;
  8598. }
  8599. BABYLON.Color4.LerpToRef(this.color1, this.color2, Math.random(), result);
  8600. };
  8601. return ColorGradient;
  8602. }());
  8603. BABYLON.ColorGradient = ColorGradient;
  8604. /** Class used to store factor gradient */
  8605. var FactorGradient = /** @class */ (function () {
  8606. function FactorGradient() {
  8607. }
  8608. /**
  8609. * Will get a number picked randomly between factor1 and factor2.
  8610. * If factor2 is undefined then factor1 will be used
  8611. * @returns the picked number
  8612. */
  8613. FactorGradient.prototype.getFactor = function () {
  8614. if (this.factor2 === undefined) {
  8615. return this.factor1;
  8616. }
  8617. return BABYLON.Scalar.Lerp(this.factor1, this.factor2, Math.random());
  8618. };
  8619. return FactorGradient;
  8620. }());
  8621. BABYLON.FactorGradient = FactorGradient;
  8622. // See https://stackoverflow.com/questions/12915412/how-do-i-extend-a-host-object-e-g-error-in-typescript
  8623. // and https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work
  8624. var LoadFileError = /** @class */ (function (_super) {
  8625. __extends(LoadFileError, _super);
  8626. function LoadFileError(message, request) {
  8627. var _this = _super.call(this, message) || this;
  8628. _this.request = request;
  8629. _this.name = "LoadFileError";
  8630. LoadFileError._setPrototypeOf(_this, LoadFileError.prototype);
  8631. return _this;
  8632. }
  8633. // Polyfill for Object.setPrototypeOf if necessary.
  8634. LoadFileError._setPrototypeOf = Object.setPrototypeOf || (function (o, proto) { o.__proto__ = proto; return o; });
  8635. return LoadFileError;
  8636. }(Error));
  8637. BABYLON.LoadFileError = LoadFileError;
  8638. var RetryStrategy = /** @class */ (function () {
  8639. function RetryStrategy() {
  8640. }
  8641. RetryStrategy.ExponentialBackoff = function (maxRetries, baseInterval) {
  8642. if (maxRetries === void 0) { maxRetries = 3; }
  8643. if (baseInterval === void 0) { baseInterval = 500; }
  8644. return function (url, request, retryIndex) {
  8645. if (request.status !== 0 || retryIndex >= maxRetries || url.indexOf("file:") !== -1) {
  8646. return -1;
  8647. }
  8648. return Math.pow(2, retryIndex) * baseInterval;
  8649. };
  8650. };
  8651. return RetryStrategy;
  8652. }());
  8653. BABYLON.RetryStrategy = RetryStrategy;
  8654. // Screenshots
  8655. var screenshotCanvas;
  8656. var cloneValue = function (source, destinationObject) {
  8657. if (!source)
  8658. return null;
  8659. if (source instanceof BABYLON.Mesh) {
  8660. return null;
  8661. }
  8662. if (source instanceof BABYLON.SubMesh) {
  8663. return source.clone(destinationObject);
  8664. }
  8665. else if (source.clone) {
  8666. return source.clone();
  8667. }
  8668. return null;
  8669. };
  8670. var Tools = /** @class */ (function () {
  8671. function Tools() {
  8672. }
  8673. /**
  8674. * Interpolates between a and b via alpha
  8675. * @param a The lower value (returned when alpha = 0)
  8676. * @param b The upper value (returned when alpha = 1)
  8677. * @param alpha The interpolation-factor
  8678. * @return The mixed value
  8679. */
  8680. Tools.Mix = function (a, b, alpha) {
  8681. return a * (1 - alpha) + b * alpha;
  8682. };
  8683. Tools.Instantiate = function (className) {
  8684. if (Tools.RegisteredExternalClasses && Tools.RegisteredExternalClasses[className]) {
  8685. return Tools.RegisteredExternalClasses[className];
  8686. }
  8687. var arr = className.split(".");
  8688. var fn = (window || this);
  8689. for (var i = 0, len = arr.length; i < len; i++) {
  8690. fn = fn[arr[i]];
  8691. }
  8692. if (typeof fn !== "function") {
  8693. return null;
  8694. }
  8695. return fn;
  8696. };
  8697. /**
  8698. * Provides a slice function that will work even on IE
  8699. * @param data defines the array to slice
  8700. * @param start defines the start of the data (optional)
  8701. * @param end defines the end of the data (optional)
  8702. * @returns the new sliced array
  8703. */
  8704. Tools.Slice = function (data, start, end) {
  8705. if (data.slice) {
  8706. return data.slice(start, end);
  8707. }
  8708. return Array.prototype.slice.call(data, start, end);
  8709. };
  8710. Tools.SetImmediate = function (action) {
  8711. if (window.setImmediate) {
  8712. window.setImmediate(action);
  8713. }
  8714. else {
  8715. setTimeout(action, 1);
  8716. }
  8717. };
  8718. Tools.IsExponentOfTwo = function (value) {
  8719. var count = 1;
  8720. do {
  8721. count *= 2;
  8722. } while (count < value);
  8723. return count === value;
  8724. };
  8725. /**
  8726. * Returns the nearest 32-bit single precision float representation of a Number
  8727. * @param value A Number. If the parameter is of a different type, it will get converted
  8728. * to a number or to NaN if it cannot be converted
  8729. * @returns number
  8730. */
  8731. Tools.FloatRound = function (value) {
  8732. if (Math.fround) {
  8733. return Math.fround(value);
  8734. }
  8735. return (Tools._tmpFloatArray[0] = value);
  8736. };
  8737. /**
  8738. * Find the next highest power of two.
  8739. * @param x Number to start search from.
  8740. * @return Next highest power of two.
  8741. */
  8742. Tools.CeilingPOT = function (x) {
  8743. x--;
  8744. x |= x >> 1;
  8745. x |= x >> 2;
  8746. x |= x >> 4;
  8747. x |= x >> 8;
  8748. x |= x >> 16;
  8749. x++;
  8750. return x;
  8751. };
  8752. /**
  8753. * Find the next lowest power of two.
  8754. * @param x Number to start search from.
  8755. * @return Next lowest power of two.
  8756. */
  8757. Tools.FloorPOT = function (x) {
  8758. x = x | (x >> 1);
  8759. x = x | (x >> 2);
  8760. x = x | (x >> 4);
  8761. x = x | (x >> 8);
  8762. x = x | (x >> 16);
  8763. return x - (x >> 1);
  8764. };
  8765. /**
  8766. * Find the nearest power of two.
  8767. * @param x Number to start search from.
  8768. * @return Next nearest power of two.
  8769. */
  8770. Tools.NearestPOT = function (x) {
  8771. var c = Tools.CeilingPOT(x);
  8772. var f = Tools.FloorPOT(x);
  8773. return (c - x) > (x - f) ? f : c;
  8774. };
  8775. Tools.GetExponentOfTwo = function (value, max, mode) {
  8776. if (mode === void 0) { mode = BABYLON.Engine.SCALEMODE_NEAREST; }
  8777. var pot;
  8778. switch (mode) {
  8779. case BABYLON.Engine.SCALEMODE_FLOOR:
  8780. pot = Tools.FloorPOT(value);
  8781. break;
  8782. case BABYLON.Engine.SCALEMODE_NEAREST:
  8783. pot = Tools.NearestPOT(value);
  8784. break;
  8785. case BABYLON.Engine.SCALEMODE_CEILING:
  8786. default:
  8787. pot = Tools.CeilingPOT(value);
  8788. break;
  8789. }
  8790. return Math.min(pot, max);
  8791. };
  8792. Tools.GetFilename = function (path) {
  8793. var index = path.lastIndexOf("/");
  8794. if (index < 0)
  8795. return path;
  8796. return path.substring(index + 1);
  8797. };
  8798. /**
  8799. * Extracts the "folder" part of a path (everything before the filename).
  8800. * @param uri The URI to extract the info from
  8801. * @param returnUnchangedIfNoSlash Do not touch the URI if no slashes are present
  8802. * @returns The "folder" part of the path
  8803. */
  8804. Tools.GetFolderPath = function (uri, returnUnchangedIfNoSlash) {
  8805. if (returnUnchangedIfNoSlash === void 0) { returnUnchangedIfNoSlash = false; }
  8806. var index = uri.lastIndexOf("/");
  8807. if (index < 0) {
  8808. if (returnUnchangedIfNoSlash) {
  8809. return uri;
  8810. }
  8811. return "";
  8812. }
  8813. return uri.substring(0, index + 1);
  8814. };
  8815. Tools.GetDOMTextContent = function (element) {
  8816. var result = "";
  8817. var child = element.firstChild;
  8818. while (child) {
  8819. if (child.nodeType === 3) {
  8820. result += child.textContent;
  8821. }
  8822. child = child.nextSibling;
  8823. }
  8824. return result;
  8825. };
  8826. Tools.ToDegrees = function (angle) {
  8827. return angle * 180 / Math.PI;
  8828. };
  8829. Tools.ToRadians = function (angle) {
  8830. return angle * Math.PI / 180;
  8831. };
  8832. Tools.EncodeArrayBufferTobase64 = function (buffer) {
  8833. var keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  8834. var output = "";
  8835. var chr1, chr2, chr3, enc1, enc2, enc3, enc4;
  8836. var i = 0;
  8837. var bytes = new Uint8Array(buffer);
  8838. while (i < bytes.length) {
  8839. chr1 = bytes[i++];
  8840. chr2 = i < bytes.length ? bytes[i++] : Number.NaN; // Not sure if the index
  8841. chr3 = i < bytes.length ? bytes[i++] : Number.NaN; // checks are needed here
  8842. enc1 = chr1 >> 2;
  8843. enc2 = ((chr1 & 3) << 4) | (chr2 >> 4);
  8844. enc3 = ((chr2 & 15) << 2) | (chr3 >> 6);
  8845. enc4 = chr3 & 63;
  8846. if (isNaN(chr2)) {
  8847. enc3 = enc4 = 64;
  8848. }
  8849. else if (isNaN(chr3)) {
  8850. enc4 = 64;
  8851. }
  8852. output += keyStr.charAt(enc1) + keyStr.charAt(enc2) +
  8853. keyStr.charAt(enc3) + keyStr.charAt(enc4);
  8854. }
  8855. return "data:image/png;base64," + output;
  8856. };
  8857. Tools.ExtractMinAndMaxIndexed = function (positions, indices, indexStart, indexCount, bias) {
  8858. if (bias === void 0) { bias = null; }
  8859. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8860. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8861. for (var index = indexStart; index < indexStart + indexCount; index++) {
  8862. var current = new BABYLON.Vector3(positions[indices[index] * 3], positions[indices[index] * 3 + 1], positions[indices[index] * 3 + 2]);
  8863. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8864. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8865. }
  8866. if (bias) {
  8867. minimum.x -= minimum.x * bias.x + bias.y;
  8868. minimum.y -= minimum.y * bias.x + bias.y;
  8869. minimum.z -= minimum.z * bias.x + bias.y;
  8870. maximum.x += maximum.x * bias.x + bias.y;
  8871. maximum.y += maximum.y * bias.x + bias.y;
  8872. maximum.z += maximum.z * bias.x + bias.y;
  8873. }
  8874. return {
  8875. minimum: minimum,
  8876. maximum: maximum
  8877. };
  8878. };
  8879. Tools.ExtractMinAndMax = function (positions, start, count, bias, stride) {
  8880. if (bias === void 0) { bias = null; }
  8881. var minimum = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  8882. var maximum = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  8883. if (!stride) {
  8884. stride = 3;
  8885. }
  8886. for (var index = start; index < start + count; index++) {
  8887. var current = new BABYLON.Vector3(positions[index * stride], positions[index * stride + 1], positions[index * stride + 2]);
  8888. minimum = BABYLON.Vector3.Minimize(current, minimum);
  8889. maximum = BABYLON.Vector3.Maximize(current, maximum);
  8890. }
  8891. if (bias) {
  8892. minimum.x -= minimum.x * bias.x + bias.y;
  8893. minimum.y -= minimum.y * bias.x + bias.y;
  8894. minimum.z -= minimum.z * bias.x + bias.y;
  8895. maximum.x += maximum.x * bias.x + bias.y;
  8896. maximum.y += maximum.y * bias.x + bias.y;
  8897. maximum.z += maximum.z * bias.x + bias.y;
  8898. }
  8899. return {
  8900. minimum: minimum,
  8901. maximum: maximum
  8902. };
  8903. };
  8904. Tools.Vector2ArrayFeeder = function (array) {
  8905. return function (index) {
  8906. var isFloatArray = (array.BYTES_PER_ELEMENT !== undefined);
  8907. var length = isFloatArray ? array.length / 2 : array.length;
  8908. if (index >= length) {
  8909. return null;
  8910. }
  8911. if (isFloatArray) {
  8912. var fa = array;
  8913. return new BABYLON.Vector2(fa[index * 2 + 0], fa[index * 2 + 1]);
  8914. }
  8915. var a = array;
  8916. return a[index];
  8917. };
  8918. };
  8919. Tools.ExtractMinAndMaxVector2 = function (feeder, bias) {
  8920. if (bias === void 0) { bias = null; }
  8921. var minimum = new BABYLON.Vector2(Number.MAX_VALUE, Number.MAX_VALUE);
  8922. var maximum = new BABYLON.Vector2(-Number.MAX_VALUE, -Number.MAX_VALUE);
  8923. var i = 0;
  8924. var cur = feeder(i++);
  8925. while (cur) {
  8926. minimum = BABYLON.Vector2.Minimize(cur, minimum);
  8927. maximum = BABYLON.Vector2.Maximize(cur, maximum);
  8928. cur = feeder(i++);
  8929. }
  8930. if (bias) {
  8931. minimum.x -= minimum.x * bias.x + bias.y;
  8932. minimum.y -= minimum.y * bias.x + bias.y;
  8933. maximum.x += maximum.x * bias.x + bias.y;
  8934. maximum.y += maximum.y * bias.x + bias.y;
  8935. }
  8936. return {
  8937. minimum: minimum,
  8938. maximum: maximum
  8939. };
  8940. };
  8941. Tools.MakeArray = function (obj, allowsNullUndefined) {
  8942. if (allowsNullUndefined !== true && (obj === undefined || obj == null))
  8943. return null;
  8944. return Array.isArray(obj) ? obj : [obj];
  8945. };
  8946. // Misc.
  8947. Tools.GetPointerPrefix = function () {
  8948. var eventPrefix = "pointer";
  8949. // Check if pointer events are supported
  8950. if (Tools.IsWindowObjectExist() && !window.PointerEvent && !navigator.pointerEnabled) {
  8951. eventPrefix = "mouse";
  8952. }
  8953. return eventPrefix;
  8954. };
  8955. /**
  8956. * @param func - the function to be called
  8957. * @param requester - the object that will request the next frame. Falls back to window.
  8958. */
  8959. Tools.QueueNewFrame = function (func, requester) {
  8960. if (!Tools.IsWindowObjectExist()) {
  8961. return setTimeout(func, 16);
  8962. }
  8963. if (!requester) {
  8964. requester = window;
  8965. }
  8966. if (requester.requestAnimationFrame) {
  8967. return requester.requestAnimationFrame(func);
  8968. }
  8969. else if (requester.msRequestAnimationFrame) {
  8970. return requester.msRequestAnimationFrame(func);
  8971. }
  8972. else if (requester.webkitRequestAnimationFrame) {
  8973. return requester.webkitRequestAnimationFrame(func);
  8974. }
  8975. else if (requester.mozRequestAnimationFrame) {
  8976. return requester.mozRequestAnimationFrame(func);
  8977. }
  8978. else if (requester.oRequestAnimationFrame) {
  8979. return requester.oRequestAnimationFrame(func);
  8980. }
  8981. else {
  8982. return window.setTimeout(func, 16);
  8983. }
  8984. };
  8985. Tools.RequestFullscreen = function (element) {
  8986. var requestFunction = element.requestFullscreen || element.msRequestFullscreen || element.webkitRequestFullscreen || element.mozRequestFullScreen;
  8987. if (!requestFunction)
  8988. return;
  8989. requestFunction.call(element);
  8990. };
  8991. Tools.ExitFullscreen = function () {
  8992. if (document.exitFullscreen) {
  8993. document.exitFullscreen();
  8994. }
  8995. else if (document.mozCancelFullScreen) {
  8996. document.mozCancelFullScreen();
  8997. }
  8998. else if (document.webkitCancelFullScreen) {
  8999. document.webkitCancelFullScreen();
  9000. }
  9001. else if (document.msCancelFullScreen) {
  9002. document.msCancelFullScreen();
  9003. }
  9004. };
  9005. Tools.SetCorsBehavior = function (url, element) {
  9006. if (url && url.indexOf("data:") === 0) {
  9007. return;
  9008. }
  9009. if (Tools.CorsBehavior) {
  9010. if (typeof (Tools.CorsBehavior) === 'string' || Tools.CorsBehavior instanceof String) {
  9011. element.crossOrigin = Tools.CorsBehavior;
  9012. }
  9013. else {
  9014. var result = Tools.CorsBehavior(url);
  9015. if (result) {
  9016. element.crossOrigin = result;
  9017. }
  9018. }
  9019. }
  9020. };
  9021. // External files
  9022. Tools.CleanUrl = function (url) {
  9023. url = url.replace(/#/mg, "%23");
  9024. return url;
  9025. };
  9026. /**
  9027. * Loads an image as an HTMLImageElement.
  9028. * @param input url string, ArrayBuffer, or Blob to load
  9029. * @param onLoad callback called when the image successfully loads
  9030. * @param onError callback called when the image fails to load
  9031. * @param database database for caching
  9032. * @returns the HTMLImageElement of the loaded image
  9033. */
  9034. Tools.LoadImage = function (input, onLoad, onError, database) {
  9035. var url;
  9036. var usingObjectURL = false;
  9037. if (input instanceof ArrayBuffer) {
  9038. url = URL.createObjectURL(new Blob([input]));
  9039. usingObjectURL = true;
  9040. }
  9041. else if (input instanceof Blob) {
  9042. url = URL.createObjectURL(input);
  9043. usingObjectURL = true;
  9044. }
  9045. else {
  9046. url = Tools.CleanUrl(input);
  9047. url = Tools.PreprocessUrl(input);
  9048. }
  9049. var img = new Image();
  9050. Tools.SetCorsBehavior(url, img);
  9051. var loadHandler = function () {
  9052. if (usingObjectURL && img.src) {
  9053. URL.revokeObjectURL(img.src);
  9054. }
  9055. img.removeEventListener("load", loadHandler);
  9056. img.removeEventListener("error", errorHandler);
  9057. onLoad(img);
  9058. };
  9059. var errorHandler = function (err) {
  9060. if (usingObjectURL && img.src) {
  9061. URL.revokeObjectURL(img.src);
  9062. }
  9063. img.removeEventListener("load", loadHandler);
  9064. img.removeEventListener("error", errorHandler);
  9065. Tools.Error("Error while trying to load image: " + input);
  9066. if (onError) {
  9067. onError("Error while trying to load image: " + input, err);
  9068. }
  9069. };
  9070. img.addEventListener("load", loadHandler);
  9071. img.addEventListener("error", errorHandler);
  9072. var noIndexedDB = function () {
  9073. img.src = url;
  9074. };
  9075. var loadFromIndexedDB = function () {
  9076. if (database) {
  9077. database.loadImageFromDB(url, img);
  9078. }
  9079. };
  9080. //ANY database to do!
  9081. if (url.substr(0, 5) !== "data:" && database && database.enableTexturesOffline && BABYLON.Database.IsUASupportingBlobStorage) {
  9082. database.openAsync(loadFromIndexedDB, noIndexedDB);
  9083. }
  9084. else {
  9085. if (url.indexOf("file:") !== -1) {
  9086. var textureName = decodeURIComponent(url.substring(5).toLowerCase());
  9087. if (BABYLON.FilesInput.FilesToLoad[textureName]) {
  9088. try {
  9089. var blobURL;
  9090. try {
  9091. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName], { oneTimeOnly: true });
  9092. }
  9093. catch (ex) {
  9094. // Chrome doesn't support oneTimeOnly parameter
  9095. blobURL = URL.createObjectURL(BABYLON.FilesInput.FilesToLoad[textureName]);
  9096. }
  9097. img.src = blobURL;
  9098. usingObjectURL = true;
  9099. }
  9100. catch (e) {
  9101. img.src = "";
  9102. }
  9103. return img;
  9104. }
  9105. }
  9106. noIndexedDB();
  9107. }
  9108. return img;
  9109. };
  9110. Tools.LoadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  9111. url = Tools.CleanUrl(url);
  9112. url = Tools.PreprocessUrl(url);
  9113. // If file and file input are set
  9114. if (url.indexOf("file:") !== -1) {
  9115. var fileName = decodeURIComponent(url.substring(5).toLowerCase());
  9116. if (BABYLON.FilesInput.FilesToLoad[fileName]) {
  9117. return Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[fileName], onSuccess, onProgress, useArrayBuffer);
  9118. }
  9119. }
  9120. var loadUrl = Tools.BaseUrl + url;
  9121. var aborted = false;
  9122. var fileRequest = {
  9123. onCompleteObservable: new BABYLON.Observable(),
  9124. abort: function () { return aborted = true; },
  9125. };
  9126. var requestFile = function () {
  9127. var request = new XMLHttpRequest();
  9128. var retryHandle = null;
  9129. fileRequest.abort = function () {
  9130. aborted = true;
  9131. if (request.readyState !== (XMLHttpRequest.DONE || 4)) {
  9132. request.abort();
  9133. }
  9134. if (retryHandle !== null) {
  9135. clearTimeout(retryHandle);
  9136. retryHandle = null;
  9137. }
  9138. };
  9139. var retryLoop = function (retryIndex) {
  9140. request.open('GET', loadUrl, true);
  9141. if (useArrayBuffer) {
  9142. request.responseType = "arraybuffer";
  9143. }
  9144. if (onProgress) {
  9145. request.addEventListener("progress", onProgress);
  9146. }
  9147. var onLoadEnd = function () {
  9148. request.removeEventListener("loadend", onLoadEnd);
  9149. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9150. fileRequest.onCompleteObservable.clear();
  9151. };
  9152. request.addEventListener("loadend", onLoadEnd);
  9153. var onReadyStateChange = function () {
  9154. if (aborted) {
  9155. return;
  9156. }
  9157. // In case of undefined state in some browsers.
  9158. if (request.readyState === (XMLHttpRequest.DONE || 4)) {
  9159. // Some browsers have issues where onreadystatechange can be called multiple times with the same value.
  9160. request.removeEventListener("readystatechange", onReadyStateChange);
  9161. if (request.status >= 200 && request.status < 300 || (!Tools.IsWindowObjectExist() && (request.status === 0))) {
  9162. onSuccess(!useArrayBuffer ? request.responseText : request.response, request.responseURL);
  9163. return;
  9164. }
  9165. var retryStrategy = Tools.DefaultRetryStrategy;
  9166. if (retryStrategy) {
  9167. var waitTime = retryStrategy(loadUrl, request, retryIndex);
  9168. if (waitTime !== -1) {
  9169. // Prevent the request from completing for retry.
  9170. request.removeEventListener("loadend", onLoadEnd);
  9171. request = new XMLHttpRequest();
  9172. retryHandle = setTimeout(function () { return retryLoop(retryIndex + 1); }, waitTime);
  9173. return;
  9174. }
  9175. }
  9176. var e = new LoadFileError("Error status: " + request.status + " " + request.statusText + " - Unable to load " + loadUrl, request);
  9177. if (onError) {
  9178. onError(request, e);
  9179. }
  9180. else {
  9181. throw e;
  9182. }
  9183. }
  9184. };
  9185. request.addEventListener("readystatechange", onReadyStateChange);
  9186. request.send();
  9187. };
  9188. retryLoop(0);
  9189. };
  9190. // Caching all files
  9191. if (database && database.enableSceneOffline) {
  9192. var noIndexedDB_1 = function () {
  9193. if (!aborted) {
  9194. requestFile();
  9195. }
  9196. };
  9197. var loadFromIndexedDB = function () {
  9198. // TODO: database needs to support aborting and should return a IFileRequest
  9199. if (aborted) {
  9200. return;
  9201. }
  9202. if (database) {
  9203. database.loadFileFromDB(url, function (data) {
  9204. if (!aborted) {
  9205. onSuccess(data);
  9206. }
  9207. fileRequest.onCompleteObservable.notifyObservers(fileRequest);
  9208. }, onProgress ? function (event) {
  9209. if (!aborted) {
  9210. onProgress(event);
  9211. }
  9212. } : undefined, noIndexedDB_1, useArrayBuffer);
  9213. }
  9214. };
  9215. database.openAsync(loadFromIndexedDB, noIndexedDB_1);
  9216. }
  9217. else {
  9218. requestFile();
  9219. }
  9220. return fileRequest;
  9221. };
  9222. /**
  9223. * Load a script (identified by an url). When the url returns, the
  9224. * content of this file is added into a new script element, attached to the DOM (body element)
  9225. */
  9226. Tools.LoadScript = function (scriptUrl, onSuccess, onError) {
  9227. var head = document.getElementsByTagName('head')[0];
  9228. var script = document.createElement('script');
  9229. script.type = 'text/javascript';
  9230. script.src = scriptUrl;
  9231. script.onload = function () {
  9232. if (onSuccess) {
  9233. onSuccess();
  9234. }
  9235. };
  9236. script.onerror = function (e) {
  9237. if (onError) {
  9238. onError("Unable to load script '" + scriptUrl + "'", e);
  9239. }
  9240. };
  9241. head.appendChild(script);
  9242. };
  9243. Tools.ReadFileAsDataURL = function (fileToLoad, callback, progressCallback) {
  9244. var reader = new FileReader();
  9245. var request = {
  9246. onCompleteObservable: new BABYLON.Observable(),
  9247. abort: function () { return reader.abort(); },
  9248. };
  9249. reader.onloadend = function (e) {
  9250. request.onCompleteObservable.notifyObservers(request);
  9251. };
  9252. reader.onload = function (e) {
  9253. //target doesn't have result from ts 1.3
  9254. callback(e.target['result']);
  9255. };
  9256. reader.onprogress = progressCallback;
  9257. reader.readAsDataURL(fileToLoad);
  9258. return request;
  9259. };
  9260. Tools.ReadFile = function (fileToLoad, callback, progressCallBack, useArrayBuffer) {
  9261. var reader = new FileReader();
  9262. var request = {
  9263. onCompleteObservable: new BABYLON.Observable(),
  9264. abort: function () { return reader.abort(); },
  9265. };
  9266. reader.onloadend = function (e) { return request.onCompleteObservable.notifyObservers(request); };
  9267. reader.onerror = function (e) {
  9268. Tools.Log("Error while reading file: " + fileToLoad.name);
  9269. callback(JSON.stringify({ autoClear: true, clearColor: [1, 0, 0], ambientColor: [0, 0, 0], gravity: [0, -9.807, 0], meshes: [], cameras: [], lights: [] }));
  9270. };
  9271. reader.onload = function (e) {
  9272. //target doesn't have result from ts 1.3
  9273. callback(e.target['result']);
  9274. };
  9275. if (progressCallBack) {
  9276. reader.onprogress = progressCallBack;
  9277. }
  9278. if (!useArrayBuffer) {
  9279. // Asynchronous read
  9280. reader.readAsText(fileToLoad);
  9281. }
  9282. else {
  9283. reader.readAsArrayBuffer(fileToLoad);
  9284. }
  9285. return request;
  9286. };
  9287. //returns a downloadable url to a file content.
  9288. Tools.FileAsURL = function (content) {
  9289. var fileBlob = new Blob([content]);
  9290. var url = window.URL || window.webkitURL;
  9291. var link = url.createObjectURL(fileBlob);
  9292. return link;
  9293. };
  9294. // Misc.
  9295. Tools.Format = function (value, decimals) {
  9296. if (decimals === void 0) { decimals = 2; }
  9297. return value.toFixed(decimals);
  9298. };
  9299. Tools.CheckExtends = function (v, min, max) {
  9300. if (v.x < min.x)
  9301. min.x = v.x;
  9302. if (v.y < min.y)
  9303. min.y = v.y;
  9304. if (v.z < min.z)
  9305. min.z = v.z;
  9306. if (v.x > max.x)
  9307. max.x = v.x;
  9308. if (v.y > max.y)
  9309. max.y = v.y;
  9310. if (v.z > max.z)
  9311. max.z = v.z;
  9312. };
  9313. Tools.DeepCopy = function (source, destination, doNotCopyList, mustCopyList) {
  9314. for (var prop in source) {
  9315. if (prop[0] === "_" && (!mustCopyList || mustCopyList.indexOf(prop) === -1)) {
  9316. continue;
  9317. }
  9318. if (doNotCopyList && doNotCopyList.indexOf(prop) !== -1) {
  9319. continue;
  9320. }
  9321. var sourceValue = source[prop];
  9322. var typeOfSourceValue = typeof sourceValue;
  9323. if (typeOfSourceValue === "function") {
  9324. continue;
  9325. }
  9326. try {
  9327. if (typeOfSourceValue === "object") {
  9328. if (sourceValue instanceof Array) {
  9329. destination[prop] = [];
  9330. if (sourceValue.length > 0) {
  9331. if (typeof sourceValue[0] == "object") {
  9332. for (var index = 0; index < sourceValue.length; index++) {
  9333. var clonedValue = cloneValue(sourceValue[index], destination);
  9334. if (destination[prop].indexOf(clonedValue) === -1) { // Test if auto inject was not done
  9335. destination[prop].push(clonedValue);
  9336. }
  9337. }
  9338. }
  9339. else {
  9340. destination[prop] = sourceValue.slice(0);
  9341. }
  9342. }
  9343. }
  9344. else {
  9345. destination[prop] = cloneValue(sourceValue, destination);
  9346. }
  9347. }
  9348. else {
  9349. destination[prop] = sourceValue;
  9350. }
  9351. }
  9352. catch (e) {
  9353. // Just ignore error (it could be because of a read-only property)
  9354. }
  9355. }
  9356. };
  9357. Tools.IsEmpty = function (obj) {
  9358. for (var i in obj) {
  9359. if (obj.hasOwnProperty(i)) {
  9360. return false;
  9361. }
  9362. }
  9363. return true;
  9364. };
  9365. Tools.RegisterTopRootEvents = function (events) {
  9366. for (var index = 0; index < events.length; index++) {
  9367. var event = events[index];
  9368. window.addEventListener(event.name, event.handler, false);
  9369. try {
  9370. if (window.parent) {
  9371. window.parent.addEventListener(event.name, event.handler, false);
  9372. }
  9373. }
  9374. catch (e) {
  9375. // Silently fails...
  9376. }
  9377. }
  9378. };
  9379. Tools.UnregisterTopRootEvents = function (events) {
  9380. for (var index = 0; index < events.length; index++) {
  9381. var event = events[index];
  9382. window.removeEventListener(event.name, event.handler);
  9383. try {
  9384. if (window.parent) {
  9385. window.parent.removeEventListener(event.name, event.handler);
  9386. }
  9387. }
  9388. catch (e) {
  9389. // Silently fails...
  9390. }
  9391. }
  9392. };
  9393. Tools.DumpFramebuffer = function (width, height, engine, successCallback, mimeType, fileName) {
  9394. if (mimeType === void 0) { mimeType = "image/png"; }
  9395. // Read the contents of the framebuffer
  9396. var numberOfChannelsByLine = width * 4;
  9397. var halfHeight = height / 2;
  9398. //Reading datas from WebGL
  9399. var data = engine.readPixels(0, 0, width, height);
  9400. //To flip image on Y axis.
  9401. for (var i = 0; i < halfHeight; i++) {
  9402. for (var j = 0; j < numberOfChannelsByLine; j++) {
  9403. var currentCell = j + i * numberOfChannelsByLine;
  9404. var targetLine = height - i - 1;
  9405. var targetCell = j + targetLine * numberOfChannelsByLine;
  9406. var temp = data[currentCell];
  9407. data[currentCell] = data[targetCell];
  9408. data[targetCell] = temp;
  9409. }
  9410. }
  9411. // Create a 2D canvas to store the result
  9412. if (!screenshotCanvas) {
  9413. screenshotCanvas = document.createElement('canvas');
  9414. }
  9415. screenshotCanvas.width = width;
  9416. screenshotCanvas.height = height;
  9417. var context = screenshotCanvas.getContext('2d');
  9418. if (context) {
  9419. // Copy the pixels to a 2D canvas
  9420. var imageData = context.createImageData(width, height);
  9421. var castData = (imageData.data);
  9422. castData.set(data);
  9423. context.putImageData(imageData, 0, 0);
  9424. Tools.EncodeScreenshotCanvasData(successCallback, mimeType, fileName);
  9425. }
  9426. };
  9427. /**
  9428. * Converts the canvas data to blob.
  9429. * This acts as a polyfill for browsers not supporting the to blob function.
  9430. * @param canvas Defines the canvas to extract the data from
  9431. * @param successCallback Defines the callback triggered once the data are available
  9432. * @param mimeType Defines the mime type of the result
  9433. */
  9434. Tools.ToBlob = function (canvas, successCallback, mimeType) {
  9435. if (mimeType === void 0) { mimeType = "image/png"; }
  9436. // We need HTMLCanvasElement.toBlob for HD screenshots
  9437. if (!screenshotCanvas.toBlob) {
  9438. // low performance polyfill based on toDataURL (https://developer.mozilla.org/en-US/docs/Web/API/HTMLCanvasElement/toBlob)
  9439. screenshotCanvas.toBlob = function (callback, type, quality) {
  9440. var _this = this;
  9441. setTimeout(function () {
  9442. var binStr = atob(_this.toDataURL(type, quality).split(',')[1]), len = binStr.length, arr = new Uint8Array(len);
  9443. for (var i = 0; i < len; i++) {
  9444. arr[i] = binStr.charCodeAt(i);
  9445. }
  9446. callback(new Blob([arr]));
  9447. });
  9448. };
  9449. }
  9450. screenshotCanvas.toBlob(function (blob) {
  9451. successCallback(blob);
  9452. }, mimeType);
  9453. };
  9454. /**
  9455. * Encodes the canvas data to base 64 or automatically download the result if filename is defined
  9456. * @param successCallback Defines the callback triggered once the data are available
  9457. * @param mimeType Defines the mime type of the result
  9458. * @param fileName The filename to download. If present, the result will automatically be downloaded
  9459. */
  9460. Tools.EncodeScreenshotCanvasData = function (successCallback, mimeType, fileName) {
  9461. if (mimeType === void 0) { mimeType = "image/png"; }
  9462. if (successCallback) {
  9463. var base64Image = screenshotCanvas.toDataURL(mimeType);
  9464. successCallback(base64Image);
  9465. }
  9466. else {
  9467. this.ToBlob(screenshotCanvas, function (blob) {
  9468. //Creating a link if the browser have the download attribute on the a tag, to automatically start download generated image.
  9469. if (("download" in document.createElement("a"))) {
  9470. if (!fileName) {
  9471. var date = new Date();
  9472. var stringDate = (date.getFullYear() + "-" + (date.getMonth() + 1)).slice(2) + "-" + date.getDate() + "_" + date.getHours() + "-" + ('0' + date.getMinutes()).slice(-2);
  9473. fileName = "screenshot_" + stringDate + ".png";
  9474. }
  9475. Tools.Download(blob, fileName);
  9476. }
  9477. else {
  9478. var url = URL.createObjectURL(blob);
  9479. var newWindow = window.open("");
  9480. if (!newWindow)
  9481. return;
  9482. var img = newWindow.document.createElement("img");
  9483. img.onload = function () {
  9484. // no longer need to read the blob so it's revoked
  9485. URL.revokeObjectURL(url);
  9486. };
  9487. img.src = url;
  9488. newWindow.document.body.appendChild(img);
  9489. }
  9490. }, mimeType);
  9491. }
  9492. };
  9493. /**
  9494. * Downloads a blob in the browser
  9495. * @param blob defines the blob to download
  9496. * @param fileName defines the name of the downloaded file
  9497. */
  9498. Tools.Download = function (blob, fileName) {
  9499. var url = window.URL.createObjectURL(blob);
  9500. var a = document.createElement("a");
  9501. document.body.appendChild(a);
  9502. a.style.display = "none";
  9503. a.href = url;
  9504. a.download = fileName;
  9505. a.addEventListener("click", function () {
  9506. if (a.parentElement) {
  9507. a.parentElement.removeChild(a);
  9508. }
  9509. });
  9510. a.click();
  9511. window.URL.revokeObjectURL(url);
  9512. };
  9513. Tools.CreateScreenshot = function (engine, camera, size, successCallback, mimeType) {
  9514. if (mimeType === void 0) { mimeType = "image/png"; }
  9515. var width;
  9516. var height;
  9517. // If a precision value is specified
  9518. if (size.precision) {
  9519. width = Math.round(engine.getRenderWidth() * size.precision);
  9520. height = Math.round(width / engine.getAspectRatio(camera));
  9521. }
  9522. else if (size.width && size.height) {
  9523. width = size.width;
  9524. height = size.height;
  9525. }
  9526. //If passing only width, computing height to keep display canvas ratio.
  9527. else if (size.width && !size.height) {
  9528. width = size.width;
  9529. height = Math.round(width / engine.getAspectRatio(camera));
  9530. }
  9531. //If passing only height, computing width to keep display canvas ratio.
  9532. else if (size.height && !size.width) {
  9533. height = size.height;
  9534. width = Math.round(height * engine.getAspectRatio(camera));
  9535. }
  9536. //Assuming here that "size" parameter is a number
  9537. else if (!isNaN(size)) {
  9538. height = size;
  9539. width = size;
  9540. }
  9541. else {
  9542. Tools.Error("Invalid 'size' parameter !");
  9543. return;
  9544. }
  9545. if (!screenshotCanvas) {
  9546. screenshotCanvas = document.createElement('canvas');
  9547. }
  9548. screenshotCanvas.width = width;
  9549. screenshotCanvas.height = height;
  9550. var renderContext = screenshotCanvas.getContext("2d");
  9551. var ratio = engine.getRenderWidth() / engine.getRenderHeight();
  9552. var newWidth = width;
  9553. var newHeight = newWidth / ratio;
  9554. if (newHeight > height) {
  9555. newHeight = height;
  9556. newWidth = newHeight * ratio;
  9557. }
  9558. var offsetX = Math.max(0, width - newWidth) / 2;
  9559. var offsetY = Math.max(0, height - newHeight) / 2;
  9560. var renderingCanvas = engine.getRenderingCanvas();
  9561. if (renderContext && renderingCanvas) {
  9562. renderContext.drawImage(renderingCanvas, offsetX, offsetY, newWidth, newHeight);
  9563. }
  9564. Tools.EncodeScreenshotCanvasData(successCallback, mimeType);
  9565. };
  9566. /**
  9567. * Generates an image screenshot from the specified camera.
  9568. *
  9569. * @param engine The engine to use for rendering
  9570. * @param camera The camera to use for rendering
  9571. * @param size This parameter can be set to a single number or to an object with the
  9572. * following (optional) properties: precision, width, height. If a single number is passed,
  9573. * it will be used for both width and height. If an object is passed, the screenshot size
  9574. * will be derived from the parameters. The precision property is a multiplier allowing
  9575. * rendering at a higher or lower resolution.
  9576. * @param successCallback The callback receives a single parameter which contains the
  9577. * screenshot as a string of base64-encoded characters. This string can be assigned to the
  9578. * src parameter of an <img> to display it.
  9579. * @param mimeType The MIME type of the screenshot image (default: image/png).
  9580. * Check your browser for supported MIME types.
  9581. * @param samples Texture samples (default: 1)
  9582. * @param antialiasing Whether antialiasing should be turned on or not (default: false)
  9583. * @param fileName A name for for the downloaded file.
  9584. * @constructor
  9585. */
  9586. Tools.CreateScreenshotUsingRenderTarget = function (engine, camera, size, successCallback, mimeType, samples, antialiasing, fileName) {
  9587. if (mimeType === void 0) { mimeType = "image/png"; }
  9588. if (samples === void 0) { samples = 1; }
  9589. if (antialiasing === void 0) { antialiasing = false; }
  9590. var width;
  9591. var height;
  9592. //If a precision value is specified
  9593. if (size.precision) {
  9594. width = Math.round(engine.getRenderWidth() * size.precision);
  9595. height = Math.round(width / engine.getAspectRatio(camera));
  9596. size = { width: width, height: height };
  9597. }
  9598. else if (size.width && size.height) {
  9599. width = size.width;
  9600. height = size.height;
  9601. }
  9602. //If passing only width, computing height to keep display canvas ratio.
  9603. else if (size.width && !size.height) {
  9604. width = size.width;
  9605. height = Math.round(width / engine.getAspectRatio(camera));
  9606. size = { width: width, height: height };
  9607. }
  9608. //If passing only height, computing width to keep display canvas ratio.
  9609. else if (size.height && !size.width) {
  9610. height = size.height;
  9611. width = Math.round(height * engine.getAspectRatio(camera));
  9612. size = { width: width, height: height };
  9613. }
  9614. //Assuming here that "size" parameter is a number
  9615. else if (!isNaN(size)) {
  9616. height = size;
  9617. width = size;
  9618. }
  9619. else {
  9620. Tools.Error("Invalid 'size' parameter !");
  9621. return;
  9622. }
  9623. var scene = camera.getScene();
  9624. var previousCamera = null;
  9625. if (scene.activeCamera !== camera) {
  9626. previousCamera = scene.activeCamera;
  9627. scene.activeCamera = camera;
  9628. }
  9629. //At this point size can be a number, or an object (according to engine.prototype.createRenderTargetTexture method)
  9630. var texture = new BABYLON.RenderTargetTexture("screenShot", size, scene, false, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  9631. texture.renderList = null;
  9632. texture.samples = samples;
  9633. if (antialiasing) {
  9634. texture.addPostProcess(new BABYLON.FxaaPostProcess('antialiasing', 1.0, scene.activeCamera));
  9635. }
  9636. texture.onAfterRenderObservable.add(function () {
  9637. Tools.DumpFramebuffer(width, height, engine, successCallback, mimeType, fileName);
  9638. });
  9639. scene.incrementRenderId();
  9640. scene.resetCachedMaterial();
  9641. texture.render(true);
  9642. texture.dispose();
  9643. if (previousCamera) {
  9644. scene.activeCamera = previousCamera;
  9645. }
  9646. camera.getProjectionMatrix(true); // Force cache refresh;
  9647. };
  9648. // XHR response validator for local file scenario
  9649. Tools.ValidateXHRData = function (xhr, dataType) {
  9650. // 1 for text (.babylon, manifest and shaders), 2 for TGA, 4 for DDS, 7 for all
  9651. if (dataType === void 0) { dataType = 7; }
  9652. try {
  9653. if (dataType & 1) {
  9654. if (xhr.responseText && xhr.responseText.length > 0) {
  9655. return true;
  9656. }
  9657. else if (dataType === 1) {
  9658. return false;
  9659. }
  9660. }
  9661. if (dataType & 2) {
  9662. // Check header width and height since there is no "TGA" magic number
  9663. var tgaHeader = BABYLON.TGATools.GetTGAHeader(xhr.response);
  9664. if (tgaHeader.width && tgaHeader.height && tgaHeader.width > 0 && tgaHeader.height > 0) {
  9665. return true;
  9666. }
  9667. else if (dataType === 2) {
  9668. return false;
  9669. }
  9670. }
  9671. if (dataType & 4) {
  9672. // Check for the "DDS" magic number
  9673. var ddsHeader = new Uint8Array(xhr.response, 0, 3);
  9674. if (ddsHeader[0] === 68 && ddsHeader[1] === 68 && ddsHeader[2] === 83) {
  9675. return true;
  9676. }
  9677. else {
  9678. return false;
  9679. }
  9680. }
  9681. }
  9682. catch (e) {
  9683. // Global protection
  9684. }
  9685. return false;
  9686. };
  9687. /**
  9688. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  9689. * Be aware Math.random() could cause collisions, but:
  9690. * "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"
  9691. */
  9692. Tools.RandomId = function () {
  9693. return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
  9694. var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
  9695. return v.toString(16);
  9696. });
  9697. };
  9698. /**
  9699. * Test if the given uri is a base64 string.
  9700. * @param uri The uri to test
  9701. * @return True if the uri is a base64 string or false otherwise.
  9702. */
  9703. Tools.IsBase64 = function (uri) {
  9704. return uri.length < 5 ? false : uri.substr(0, 5) === "data:";
  9705. };
  9706. /**
  9707. * Decode the given base64 uri.
  9708. * @param uri The uri to decode
  9709. * @return The decoded base64 data.
  9710. */
  9711. Tools.DecodeBase64 = function (uri) {
  9712. var decodedString = atob(uri.split(",")[1]);
  9713. var bufferLength = decodedString.length;
  9714. var bufferView = new Uint8Array(new ArrayBuffer(bufferLength));
  9715. for (var i = 0; i < bufferLength; i++) {
  9716. bufferView[i] = decodedString.charCodeAt(i);
  9717. }
  9718. return bufferView.buffer;
  9719. };
  9720. Object.defineProperty(Tools, "NoneLogLevel", {
  9721. get: function () {
  9722. return Tools._NoneLogLevel;
  9723. },
  9724. enumerable: true,
  9725. configurable: true
  9726. });
  9727. Object.defineProperty(Tools, "MessageLogLevel", {
  9728. get: function () {
  9729. return Tools._MessageLogLevel;
  9730. },
  9731. enumerable: true,
  9732. configurable: true
  9733. });
  9734. Object.defineProperty(Tools, "WarningLogLevel", {
  9735. get: function () {
  9736. return Tools._WarningLogLevel;
  9737. },
  9738. enumerable: true,
  9739. configurable: true
  9740. });
  9741. Object.defineProperty(Tools, "ErrorLogLevel", {
  9742. get: function () {
  9743. return Tools._ErrorLogLevel;
  9744. },
  9745. enumerable: true,
  9746. configurable: true
  9747. });
  9748. Object.defineProperty(Tools, "AllLogLevel", {
  9749. get: function () {
  9750. return Tools._MessageLogLevel | Tools._WarningLogLevel | Tools._ErrorLogLevel;
  9751. },
  9752. enumerable: true,
  9753. configurable: true
  9754. });
  9755. Tools._AddLogEntry = function (entry) {
  9756. Tools._LogCache = entry + Tools._LogCache;
  9757. if (Tools.OnNewCacheEntry) {
  9758. Tools.OnNewCacheEntry(entry);
  9759. }
  9760. };
  9761. Tools._FormatMessage = function (message) {
  9762. var padStr = function (i) { return (i < 10) ? "0" + i : "" + i; };
  9763. var date = new Date();
  9764. return "[" + padStr(date.getHours()) + ":" + padStr(date.getMinutes()) + ":" + padStr(date.getSeconds()) + "]: " + message;
  9765. };
  9766. Tools._LogDisabled = function (message) {
  9767. // nothing to do
  9768. };
  9769. Tools._LogEnabled = function (message) {
  9770. var formattedMessage = Tools._FormatMessage(message);
  9771. console.log("BJS - " + formattedMessage);
  9772. var entry = "<div style='color:white'>" + formattedMessage + "</div><br>";
  9773. Tools._AddLogEntry(entry);
  9774. };
  9775. Tools._WarnDisabled = function (message) {
  9776. // nothing to do
  9777. };
  9778. Tools._WarnEnabled = function (message) {
  9779. var formattedMessage = Tools._FormatMessage(message);
  9780. console.warn("BJS - " + formattedMessage);
  9781. var entry = "<div style='color:orange'>" + formattedMessage + "</div><br>";
  9782. Tools._AddLogEntry(entry);
  9783. };
  9784. Tools._ErrorDisabled = function (message) {
  9785. // nothing to do
  9786. };
  9787. Tools._ErrorEnabled = function (message) {
  9788. Tools.errorsCount++;
  9789. var formattedMessage = Tools._FormatMessage(message);
  9790. console.error("BJS - " + formattedMessage);
  9791. var entry = "<div style='color:red'>" + formattedMessage + "</div><br>";
  9792. Tools._AddLogEntry(entry);
  9793. };
  9794. Object.defineProperty(Tools, "LogCache", {
  9795. get: function () {
  9796. return Tools._LogCache;
  9797. },
  9798. enumerable: true,
  9799. configurable: true
  9800. });
  9801. Tools.ClearLogCache = function () {
  9802. Tools._LogCache = "";
  9803. Tools.errorsCount = 0;
  9804. };
  9805. Object.defineProperty(Tools, "LogLevels", {
  9806. set: function (level) {
  9807. if ((level & Tools.MessageLogLevel) === Tools.MessageLogLevel) {
  9808. Tools.Log = Tools._LogEnabled;
  9809. }
  9810. else {
  9811. Tools.Log = Tools._LogDisabled;
  9812. }
  9813. if ((level & Tools.WarningLogLevel) === Tools.WarningLogLevel) {
  9814. Tools.Warn = Tools._WarnEnabled;
  9815. }
  9816. else {
  9817. Tools.Warn = Tools._WarnDisabled;
  9818. }
  9819. if ((level & Tools.ErrorLogLevel) === Tools.ErrorLogLevel) {
  9820. Tools.Error = Tools._ErrorEnabled;
  9821. }
  9822. else {
  9823. Tools.Error = Tools._ErrorDisabled;
  9824. }
  9825. },
  9826. enumerable: true,
  9827. configurable: true
  9828. });
  9829. Tools.IsWindowObjectExist = function () {
  9830. return (typeof window) !== "undefined";
  9831. };
  9832. Object.defineProperty(Tools, "PerformanceNoneLogLevel", {
  9833. get: function () {
  9834. return Tools._PerformanceNoneLogLevel;
  9835. },
  9836. enumerable: true,
  9837. configurable: true
  9838. });
  9839. Object.defineProperty(Tools, "PerformanceUserMarkLogLevel", {
  9840. get: function () {
  9841. return Tools._PerformanceUserMarkLogLevel;
  9842. },
  9843. enumerable: true,
  9844. configurable: true
  9845. });
  9846. Object.defineProperty(Tools, "PerformanceConsoleLogLevel", {
  9847. get: function () {
  9848. return Tools._PerformanceConsoleLogLevel;
  9849. },
  9850. enumerable: true,
  9851. configurable: true
  9852. });
  9853. Object.defineProperty(Tools, "PerformanceLogLevel", {
  9854. set: function (level) {
  9855. if ((level & Tools.PerformanceUserMarkLogLevel) === Tools.PerformanceUserMarkLogLevel) {
  9856. Tools.StartPerformanceCounter = Tools._StartUserMark;
  9857. Tools.EndPerformanceCounter = Tools._EndUserMark;
  9858. return;
  9859. }
  9860. if ((level & Tools.PerformanceConsoleLogLevel) === Tools.PerformanceConsoleLogLevel) {
  9861. Tools.StartPerformanceCounter = Tools._StartPerformanceConsole;
  9862. Tools.EndPerformanceCounter = Tools._EndPerformanceConsole;
  9863. return;
  9864. }
  9865. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  9866. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  9867. },
  9868. enumerable: true,
  9869. configurable: true
  9870. });
  9871. Tools._StartPerformanceCounterDisabled = function (counterName, condition) {
  9872. };
  9873. Tools._EndPerformanceCounterDisabled = function (counterName, condition) {
  9874. };
  9875. Tools._StartUserMark = function (counterName, condition) {
  9876. if (condition === void 0) { condition = true; }
  9877. if (!Tools._performance) {
  9878. if (!Tools.IsWindowObjectExist()) {
  9879. return;
  9880. }
  9881. Tools._performance = window.performance;
  9882. }
  9883. if (!condition || !Tools._performance.mark) {
  9884. return;
  9885. }
  9886. Tools._performance.mark(counterName + "-Begin");
  9887. };
  9888. Tools._EndUserMark = function (counterName, condition) {
  9889. if (condition === void 0) { condition = true; }
  9890. if (!condition || !Tools._performance.mark) {
  9891. return;
  9892. }
  9893. Tools._performance.mark(counterName + "-End");
  9894. Tools._performance.measure(counterName, counterName + "-Begin", counterName + "-End");
  9895. };
  9896. Tools._StartPerformanceConsole = function (counterName, condition) {
  9897. if (condition === void 0) { condition = true; }
  9898. if (!condition) {
  9899. return;
  9900. }
  9901. Tools._StartUserMark(counterName, condition);
  9902. if (console.time) {
  9903. console.time(counterName);
  9904. }
  9905. };
  9906. Tools._EndPerformanceConsole = function (counterName, condition) {
  9907. if (condition === void 0) { condition = true; }
  9908. if (!condition) {
  9909. return;
  9910. }
  9911. Tools._EndUserMark(counterName, condition);
  9912. if (console.time) {
  9913. console.timeEnd(counterName);
  9914. }
  9915. };
  9916. Object.defineProperty(Tools, "Now", {
  9917. get: function () {
  9918. if (Tools.IsWindowObjectExist() && window.performance && window.performance.now) {
  9919. return window.performance.now();
  9920. }
  9921. return Date.now();
  9922. },
  9923. enumerable: true,
  9924. configurable: true
  9925. });
  9926. /**
  9927. * This method will return the name of the class used to create the instance of the given object.
  9928. * It will works only on Javascript basic data types (number, string, ...) and instance of class declared with the @className decorator.
  9929. * @param object the object to get the class name from
  9930. * @return the name of the class, will be "object" for a custom data type not using the @className decorator
  9931. */
  9932. Tools.GetClassName = function (object, isType) {
  9933. if (isType === void 0) { isType = false; }
  9934. var name = null;
  9935. if (!isType && object.getClassName) {
  9936. name = object.getClassName();
  9937. }
  9938. else {
  9939. if (object instanceof Object) {
  9940. var classObj = isType ? object : Object.getPrototypeOf(object);
  9941. name = classObj.constructor["__bjsclassName__"];
  9942. }
  9943. if (!name) {
  9944. name = typeof object;
  9945. }
  9946. }
  9947. return name;
  9948. };
  9949. Tools.First = function (array, predicate) {
  9950. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  9951. var el = array_1[_i];
  9952. if (predicate(el)) {
  9953. return el;
  9954. }
  9955. }
  9956. return null;
  9957. };
  9958. /**
  9959. * This method will return the name of the full name of the class, including its owning module (if any).
  9960. * 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).
  9961. * @param object the object to get the class name from
  9962. * @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.
  9963. */
  9964. Tools.getFullClassName = function (object, isType) {
  9965. if (isType === void 0) { isType = false; }
  9966. var className = null;
  9967. var moduleName = null;
  9968. if (!isType && object.getClassName) {
  9969. className = object.getClassName();
  9970. }
  9971. else {
  9972. if (object instanceof Object) {
  9973. var classObj = isType ? object : Object.getPrototypeOf(object);
  9974. className = classObj.constructor["__bjsclassName__"];
  9975. moduleName = classObj.constructor["__bjsmoduleName__"];
  9976. }
  9977. if (!className) {
  9978. className = typeof object;
  9979. }
  9980. }
  9981. if (!className) {
  9982. return null;
  9983. }
  9984. return ((moduleName != null) ? (moduleName + ".") : "") + className;
  9985. };
  9986. /**
  9987. * 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.
  9988. * @param array
  9989. */
  9990. Tools.arrayOrStringFeeder = function (array) {
  9991. return function (index) {
  9992. if (index >= array.length) {
  9993. return null;
  9994. }
  9995. var val = array.charCodeAt ? array.charCodeAt(index) : array[index];
  9996. if (val && val.getHashCode) {
  9997. val = val.getHashCode();
  9998. }
  9999. if (typeof val === "string") {
  10000. return Tools.hashCodeFromStream(Tools.arrayOrStringFeeder(val));
  10001. }
  10002. return val;
  10003. };
  10004. };
  10005. /**
  10006. * Compute the hashCode of a stream of number
  10007. * To compute the HashCode on a string or an Array of data types implementing the getHashCode() method, use the arrayOrStringFeeder method.
  10008. * @param feeder a callback that will be called until it returns null, each valid returned values will be used to compute the hash code.
  10009. * @return the hash code computed
  10010. */
  10011. Tools.hashCodeFromStream = function (feeder) {
  10012. // Based from here: http://stackoverflow.com/a/7616484/802124
  10013. var hash = 0;
  10014. var index = 0;
  10015. var chr = feeder(index++);
  10016. while (chr != null) {
  10017. hash = ((hash << 5) - hash) + chr;
  10018. hash |= 0; // Convert to 32bit integer
  10019. chr = feeder(index++);
  10020. }
  10021. return hash;
  10022. };
  10023. /**
  10024. * Returns a promise that resolves after the given amount of time.
  10025. * @param delay Number of milliseconds to delay
  10026. * @returns Promise that resolves after the given amount of time
  10027. */
  10028. Tools.DelayAsync = function (delay) {
  10029. return new Promise(function (resolve) {
  10030. setTimeout(function () {
  10031. resolve();
  10032. }, delay);
  10033. });
  10034. };
  10035. /**
  10036. * Gets the current gradient from an array of IValueGradient
  10037. * @param ratio defines the current ratio to get
  10038. * @param gradients defines the array of IValueGradient
  10039. * @param updateFunc defines the callback function used to get the final value from the selected gradients
  10040. */
  10041. Tools.GetCurrentGradient = function (ratio, gradients, updateFunc) {
  10042. for (var gradientIndex = 0; gradientIndex < gradients.length - 1; gradientIndex++) {
  10043. var currentGradient = gradients[gradientIndex];
  10044. var nextGradient = gradients[gradientIndex + 1];
  10045. if (ratio >= currentGradient.gradient && ratio <= nextGradient.gradient) {
  10046. var scale = (ratio - currentGradient.gradient) / (nextGradient.gradient - currentGradient.gradient);
  10047. updateFunc(currentGradient, nextGradient, scale);
  10048. }
  10049. }
  10050. };
  10051. Tools.BaseUrl = "";
  10052. Tools.DefaultRetryStrategy = RetryStrategy.ExponentialBackoff();
  10053. /**
  10054. * Default behaviour for cors in the application.
  10055. * It can be a string if the expected behavior is identical in the entire app.
  10056. * Or a callback to be able to set it per url or on a group of them (in case of Video source for instance)
  10057. */
  10058. Tools.CorsBehavior = "anonymous";
  10059. Tools.UseFallbackTexture = true;
  10060. /**
  10061. * Use this object to register external classes like custom textures or material
  10062. * to allow the laoders to instantiate them
  10063. */
  10064. Tools.RegisteredExternalClasses = {};
  10065. // Used in case of a texture loading problem
  10066. 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";
  10067. Tools._tmpFloatArray = new Float32Array(1);
  10068. Tools.PreprocessUrl = function (url) {
  10069. return url;
  10070. };
  10071. // Logs
  10072. Tools._NoneLogLevel = 0;
  10073. Tools._MessageLogLevel = 1;
  10074. Tools._WarningLogLevel = 2;
  10075. Tools._ErrorLogLevel = 4;
  10076. Tools._LogCache = "";
  10077. Tools.errorsCount = 0;
  10078. Tools.Log = Tools._LogEnabled;
  10079. Tools.Warn = Tools._WarnEnabled;
  10080. Tools.Error = Tools._ErrorEnabled;
  10081. // Performances
  10082. Tools._PerformanceNoneLogLevel = 0;
  10083. Tools._PerformanceUserMarkLogLevel = 1;
  10084. Tools._PerformanceConsoleLogLevel = 2;
  10085. Tools.StartPerformanceCounter = Tools._StartPerformanceCounterDisabled;
  10086. Tools.EndPerformanceCounter = Tools._EndPerformanceCounterDisabled;
  10087. return Tools;
  10088. }());
  10089. BABYLON.Tools = Tools;
  10090. /**
  10091. * This class is used to track a performance counter which is number based.
  10092. * The user has access to many properties which give statistics of different nature
  10093. *
  10094. * The implementer can track two kinds of Performance Counter: time and count
  10095. * 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.
  10096. * 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.
  10097. */
  10098. var PerfCounter = /** @class */ (function () {
  10099. function PerfCounter() {
  10100. this._startMonitoringTime = 0;
  10101. this._min = 0;
  10102. this._max = 0;
  10103. this._average = 0;
  10104. this._lastSecAverage = 0;
  10105. this._current = 0;
  10106. this._totalValueCount = 0;
  10107. this._totalAccumulated = 0;
  10108. this._lastSecAccumulated = 0;
  10109. this._lastSecTime = 0;
  10110. this._lastSecValueCount = 0;
  10111. }
  10112. Object.defineProperty(PerfCounter.prototype, "min", {
  10113. /**
  10114. * Returns the smallest value ever
  10115. */
  10116. get: function () {
  10117. return this._min;
  10118. },
  10119. enumerable: true,
  10120. configurable: true
  10121. });
  10122. Object.defineProperty(PerfCounter.prototype, "max", {
  10123. /**
  10124. * Returns the biggest value ever
  10125. */
  10126. get: function () {
  10127. return this._max;
  10128. },
  10129. enumerable: true,
  10130. configurable: true
  10131. });
  10132. Object.defineProperty(PerfCounter.prototype, "average", {
  10133. /**
  10134. * Returns the average value since the performance counter is running
  10135. */
  10136. get: function () {
  10137. return this._average;
  10138. },
  10139. enumerable: true,
  10140. configurable: true
  10141. });
  10142. Object.defineProperty(PerfCounter.prototype, "lastSecAverage", {
  10143. /**
  10144. * Returns the average value of the last second the counter was monitored
  10145. */
  10146. get: function () {
  10147. return this._lastSecAverage;
  10148. },
  10149. enumerable: true,
  10150. configurable: true
  10151. });
  10152. Object.defineProperty(PerfCounter.prototype, "current", {
  10153. /**
  10154. * Returns the current value
  10155. */
  10156. get: function () {
  10157. return this._current;
  10158. },
  10159. enumerable: true,
  10160. configurable: true
  10161. });
  10162. Object.defineProperty(PerfCounter.prototype, "total", {
  10163. get: function () {
  10164. return this._totalAccumulated;
  10165. },
  10166. enumerable: true,
  10167. configurable: true
  10168. });
  10169. Object.defineProperty(PerfCounter.prototype, "count", {
  10170. get: function () {
  10171. return this._totalValueCount;
  10172. },
  10173. enumerable: true,
  10174. configurable: true
  10175. });
  10176. /**
  10177. * Call this method to start monitoring a new frame.
  10178. * 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.
  10179. */
  10180. PerfCounter.prototype.fetchNewFrame = function () {
  10181. this._totalValueCount++;
  10182. this._current = 0;
  10183. this._lastSecValueCount++;
  10184. };
  10185. /**
  10186. * Call this method to monitor a count of something (e.g. mesh drawn in viewport count)
  10187. * @param newCount the count value to add to the monitored count
  10188. * @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.
  10189. */
  10190. PerfCounter.prototype.addCount = function (newCount, fetchResult) {
  10191. if (!PerfCounter.Enabled) {
  10192. return;
  10193. }
  10194. this._current += newCount;
  10195. if (fetchResult) {
  10196. this._fetchResult();
  10197. }
  10198. };
  10199. /**
  10200. * Start monitoring this performance counter
  10201. */
  10202. PerfCounter.prototype.beginMonitoring = function () {
  10203. if (!PerfCounter.Enabled) {
  10204. return;
  10205. }
  10206. this._startMonitoringTime = Tools.Now;
  10207. };
  10208. /**
  10209. * Compute the time lapsed since the previous beginMonitoring() call.
  10210. * @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
  10211. */
  10212. PerfCounter.prototype.endMonitoring = function (newFrame) {
  10213. if (newFrame === void 0) { newFrame = true; }
  10214. if (!PerfCounter.Enabled) {
  10215. return;
  10216. }
  10217. if (newFrame) {
  10218. this.fetchNewFrame();
  10219. }
  10220. var currentTime = Tools.Now;
  10221. this._current = currentTime - this._startMonitoringTime;
  10222. if (newFrame) {
  10223. this._fetchResult();
  10224. }
  10225. };
  10226. PerfCounter.prototype._fetchResult = function () {
  10227. this._totalAccumulated += this._current;
  10228. this._lastSecAccumulated += this._current;
  10229. // Min/Max update
  10230. this._min = Math.min(this._min, this._current);
  10231. this._max = Math.max(this._max, this._current);
  10232. this._average = this._totalAccumulated / this._totalValueCount;
  10233. // Reset last sec?
  10234. var now = Tools.Now;
  10235. if ((now - this._lastSecTime) > 1000) {
  10236. this._lastSecAverage = this._lastSecAccumulated / this._lastSecValueCount;
  10237. this._lastSecTime = now;
  10238. this._lastSecAccumulated = 0;
  10239. this._lastSecValueCount = 0;
  10240. }
  10241. };
  10242. PerfCounter.Enabled = true;
  10243. return PerfCounter;
  10244. }());
  10245. BABYLON.PerfCounter = PerfCounter;
  10246. /**
  10247. * Use this className as a decorator on a given class definition to add it a name and optionally its module.
  10248. * You can then use the Tools.getClassName(obj) on an instance to retrieve its class name.
  10249. * This method is the only way to get it done in all cases, even if the .js file declaring the class is minified
  10250. * @param name The name of the class, case should be preserved
  10251. * @param module The name of the Module hosting the class, optional, but strongly recommended to specify if possible. Case should be preserved.
  10252. */
  10253. function className(name, module) {
  10254. return function (target) {
  10255. target["__bjsclassName__"] = name;
  10256. target["__bjsmoduleName__"] = (module != null) ? module : null;
  10257. };
  10258. }
  10259. BABYLON.className = className;
  10260. /**
  10261. * An implementation of a loop for asynchronous functions.
  10262. */
  10263. var AsyncLoop = /** @class */ (function () {
  10264. /**
  10265. * Constroctor.
  10266. * @param iterations the number of iterations.
  10267. * @param _fn the function to run each iteration
  10268. * @param _successCallback the callback that will be called upon succesful execution
  10269. * @param offset starting offset.
  10270. */
  10271. function AsyncLoop(iterations, _fn, _successCallback, offset) {
  10272. if (offset === void 0) { offset = 0; }
  10273. this.iterations = iterations;
  10274. this._fn = _fn;
  10275. this._successCallback = _successCallback;
  10276. this.index = offset - 1;
  10277. this._done = false;
  10278. }
  10279. /**
  10280. * Execute the next iteration. Must be called after the last iteration was finished.
  10281. */
  10282. AsyncLoop.prototype.executeNext = function () {
  10283. if (!this._done) {
  10284. if (this.index + 1 < this.iterations) {
  10285. ++this.index;
  10286. this._fn(this);
  10287. }
  10288. else {
  10289. this.breakLoop();
  10290. }
  10291. }
  10292. };
  10293. /**
  10294. * Break the loop and run the success callback.
  10295. */
  10296. AsyncLoop.prototype.breakLoop = function () {
  10297. this._done = true;
  10298. this._successCallback();
  10299. };
  10300. /**
  10301. * Helper function
  10302. */
  10303. AsyncLoop.Run = function (iterations, _fn, _successCallback, offset) {
  10304. if (offset === void 0) { offset = 0; }
  10305. var loop = new AsyncLoop(iterations, _fn, _successCallback, offset);
  10306. loop.executeNext();
  10307. return loop;
  10308. };
  10309. /**
  10310. * A for-loop that will run a given number of iterations synchronous and the rest async.
  10311. * @param iterations total number of iterations
  10312. * @param syncedIterations number of synchronous iterations in each async iteration.
  10313. * @param fn the function to call each iteration.
  10314. * @param callback a success call back that will be called when iterating stops.
  10315. * @param breakFunction a break condition (optional)
  10316. * @param timeout timeout settings for the setTimeout function. default - 0.
  10317. * @constructor
  10318. */
  10319. AsyncLoop.SyncAsyncForLoop = function (iterations, syncedIterations, fn, callback, breakFunction, timeout) {
  10320. if (timeout === void 0) { timeout = 0; }
  10321. AsyncLoop.Run(Math.ceil(iterations / syncedIterations), function (loop) {
  10322. if (breakFunction && breakFunction())
  10323. loop.breakLoop();
  10324. else {
  10325. setTimeout(function () {
  10326. for (var i = 0; i < syncedIterations; ++i) {
  10327. var iteration = (loop.index * syncedIterations) + i;
  10328. if (iteration >= iterations)
  10329. break;
  10330. fn(iteration);
  10331. if (breakFunction && breakFunction()) {
  10332. loop.breakLoop();
  10333. break;
  10334. }
  10335. }
  10336. loop.executeNext();
  10337. }, timeout);
  10338. }
  10339. }, callback);
  10340. };
  10341. return AsyncLoop;
  10342. }());
  10343. BABYLON.AsyncLoop = AsyncLoop;
  10344. })(BABYLON || (BABYLON = {}));
  10345. //# sourceMappingURL=babylon.tools.js.map
  10346. var BABYLON;
  10347. (function (BABYLON) {
  10348. var PromiseStates;
  10349. (function (PromiseStates) {
  10350. PromiseStates[PromiseStates["Pending"] = 0] = "Pending";
  10351. PromiseStates[PromiseStates["Fulfilled"] = 1] = "Fulfilled";
  10352. PromiseStates[PromiseStates["Rejected"] = 2] = "Rejected";
  10353. })(PromiseStates || (PromiseStates = {}));
  10354. var FulFillmentAgregator = /** @class */ (function () {
  10355. function FulFillmentAgregator() {
  10356. this.count = 0;
  10357. this.target = 0;
  10358. this.results = [];
  10359. }
  10360. return FulFillmentAgregator;
  10361. }());
  10362. var InternalPromise = /** @class */ (function () {
  10363. function InternalPromise(resolver) {
  10364. var _this = this;
  10365. this._state = PromiseStates.Pending;
  10366. this._children = new Array();
  10367. this._rejectWasConsumed = false;
  10368. if (!resolver) {
  10369. return;
  10370. }
  10371. try {
  10372. resolver(function (value) {
  10373. _this._resolve(value);
  10374. }, function (reason) {
  10375. _this._reject(reason);
  10376. });
  10377. }
  10378. catch (e) {
  10379. this._reject(e);
  10380. }
  10381. }
  10382. Object.defineProperty(InternalPromise.prototype, "_result", {
  10383. get: function () {
  10384. return this._resultValue;
  10385. },
  10386. set: function (value) {
  10387. this._resultValue = value;
  10388. if (this._parent && this._parent._result === undefined) {
  10389. this._parent._result = value;
  10390. }
  10391. },
  10392. enumerable: true,
  10393. configurable: true
  10394. });
  10395. InternalPromise.prototype.catch = function (onRejected) {
  10396. return this.then(undefined, onRejected);
  10397. };
  10398. InternalPromise.prototype.then = function (onFulfilled, onRejected) {
  10399. var _this = this;
  10400. var newPromise = new InternalPromise();
  10401. newPromise._onFulfilled = onFulfilled;
  10402. newPromise._onRejected = onRejected;
  10403. // Composition
  10404. this._children.push(newPromise);
  10405. newPromise._parent = this;
  10406. if (this._state !== PromiseStates.Pending) {
  10407. BABYLON.Tools.SetImmediate(function () {
  10408. if (_this._state === PromiseStates.Fulfilled || _this._rejectWasConsumed) {
  10409. var returnedValue = newPromise._resolve(_this._result);
  10410. if (returnedValue !== undefined && returnedValue !== null) {
  10411. if (returnedValue._state !== undefined) {
  10412. var returnedPromise = returnedValue;
  10413. newPromise._children.push(returnedPromise);
  10414. returnedPromise._parent = newPromise;
  10415. newPromise = returnedPromise;
  10416. }
  10417. else {
  10418. newPromise._result = returnedValue;
  10419. }
  10420. }
  10421. }
  10422. else {
  10423. newPromise._reject(_this._reason);
  10424. }
  10425. });
  10426. }
  10427. return newPromise;
  10428. };
  10429. InternalPromise.prototype._moveChildren = function (children) {
  10430. var _this = this;
  10431. (_a = this._children).push.apply(_a, children.splice(0, children.length));
  10432. this._children.forEach(function (child) {
  10433. child._parent = _this;
  10434. });
  10435. if (this._state === PromiseStates.Fulfilled) {
  10436. for (var _i = 0, _b = this._children; _i < _b.length; _i++) {
  10437. var child = _b[_i];
  10438. child._resolve(this._result);
  10439. }
  10440. }
  10441. else if (this._state === PromiseStates.Rejected) {
  10442. for (var _c = 0, _d = this._children; _c < _d.length; _c++) {
  10443. var child = _d[_c];
  10444. child._reject(this._reason);
  10445. }
  10446. }
  10447. var _a;
  10448. };
  10449. InternalPromise.prototype._resolve = function (value) {
  10450. try {
  10451. this._state = PromiseStates.Fulfilled;
  10452. var returnedValue = null;
  10453. if (this._onFulfilled) {
  10454. returnedValue = this._onFulfilled(value);
  10455. }
  10456. if (returnedValue !== undefined && returnedValue !== null) {
  10457. if (returnedValue._state !== undefined) {
  10458. // Transmit children
  10459. var returnedPromise = returnedValue;
  10460. returnedPromise._parent = this;
  10461. returnedPromise._moveChildren(this._children);
  10462. value = returnedPromise._result;
  10463. }
  10464. else {
  10465. value = returnedValue;
  10466. }
  10467. }
  10468. this._result = value;
  10469. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10470. var child = _a[_i];
  10471. child._resolve(value);
  10472. }
  10473. this._children.length = 0;
  10474. delete this._onFulfilled;
  10475. delete this._onRejected;
  10476. }
  10477. catch (e) {
  10478. this._reject(e, true);
  10479. }
  10480. };
  10481. InternalPromise.prototype._reject = function (reason, onLocalThrow) {
  10482. if (onLocalThrow === void 0) { onLocalThrow = false; }
  10483. this._state = PromiseStates.Rejected;
  10484. this._reason = reason;
  10485. if (this._onRejected && !onLocalThrow) {
  10486. try {
  10487. this._onRejected(reason);
  10488. this._rejectWasConsumed = true;
  10489. }
  10490. catch (e) {
  10491. reason = e;
  10492. }
  10493. }
  10494. for (var _i = 0, _a = this._children; _i < _a.length; _i++) {
  10495. var child = _a[_i];
  10496. if (this._rejectWasConsumed) {
  10497. child._resolve(null);
  10498. }
  10499. else {
  10500. child._reject(reason);
  10501. }
  10502. }
  10503. this._children.length = 0;
  10504. delete this._onFulfilled;
  10505. delete this._onRejected;
  10506. };
  10507. InternalPromise.resolve = function (value) {
  10508. var newPromise = new InternalPromise();
  10509. newPromise._resolve(value);
  10510. return newPromise;
  10511. };
  10512. InternalPromise._RegisterForFulfillment = function (promise, agregator, index) {
  10513. promise.then(function (value) {
  10514. agregator.results[index] = value;
  10515. agregator.count++;
  10516. if (agregator.count === agregator.target) {
  10517. agregator.rootPromise._resolve(agregator.results);
  10518. }
  10519. return null;
  10520. }, function (reason) {
  10521. if (agregator.rootPromise._state !== PromiseStates.Rejected) {
  10522. agregator.rootPromise._reject(reason);
  10523. }
  10524. });
  10525. };
  10526. InternalPromise.all = function (promises) {
  10527. var newPromise = new InternalPromise();
  10528. var agregator = new FulFillmentAgregator();
  10529. agregator.target = promises.length;
  10530. agregator.rootPromise = newPromise;
  10531. if (promises.length) {
  10532. for (var index = 0; index < promises.length; index++) {
  10533. InternalPromise._RegisterForFulfillment(promises[index], agregator, index);
  10534. }
  10535. }
  10536. else {
  10537. newPromise._resolve([]);
  10538. }
  10539. return newPromise;
  10540. };
  10541. InternalPromise.race = function (promises) {
  10542. var newPromise = new InternalPromise();
  10543. if (promises.length) {
  10544. for (var _i = 0, promises_1 = promises; _i < promises_1.length; _i++) {
  10545. var promise = promises_1[_i];
  10546. promise.then(function (value) {
  10547. if (newPromise) {
  10548. newPromise._resolve(value);
  10549. newPromise = null;
  10550. }
  10551. return null;
  10552. }, function (reason) {
  10553. if (newPromise) {
  10554. newPromise._reject(reason);
  10555. newPromise = null;
  10556. }
  10557. });
  10558. }
  10559. }
  10560. return newPromise;
  10561. };
  10562. return InternalPromise;
  10563. }());
  10564. /**
  10565. * Helper class that provides a small promise polyfill
  10566. */
  10567. var PromisePolyfill = /** @class */ (function () {
  10568. function PromisePolyfill() {
  10569. }
  10570. /**
  10571. * Static function used to check if the polyfill is required
  10572. * If this is the case then the function will inject the polyfill to window.Promise
  10573. * @param force defines a boolean used to force the injection (mostly for testing purposes)
  10574. */
  10575. PromisePolyfill.Apply = function (force) {
  10576. if (force === void 0) { force = false; }
  10577. if (force || typeof Promise === 'undefined') {
  10578. var root = window;
  10579. root.Promise = InternalPromise;
  10580. }
  10581. };
  10582. return PromisePolyfill;
  10583. }());
  10584. BABYLON.PromisePolyfill = PromisePolyfill;
  10585. })(BABYLON || (BABYLON = {}));
  10586. //# sourceMappingURL=babylon.promise.js.map
  10587. /// <reference path="../../../dist/preview release/babylon.d.ts" />
  10588. var BABYLON;
  10589. (function (BABYLON) {
  10590. /**
  10591. * Helper class to push actions to a pool of workers.
  10592. */
  10593. var WorkerPool = /** @class */ (function () {
  10594. /**
  10595. * Constructor
  10596. * @param workers Array of workers to use for actions
  10597. */
  10598. function WorkerPool(workers) {
  10599. this._pendingActions = new Array();
  10600. this._workerInfos = workers.map(function (worker) { return ({
  10601. worker: worker,
  10602. active: false
  10603. }); });
  10604. }
  10605. /**
  10606. * Terminates all workers and clears any pending actions.
  10607. */
  10608. WorkerPool.prototype.dispose = function () {
  10609. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10610. var workerInfo = _a[_i];
  10611. workerInfo.worker.terminate();
  10612. }
  10613. delete this._workerInfos;
  10614. delete this._pendingActions;
  10615. };
  10616. /**
  10617. * Pushes an action to the worker pool. If all the workers are active, the action will be
  10618. * pended until a worker has completed its action.
  10619. * @param action The action to perform. Call onComplete when the action is complete.
  10620. */
  10621. WorkerPool.prototype.push = function (action) {
  10622. for (var _i = 0, _a = this._workerInfos; _i < _a.length; _i++) {
  10623. var workerInfo = _a[_i];
  10624. if (!workerInfo.active) {
  10625. this._execute(workerInfo, action);
  10626. return;
  10627. }
  10628. }
  10629. this._pendingActions.push(action);
  10630. };
  10631. WorkerPool.prototype._execute = function (workerInfo, action) {
  10632. var _this = this;
  10633. workerInfo.active = true;
  10634. action(workerInfo.worker, function () {
  10635. workerInfo.active = false;
  10636. var nextAction = _this._pendingActions.shift();
  10637. if (nextAction) {
  10638. _this._execute(workerInfo, nextAction);
  10639. }
  10640. });
  10641. };
  10642. return WorkerPool;
  10643. }());
  10644. BABYLON.WorkerPool = WorkerPool;
  10645. })(BABYLON || (BABYLON = {}));
  10646. //# sourceMappingURL=babylon.workerPool.js.map
  10647. var BABYLON;
  10648. (function (BABYLON) {
  10649. /**
  10650. * @hidden
  10651. **/
  10652. var _AlphaState = /** @class */ (function () {
  10653. /**
  10654. * Initializes the state.
  10655. */
  10656. function _AlphaState() {
  10657. this._isAlphaBlendDirty = false;
  10658. this._isBlendFunctionParametersDirty = false;
  10659. this._isBlendEquationParametersDirty = false;
  10660. this._isBlendConstantsDirty = false;
  10661. this._alphaBlend = false;
  10662. this._blendFunctionParameters = new Array(4);
  10663. this._blendEquationParameters = new Array(2);
  10664. this._blendConstants = new Array(4);
  10665. this.reset();
  10666. }
  10667. Object.defineProperty(_AlphaState.prototype, "isDirty", {
  10668. get: function () {
  10669. return this._isAlphaBlendDirty || this._isBlendFunctionParametersDirty;
  10670. },
  10671. enumerable: true,
  10672. configurable: true
  10673. });
  10674. Object.defineProperty(_AlphaState.prototype, "alphaBlend", {
  10675. get: function () {
  10676. return this._alphaBlend;
  10677. },
  10678. set: function (value) {
  10679. if (this._alphaBlend === value) {
  10680. return;
  10681. }
  10682. this._alphaBlend = value;
  10683. this._isAlphaBlendDirty = true;
  10684. },
  10685. enumerable: true,
  10686. configurable: true
  10687. });
  10688. _AlphaState.prototype.setAlphaBlendConstants = function (r, g, b, a) {
  10689. if (this._blendConstants[0] === r &&
  10690. this._blendConstants[1] === g &&
  10691. this._blendConstants[2] === b &&
  10692. this._blendConstants[3] === a) {
  10693. return;
  10694. }
  10695. this._blendConstants[0] = r;
  10696. this._blendConstants[1] = g;
  10697. this._blendConstants[2] = b;
  10698. this._blendConstants[3] = a;
  10699. this._isBlendConstantsDirty = true;
  10700. };
  10701. _AlphaState.prototype.setAlphaBlendFunctionParameters = function (value0, value1, value2, value3) {
  10702. if (this._blendFunctionParameters[0] === value0 &&
  10703. this._blendFunctionParameters[1] === value1 &&
  10704. this._blendFunctionParameters[2] === value2 &&
  10705. this._blendFunctionParameters[3] === value3) {
  10706. return;
  10707. }
  10708. this._blendFunctionParameters[0] = value0;
  10709. this._blendFunctionParameters[1] = value1;
  10710. this._blendFunctionParameters[2] = value2;
  10711. this._blendFunctionParameters[3] = value3;
  10712. this._isBlendFunctionParametersDirty = true;
  10713. };
  10714. _AlphaState.prototype.setAlphaEquationParameters = function (rgb, alpha) {
  10715. if (this._blendEquationParameters[0] === rgb &&
  10716. this._blendEquationParameters[1] === alpha) {
  10717. return;
  10718. }
  10719. this._blendEquationParameters[0] = rgb;
  10720. this._blendEquationParameters[1] = alpha;
  10721. this._isBlendEquationParametersDirty = true;
  10722. };
  10723. _AlphaState.prototype.reset = function () {
  10724. this._alphaBlend = false;
  10725. this._blendFunctionParameters[0] = null;
  10726. this._blendFunctionParameters[1] = null;
  10727. this._blendFunctionParameters[2] = null;
  10728. this._blendFunctionParameters[3] = null;
  10729. this._blendEquationParameters[0] = null;
  10730. this._blendEquationParameters[1] = null;
  10731. this._blendConstants[0] = null;
  10732. this._blendConstants[1] = null;
  10733. this._blendConstants[2] = null;
  10734. this._blendConstants[3] = null;
  10735. this._isAlphaBlendDirty = true;
  10736. this._isBlendFunctionParametersDirty = false;
  10737. this._isBlendEquationParametersDirty = false;
  10738. this._isBlendConstantsDirty = false;
  10739. };
  10740. _AlphaState.prototype.apply = function (gl) {
  10741. if (!this.isDirty) {
  10742. return;
  10743. }
  10744. // Alpha blend
  10745. if (this._isAlphaBlendDirty) {
  10746. if (this._alphaBlend) {
  10747. gl.enable(gl.BLEND);
  10748. }
  10749. else {
  10750. gl.disable(gl.BLEND);
  10751. }
  10752. this._isAlphaBlendDirty = false;
  10753. }
  10754. // Alpha function
  10755. if (this._isBlendFunctionParametersDirty) {
  10756. gl.blendFuncSeparate(this._blendFunctionParameters[0], this._blendFunctionParameters[1], this._blendFunctionParameters[2], this._blendFunctionParameters[3]);
  10757. this._isBlendFunctionParametersDirty = false;
  10758. }
  10759. // Alpha equation
  10760. if (this._isBlendEquationParametersDirty) {
  10761. gl.blendEquationSeparate(this._isBlendEquationParametersDirty[0], this._isBlendEquationParametersDirty[1]);
  10762. this._isBlendEquationParametersDirty = false;
  10763. }
  10764. // Constants
  10765. if (this._isBlendConstantsDirty) {
  10766. gl.blendColor(this._blendConstants[0], this._blendConstants[1], this._blendConstants[2], this._blendConstants[3]);
  10767. this._isBlendConstantsDirty = false;
  10768. }
  10769. };
  10770. return _AlphaState;
  10771. }());
  10772. BABYLON._AlphaState = _AlphaState;
  10773. })(BABYLON || (BABYLON = {}));
  10774. //# sourceMappingURL=babylon.alphaCullingState.js.map
  10775. var BABYLON;
  10776. (function (BABYLON) {
  10777. /**
  10778. * @hidden
  10779. **/
  10780. var _DepthCullingState = /** @class */ (function () {
  10781. /**
  10782. * Initializes the state.
  10783. */
  10784. function _DepthCullingState() {
  10785. this._isDepthTestDirty = false;
  10786. this._isDepthMaskDirty = false;
  10787. this._isDepthFuncDirty = false;
  10788. this._isCullFaceDirty = false;
  10789. this._isCullDirty = false;
  10790. this._isZOffsetDirty = false;
  10791. this._isFrontFaceDirty = false;
  10792. this.reset();
  10793. }
  10794. Object.defineProperty(_DepthCullingState.prototype, "isDirty", {
  10795. get: function () {
  10796. return this._isDepthFuncDirty || this._isDepthTestDirty || this._isDepthMaskDirty || this._isCullFaceDirty || this._isCullDirty || this._isZOffsetDirty || this._isFrontFaceDirty;
  10797. },
  10798. enumerable: true,
  10799. configurable: true
  10800. });
  10801. Object.defineProperty(_DepthCullingState.prototype, "zOffset", {
  10802. get: function () {
  10803. return this._zOffset;
  10804. },
  10805. set: function (value) {
  10806. if (this._zOffset === value) {
  10807. return;
  10808. }
  10809. this._zOffset = value;
  10810. this._isZOffsetDirty = true;
  10811. },
  10812. enumerable: true,
  10813. configurable: true
  10814. });
  10815. Object.defineProperty(_DepthCullingState.prototype, "cullFace", {
  10816. get: function () {
  10817. return this._cullFace;
  10818. },
  10819. set: function (value) {
  10820. if (this._cullFace === value) {
  10821. return;
  10822. }
  10823. this._cullFace = value;
  10824. this._isCullFaceDirty = true;
  10825. },
  10826. enumerable: true,
  10827. configurable: true
  10828. });
  10829. Object.defineProperty(_DepthCullingState.prototype, "cull", {
  10830. get: function () {
  10831. return this._cull;
  10832. },
  10833. set: function (value) {
  10834. if (this._cull === value) {
  10835. return;
  10836. }
  10837. this._cull = value;
  10838. this._isCullDirty = true;
  10839. },
  10840. enumerable: true,
  10841. configurable: true
  10842. });
  10843. Object.defineProperty(_DepthCullingState.prototype, "depthFunc", {
  10844. get: function () {
  10845. return this._depthFunc;
  10846. },
  10847. set: function (value) {
  10848. if (this._depthFunc === value) {
  10849. return;
  10850. }
  10851. this._depthFunc = value;
  10852. this._isDepthFuncDirty = true;
  10853. },
  10854. enumerable: true,
  10855. configurable: true
  10856. });
  10857. Object.defineProperty(_DepthCullingState.prototype, "depthMask", {
  10858. get: function () {
  10859. return this._depthMask;
  10860. },
  10861. set: function (value) {
  10862. if (this._depthMask === value) {
  10863. return;
  10864. }
  10865. this._depthMask = value;
  10866. this._isDepthMaskDirty = true;
  10867. },
  10868. enumerable: true,
  10869. configurable: true
  10870. });
  10871. Object.defineProperty(_DepthCullingState.prototype, "depthTest", {
  10872. get: function () {
  10873. return this._depthTest;
  10874. },
  10875. set: function (value) {
  10876. if (this._depthTest === value) {
  10877. return;
  10878. }
  10879. this._depthTest = value;
  10880. this._isDepthTestDirty = true;
  10881. },
  10882. enumerable: true,
  10883. configurable: true
  10884. });
  10885. Object.defineProperty(_DepthCullingState.prototype, "frontFace", {
  10886. get: function () {
  10887. return this._frontFace;
  10888. },
  10889. set: function (value) {
  10890. if (this._frontFace === value) {
  10891. return;
  10892. }
  10893. this._frontFace = value;
  10894. this._isFrontFaceDirty = true;
  10895. },
  10896. enumerable: true,
  10897. configurable: true
  10898. });
  10899. _DepthCullingState.prototype.reset = function () {
  10900. this._depthMask = true;
  10901. this._depthTest = true;
  10902. this._depthFunc = null;
  10903. this._cullFace = null;
  10904. this._cull = null;
  10905. this._zOffset = 0;
  10906. this._frontFace = null;
  10907. this._isDepthTestDirty = true;
  10908. this._isDepthMaskDirty = true;
  10909. this._isDepthFuncDirty = false;
  10910. this._isCullFaceDirty = false;
  10911. this._isCullDirty = false;
  10912. this._isZOffsetDirty = false;
  10913. this._isFrontFaceDirty = false;
  10914. };
  10915. _DepthCullingState.prototype.apply = function (gl) {
  10916. if (!this.isDirty) {
  10917. return;
  10918. }
  10919. // Cull
  10920. if (this._isCullDirty) {
  10921. if (this.cull) {
  10922. gl.enable(gl.CULL_FACE);
  10923. }
  10924. else {
  10925. gl.disable(gl.CULL_FACE);
  10926. }
  10927. this._isCullDirty = false;
  10928. }
  10929. // Cull face
  10930. if (this._isCullFaceDirty) {
  10931. gl.cullFace(this.cullFace);
  10932. this._isCullFaceDirty = false;
  10933. }
  10934. // Depth mask
  10935. if (this._isDepthMaskDirty) {
  10936. gl.depthMask(this.depthMask);
  10937. this._isDepthMaskDirty = false;
  10938. }
  10939. // Depth test
  10940. if (this._isDepthTestDirty) {
  10941. if (this.depthTest) {
  10942. gl.enable(gl.DEPTH_TEST);
  10943. }
  10944. else {
  10945. gl.disable(gl.DEPTH_TEST);
  10946. }
  10947. this._isDepthTestDirty = false;
  10948. }
  10949. // Depth func
  10950. if (this._isDepthFuncDirty) {
  10951. gl.depthFunc(this.depthFunc);
  10952. this._isDepthFuncDirty = false;
  10953. }
  10954. // zOffset
  10955. if (this._isZOffsetDirty) {
  10956. if (this.zOffset) {
  10957. gl.enable(gl.POLYGON_OFFSET_FILL);
  10958. gl.polygonOffset(this.zOffset, 0);
  10959. }
  10960. else {
  10961. gl.disable(gl.POLYGON_OFFSET_FILL);
  10962. }
  10963. this._isZOffsetDirty = false;
  10964. }
  10965. // Front face
  10966. if (this._isFrontFaceDirty) {
  10967. gl.frontFace(this.frontFace);
  10968. this._isFrontFaceDirty = false;
  10969. }
  10970. };
  10971. return _DepthCullingState;
  10972. }());
  10973. BABYLON._DepthCullingState = _DepthCullingState;
  10974. })(BABYLON || (BABYLON = {}));
  10975. //# sourceMappingURL=babylon.depthCullingState.js.map
  10976. var BABYLON;
  10977. (function (BABYLON) {
  10978. /**
  10979. * @hidden
  10980. **/
  10981. var _StencilState = /** @class */ (function () {
  10982. function _StencilState() {
  10983. this._isStencilTestDirty = false;
  10984. this._isStencilMaskDirty = false;
  10985. this._isStencilFuncDirty = false;
  10986. this._isStencilOpDirty = false;
  10987. this.reset();
  10988. }
  10989. Object.defineProperty(_StencilState.prototype, "isDirty", {
  10990. get: function () {
  10991. return this._isStencilTestDirty || this._isStencilMaskDirty || this._isStencilFuncDirty || this._isStencilOpDirty;
  10992. },
  10993. enumerable: true,
  10994. configurable: true
  10995. });
  10996. Object.defineProperty(_StencilState.prototype, "stencilFunc", {
  10997. get: function () {
  10998. return this._stencilFunc;
  10999. },
  11000. set: function (value) {
  11001. if (this._stencilFunc === value) {
  11002. return;
  11003. }
  11004. this._stencilFunc = value;
  11005. this._isStencilFuncDirty = true;
  11006. },
  11007. enumerable: true,
  11008. configurable: true
  11009. });
  11010. Object.defineProperty(_StencilState.prototype, "stencilFuncRef", {
  11011. get: function () {
  11012. return this._stencilFuncRef;
  11013. },
  11014. set: function (value) {
  11015. if (this._stencilFuncRef === value) {
  11016. return;
  11017. }
  11018. this._stencilFuncRef = value;
  11019. this._isStencilFuncDirty = true;
  11020. },
  11021. enumerable: true,
  11022. configurable: true
  11023. });
  11024. Object.defineProperty(_StencilState.prototype, "stencilFuncMask", {
  11025. get: function () {
  11026. return this._stencilFuncMask;
  11027. },
  11028. set: function (value) {
  11029. if (this._stencilFuncMask === value) {
  11030. return;
  11031. }
  11032. this._stencilFuncMask = value;
  11033. this._isStencilFuncDirty = true;
  11034. },
  11035. enumerable: true,
  11036. configurable: true
  11037. });
  11038. Object.defineProperty(_StencilState.prototype, "stencilOpStencilFail", {
  11039. get: function () {
  11040. return this._stencilOpStencilFail;
  11041. },
  11042. set: function (value) {
  11043. if (this._stencilOpStencilFail === value) {
  11044. return;
  11045. }
  11046. this._stencilOpStencilFail = value;
  11047. this._isStencilOpDirty = true;
  11048. },
  11049. enumerable: true,
  11050. configurable: true
  11051. });
  11052. Object.defineProperty(_StencilState.prototype, "stencilOpDepthFail", {
  11053. get: function () {
  11054. return this._stencilOpDepthFail;
  11055. },
  11056. set: function (value) {
  11057. if (this._stencilOpDepthFail === value) {
  11058. return;
  11059. }
  11060. this._stencilOpDepthFail = value;
  11061. this._isStencilOpDirty = true;
  11062. },
  11063. enumerable: true,
  11064. configurable: true
  11065. });
  11066. Object.defineProperty(_StencilState.prototype, "stencilOpStencilDepthPass", {
  11067. get: function () {
  11068. return this._stencilOpStencilDepthPass;
  11069. },
  11070. set: function (value) {
  11071. if (this._stencilOpStencilDepthPass === value) {
  11072. return;
  11073. }
  11074. this._stencilOpStencilDepthPass = value;
  11075. this._isStencilOpDirty = true;
  11076. },
  11077. enumerable: true,
  11078. configurable: true
  11079. });
  11080. Object.defineProperty(_StencilState.prototype, "stencilMask", {
  11081. get: function () {
  11082. return this._stencilMask;
  11083. },
  11084. set: function (value) {
  11085. if (this._stencilMask === value) {
  11086. return;
  11087. }
  11088. this._stencilMask = value;
  11089. this._isStencilMaskDirty = true;
  11090. },
  11091. enumerable: true,
  11092. configurable: true
  11093. });
  11094. Object.defineProperty(_StencilState.prototype, "stencilTest", {
  11095. get: function () {
  11096. return this._stencilTest;
  11097. },
  11098. set: function (value) {
  11099. if (this._stencilTest === value) {
  11100. return;
  11101. }
  11102. this._stencilTest = value;
  11103. this._isStencilTestDirty = true;
  11104. },
  11105. enumerable: true,
  11106. configurable: true
  11107. });
  11108. _StencilState.prototype.reset = function () {
  11109. this._stencilTest = false;
  11110. this._stencilMask = 0xFF;
  11111. this._stencilFunc = BABYLON.Engine.ALWAYS;
  11112. this._stencilFuncRef = 1;
  11113. this._stencilFuncMask = 0xFF;
  11114. this._stencilOpStencilFail = BABYLON.Engine.KEEP;
  11115. this._stencilOpDepthFail = BABYLON.Engine.KEEP;
  11116. this._stencilOpStencilDepthPass = BABYLON.Engine.REPLACE;
  11117. this._isStencilTestDirty = true;
  11118. this._isStencilMaskDirty = true;
  11119. this._isStencilFuncDirty = true;
  11120. this._isStencilOpDirty = true;
  11121. };
  11122. _StencilState.prototype.apply = function (gl) {
  11123. if (!this.isDirty) {
  11124. return;
  11125. }
  11126. // Stencil test
  11127. if (this._isStencilTestDirty) {
  11128. if (this.stencilTest) {
  11129. gl.enable(gl.STENCIL_TEST);
  11130. }
  11131. else {
  11132. gl.disable(gl.STENCIL_TEST);
  11133. }
  11134. this._isStencilTestDirty = false;
  11135. }
  11136. // Stencil mask
  11137. if (this._isStencilMaskDirty) {
  11138. gl.stencilMask(this.stencilMask);
  11139. this._isStencilMaskDirty = false;
  11140. }
  11141. // Stencil func
  11142. if (this._isStencilFuncDirty) {
  11143. gl.stencilFunc(this.stencilFunc, this.stencilFuncRef, this.stencilFuncMask);
  11144. this._isStencilFuncDirty = false;
  11145. }
  11146. // Stencil op
  11147. if (this._isStencilOpDirty) {
  11148. gl.stencilOp(this.stencilOpStencilFail, this.stencilOpDepthFail, this.stencilOpStencilDepthPass);
  11149. this._isStencilOpDirty = false;
  11150. }
  11151. };
  11152. return _StencilState;
  11153. }());
  11154. BABYLON._StencilState = _StencilState;
  11155. })(BABYLON || (BABYLON = {}));
  11156. //# sourceMappingURL=babylon.stencilState.js.map
  11157. var __assign = (this && this.__assign) || Object.assign || function(t) {
  11158. for (var s, i = 1, n = arguments.length; i < n; i++) {
  11159. s = arguments[i];
  11160. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  11161. t[p] = s[p];
  11162. }
  11163. return t;
  11164. };
  11165. var BABYLON;
  11166. (function (BABYLON) {
  11167. var compileShader = function (gl, source, type, defines, shaderVersion) {
  11168. return compileRawShader(gl, shaderVersion + (defines ? defines + "\n" : "") + source, type);
  11169. };
  11170. var compileRawShader = function (gl, source, type) {
  11171. var shader = gl.createShader(type === "vertex" ? gl.VERTEX_SHADER : gl.FRAGMENT_SHADER);
  11172. gl.shaderSource(shader, source);
  11173. gl.compileShader(shader);
  11174. if (!gl.getShaderParameter(shader, gl.COMPILE_STATUS)) {
  11175. var log = gl.getShaderInfoLog(shader);
  11176. if (log) {
  11177. throw new Error(log);
  11178. }
  11179. }
  11180. if (!shader) {
  11181. throw new Error("Something went wrong while compile the shader.");
  11182. }
  11183. return shader;
  11184. };
  11185. var getSamplingParameters = function (samplingMode, generateMipMaps, gl) {
  11186. var magFilter = gl.NEAREST;
  11187. var minFilter = gl.NEAREST;
  11188. switch (samplingMode) {
  11189. case BABYLON.Texture.BILINEAR_SAMPLINGMODE:
  11190. magFilter = gl.LINEAR;
  11191. if (generateMipMaps) {
  11192. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11193. }
  11194. else {
  11195. minFilter = gl.LINEAR;
  11196. }
  11197. break;
  11198. case BABYLON.Texture.TRILINEAR_SAMPLINGMODE:
  11199. magFilter = gl.LINEAR;
  11200. if (generateMipMaps) {
  11201. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11202. }
  11203. else {
  11204. minFilter = gl.LINEAR;
  11205. }
  11206. break;
  11207. case BABYLON.Texture.NEAREST_SAMPLINGMODE:
  11208. magFilter = gl.NEAREST;
  11209. if (generateMipMaps) {
  11210. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11211. }
  11212. else {
  11213. minFilter = gl.NEAREST;
  11214. }
  11215. break;
  11216. case BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST:
  11217. magFilter = gl.NEAREST;
  11218. if (generateMipMaps) {
  11219. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11220. }
  11221. else {
  11222. minFilter = gl.NEAREST;
  11223. }
  11224. break;
  11225. case BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST:
  11226. magFilter = gl.NEAREST;
  11227. if (generateMipMaps) {
  11228. minFilter = gl.LINEAR_MIPMAP_NEAREST;
  11229. }
  11230. else {
  11231. minFilter = gl.LINEAR;
  11232. }
  11233. break;
  11234. case BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR:
  11235. magFilter = gl.NEAREST;
  11236. if (generateMipMaps) {
  11237. minFilter = gl.LINEAR_MIPMAP_LINEAR;
  11238. }
  11239. else {
  11240. minFilter = gl.LINEAR;
  11241. }
  11242. break;
  11243. case BABYLON.Texture.NEAREST_LINEAR:
  11244. magFilter = gl.NEAREST;
  11245. minFilter = gl.LINEAR;
  11246. break;
  11247. case BABYLON.Texture.NEAREST_NEAREST:
  11248. magFilter = gl.NEAREST;
  11249. minFilter = gl.NEAREST;
  11250. break;
  11251. case BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST:
  11252. magFilter = gl.LINEAR;
  11253. if (generateMipMaps) {
  11254. minFilter = gl.NEAREST_MIPMAP_NEAREST;
  11255. }
  11256. else {
  11257. minFilter = gl.NEAREST;
  11258. }
  11259. break;
  11260. case BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR:
  11261. magFilter = gl.LINEAR;
  11262. if (generateMipMaps) {
  11263. minFilter = gl.NEAREST_MIPMAP_LINEAR;
  11264. }
  11265. else {
  11266. minFilter = gl.NEAREST;
  11267. }
  11268. break;
  11269. case BABYLON.Texture.LINEAR_LINEAR:
  11270. magFilter = gl.LINEAR;
  11271. minFilter = gl.LINEAR;
  11272. break;
  11273. case BABYLON.Texture.LINEAR_NEAREST:
  11274. magFilter = gl.LINEAR;
  11275. minFilter = gl.NEAREST;
  11276. break;
  11277. }
  11278. return {
  11279. min: minFilter,
  11280. mag: magFilter
  11281. };
  11282. };
  11283. var partialLoadImg = function (url, index, loadedImages, scene, onfinish, onErrorCallBack) {
  11284. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  11285. var img;
  11286. var onload = function () {
  11287. loadedImages[index] = img;
  11288. loadedImages._internalCount++;
  11289. if (scene) {
  11290. scene._removePendingData(img);
  11291. }
  11292. if (loadedImages._internalCount === 6) {
  11293. onfinish(loadedImages);
  11294. }
  11295. };
  11296. var onerror = function (message, exception) {
  11297. if (scene) {
  11298. scene._removePendingData(img);
  11299. }
  11300. if (onErrorCallBack) {
  11301. onErrorCallBack(message, exception);
  11302. }
  11303. };
  11304. img = BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  11305. if (scene) {
  11306. scene._addPendingData(img);
  11307. }
  11308. };
  11309. var cascadeLoadImgs = function (rootUrl, scene, onfinish, files, onError) {
  11310. if (onError === void 0) { onError = null; }
  11311. var loadedImages = [];
  11312. loadedImages._internalCount = 0;
  11313. for (var index = 0; index < 6; index++) {
  11314. partialLoadImg(files[index], index, loadedImages, scene, onfinish, onError);
  11315. }
  11316. };
  11317. var BufferPointer = /** @class */ (function () {
  11318. function BufferPointer() {
  11319. }
  11320. return BufferPointer;
  11321. }());
  11322. /**
  11323. * Interface for attribute information associated with buffer instanciation
  11324. */
  11325. var InstancingAttributeInfo = /** @class */ (function () {
  11326. function InstancingAttributeInfo() {
  11327. }
  11328. return InstancingAttributeInfo;
  11329. }());
  11330. BABYLON.InstancingAttributeInfo = InstancingAttributeInfo;
  11331. /**
  11332. * Define options used to create a render target texture
  11333. */
  11334. var RenderTargetCreationOptions = /** @class */ (function () {
  11335. function RenderTargetCreationOptions() {
  11336. }
  11337. return RenderTargetCreationOptions;
  11338. }());
  11339. BABYLON.RenderTargetCreationOptions = RenderTargetCreationOptions;
  11340. /**
  11341. * Define options used to create a depth texture
  11342. */
  11343. var DepthTextureCreationOptions = /** @class */ (function () {
  11344. function DepthTextureCreationOptions() {
  11345. }
  11346. return DepthTextureCreationOptions;
  11347. }());
  11348. BABYLON.DepthTextureCreationOptions = DepthTextureCreationOptions;
  11349. /**
  11350. * Class used to describe the capabilities of the engine relatively to the current browser
  11351. */
  11352. var EngineCapabilities = /** @class */ (function () {
  11353. function EngineCapabilities() {
  11354. }
  11355. return EngineCapabilities;
  11356. }());
  11357. BABYLON.EngineCapabilities = EngineCapabilities;
  11358. /**
  11359. * The engine class is responsible for interfacing with all lower-level APIs such as WebGL and Audio
  11360. */
  11361. var Engine = /** @class */ (function () {
  11362. /**
  11363. * Creates a new engine
  11364. * @param canvasOrContext defines the canvas or WebGL context to use for rendering
  11365. * @param antialias defines enable antialiasing (default: false)
  11366. * @param options defines further options to be sent to the getContext() function
  11367. * @param adaptToDeviceRatio defines whether to adapt to the device's viewport characteristics (default: false)
  11368. */
  11369. function Engine(canvasOrContext, antialias, options, adaptToDeviceRatio) {
  11370. if (adaptToDeviceRatio === void 0) { adaptToDeviceRatio = false; }
  11371. var _this = this;
  11372. // Public members
  11373. /**
  11374. * Gets or sets a boolean that indicates if textures must be forced to power of 2 size even if not required
  11375. */
  11376. this.forcePOTTextures = false;
  11377. /**
  11378. * Gets a boolean indicating if the engine is currently rendering in fullscreen mode
  11379. */
  11380. this.isFullscreen = false;
  11381. /**
  11382. * Gets a boolean indicating if the pointer is currently locked
  11383. */
  11384. this.isPointerLock = false;
  11385. /**
  11386. * Gets or sets a boolean indicating if back faces must be culled (true by default)
  11387. */
  11388. this.cullBackFaces = true;
  11389. /**
  11390. * Gets or sets a boolean indicating if the engine must keep rendering even if the window is not in foregroun
  11391. */
  11392. this.renderEvenInBackground = true;
  11393. /**
  11394. * Gets or sets a boolean indicating that cache can be kept between frames
  11395. */
  11396. this.preventCacheWipeBetweenFrames = false;
  11397. /**
  11398. * Gets or sets a boolean to enable/disable IndexedDB support and avoid XHR on .manifest
  11399. **/
  11400. this.enableOfflineSupport = false;
  11401. /**
  11402. * Gets or sets a boolean to enable/disable checking manifest if IndexedDB support is enabled (Babylon.js will always consider the database is up to date)
  11403. **/
  11404. this.disableManifestCheck = false;
  11405. /**
  11406. * Gets the list of created scenes
  11407. */
  11408. this.scenes = new Array();
  11409. /**
  11410. * Gets the list of created postprocesses
  11411. */
  11412. this.postProcesses = new Array();
  11413. // Observables
  11414. /**
  11415. * Observable event triggered each time the rendering canvas is resized
  11416. */
  11417. this.onResizeObservable = new BABYLON.Observable();
  11418. /**
  11419. * Observable event triggered each time the canvas loses focus
  11420. */
  11421. this.onCanvasBlurObservable = new BABYLON.Observable();
  11422. /**
  11423. * Observable event triggered each time the canvas gains focus
  11424. */
  11425. this.onCanvasFocusObservable = new BABYLON.Observable();
  11426. /**
  11427. * Observable event triggered each time the canvas receives pointerout event
  11428. */
  11429. this.onCanvasPointerOutObservable = new BABYLON.Observable();
  11430. /**
  11431. * Observable event triggered before each texture is initialized
  11432. */
  11433. this.onBeforeTextureInitObservable = new BABYLON.Observable();
  11434. //WebVR
  11435. this._vrDisplay = undefined;
  11436. this._vrSupported = false;
  11437. this._vrExclusivePointerMode = false;
  11438. // Uniform buffers list
  11439. /**
  11440. * Gets or sets a boolean indicating that uniform buffers must be disabled even if they are supported
  11441. */
  11442. this.disableUniformBuffers = false;
  11443. /** @hidden */
  11444. this._uniformBuffers = new Array();
  11445. // Observables
  11446. /**
  11447. * Observable raised when the engine begins a new frame
  11448. */
  11449. this.onBeginFrameObservable = new BABYLON.Observable();
  11450. /**
  11451. * Observable raised when the engine ends the current frame
  11452. */
  11453. this.onEndFrameObservable = new BABYLON.Observable();
  11454. /**
  11455. * Observable raised when the engine is about to compile a shader
  11456. */
  11457. this.onBeforeShaderCompilationObservable = new BABYLON.Observable();
  11458. /**
  11459. * Observable raised when the engine has jsut compiled a shader
  11460. */
  11461. this.onAfterShaderCompilationObservable = new BABYLON.Observable();
  11462. this._windowIsBackground = false;
  11463. this._webGLVersion = 1.0;
  11464. /** @hidden */
  11465. this._badOS = false;
  11466. /** @hidden */
  11467. this._badDesktopOS = false;
  11468. /**
  11469. * Gets or sets a value indicating if we want to disable texture binding optmization.
  11470. * This could be required on some buggy drivers which wants to have textures bound in a progressive order.
  11471. * By default Babylon.js will try to let textures bound where they are and only update the samplers to point where the texture is
  11472. */
  11473. this.disableTextureBindingOptimization = false;
  11474. /**
  11475. * Observable signaled when VR display mode changes
  11476. */
  11477. this.onVRDisplayChangedObservable = new BABYLON.Observable();
  11478. /**
  11479. * Observable signaled when VR request present is complete
  11480. */
  11481. this.onVRRequestPresentComplete = new BABYLON.Observable();
  11482. /**
  11483. * Observable signaled when VR request present starts
  11484. */
  11485. this.onVRRequestPresentStart = new BABYLON.Observable();
  11486. this._colorWrite = true;
  11487. /** @hidden */
  11488. this._drawCalls = new BABYLON.PerfCounter();
  11489. /** @hidden */
  11490. this._textureCollisions = new BABYLON.PerfCounter();
  11491. this._renderingQueueLaunched = false;
  11492. this._activeRenderLoops = new Array();
  11493. // Deterministic lockstepMaxSteps
  11494. this._deterministicLockstep = false;
  11495. this._lockstepMaxSteps = 4;
  11496. // Lost context
  11497. /**
  11498. * Observable signaled when a context lost event is raised
  11499. */
  11500. this.onContextLostObservable = new BABYLON.Observable();
  11501. /**
  11502. * Observable signaled when a context restored event is raised
  11503. */
  11504. this.onContextRestoredObservable = new BABYLON.Observable();
  11505. this._contextWasLost = false;
  11506. this._doNotHandleContextLost = false;
  11507. // FPS
  11508. this._performanceMonitor = new BABYLON.PerformanceMonitor();
  11509. this._fps = 60;
  11510. this._deltaTime = 0;
  11511. /**
  11512. * Turn this value on if you want to pause FPS computation when in background
  11513. */
  11514. this.disablePerformanceMonitorInBackground = false;
  11515. // States
  11516. /** @hidden */
  11517. this._depthCullingState = new BABYLON._DepthCullingState();
  11518. /** @hidden */
  11519. this._stencilState = new BABYLON._StencilState();
  11520. /** @hidden */
  11521. this._alphaState = new BABYLON._AlphaState();
  11522. /** @hidden */
  11523. this._alphaMode = Engine.ALPHA_DISABLE;
  11524. // Cache
  11525. this._internalTexturesCache = new Array();
  11526. /** @hidden */
  11527. this._activeChannel = 0;
  11528. this._currentTextureChannel = -1;
  11529. /** @hidden */
  11530. this._boundTexturesCache = {};
  11531. this._compiledEffects = {};
  11532. this._vertexAttribArraysEnabled = [];
  11533. this._uintIndicesCurrentlySet = false;
  11534. this._currentBoundBuffer = new Array();
  11535. this._currentBufferPointers = new Array();
  11536. this._currentInstanceLocations = new Array();
  11537. this._currentInstanceBuffers = new Array();
  11538. this._firstBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11539. this._lastBoundInternalTextureTracker = new BABYLON.DummyInternalTextureTracker();
  11540. this._vaoRecordInProgress = false;
  11541. this._mustWipeVertexAttributes = false;
  11542. this._nextFreeTextureSlots = new Array();
  11543. this._maxSimultaneousTextures = 0;
  11544. this._activeRequests = new Array();
  11545. // Hardware supported Compressed Textures
  11546. this._texturesSupported = new Array();
  11547. /**
  11548. * Defines whether the engine has been created with the premultipliedAlpha option on or not.
  11549. */
  11550. this.premultipliedAlpha = true;
  11551. this._viewportCached = new BABYLON.Vector4(0, 0, 0, 0);
  11552. this._onVRFullScreenTriggered = function () {
  11553. if (_this._vrDisplay && _this._vrDisplay.isPresenting) {
  11554. //get the old size before we change
  11555. _this._oldSize = new BABYLON.Size(_this.getRenderWidth(), _this.getRenderHeight());
  11556. _this._oldHardwareScaleFactor = _this.getHardwareScalingLevel();
  11557. //get the width and height, change the render size
  11558. var leftEye = _this._vrDisplay.getEyeParameters('left');
  11559. _this.setHardwareScalingLevel(1);
  11560. _this.setSize(leftEye.renderWidth * 2, leftEye.renderHeight);
  11561. }
  11562. else {
  11563. _this.setHardwareScalingLevel(_this._oldHardwareScaleFactor);
  11564. _this.setSize(_this._oldSize.width, _this._oldSize.height);
  11565. }
  11566. };
  11567. this._unpackFlipYCached = null;
  11568. this._boundUniforms = {};
  11569. // Register promises
  11570. BABYLON.PromisePolyfill.Apply();
  11571. var canvas = null;
  11572. Engine.Instances.push(this);
  11573. if (!canvasOrContext) {
  11574. return;
  11575. }
  11576. options = options || {};
  11577. if (canvasOrContext.getContext) {
  11578. canvas = canvasOrContext;
  11579. this._renderingCanvas = canvas;
  11580. if (antialias != null) {
  11581. options.antialias = antialias;
  11582. }
  11583. if (options.deterministicLockstep === undefined) {
  11584. options.deterministicLockstep = false;
  11585. }
  11586. if (options.lockstepMaxSteps === undefined) {
  11587. options.lockstepMaxSteps = 4;
  11588. }
  11589. if (options.preserveDrawingBuffer === undefined) {
  11590. options.preserveDrawingBuffer = false;
  11591. }
  11592. if (options.audioEngine === undefined) {
  11593. options.audioEngine = true;
  11594. }
  11595. if (options.stencil === undefined) {
  11596. options.stencil = true;
  11597. }
  11598. if (options.premultipliedAlpha === false) {
  11599. this.premultipliedAlpha = false;
  11600. }
  11601. this._deterministicLockstep = options.deterministicLockstep;
  11602. this._lockstepMaxSteps = options.lockstepMaxSteps;
  11603. this._doNotHandleContextLost = options.doNotHandleContextLost ? true : false;
  11604. // Exceptions
  11605. if (navigator && navigator.userAgent) {
  11606. var ua = navigator.userAgent;
  11607. for (var _i = 0, _a = Engine.ExceptionList; _i < _a.length; _i++) {
  11608. var exception = _a[_i];
  11609. var key = exception.key;
  11610. var targets = exception.targets;
  11611. if (ua.indexOf(key) > -1) {
  11612. if (exception.capture && exception.captureConstraint) {
  11613. var capture = exception.capture;
  11614. var constraint = exception.captureConstraint;
  11615. var regex = new RegExp(capture);
  11616. var matches = regex.exec(ua);
  11617. if (matches && matches.length > 0) {
  11618. var capturedValue = parseInt(matches[matches.length - 1]);
  11619. if (capturedValue >= constraint) {
  11620. continue;
  11621. }
  11622. }
  11623. }
  11624. for (var _b = 0, targets_1 = targets; _b < targets_1.length; _b++) {
  11625. var target = targets_1[_b];
  11626. switch (target) {
  11627. case "uniformBuffer":
  11628. this.disableUniformBuffers = true;
  11629. break;
  11630. case "textureBindingOptimization":
  11631. this.disableTextureBindingOptimization = true;
  11632. break;
  11633. }
  11634. }
  11635. }
  11636. }
  11637. }
  11638. // GL
  11639. if (!options.disableWebGL2Support) {
  11640. try {
  11641. this._gl = (canvas.getContext("webgl2", options) || canvas.getContext("experimental-webgl2", options));
  11642. if (this._gl) {
  11643. this._webGLVersion = 2.0;
  11644. }
  11645. }
  11646. catch (e) {
  11647. // Do nothing
  11648. }
  11649. }
  11650. if (!this._gl) {
  11651. if (!canvas) {
  11652. throw new Error("The provided canvas is null or undefined.");
  11653. }
  11654. try {
  11655. this._gl = (canvas.getContext("webgl", options) || canvas.getContext("experimental-webgl", options));
  11656. }
  11657. catch (e) {
  11658. throw new Error("WebGL not supported");
  11659. }
  11660. }
  11661. if (!this._gl) {
  11662. throw new Error("WebGL not supported");
  11663. }
  11664. this._onCanvasFocus = function () {
  11665. _this.onCanvasFocusObservable.notifyObservers(_this);
  11666. };
  11667. this._onCanvasBlur = function () {
  11668. _this.onCanvasBlurObservable.notifyObservers(_this);
  11669. };
  11670. canvas.addEventListener("focus", this._onCanvasFocus);
  11671. canvas.addEventListener("blur", this._onCanvasBlur);
  11672. this._onBlur = function () {
  11673. if (_this.disablePerformanceMonitorInBackground) {
  11674. _this._performanceMonitor.disable();
  11675. }
  11676. _this._windowIsBackground = true;
  11677. };
  11678. this._onFocus = function () {
  11679. if (_this.disablePerformanceMonitorInBackground) {
  11680. _this._performanceMonitor.enable();
  11681. }
  11682. _this._windowIsBackground = false;
  11683. };
  11684. this._onCanvasPointerOut = function (ev) {
  11685. _this.onCanvasPointerOutObservable.notifyObservers(ev);
  11686. };
  11687. window.addEventListener("blur", this._onBlur);
  11688. window.addEventListener("focus", this._onFocus);
  11689. canvas.addEventListener("pointerout", this._onCanvasPointerOut);
  11690. // Context lost
  11691. if (!this._doNotHandleContextLost) {
  11692. this._onContextLost = function (evt) {
  11693. evt.preventDefault();
  11694. _this._contextWasLost = true;
  11695. BABYLON.Tools.Warn("WebGL context lost.");
  11696. _this.onContextLostObservable.notifyObservers(_this);
  11697. };
  11698. this._onContextRestored = function (evt) {
  11699. // Adding a timeout to avoid race condition at browser level
  11700. setTimeout(function () {
  11701. // Rebuild gl context
  11702. _this._initGLContext();
  11703. // Rebuild effects
  11704. _this._rebuildEffects();
  11705. // Rebuild textures
  11706. _this._rebuildInternalTextures();
  11707. // Rebuild buffers
  11708. _this._rebuildBuffers();
  11709. // Cache
  11710. _this.wipeCaches(true);
  11711. BABYLON.Tools.Warn("WebGL context successfully restored.");
  11712. _this.onContextRestoredObservable.notifyObservers(_this);
  11713. _this._contextWasLost = false;
  11714. }, 0);
  11715. };
  11716. canvas.addEventListener("webglcontextlost", this._onContextLost, false);
  11717. canvas.addEventListener("webglcontextrestored", this._onContextRestored, false);
  11718. }
  11719. }
  11720. else {
  11721. this._gl = canvasOrContext;
  11722. this._renderingCanvas = this._gl.canvas;
  11723. if (this._gl.renderbufferStorageMultisample) {
  11724. this._webGLVersion = 2.0;
  11725. }
  11726. options.stencil = this._gl.getContextAttributes().stencil;
  11727. }
  11728. // Viewport
  11729. var limitDeviceRatio = options.limitDeviceRatio || window.devicePixelRatio || 1.0;
  11730. this._hardwareScalingLevel = adaptToDeviceRatio ? 1.0 / Math.min(limitDeviceRatio, window.devicePixelRatio || 1.0) : 1.0;
  11731. this.resize();
  11732. this._isStencilEnable = options.stencil ? true : false;
  11733. this._initGLContext();
  11734. if (canvas) {
  11735. // Fullscreen
  11736. this._onFullscreenChange = function () {
  11737. if (document.fullscreen !== undefined) {
  11738. _this.isFullscreen = document.fullscreen;
  11739. }
  11740. else if (document.mozFullScreen !== undefined) {
  11741. _this.isFullscreen = document.mozFullScreen;
  11742. }
  11743. else if (document.webkitIsFullScreen !== undefined) {
  11744. _this.isFullscreen = document.webkitIsFullScreen;
  11745. }
  11746. else if (document.msIsFullScreen !== undefined) {
  11747. _this.isFullscreen = document.msIsFullScreen;
  11748. }
  11749. // Pointer lock
  11750. if (_this.isFullscreen && _this._pointerLockRequested && canvas) {
  11751. canvas.requestPointerLock = canvas.requestPointerLock ||
  11752. canvas.msRequestPointerLock ||
  11753. canvas.mozRequestPointerLock ||
  11754. canvas.webkitRequestPointerLock;
  11755. if (canvas.requestPointerLock) {
  11756. canvas.requestPointerLock();
  11757. }
  11758. }
  11759. };
  11760. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  11761. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  11762. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  11763. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  11764. // Pointer lock
  11765. this._onPointerLockChange = function () {
  11766. _this.isPointerLock = (document.mozPointerLockElement === canvas ||
  11767. document.webkitPointerLockElement === canvas ||
  11768. document.msPointerLockElement === canvas ||
  11769. document.pointerLockElement === canvas);
  11770. };
  11771. document.addEventListener("pointerlockchange", this._onPointerLockChange, false);
  11772. document.addEventListener("mspointerlockchange", this._onPointerLockChange, false);
  11773. document.addEventListener("mozpointerlockchange", this._onPointerLockChange, false);
  11774. document.addEventListener("webkitpointerlockchange", this._onPointerLockChange, false);
  11775. this._onVRDisplayPointerRestricted = function () {
  11776. if (canvas) {
  11777. canvas.requestPointerLock();
  11778. }
  11779. };
  11780. this._onVRDisplayPointerUnrestricted = function () {
  11781. document.exitPointerLock();
  11782. };
  11783. window.addEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted, false);
  11784. window.addEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted, false);
  11785. }
  11786. if (options.audioEngine && BABYLON.AudioEngine && !Engine.audioEngine) {
  11787. Engine.audioEngine = new BABYLON.AudioEngine();
  11788. }
  11789. // Prepare buffer pointers
  11790. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  11791. this._currentBufferPointers[i] = new BufferPointer();
  11792. }
  11793. this._linkTrackers(this._firstBoundInternalTextureTracker, this._lastBoundInternalTextureTracker);
  11794. // Load WebVR Devices
  11795. if (options.autoEnableWebVR) {
  11796. this.initWebVR();
  11797. }
  11798. // Detect if we are running on a faulty buggy OS.
  11799. this._badOS = /iPad/i.test(navigator.userAgent) || /iPhone/i.test(navigator.userAgent);
  11800. // Detect if we are running on a faulty buggy desktop OS.
  11801. this._badDesktopOS = /^((?!chrome|android).)*safari/i.test(navigator.userAgent);
  11802. console.log("Babylon.js engine (v" + Engine.Version + ") launched");
  11803. this.enableOfflineSupport = (BABYLON.Database !== undefined);
  11804. }
  11805. Object.defineProperty(Engine, "LastCreatedEngine", {
  11806. /**
  11807. * Gets the latest created engine
  11808. */
  11809. get: function () {
  11810. if (Engine.Instances.length === 0) {
  11811. return null;
  11812. }
  11813. return Engine.Instances[Engine.Instances.length - 1];
  11814. },
  11815. enumerable: true,
  11816. configurable: true
  11817. });
  11818. Object.defineProperty(Engine, "LastCreatedScene", {
  11819. /**
  11820. * Gets the latest created scene
  11821. */
  11822. get: function () {
  11823. var lastCreatedEngine = Engine.LastCreatedEngine;
  11824. if (!lastCreatedEngine) {
  11825. return null;
  11826. }
  11827. if (lastCreatedEngine.scenes.length === 0) {
  11828. return null;
  11829. }
  11830. return lastCreatedEngine.scenes[lastCreatedEngine.scenes.length - 1];
  11831. },
  11832. enumerable: true,
  11833. configurable: true
  11834. });
  11835. /**
  11836. * Will flag all materials in all scenes in all engines as dirty to trigger new shader compilation
  11837. * @param flag defines which part of the materials must be marked as dirty
  11838. * @param predicate defines a predicate used to filter which materials should be affected
  11839. */
  11840. Engine.MarkAllMaterialsAsDirty = function (flag, predicate) {
  11841. for (var engineIndex = 0; engineIndex < Engine.Instances.length; engineIndex++) {
  11842. var engine = Engine.Instances[engineIndex];
  11843. for (var sceneIndex = 0; sceneIndex < engine.scenes.length; sceneIndex++) {
  11844. engine.scenes[sceneIndex].markAllMaterialsAsDirty(flag, predicate);
  11845. }
  11846. }
  11847. };
  11848. Object.defineProperty(Engine, "NEVER", {
  11849. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn */
  11850. get: function () {
  11851. return Engine._NEVER;
  11852. },
  11853. enumerable: true,
  11854. configurable: true
  11855. });
  11856. Object.defineProperty(Engine, "ALWAYS", {
  11857. /** 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 */
  11858. get: function () {
  11859. return Engine._ALWAYS;
  11860. },
  11861. enumerable: true,
  11862. configurable: true
  11863. });
  11864. Object.defineProperty(Engine, "LESS", {
  11865. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is less than the stored value */
  11866. get: function () {
  11867. return Engine._LESS;
  11868. },
  11869. enumerable: true,
  11870. configurable: true
  11871. });
  11872. Object.defineProperty(Engine, "EQUAL", {
  11873. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is equals to the stored value */
  11874. get: function () {
  11875. return Engine._EQUAL;
  11876. },
  11877. enumerable: true,
  11878. configurable: true
  11879. });
  11880. Object.defineProperty(Engine, "LEQUAL", {
  11881. /** 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 */
  11882. get: function () {
  11883. return Engine._LEQUAL;
  11884. },
  11885. enumerable: true,
  11886. configurable: true
  11887. });
  11888. Object.defineProperty(Engine, "GREATER", {
  11889. /** Passed to depthFunction or stencilFunction to specify depth or stencil tests will pass if the new depth value is greater than the stored value */
  11890. get: function () {
  11891. return Engine._GREATER;
  11892. },
  11893. enumerable: true,
  11894. configurable: true
  11895. });
  11896. Object.defineProperty(Engine, "GEQUAL", {
  11897. /** 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 */
  11898. get: function () {
  11899. return Engine._GEQUAL;
  11900. },
  11901. enumerable: true,
  11902. configurable: true
  11903. });
  11904. Object.defineProperty(Engine, "NOTEQUAL", {
  11905. /** 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 */
  11906. get: function () {
  11907. return Engine._NOTEQUAL;
  11908. },
  11909. enumerable: true,
  11910. configurable: true
  11911. });
  11912. Object.defineProperty(Engine, "KEEP", {
  11913. /** Passed to stencilOperation to specify that stencil value must be kept */
  11914. get: function () {
  11915. return Engine._KEEP;
  11916. },
  11917. enumerable: true,
  11918. configurable: true
  11919. });
  11920. Object.defineProperty(Engine, "REPLACE", {
  11921. /** Passed to stencilOperation to specify that stencil value must be replaced */
  11922. get: function () {
  11923. return Engine._REPLACE;
  11924. },
  11925. enumerable: true,
  11926. configurable: true
  11927. });
  11928. Object.defineProperty(Engine, "INCR", {
  11929. /** Passed to stencilOperation to specify that stencil value must be incremented */
  11930. get: function () {
  11931. return Engine._INCR;
  11932. },
  11933. enumerable: true,
  11934. configurable: true
  11935. });
  11936. Object.defineProperty(Engine, "DECR", {
  11937. /** Passed to stencilOperation to specify that stencil value must be decremented */
  11938. get: function () {
  11939. return Engine._DECR;
  11940. },
  11941. enumerable: true,
  11942. configurable: true
  11943. });
  11944. Object.defineProperty(Engine, "INVERT", {
  11945. /** Passed to stencilOperation to specify that stencil value must be inverted */
  11946. get: function () {
  11947. return Engine._INVERT;
  11948. },
  11949. enumerable: true,
  11950. configurable: true
  11951. });
  11952. Object.defineProperty(Engine, "INCR_WRAP", {
  11953. /** Passed to stencilOperation to specify that stencil value must be incremented with wrapping */
  11954. get: function () {
  11955. return Engine._INCR_WRAP;
  11956. },
  11957. enumerable: true,
  11958. configurable: true
  11959. });
  11960. Object.defineProperty(Engine, "DECR_WRAP", {
  11961. /** Passed to stencilOperation to specify that stencil value must be decremented with wrapping */
  11962. get: function () {
  11963. return Engine._DECR_WRAP;
  11964. },
  11965. enumerable: true,
  11966. configurable: true
  11967. });
  11968. Object.defineProperty(Engine, "ALPHA_DISABLE", {
  11969. // Alpha
  11970. /** Defines that alpha blending is disabled */
  11971. get: function () {
  11972. return Engine._ALPHA_DISABLE;
  11973. },
  11974. enumerable: true,
  11975. configurable: true
  11976. });
  11977. Object.defineProperty(Engine, "ALPHA_ONEONE", {
  11978. /** Defines that alpha blending to SRC + DEST */
  11979. get: function () {
  11980. return Engine._ALPHA_ONEONE;
  11981. },
  11982. enumerable: true,
  11983. configurable: true
  11984. });
  11985. Object.defineProperty(Engine, "ALPHA_ADD", {
  11986. /** Defines that alpha blending to SRC ALPHA * SRC + DEST */
  11987. get: function () {
  11988. return Engine._ALPHA_ADD;
  11989. },
  11990. enumerable: true,
  11991. configurable: true
  11992. });
  11993. Object.defineProperty(Engine, "ALPHA_COMBINE", {
  11994. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC ALPHA) * DEST */
  11995. get: function () {
  11996. return Engine._ALPHA_COMBINE;
  11997. },
  11998. enumerable: true,
  11999. configurable: true
  12000. });
  12001. Object.defineProperty(Engine, "ALPHA_SUBTRACT", {
  12002. /** Defines that alpha blending to DEST - SRC * DEST */
  12003. get: function () {
  12004. return Engine._ALPHA_SUBTRACT;
  12005. },
  12006. enumerable: true,
  12007. configurable: true
  12008. });
  12009. Object.defineProperty(Engine, "ALPHA_MULTIPLY", {
  12010. /** Defines that alpha blending to SRC * DEST */
  12011. get: function () {
  12012. return Engine._ALPHA_MULTIPLY;
  12013. },
  12014. enumerable: true,
  12015. configurable: true
  12016. });
  12017. Object.defineProperty(Engine, "ALPHA_MAXIMIZED", {
  12018. /** Defines that alpha blending to SRC ALPHA * SRC + (1 - SRC) * DEST */
  12019. get: function () {
  12020. return Engine._ALPHA_MAXIMIZED;
  12021. },
  12022. enumerable: true,
  12023. configurable: true
  12024. });
  12025. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED", {
  12026. /** Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST */
  12027. get: function () {
  12028. return Engine._ALPHA_PREMULTIPLIED;
  12029. },
  12030. enumerable: true,
  12031. configurable: true
  12032. });
  12033. Object.defineProperty(Engine, "ALPHA_PREMULTIPLIED_PORTERDUFF", {
  12034. /**
  12035. * Defines that alpha blending to SRC + (1 - SRC ALPHA) * DEST
  12036. * Alpha will be set to (1 - SRC ALPHA) * DEST ALPHA
  12037. */
  12038. get: function () {
  12039. return Engine._ALPHA_PREMULTIPLIED_PORTERDUFF;
  12040. },
  12041. enumerable: true,
  12042. configurable: true
  12043. });
  12044. Object.defineProperty(Engine, "ALPHA_INTERPOLATE", {
  12045. /** Defines that alpha blending to CST * SRC + (1 - CST) * DEST */
  12046. get: function () {
  12047. return Engine._ALPHA_INTERPOLATE;
  12048. },
  12049. enumerable: true,
  12050. configurable: true
  12051. });
  12052. Object.defineProperty(Engine, "ALPHA_SCREENMODE", {
  12053. /**
  12054. * Defines that alpha blending to SRC + (1 - SRC) * DEST
  12055. * Alpha will be set to SRC ALPHA + (1 - SRC ALPHA) * DEST ALPHA
  12056. */
  12057. get: function () {
  12058. return Engine._ALPHA_SCREENMODE;
  12059. },
  12060. enumerable: true,
  12061. configurable: true
  12062. });
  12063. Object.defineProperty(Engine, "DELAYLOADSTATE_NONE", {
  12064. // Delays
  12065. /** Defines that the ressource is not delayed*/
  12066. get: function () {
  12067. return Engine._DELAYLOADSTATE_NONE;
  12068. },
  12069. enumerable: true,
  12070. configurable: true
  12071. });
  12072. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADED", {
  12073. /** Defines that the ressource was successfully delay loaded */
  12074. get: function () {
  12075. return Engine._DELAYLOADSTATE_LOADED;
  12076. },
  12077. enumerable: true,
  12078. configurable: true
  12079. });
  12080. Object.defineProperty(Engine, "DELAYLOADSTATE_LOADING", {
  12081. /** Defines that the ressource is currently delay loading */
  12082. get: function () {
  12083. return Engine._DELAYLOADSTATE_LOADING;
  12084. },
  12085. enumerable: true,
  12086. configurable: true
  12087. });
  12088. Object.defineProperty(Engine, "DELAYLOADSTATE_NOTLOADED", {
  12089. /** Defines that the ressource is delayed and has not started loading */
  12090. get: function () {
  12091. return Engine._DELAYLOADSTATE_NOTLOADED;
  12092. },
  12093. enumerable: true,
  12094. configurable: true
  12095. });
  12096. Object.defineProperty(Engine, "TEXTUREFORMAT_ALPHA", {
  12097. /** ALPHA */
  12098. get: function () {
  12099. return Engine._TEXTUREFORMAT_ALPHA;
  12100. },
  12101. enumerable: true,
  12102. configurable: true
  12103. });
  12104. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE", {
  12105. /** LUMINANCE */
  12106. get: function () {
  12107. return Engine._TEXTUREFORMAT_LUMINANCE;
  12108. },
  12109. enumerable: true,
  12110. configurable: true
  12111. });
  12112. Object.defineProperty(Engine, "TEXTUREFORMAT_R", {
  12113. /**
  12114. * R
  12115. */
  12116. get: function () {
  12117. return Engine._TEXTUREFORMAT_R;
  12118. },
  12119. enumerable: true,
  12120. configurable: true
  12121. });
  12122. Object.defineProperty(Engine, "TEXTUREFORMAT_RG", {
  12123. /**
  12124. * RG
  12125. */
  12126. get: function () {
  12127. return Engine._TEXTUREFORMAT_RG;
  12128. },
  12129. enumerable: true,
  12130. configurable: true
  12131. });
  12132. Object.defineProperty(Engine, "TEXTUREFORMAT_LUMINANCE_ALPHA", {
  12133. /** LUMINANCE_ALPHA */
  12134. get: function () {
  12135. return Engine._TEXTUREFORMAT_LUMINANCE_ALPHA;
  12136. },
  12137. enumerable: true,
  12138. configurable: true
  12139. });
  12140. Object.defineProperty(Engine, "TEXTUREFORMAT_RGB", {
  12141. /** RGB */
  12142. get: function () {
  12143. return Engine._TEXTUREFORMAT_RGB;
  12144. },
  12145. enumerable: true,
  12146. configurable: true
  12147. });
  12148. Object.defineProperty(Engine, "TEXTUREFORMAT_RGBA", {
  12149. /** RGBA */
  12150. get: function () {
  12151. return Engine._TEXTUREFORMAT_RGBA;
  12152. },
  12153. enumerable: true,
  12154. configurable: true
  12155. });
  12156. Object.defineProperty(Engine, "TEXTURETYPE_UNSIGNED_INT", {
  12157. /** UNSIGNED_INT */
  12158. get: function () {
  12159. return Engine._TEXTURETYPE_UNSIGNED_INT;
  12160. },
  12161. enumerable: true,
  12162. configurable: true
  12163. });
  12164. Object.defineProperty(Engine, "TEXTURETYPE_FLOAT", {
  12165. /** FLOAT */
  12166. get: function () {
  12167. return Engine._TEXTURETYPE_FLOAT;
  12168. },
  12169. enumerable: true,
  12170. configurable: true
  12171. });
  12172. Object.defineProperty(Engine, "TEXTURETYPE_HALF_FLOAT", {
  12173. /** HALF_FLOAT */
  12174. get: function () {
  12175. return Engine._TEXTURETYPE_HALF_FLOAT;
  12176. },
  12177. enumerable: true,
  12178. configurable: true
  12179. });
  12180. Object.defineProperty(Engine, "SCALEMODE_FLOOR", {
  12181. /** Defines that texture rescaling will use a floor to find the closer power of 2 size */
  12182. get: function () {
  12183. return Engine._SCALEMODE_FLOOR;
  12184. },
  12185. enumerable: true,
  12186. configurable: true
  12187. });
  12188. Object.defineProperty(Engine, "SCALEMODE_NEAREST", {
  12189. /** Defines that texture rescaling will look for the nearest power of 2 size */
  12190. get: function () {
  12191. return Engine._SCALEMODE_NEAREST;
  12192. },
  12193. enumerable: true,
  12194. configurable: true
  12195. });
  12196. Object.defineProperty(Engine, "SCALEMODE_CEILING", {
  12197. /** Defines that texture rescaling will use a ceil to find the closer power of 2 size */
  12198. get: function () {
  12199. return Engine._SCALEMODE_CEILING;
  12200. },
  12201. enumerable: true,
  12202. configurable: true
  12203. });
  12204. Object.defineProperty(Engine, "Version", {
  12205. /**
  12206. * Returns the current version of the framework
  12207. */
  12208. get: function () {
  12209. return "3.3.0-alpha.9";
  12210. },
  12211. enumerable: true,
  12212. configurable: true
  12213. });
  12214. Object.defineProperty(Engine.prototype, "isInVRExclusivePointerMode", {
  12215. /**
  12216. * Gets a boolean indicating that the engine is currently in VR exclusive mode for the pointers
  12217. * @see https://docs.microsoft.com/en-us/microsoft-edge/webvr/essentials#mouse-input
  12218. */
  12219. get: function () {
  12220. return this._vrExclusivePointerMode;
  12221. },
  12222. enumerable: true,
  12223. configurable: true
  12224. });
  12225. Object.defineProperty(Engine.prototype, "supportsUniformBuffers", {
  12226. /**
  12227. * Gets a boolean indicating that the engine supports uniform buffers
  12228. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  12229. */
  12230. get: function () {
  12231. return this.webGLVersion > 1 && !this.disableUniformBuffers;
  12232. },
  12233. enumerable: true,
  12234. configurable: true
  12235. });
  12236. Object.defineProperty(Engine.prototype, "needPOTTextures", {
  12237. /**
  12238. * Gets a boolean indicating that only power of 2 textures are supported
  12239. * Please note that you can still use non power of 2 textures but in this case the engine will forcefully convert them
  12240. */
  12241. get: function () {
  12242. return this._webGLVersion < 2 || this.forcePOTTextures;
  12243. },
  12244. enumerable: true,
  12245. configurable: true
  12246. });
  12247. Object.defineProperty(Engine.prototype, "doNotHandleContextLost", {
  12248. /**
  12249. * Gets or sets a boolean indicating if resources should be retained to be able to handle context lost events
  12250. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#handling-webgl-context-lost
  12251. */
  12252. get: function () {
  12253. return this._doNotHandleContextLost;
  12254. },
  12255. set: function (value) {
  12256. this._doNotHandleContextLost = value;
  12257. },
  12258. enumerable: true,
  12259. configurable: true
  12260. });
  12261. Object.defineProperty(Engine.prototype, "performanceMonitor", {
  12262. /**
  12263. * Gets the performance monitor attached to this engine
  12264. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#engineinstrumentation
  12265. */
  12266. get: function () {
  12267. return this._performanceMonitor;
  12268. },
  12269. enumerable: true,
  12270. configurable: true
  12271. });
  12272. Object.defineProperty(Engine.prototype, "texturesSupported", {
  12273. /**
  12274. * Gets the list of texture formats supported
  12275. */
  12276. get: function () {
  12277. return this._texturesSupported;
  12278. },
  12279. enumerable: true,
  12280. configurable: true
  12281. });
  12282. Object.defineProperty(Engine.prototype, "textureFormatInUse", {
  12283. /**
  12284. * Gets the list of texture formats in use
  12285. */
  12286. get: function () {
  12287. return this._textureFormatInUse;
  12288. },
  12289. enumerable: true,
  12290. configurable: true
  12291. });
  12292. Object.defineProperty(Engine.prototype, "currentViewport", {
  12293. /**
  12294. * Gets the current viewport
  12295. */
  12296. get: function () {
  12297. return this._cachedViewport;
  12298. },
  12299. enumerable: true,
  12300. configurable: true
  12301. });
  12302. Object.defineProperty(Engine.prototype, "emptyTexture", {
  12303. /**
  12304. * Gets the default empty texture
  12305. */
  12306. get: function () {
  12307. if (!this._emptyTexture) {
  12308. this._emptyTexture = this.createRawTexture(new Uint8Array(4), 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12309. }
  12310. return this._emptyTexture;
  12311. },
  12312. enumerable: true,
  12313. configurable: true
  12314. });
  12315. Object.defineProperty(Engine.prototype, "emptyTexture3D", {
  12316. /**
  12317. * Gets the default empty 3D texture
  12318. */
  12319. get: function () {
  12320. if (!this._emptyTexture3D) {
  12321. this._emptyTexture3D = this.createRawTexture3D(new Uint8Array(4), 1, 1, 1, Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12322. }
  12323. return this._emptyTexture3D;
  12324. },
  12325. enumerable: true,
  12326. configurable: true
  12327. });
  12328. Object.defineProperty(Engine.prototype, "emptyCubeTexture", {
  12329. /**
  12330. * Gets the default empty cube texture
  12331. */
  12332. get: function () {
  12333. if (!this._emptyCubeTexture) {
  12334. var faceData = new Uint8Array(4);
  12335. var cubeData = [faceData, faceData, faceData, faceData, faceData, faceData];
  12336. this._emptyCubeTexture = this.createRawCubeTexture(cubeData, 1, Engine.TEXTUREFORMAT_RGBA, Engine.TEXTURETYPE_UNSIGNED_INT, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  12337. }
  12338. return this._emptyCubeTexture;
  12339. },
  12340. enumerable: true,
  12341. configurable: true
  12342. });
  12343. Engine.prototype._rebuildInternalTextures = function () {
  12344. var currentState = this._internalTexturesCache.slice(); // Do a copy because the rebuild will add proxies
  12345. for (var _i = 0, currentState_1 = currentState; _i < currentState_1.length; _i++) {
  12346. var internalTexture = currentState_1[_i];
  12347. internalTexture._rebuild();
  12348. }
  12349. };
  12350. Engine.prototype._rebuildEffects = function () {
  12351. for (var key in this._compiledEffects) {
  12352. var effect = this._compiledEffects[key];
  12353. effect._prepareEffect();
  12354. }
  12355. BABYLON.Effect.ResetCache();
  12356. };
  12357. Engine.prototype._rebuildBuffers = function () {
  12358. // Index / Vertex
  12359. for (var _i = 0, _a = this.scenes; _i < _a.length; _i++) {
  12360. var scene = _a[_i];
  12361. scene.resetCachedMaterial();
  12362. scene._rebuildGeometries();
  12363. scene._rebuildTextures();
  12364. }
  12365. // Uniforms
  12366. for (var _b = 0, _c = this._uniformBuffers; _b < _c.length; _b++) {
  12367. var uniformBuffer = _c[_b];
  12368. uniformBuffer._rebuild();
  12369. }
  12370. };
  12371. Engine.prototype._initGLContext = function () {
  12372. // Caps
  12373. this._caps = new EngineCapabilities();
  12374. this._caps.maxTexturesImageUnits = this._gl.getParameter(this._gl.MAX_TEXTURE_IMAGE_UNITS);
  12375. this._caps.maxCombinedTexturesImageUnits = this._gl.getParameter(this._gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS);
  12376. this._caps.maxVertexTextureImageUnits = this._gl.getParameter(this._gl.MAX_VERTEX_TEXTURE_IMAGE_UNITS);
  12377. this._caps.maxTextureSize = this._gl.getParameter(this._gl.MAX_TEXTURE_SIZE);
  12378. this._caps.maxCubemapTextureSize = this._gl.getParameter(this._gl.MAX_CUBE_MAP_TEXTURE_SIZE);
  12379. this._caps.maxRenderTextureSize = this._gl.getParameter(this._gl.MAX_RENDERBUFFER_SIZE);
  12380. this._caps.maxVertexAttribs = this._gl.getParameter(this._gl.MAX_VERTEX_ATTRIBS);
  12381. this._caps.maxVaryingVectors = this._gl.getParameter(this._gl.MAX_VARYING_VECTORS);
  12382. this._caps.maxFragmentUniformVectors = this._gl.getParameter(this._gl.MAX_FRAGMENT_UNIFORM_VECTORS);
  12383. this._caps.maxVertexUniformVectors = this._gl.getParameter(this._gl.MAX_VERTEX_UNIFORM_VECTORS);
  12384. // Infos
  12385. this._glVersion = this._gl.getParameter(this._gl.VERSION);
  12386. var rendererInfo = this._gl.getExtension("WEBGL_debug_renderer_info");
  12387. if (rendererInfo != null) {
  12388. this._glRenderer = this._gl.getParameter(rendererInfo.UNMASKED_RENDERER_WEBGL);
  12389. this._glVendor = this._gl.getParameter(rendererInfo.UNMASKED_VENDOR_WEBGL);
  12390. }
  12391. if (!this._glVendor) {
  12392. this._glVendor = "Unknown vendor";
  12393. }
  12394. if (!this._glRenderer) {
  12395. this._glRenderer = "Unknown renderer";
  12396. }
  12397. // Constants
  12398. this._gl.HALF_FLOAT_OES = 0x8D61; // Half floating-point type (16-bit).
  12399. if (this._gl.RGBA16F !== 0x881A) {
  12400. this._gl.RGBA16F = 0x881A; // RGBA 16-bit floating-point color-renderable internal sized format.
  12401. }
  12402. if (this._gl.RGBA32F !== 0x8814) {
  12403. this._gl.RGBA32F = 0x8814; // RGBA 32-bit floating-point color-renderable internal sized format.
  12404. }
  12405. if (this._gl.DEPTH24_STENCIL8 !== 35056) {
  12406. this._gl.DEPTH24_STENCIL8 = 35056;
  12407. }
  12408. // Extensions
  12409. this._caps.standardDerivatives = this._webGLVersion > 1 || (this._gl.getExtension('OES_standard_derivatives') !== null);
  12410. this._caps.astc = this._gl.getExtension('WEBGL_compressed_texture_astc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_astc');
  12411. this._caps.s3tc = this._gl.getExtension('WEBGL_compressed_texture_s3tc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_s3tc');
  12412. this._caps.pvrtc = this._gl.getExtension('WEBGL_compressed_texture_pvrtc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_pvrtc');
  12413. this._caps.etc1 = this._gl.getExtension('WEBGL_compressed_texture_etc1') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc1');
  12414. this._caps.etc2 = this._gl.getExtension('WEBGL_compressed_texture_etc') || this._gl.getExtension('WEBKIT_WEBGL_compressed_texture_etc') ||
  12415. this._gl.getExtension('WEBGL_compressed_texture_es3_0'); // also a requirement of OpenGL ES 3
  12416. 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');
  12417. this._caps.maxAnisotropy = this._caps.textureAnisotropicFilterExtension ? this._gl.getParameter(this._caps.textureAnisotropicFilterExtension.MAX_TEXTURE_MAX_ANISOTROPY_EXT) : 0;
  12418. this._caps.uintIndices = this._webGLVersion > 1 || this._gl.getExtension('OES_element_index_uint') !== null;
  12419. this._caps.fragmentDepthSupported = this._webGLVersion > 1 || this._gl.getExtension('EXT_frag_depth') !== null;
  12420. this._caps.highPrecisionShaderSupported = true;
  12421. this._caps.timerQuery = this._gl.getExtension('EXT_disjoint_timer_query_webgl2') || this._gl.getExtension("EXT_disjoint_timer_query");
  12422. if (this._caps.timerQuery) {
  12423. if (this._webGLVersion === 1) {
  12424. this._gl.getQuery = this._caps.timerQuery.getQueryEXT.bind(this._caps.timerQuery);
  12425. }
  12426. this._caps.canUseTimestampForTimerQuery = this._gl.getQuery(this._caps.timerQuery.TIMESTAMP_EXT, this._caps.timerQuery.QUERY_COUNTER_BITS_EXT) > 0;
  12427. }
  12428. // Checks if some of the format renders first to allow the use of webgl inspector.
  12429. this._caps.colorBufferFloat = this._webGLVersion > 1 && this._gl.getExtension('EXT_color_buffer_float');
  12430. this._caps.textureFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_float')) ? true : false;
  12431. this._caps.textureFloatLinearFiltering = this._caps.textureFloat && this._gl.getExtension('OES_texture_float_linear') ? true : false;
  12432. this._caps.textureFloatRender = this._caps.textureFloat && this._canRenderToFloatFramebuffer() ? true : false;
  12433. this._caps.textureHalfFloat = (this._webGLVersion > 1 || this._gl.getExtension('OES_texture_half_float')) ? true : false;
  12434. this._caps.textureHalfFloatLinearFiltering = (this._webGLVersion > 1 || (this._caps.textureHalfFloat && this._gl.getExtension('OES_texture_half_float_linear'))) ? true : false;
  12435. if (this._webGLVersion > 1) {
  12436. this._gl.HALF_FLOAT_OES = 0x140B;
  12437. }
  12438. this._caps.textureHalfFloatRender = this._caps.textureHalfFloat && this._canRenderToHalfFloatFramebuffer();
  12439. this._caps.textureLOD = (this._webGLVersion > 1 || this._gl.getExtension('EXT_shader_texture_lod')) ? true : false;
  12440. // Draw buffers
  12441. if (this._webGLVersion > 1) {
  12442. this._caps.drawBuffersExtension = true;
  12443. }
  12444. else {
  12445. var drawBuffersExtension = this._gl.getExtension('WEBGL_draw_buffers');
  12446. if (drawBuffersExtension !== null) {
  12447. this._caps.drawBuffersExtension = true;
  12448. this._gl.drawBuffers = drawBuffersExtension.drawBuffersWEBGL.bind(drawBuffersExtension);
  12449. this._gl.DRAW_FRAMEBUFFER = this._gl.FRAMEBUFFER;
  12450. for (var i = 0; i < 16; i++) {
  12451. this._gl["COLOR_ATTACHMENT" + i + "_WEBGL"] = drawBuffersExtension["COLOR_ATTACHMENT" + i + "_WEBGL"];
  12452. }
  12453. }
  12454. else {
  12455. this._caps.drawBuffersExtension = false;
  12456. }
  12457. }
  12458. // Depth Texture
  12459. if (this._webGLVersion > 1) {
  12460. this._caps.depthTextureExtension = true;
  12461. }
  12462. else {
  12463. var depthTextureExtension = this._gl.getExtension('WEBGL_depth_texture');
  12464. if (depthTextureExtension != null) {
  12465. this._caps.depthTextureExtension = true;
  12466. this._gl.UNSIGNED_INT_24_8 = depthTextureExtension.UNSIGNED_INT_24_8_WEBGL;
  12467. }
  12468. }
  12469. // Vertex array object
  12470. if (this._webGLVersion > 1) {
  12471. this._caps.vertexArrayObject = true;
  12472. }
  12473. else {
  12474. var vertexArrayObjectExtension = this._gl.getExtension('OES_vertex_array_object');
  12475. if (vertexArrayObjectExtension != null) {
  12476. this._caps.vertexArrayObject = true;
  12477. this._gl.createVertexArray = vertexArrayObjectExtension.createVertexArrayOES.bind(vertexArrayObjectExtension);
  12478. this._gl.bindVertexArray = vertexArrayObjectExtension.bindVertexArrayOES.bind(vertexArrayObjectExtension);
  12479. this._gl.deleteVertexArray = vertexArrayObjectExtension.deleteVertexArrayOES.bind(vertexArrayObjectExtension);
  12480. }
  12481. else {
  12482. this._caps.vertexArrayObject = false;
  12483. }
  12484. }
  12485. // Instances count
  12486. if (this._webGLVersion > 1) {
  12487. this._caps.instancedArrays = true;
  12488. }
  12489. else {
  12490. var instanceExtension = this._gl.getExtension('ANGLE_instanced_arrays');
  12491. if (instanceExtension != null) {
  12492. this._caps.instancedArrays = true;
  12493. this._gl.drawArraysInstanced = instanceExtension.drawArraysInstancedANGLE.bind(instanceExtension);
  12494. this._gl.drawElementsInstanced = instanceExtension.drawElementsInstancedANGLE.bind(instanceExtension);
  12495. this._gl.vertexAttribDivisor = instanceExtension.vertexAttribDivisorANGLE.bind(instanceExtension);
  12496. }
  12497. else {
  12498. this._caps.instancedArrays = false;
  12499. }
  12500. }
  12501. // Intelligently add supported compressed formats in order to check for.
  12502. // Check for ASTC support first as it is most powerful and to be very cross platform.
  12503. // Next PVRTC & DXT, which are probably superior to ETC1/2.
  12504. // Likely no hardware which supports both PVR & DXT, so order matters little.
  12505. // ETC2 is newer and handles ETC1 (no alpha capability), so check for first.
  12506. if (this._caps.astc)
  12507. this.texturesSupported.push('-astc.ktx');
  12508. if (this._caps.s3tc)
  12509. this.texturesSupported.push('-dxt.ktx');
  12510. if (this._caps.pvrtc)
  12511. this.texturesSupported.push('-pvrtc.ktx');
  12512. if (this._caps.etc2)
  12513. this.texturesSupported.push('-etc2.ktx');
  12514. if (this._caps.etc1)
  12515. this.texturesSupported.push('-etc1.ktx');
  12516. if (this._gl.getShaderPrecisionFormat) {
  12517. var highp = this._gl.getShaderPrecisionFormat(this._gl.FRAGMENT_SHADER, this._gl.HIGH_FLOAT);
  12518. if (highp) {
  12519. this._caps.highPrecisionShaderSupported = highp.precision !== 0;
  12520. }
  12521. }
  12522. // Depth buffer
  12523. this.setDepthBuffer(true);
  12524. this.setDepthFunctionToLessOrEqual();
  12525. this.setDepthWrite(true);
  12526. // Texture maps
  12527. this._maxSimultaneousTextures = this._caps.maxCombinedTexturesImageUnits;
  12528. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12529. this._nextFreeTextureSlots.push(slot);
  12530. }
  12531. };
  12532. Object.defineProperty(Engine.prototype, "webGLVersion", {
  12533. /**
  12534. * Gets version of the current webGL context
  12535. */
  12536. get: function () {
  12537. return this._webGLVersion;
  12538. },
  12539. enumerable: true,
  12540. configurable: true
  12541. });
  12542. Object.defineProperty(Engine.prototype, "isStencilEnable", {
  12543. /**
  12544. * Returns true if the stencil buffer has been enabled through the creation option of the context.
  12545. */
  12546. get: function () {
  12547. return this._isStencilEnable;
  12548. },
  12549. enumerable: true,
  12550. configurable: true
  12551. });
  12552. Engine.prototype._prepareWorkingCanvas = function () {
  12553. if (this._workingCanvas) {
  12554. return;
  12555. }
  12556. this._workingCanvas = document.createElement("canvas");
  12557. var context = this._workingCanvas.getContext("2d");
  12558. if (context) {
  12559. this._workingContext = context;
  12560. }
  12561. };
  12562. /**
  12563. * Reset the texture cache to empty state
  12564. */
  12565. Engine.prototype.resetTextureCache = function () {
  12566. for (var key in this._boundTexturesCache) {
  12567. if (!this._boundTexturesCache.hasOwnProperty(key)) {
  12568. continue;
  12569. }
  12570. var boundTexture = this._boundTexturesCache[key];
  12571. if (boundTexture) {
  12572. this._removeDesignatedSlot(boundTexture);
  12573. }
  12574. this._boundTexturesCache[key] = null;
  12575. }
  12576. if (!this.disableTextureBindingOptimization) {
  12577. this._nextFreeTextureSlots = [];
  12578. for (var slot = 0; slot < this._maxSimultaneousTextures; slot++) {
  12579. this._nextFreeTextureSlots.push(slot);
  12580. }
  12581. }
  12582. this._currentTextureChannel = -1;
  12583. };
  12584. /**
  12585. * Gets a boolean indicating that the engine is running in deterministic lock step mode
  12586. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12587. * @returns true if engine is in deterministic lock step mode
  12588. */
  12589. Engine.prototype.isDeterministicLockStep = function () {
  12590. return this._deterministicLockstep;
  12591. };
  12592. /**
  12593. * Gets the max steps when engine is running in deterministic lock step
  12594. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  12595. * @returns the max steps
  12596. */
  12597. Engine.prototype.getLockstepMaxSteps = function () {
  12598. return this._lockstepMaxSteps;
  12599. };
  12600. /**
  12601. * Gets an object containing information about the current webGL context
  12602. * @returns an object containing the vender, the renderer and the version of the current webGL context
  12603. */
  12604. Engine.prototype.getGlInfo = function () {
  12605. return {
  12606. vendor: this._glVendor,
  12607. renderer: this._glRenderer,
  12608. version: this._glVersion
  12609. };
  12610. };
  12611. /**
  12612. * Gets current aspect ratio
  12613. * @param camera defines the camera to use to get the aspect ratio
  12614. * @param useScreen defines if screen size must be used (or the current render target if any)
  12615. * @returns a number defining the aspect ratio
  12616. */
  12617. Engine.prototype.getAspectRatio = function (camera, useScreen) {
  12618. if (useScreen === void 0) { useScreen = false; }
  12619. var viewport = camera.viewport;
  12620. return (this.getRenderWidth(useScreen) * viewport.width) / (this.getRenderHeight(useScreen) * viewport.height);
  12621. };
  12622. /**
  12623. * Gets current screen aspect ratio
  12624. * @returns a number defining the aspect ratio
  12625. */
  12626. Engine.prototype.getScreenAspectRatio = function () {
  12627. return (this.getRenderWidth(true)) / (this.getRenderHeight(true));
  12628. };
  12629. /**
  12630. * Gets the current render width
  12631. * @param useScreen defines if screen size must be used (or the current render target if any)
  12632. * @returns a number defining the current render width
  12633. */
  12634. Engine.prototype.getRenderWidth = function (useScreen) {
  12635. if (useScreen === void 0) { useScreen = false; }
  12636. if (!useScreen && this._currentRenderTarget) {
  12637. return this._currentRenderTarget.width;
  12638. }
  12639. return this._gl.drawingBufferWidth;
  12640. };
  12641. /**
  12642. * Gets the current render height
  12643. * @param useScreen defines if screen size must be used (or the current render target if any)
  12644. * @returns a number defining the current render height
  12645. */
  12646. Engine.prototype.getRenderHeight = function (useScreen) {
  12647. if (useScreen === void 0) { useScreen = false; }
  12648. if (!useScreen && this._currentRenderTarget) {
  12649. return this._currentRenderTarget.height;
  12650. }
  12651. return this._gl.drawingBufferHeight;
  12652. };
  12653. /**
  12654. * Gets the HTML canvas attached with the current webGL context
  12655. * @returns a HTML canvas
  12656. */
  12657. Engine.prototype.getRenderingCanvas = function () {
  12658. return this._renderingCanvas;
  12659. };
  12660. /**
  12661. * Gets the client rect of the HTML canvas attached with the current webGL context
  12662. * @returns a client rectanglee
  12663. */
  12664. Engine.prototype.getRenderingCanvasClientRect = function () {
  12665. if (!this._renderingCanvas) {
  12666. return null;
  12667. }
  12668. return this._renderingCanvas.getBoundingClientRect();
  12669. };
  12670. /**
  12671. * Defines the hardware scaling level.
  12672. * By default the hardware scaling level is computed from the window device ratio.
  12673. * 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.
  12674. * @param level defines the level to use
  12675. */
  12676. Engine.prototype.setHardwareScalingLevel = function (level) {
  12677. this._hardwareScalingLevel = level;
  12678. this.resize();
  12679. };
  12680. /**
  12681. * Gets the current hardware scaling level.
  12682. * By default the hardware scaling level is computed from the window device ratio.
  12683. * 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.
  12684. * @returns a number indicating the current hardware scaling level
  12685. */
  12686. Engine.prototype.getHardwareScalingLevel = function () {
  12687. return this._hardwareScalingLevel;
  12688. };
  12689. /**
  12690. * Gets the list of loaded textures
  12691. * @returns an array containing all loaded textures
  12692. */
  12693. Engine.prototype.getLoadedTexturesCache = function () {
  12694. return this._internalTexturesCache;
  12695. };
  12696. /**
  12697. * Gets the object containing all engine capabilities
  12698. * @returns the EngineCapabilities object
  12699. */
  12700. Engine.prototype.getCaps = function () {
  12701. return this._caps;
  12702. };
  12703. Object.defineProperty(Engine.prototype, "drawCalls", {
  12704. /** @hidden */
  12705. get: function () {
  12706. BABYLON.Tools.Warn("drawCalls is deprecated. Please use SceneInstrumentation class");
  12707. return 0;
  12708. },
  12709. enumerable: true,
  12710. configurable: true
  12711. });
  12712. Object.defineProperty(Engine.prototype, "drawCallsPerfCounter", {
  12713. /** @hidden */
  12714. get: function () {
  12715. BABYLON.Tools.Warn("drawCallsPerfCounter is deprecated. Please use SceneInstrumentation class");
  12716. return null;
  12717. },
  12718. enumerable: true,
  12719. configurable: true
  12720. });
  12721. /**
  12722. * Gets the current depth function
  12723. * @returns a number defining the depth function
  12724. */
  12725. Engine.prototype.getDepthFunction = function () {
  12726. return this._depthCullingState.depthFunc;
  12727. };
  12728. /**
  12729. * Sets the current depth function
  12730. * @param depthFunc defines the function to use
  12731. */
  12732. Engine.prototype.setDepthFunction = function (depthFunc) {
  12733. this._depthCullingState.depthFunc = depthFunc;
  12734. };
  12735. /**
  12736. * Sets the current depth function to GREATER
  12737. */
  12738. Engine.prototype.setDepthFunctionToGreater = function () {
  12739. this._depthCullingState.depthFunc = this._gl.GREATER;
  12740. };
  12741. /**
  12742. * Sets the current depth function to GEQUAL
  12743. */
  12744. Engine.prototype.setDepthFunctionToGreaterOrEqual = function () {
  12745. this._depthCullingState.depthFunc = this._gl.GEQUAL;
  12746. };
  12747. /**
  12748. * Sets the current depth function to LESS
  12749. */
  12750. Engine.prototype.setDepthFunctionToLess = function () {
  12751. this._depthCullingState.depthFunc = this._gl.LESS;
  12752. };
  12753. /**
  12754. * Sets the current depth function to LEQUAL
  12755. */
  12756. Engine.prototype.setDepthFunctionToLessOrEqual = function () {
  12757. this._depthCullingState.depthFunc = this._gl.LEQUAL;
  12758. };
  12759. /**
  12760. * Gets a boolean indicating if stencil buffer is enabled
  12761. * @returns the current stencil buffer state
  12762. */
  12763. Engine.prototype.getStencilBuffer = function () {
  12764. return this._stencilState.stencilTest;
  12765. };
  12766. /**
  12767. * Enable or disable the stencil buffer
  12768. * @param enable defines if the stencil buffer must be enabled or disabled
  12769. */
  12770. Engine.prototype.setStencilBuffer = function (enable) {
  12771. this._stencilState.stencilTest = enable;
  12772. };
  12773. /**
  12774. * Gets the current stencil mask
  12775. * @returns a number defining the new stencil mask to use
  12776. */
  12777. Engine.prototype.getStencilMask = function () {
  12778. return this._stencilState.stencilMask;
  12779. };
  12780. /**
  12781. * Sets the current stencil mask
  12782. * @param mask defines the new stencil mask to use
  12783. */
  12784. Engine.prototype.setStencilMask = function (mask) {
  12785. this._stencilState.stencilMask = mask;
  12786. };
  12787. /**
  12788. * Gets the current stencil function
  12789. * @returns a number defining the stencil function to use
  12790. */
  12791. Engine.prototype.getStencilFunction = function () {
  12792. return this._stencilState.stencilFunc;
  12793. };
  12794. /**
  12795. * Gets the current stencil reference value
  12796. * @returns a number defining the stencil reference value to use
  12797. */
  12798. Engine.prototype.getStencilFunctionReference = function () {
  12799. return this._stencilState.stencilFuncRef;
  12800. };
  12801. /**
  12802. * Gets the current stencil mask
  12803. * @returns a number defining the stencil mask to use
  12804. */
  12805. Engine.prototype.getStencilFunctionMask = function () {
  12806. return this._stencilState.stencilFuncMask;
  12807. };
  12808. /**
  12809. * Sets the current stencil function
  12810. * @param stencilFunc defines the new stencil function to use
  12811. */
  12812. Engine.prototype.setStencilFunction = function (stencilFunc) {
  12813. this._stencilState.stencilFunc = stencilFunc;
  12814. };
  12815. /**
  12816. * Sets the current stencil reference
  12817. * @param reference defines the new stencil reference to use
  12818. */
  12819. Engine.prototype.setStencilFunctionReference = function (reference) {
  12820. this._stencilState.stencilFuncRef = reference;
  12821. };
  12822. /**
  12823. * Sets the current stencil mask
  12824. * @param mask defines the new stencil mask to use
  12825. */
  12826. Engine.prototype.setStencilFunctionMask = function (mask) {
  12827. this._stencilState.stencilFuncMask = mask;
  12828. };
  12829. /**
  12830. * Gets the current stencil operation when stencil fails
  12831. * @returns a number defining stencil operation to use when stencil fails
  12832. */
  12833. Engine.prototype.getStencilOperationFail = function () {
  12834. return this._stencilState.stencilOpStencilFail;
  12835. };
  12836. /**
  12837. * Gets the current stencil operation when depth fails
  12838. * @returns a number defining stencil operation to use when depth fails
  12839. */
  12840. Engine.prototype.getStencilOperationDepthFail = function () {
  12841. return this._stencilState.stencilOpDepthFail;
  12842. };
  12843. /**
  12844. * Gets the current stencil operation when stencil passes
  12845. * @returns a number defining stencil operation to use when stencil passes
  12846. */
  12847. Engine.prototype.getStencilOperationPass = function () {
  12848. return this._stencilState.stencilOpStencilDepthPass;
  12849. };
  12850. /**
  12851. * Sets the stencil operation to use when stencil fails
  12852. * @param operation defines the stencil operation to use when stencil fails
  12853. */
  12854. Engine.prototype.setStencilOperationFail = function (operation) {
  12855. this._stencilState.stencilOpStencilFail = operation;
  12856. };
  12857. /**
  12858. * Sets the stencil operation to use when depth fails
  12859. * @param operation defines the stencil operation to use when depth fails
  12860. */
  12861. Engine.prototype.setStencilOperationDepthFail = function (operation) {
  12862. this._stencilState.stencilOpDepthFail = operation;
  12863. };
  12864. /**
  12865. * Sets the stencil operation to use when stencil passes
  12866. * @param operation defines the stencil operation to use when stencil passes
  12867. */
  12868. Engine.prototype.setStencilOperationPass = function (operation) {
  12869. this._stencilState.stencilOpStencilDepthPass = operation;
  12870. };
  12871. /**
  12872. * Sets a boolean indicating if the dithering state is enabled or disabled
  12873. * @param value defines the dithering state
  12874. */
  12875. Engine.prototype.setDitheringState = function (value) {
  12876. if (value) {
  12877. this._gl.enable(this._gl.DITHER);
  12878. }
  12879. else {
  12880. this._gl.disable(this._gl.DITHER);
  12881. }
  12882. };
  12883. /**
  12884. * Sets a boolean indicating if the rasterizer state is enabled or disabled
  12885. * @param value defines the rasterizer state
  12886. */
  12887. Engine.prototype.setRasterizerState = function (value) {
  12888. if (value) {
  12889. this._gl.disable(this._gl.RASTERIZER_DISCARD);
  12890. }
  12891. else {
  12892. this._gl.enable(this._gl.RASTERIZER_DISCARD);
  12893. }
  12894. };
  12895. /**
  12896. * stop executing a render loop function and remove it from the execution array
  12897. * @param renderFunction defines the function to be removed. If not provided all functions will be removed.
  12898. */
  12899. Engine.prototype.stopRenderLoop = function (renderFunction) {
  12900. if (!renderFunction) {
  12901. this._activeRenderLoops = [];
  12902. return;
  12903. }
  12904. var index = this._activeRenderLoops.indexOf(renderFunction);
  12905. if (index >= 0) {
  12906. this._activeRenderLoops.splice(index, 1);
  12907. }
  12908. };
  12909. /** @hidden */
  12910. Engine.prototype._renderLoop = function () {
  12911. if (!this._contextWasLost) {
  12912. var shouldRender = true;
  12913. if (!this.renderEvenInBackground && this._windowIsBackground) {
  12914. shouldRender = false;
  12915. }
  12916. if (shouldRender) {
  12917. // Start new frame
  12918. this.beginFrame();
  12919. for (var index = 0; index < this._activeRenderLoops.length; index++) {
  12920. var renderFunction = this._activeRenderLoops[index];
  12921. renderFunction();
  12922. }
  12923. // Present
  12924. this.endFrame();
  12925. }
  12926. }
  12927. if (this._activeRenderLoops.length > 0) {
  12928. // Register new frame
  12929. var requester = null;
  12930. if (this._vrDisplay && this._vrDisplay.isPresenting)
  12931. requester = this._vrDisplay;
  12932. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction, requester);
  12933. }
  12934. else {
  12935. this._renderingQueueLaunched = false;
  12936. }
  12937. };
  12938. /**
  12939. * Register and execute a render loop. The engine can have more than one render function
  12940. * @param renderFunction defines the function to continuously execute
  12941. */
  12942. Engine.prototype.runRenderLoop = function (renderFunction) {
  12943. if (this._activeRenderLoops.indexOf(renderFunction) !== -1) {
  12944. return;
  12945. }
  12946. this._activeRenderLoops.push(renderFunction);
  12947. if (!this._renderingQueueLaunched) {
  12948. this._renderingQueueLaunched = true;
  12949. this._bindedRenderFunction = this._renderLoop.bind(this);
  12950. this._frameHandler = BABYLON.Tools.QueueNewFrame(this._bindedRenderFunction);
  12951. }
  12952. };
  12953. /**
  12954. * Toggle full screen mode
  12955. * @param requestPointerLock defines if a pointer lock should be requested from the user
  12956. * @param options defines an option object to be sent to the requestFullscreen function
  12957. */
  12958. Engine.prototype.switchFullscreen = function (requestPointerLock) {
  12959. if (this.isFullscreen) {
  12960. BABYLON.Tools.ExitFullscreen();
  12961. }
  12962. else {
  12963. this._pointerLockRequested = requestPointerLock;
  12964. if (this._renderingCanvas) {
  12965. BABYLON.Tools.RequestFullscreen(this._renderingCanvas);
  12966. }
  12967. }
  12968. };
  12969. /**
  12970. * Clear the current render buffer or the current render target (if any is set up)
  12971. * @param color defines the color to use
  12972. * @param backBuffer defines if the back buffer must be cleared
  12973. * @param depth defines if the depth buffer must be cleared
  12974. * @param stencil defines if the stencil buffer must be cleared
  12975. */
  12976. Engine.prototype.clear = function (color, backBuffer, depth, stencil) {
  12977. if (stencil === void 0) { stencil = false; }
  12978. this.applyStates();
  12979. var mode = 0;
  12980. if (backBuffer && color) {
  12981. this._gl.clearColor(color.r, color.g, color.b, color.a !== undefined ? color.a : 1.0);
  12982. mode |= this._gl.COLOR_BUFFER_BIT;
  12983. }
  12984. if (depth) {
  12985. this._gl.clearDepth(1.0);
  12986. mode |= this._gl.DEPTH_BUFFER_BIT;
  12987. }
  12988. if (stencil) {
  12989. this._gl.clearStencil(0);
  12990. mode |= this._gl.STENCIL_BUFFER_BIT;
  12991. }
  12992. this._gl.clear(mode);
  12993. };
  12994. /**
  12995. * Executes a scissor clear (ie. a clear on a specific portion of the screen)
  12996. * @param x defines the x-coordinate of the top left corner of the clear rectangle
  12997. * @param y defines the y-coordinate of the corner of the clear rectangle
  12998. * @param width defines the width of the clear rectangle
  12999. * @param height defines the height of the clear rectangle
  13000. * @param clearColor defines the clear color
  13001. */
  13002. Engine.prototype.scissorClear = function (x, y, width, height, clearColor) {
  13003. var gl = this._gl;
  13004. // Save state
  13005. var curScissor = gl.getParameter(gl.SCISSOR_TEST);
  13006. var curScissorBox = gl.getParameter(gl.SCISSOR_BOX);
  13007. // Change state
  13008. gl.enable(gl.SCISSOR_TEST);
  13009. gl.scissor(x, y, width, height);
  13010. // Clear
  13011. this.clear(clearColor, true, true, true);
  13012. // Restore state
  13013. gl.scissor(curScissorBox[0], curScissorBox[1], curScissorBox[2], curScissorBox[3]);
  13014. if (curScissor === true) {
  13015. gl.enable(gl.SCISSOR_TEST);
  13016. }
  13017. else {
  13018. gl.disable(gl.SCISSOR_TEST);
  13019. }
  13020. };
  13021. /** @hidden */
  13022. Engine.prototype._viewport = function (x, y, width, height) {
  13023. if (x !== this._viewportCached.x ||
  13024. y !== this._viewportCached.y ||
  13025. width !== this._viewportCached.z ||
  13026. height !== this._viewportCached.w) {
  13027. this._viewportCached.x = x;
  13028. this._viewportCached.y = y;
  13029. this._viewportCached.z = width;
  13030. this._viewportCached.w = height;
  13031. this._gl.viewport(x, y, width, height);
  13032. }
  13033. };
  13034. /**
  13035. * Set the WebGL's viewport
  13036. * @param viewport defines the viewport element to be used
  13037. * @param requiredWidth defines the width required for rendering. If not provided the rendering canvas' width is used
  13038. * @param requiredHeight defines the height required for rendering. If not provided the rendering canvas' height is used
  13039. */
  13040. Engine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  13041. var width = requiredWidth || this.getRenderWidth();
  13042. var height = requiredHeight || this.getRenderHeight();
  13043. var x = viewport.x || 0;
  13044. var y = viewport.y || 0;
  13045. this._cachedViewport = viewport;
  13046. this._viewport(x * width, y * height, width * viewport.width, height * viewport.height);
  13047. };
  13048. /**
  13049. * Directly set the WebGL Viewport
  13050. * @param x defines the x coordinate of the viewport (in screen space)
  13051. * @param y defines the y coordinate of the viewport (in screen space)
  13052. * @param width defines the width of the viewport (in screen space)
  13053. * @param height defines the height of the viewport (in screen space)
  13054. * @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
  13055. */
  13056. Engine.prototype.setDirectViewport = function (x, y, width, height) {
  13057. var currentViewport = this._cachedViewport;
  13058. this._cachedViewport = null;
  13059. this._viewport(x, y, width, height);
  13060. return currentViewport;
  13061. };
  13062. /**
  13063. * Begin a new frame
  13064. */
  13065. Engine.prototype.beginFrame = function () {
  13066. this.onBeginFrameObservable.notifyObservers(this);
  13067. this._measureFps();
  13068. };
  13069. /**
  13070. * Enf the current frame
  13071. */
  13072. Engine.prototype.endFrame = function () {
  13073. // Force a flush in case we are using a bad OS.
  13074. if (this._badOS) {
  13075. this.flushFramebuffer();
  13076. }
  13077. // Submit frame to the vr device, if enabled
  13078. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13079. // TODO: We should only submit the frame if we read frameData successfully.
  13080. this._vrDisplay.submitFrame();
  13081. }
  13082. this.onEndFrameObservable.notifyObservers(this);
  13083. };
  13084. /**
  13085. * Resize the view according to the canvas' size
  13086. */
  13087. Engine.prototype.resize = function () {
  13088. // We're not resizing the size of the canvas while in VR mode & presenting
  13089. if (!(this._vrDisplay && this._vrDisplay.isPresenting)) {
  13090. var width = this._renderingCanvas ? this._renderingCanvas.clientWidth : window.innerWidth;
  13091. var height = this._renderingCanvas ? this._renderingCanvas.clientHeight : window.innerHeight;
  13092. this.setSize(width / this._hardwareScalingLevel, height / this._hardwareScalingLevel);
  13093. }
  13094. };
  13095. /**
  13096. * Force a specific size of the canvas
  13097. * @param width defines the new canvas' width
  13098. * @param height defines the new canvas' height
  13099. */
  13100. Engine.prototype.setSize = function (width, height) {
  13101. if (!this._renderingCanvas) {
  13102. return;
  13103. }
  13104. if (this._renderingCanvas.width === width && this._renderingCanvas.height === height) {
  13105. return;
  13106. }
  13107. this._renderingCanvas.width = width;
  13108. this._renderingCanvas.height = height;
  13109. for (var index = 0; index < this.scenes.length; index++) {
  13110. var scene = this.scenes[index];
  13111. for (var camIndex = 0; camIndex < scene.cameras.length; camIndex++) {
  13112. var cam = scene.cameras[camIndex];
  13113. cam._currentRenderId = 0;
  13114. }
  13115. }
  13116. if (this.onResizeObservable.hasObservers) {
  13117. this.onResizeObservable.notifyObservers(this);
  13118. }
  13119. };
  13120. // WebVR functions
  13121. /**
  13122. * Gets a boolean indicating if a webVR device was detected
  13123. * @returns true if a webVR device was detected
  13124. */
  13125. Engine.prototype.isVRDevicePresent = function () {
  13126. return !!this._vrDisplay;
  13127. };
  13128. /**
  13129. * Gets the current webVR device
  13130. * @returns the current webVR device (or null)
  13131. */
  13132. Engine.prototype.getVRDevice = function () {
  13133. return this._vrDisplay;
  13134. };
  13135. /**
  13136. * Initializes a webVR display and starts listening to display change events
  13137. * The onVRDisplayChangedObservable will be notified upon these changes
  13138. * @returns The onVRDisplayChangedObservable
  13139. */
  13140. Engine.prototype.initWebVR = function () {
  13141. this.initWebVRAsync();
  13142. return this.onVRDisplayChangedObservable;
  13143. };
  13144. /**
  13145. * Initializes a webVR display and starts listening to display change events
  13146. * The onVRDisplayChangedObservable will be notified upon these changes
  13147. * @returns A promise containing a VRDisplay and if vr is supported
  13148. */
  13149. Engine.prototype.initWebVRAsync = function () {
  13150. var _this = this;
  13151. var notifyObservers = function () {
  13152. var eventArgs = {
  13153. vrDisplay: _this._vrDisplay,
  13154. vrSupported: _this._vrSupported
  13155. };
  13156. _this.onVRDisplayChangedObservable.notifyObservers(eventArgs);
  13157. _this._webVRInitPromise = new Promise(function (res) { res(eventArgs); });
  13158. };
  13159. if (!this._onVrDisplayConnect) {
  13160. this._onVrDisplayConnect = function (event) {
  13161. _this._vrDisplay = event.display;
  13162. notifyObservers();
  13163. };
  13164. this._onVrDisplayDisconnect = function () {
  13165. _this._vrDisplay.cancelAnimationFrame(_this._frameHandler);
  13166. _this._vrDisplay = undefined;
  13167. _this._frameHandler = BABYLON.Tools.QueueNewFrame(_this._bindedRenderFunction);
  13168. notifyObservers();
  13169. };
  13170. this._onVrDisplayPresentChange = function () {
  13171. _this._vrExclusivePointerMode = _this._vrDisplay && _this._vrDisplay.isPresenting;
  13172. };
  13173. window.addEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  13174. window.addEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  13175. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  13176. }
  13177. this._webVRInitPromise = this._webVRInitPromise || this._getVRDisplaysAsync();
  13178. this._webVRInitPromise.then(notifyObservers);
  13179. return this._webVRInitPromise;
  13180. };
  13181. /**
  13182. * Call this function to switch to webVR mode
  13183. * Will do nothing if webVR is not supported or if there is no webVR device
  13184. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13185. */
  13186. Engine.prototype.enableVR = function () {
  13187. var _this = this;
  13188. if (this._vrDisplay && !this._vrDisplay.isPresenting) {
  13189. var onResolved = function () {
  13190. _this.onVRRequestPresentComplete.notifyObservers(true);
  13191. _this._onVRFullScreenTriggered();
  13192. };
  13193. var onRejected = function () {
  13194. _this.onVRRequestPresentComplete.notifyObservers(false);
  13195. };
  13196. this.onVRRequestPresentStart.notifyObservers(this);
  13197. this._vrDisplay.requestPresent([{ source: this.getRenderingCanvas() }]).then(onResolved).catch(onRejected);
  13198. }
  13199. };
  13200. /**
  13201. * Call this function to leave webVR mode
  13202. * Will do nothing if webVR is not supported or if there is no webVR device
  13203. * @see http://doc.babylonjs.com/how_to/webvr_camera
  13204. */
  13205. Engine.prototype.disableVR = function () {
  13206. if (this._vrDisplay && this._vrDisplay.isPresenting) {
  13207. this._vrDisplay.exitPresent().then(this._onVRFullScreenTriggered).catch(this._onVRFullScreenTriggered);
  13208. }
  13209. };
  13210. Engine.prototype._getVRDisplaysAsync = function () {
  13211. var _this = this;
  13212. return new Promise(function (res, rej) {
  13213. if (navigator.getVRDisplays) {
  13214. navigator.getVRDisplays().then(function (devices) {
  13215. _this._vrSupported = true;
  13216. // note that devices may actually be an empty array. This is fine;
  13217. // we expect this._vrDisplay to be undefined in this case.
  13218. _this._vrDisplay = devices[0];
  13219. res({
  13220. vrDisplay: _this._vrDisplay,
  13221. vrSupported: _this._vrSupported
  13222. });
  13223. });
  13224. }
  13225. else {
  13226. _this._vrDisplay = undefined;
  13227. _this._vrSupported = false;
  13228. res({
  13229. vrDisplay: _this._vrDisplay,
  13230. vrSupported: _this._vrSupported
  13231. });
  13232. }
  13233. });
  13234. };
  13235. /**
  13236. * Binds the frame buffer to the specified texture.
  13237. * @param texture The texture to render to or null for the default canvas
  13238. * @param faceIndex The face of the texture to render to in case of cube texture
  13239. * @param requiredWidth The width of the target to render to
  13240. * @param requiredHeight The height of the target to render to
  13241. * @param forceFullscreenViewport Forces the viewport to be the entire texture/screen if true
  13242. * @param depthStencilTexture The depth stencil texture to use to render
  13243. * @param lodLevel defines le lod level to bind to the frame buffer
  13244. */
  13245. Engine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport, depthStencilTexture, lodLevel) {
  13246. if (lodLevel === void 0) { lodLevel = 0; }
  13247. if (this._currentRenderTarget) {
  13248. this.unBindFramebuffer(this._currentRenderTarget);
  13249. }
  13250. this._currentRenderTarget = texture;
  13251. this.bindUnboundFramebuffer(texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer);
  13252. var gl = this._gl;
  13253. if (texture.isCube) {
  13254. if (faceIndex === undefined) {
  13255. faceIndex = 0;
  13256. }
  13257. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, lodLevel);
  13258. if (depthStencilTexture) {
  13259. if (depthStencilTexture._generateStencilBuffer) {
  13260. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13261. }
  13262. else {
  13263. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, depthStencilTexture._webGLTexture, lodLevel);
  13264. }
  13265. }
  13266. }
  13267. if (this._cachedViewport && !forceFullscreenViewport) {
  13268. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  13269. }
  13270. else {
  13271. if (!requiredWidth) {
  13272. requiredWidth = texture.width;
  13273. if (lodLevel) {
  13274. requiredWidth = requiredWidth / Math.pow(2, lodLevel);
  13275. }
  13276. }
  13277. if (!requiredHeight) {
  13278. requiredHeight = texture.height;
  13279. if (lodLevel) {
  13280. requiredHeight = requiredHeight / Math.pow(2, lodLevel);
  13281. }
  13282. }
  13283. this._viewport(0, 0, requiredWidth, requiredHeight);
  13284. }
  13285. this.wipeCaches();
  13286. };
  13287. Engine.prototype.bindUnboundFramebuffer = function (framebuffer) {
  13288. if (this._currentFramebuffer !== framebuffer) {
  13289. this._gl.bindFramebuffer(this._gl.FRAMEBUFFER, framebuffer);
  13290. this._currentFramebuffer = framebuffer;
  13291. }
  13292. };
  13293. /**
  13294. * Unbind the current render target texture from the webGL context
  13295. * @param texture defines the render target texture to unbind
  13296. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13297. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13298. */
  13299. Engine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  13300. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13301. this._currentRenderTarget = null;
  13302. // If MSAA, we need to bitblt back to main texture
  13303. var gl = this._gl;
  13304. if (texture._MSAAFramebuffer) {
  13305. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, texture._MSAAFramebuffer);
  13306. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, texture._framebuffer);
  13307. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13308. }
  13309. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13310. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  13311. gl.generateMipmap(gl.TEXTURE_2D);
  13312. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13313. }
  13314. if (onBeforeUnbind) {
  13315. if (texture._MSAAFramebuffer) {
  13316. // Bind the correct framebuffer
  13317. this.bindUnboundFramebuffer(texture._framebuffer);
  13318. }
  13319. onBeforeUnbind();
  13320. }
  13321. this.bindUnboundFramebuffer(null);
  13322. };
  13323. /**
  13324. * Unbind a list of render target textures from the webGL context
  13325. * This is used only when drawBuffer extension or webGL2 are active
  13326. * @param textures defines the render target textures to unbind
  13327. * @param disableGenerateMipMaps defines a boolean indicating that mipmaps must not be generated
  13328. * @param onBeforeUnbind defines a function which will be called before the effective unbind
  13329. */
  13330. Engine.prototype.unBindMultiColorAttachmentFramebuffer = function (textures, disableGenerateMipMaps, onBeforeUnbind) {
  13331. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  13332. this._currentRenderTarget = null;
  13333. // If MSAA, we need to bitblt back to main texture
  13334. var gl = this._gl;
  13335. if (textures[0]._MSAAFramebuffer) {
  13336. gl.bindFramebuffer(gl.READ_FRAMEBUFFER, textures[0]._MSAAFramebuffer);
  13337. gl.bindFramebuffer(gl.DRAW_FRAMEBUFFER, textures[0]._framebuffer);
  13338. var attachments = textures[0]._attachments;
  13339. if (!attachments) {
  13340. attachments = new Array(textures.length);
  13341. textures[0]._attachments = attachments;
  13342. }
  13343. for (var i = 0; i < textures.length; i++) {
  13344. var texture = textures[i];
  13345. for (var j = 0; j < attachments.length; j++) {
  13346. attachments[j] = gl.NONE;
  13347. }
  13348. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13349. gl.readBuffer(attachments[i]);
  13350. gl.drawBuffers(attachments);
  13351. gl.blitFramebuffer(0, 0, texture.width, texture.height, 0, 0, texture.width, texture.height, gl.COLOR_BUFFER_BIT, gl.NEAREST);
  13352. }
  13353. for (var i = 0; i < attachments.length; i++) {
  13354. attachments[i] = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  13355. }
  13356. gl.drawBuffers(attachments);
  13357. }
  13358. for (var i = 0; i < textures.length; i++) {
  13359. var texture = textures[i];
  13360. if (texture.generateMipMaps && !disableGenerateMipMaps && !texture.isCube) {
  13361. this._bindTextureDirectly(gl.TEXTURE_2D, texture);
  13362. gl.generateMipmap(gl.TEXTURE_2D);
  13363. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  13364. }
  13365. }
  13366. if (onBeforeUnbind) {
  13367. if (textures[0]._MSAAFramebuffer) {
  13368. // Bind the correct framebuffer
  13369. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  13370. }
  13371. onBeforeUnbind();
  13372. }
  13373. this.bindUnboundFramebuffer(null);
  13374. };
  13375. /**
  13376. * Force the mipmap generation for the given render target texture
  13377. * @param texture defines the render target texture to use
  13378. */
  13379. Engine.prototype.generateMipMapsForCubemap = function (texture) {
  13380. if (texture.generateMipMaps) {
  13381. var gl = this._gl;
  13382. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  13383. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  13384. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  13385. }
  13386. };
  13387. /**
  13388. * Force a webGL flush (ie. a flush of all waiting webGL commands)
  13389. */
  13390. Engine.prototype.flushFramebuffer = function () {
  13391. this._gl.flush();
  13392. };
  13393. /**
  13394. * Unbind the current render target and bind the default framebuffer
  13395. */
  13396. Engine.prototype.restoreDefaultFramebuffer = function () {
  13397. if (this._currentRenderTarget) {
  13398. this.unBindFramebuffer(this._currentRenderTarget);
  13399. }
  13400. else {
  13401. this.bindUnboundFramebuffer(null);
  13402. }
  13403. if (this._cachedViewport) {
  13404. this.setViewport(this._cachedViewport);
  13405. }
  13406. this.wipeCaches();
  13407. };
  13408. // UBOs
  13409. /**
  13410. * Create an uniform buffer
  13411. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13412. * @param elements defines the content of the uniform buffer
  13413. * @returns the webGL uniform buffer
  13414. */
  13415. Engine.prototype.createUniformBuffer = function (elements) {
  13416. var ubo = this._gl.createBuffer();
  13417. if (!ubo) {
  13418. throw new Error("Unable to create uniform buffer");
  13419. }
  13420. this.bindUniformBuffer(ubo);
  13421. if (elements instanceof Float32Array) {
  13422. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.STATIC_DRAW);
  13423. }
  13424. else {
  13425. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.STATIC_DRAW);
  13426. }
  13427. this.bindUniformBuffer(null);
  13428. ubo.references = 1;
  13429. return ubo;
  13430. };
  13431. /**
  13432. * Create a dynamic uniform buffer
  13433. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13434. * @param elements defines the content of the uniform buffer
  13435. * @returns the webGL uniform buffer
  13436. */
  13437. Engine.prototype.createDynamicUniformBuffer = function (elements) {
  13438. var ubo = this._gl.createBuffer();
  13439. if (!ubo) {
  13440. throw new Error("Unable to create dynamic uniform buffer");
  13441. }
  13442. this.bindUniformBuffer(ubo);
  13443. if (elements instanceof Float32Array) {
  13444. this._gl.bufferData(this._gl.UNIFORM_BUFFER, elements, this._gl.DYNAMIC_DRAW);
  13445. }
  13446. else {
  13447. this._gl.bufferData(this._gl.UNIFORM_BUFFER, new Float32Array(elements), this._gl.DYNAMIC_DRAW);
  13448. }
  13449. this.bindUniformBuffer(null);
  13450. ubo.references = 1;
  13451. return ubo;
  13452. };
  13453. /**
  13454. * Update an existing uniform buffer
  13455. * @see http://doc.babylonjs.com/features/webgl2#uniform-buffer-objets
  13456. * @param uniformBuffer defines the target uniform buffer
  13457. * @param elements defines the content to update
  13458. * @param offset defines the offset in the uniform buffer where update should start
  13459. * @param count defines the size of the data to update
  13460. */
  13461. Engine.prototype.updateUniformBuffer = function (uniformBuffer, elements, offset, count) {
  13462. this.bindUniformBuffer(uniformBuffer);
  13463. if (offset === undefined) {
  13464. offset = 0;
  13465. }
  13466. if (count === undefined) {
  13467. if (elements instanceof Float32Array) {
  13468. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, elements);
  13469. }
  13470. else {
  13471. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, offset, new Float32Array(elements));
  13472. }
  13473. }
  13474. else {
  13475. if (elements instanceof Float32Array) {
  13476. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, elements.subarray(offset, offset + count));
  13477. }
  13478. else {
  13479. this._gl.bufferSubData(this._gl.UNIFORM_BUFFER, 0, new Float32Array(elements).subarray(offset, offset + count));
  13480. }
  13481. }
  13482. this.bindUniformBuffer(null);
  13483. };
  13484. // VBOs
  13485. Engine.prototype._resetVertexBufferBinding = function () {
  13486. this.bindArrayBuffer(null);
  13487. this._cachedVertexBuffers = null;
  13488. };
  13489. /**
  13490. * Creates a vertex buffer
  13491. * @param data the data for the vertex buffer
  13492. * @returns the new WebGL static buffer
  13493. */
  13494. Engine.prototype.createVertexBuffer = function (data) {
  13495. var vbo = this._gl.createBuffer();
  13496. if (!vbo) {
  13497. throw new Error("Unable to create vertex buffer");
  13498. }
  13499. this.bindArrayBuffer(vbo);
  13500. if (data instanceof Array) {
  13501. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.STATIC_DRAW);
  13502. }
  13503. else {
  13504. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.STATIC_DRAW);
  13505. }
  13506. this._resetVertexBufferBinding();
  13507. vbo.references = 1;
  13508. return vbo;
  13509. };
  13510. /**
  13511. * Creates a dynamic vertex buffer
  13512. * @param data the data for the dynamic vertex buffer
  13513. * @returns the new WebGL dynamic buffer
  13514. */
  13515. Engine.prototype.createDynamicVertexBuffer = function (data) {
  13516. var vbo = this._gl.createBuffer();
  13517. if (!vbo) {
  13518. throw new Error("Unable to create dynamic vertex buffer");
  13519. }
  13520. this.bindArrayBuffer(vbo);
  13521. if (data instanceof Array) {
  13522. this._gl.bufferData(this._gl.ARRAY_BUFFER, new Float32Array(data), this._gl.DYNAMIC_DRAW);
  13523. }
  13524. else {
  13525. this._gl.bufferData(this._gl.ARRAY_BUFFER, data, this._gl.DYNAMIC_DRAW);
  13526. }
  13527. this._resetVertexBufferBinding();
  13528. vbo.references = 1;
  13529. return vbo;
  13530. };
  13531. /**
  13532. * Update a dynamic index buffer
  13533. * @param indexBuffer defines the target index buffer
  13534. * @param indices defines the data to update
  13535. * @param offset defines the offset in the target index buffer where update should start
  13536. */
  13537. Engine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  13538. if (offset === void 0) { offset = 0; }
  13539. // Force cache update
  13540. this._currentBoundBuffer[this._gl.ELEMENT_ARRAY_BUFFER] = null;
  13541. this.bindIndexBuffer(indexBuffer);
  13542. var arrayBuffer;
  13543. if (indices instanceof Uint16Array || indices instanceof Uint32Array) {
  13544. arrayBuffer = indices;
  13545. }
  13546. else {
  13547. arrayBuffer = indexBuffer.is32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13548. }
  13549. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, this._gl.DYNAMIC_DRAW);
  13550. this._resetIndexBufferBinding();
  13551. };
  13552. /**
  13553. * Updates a dynamic vertex buffer.
  13554. * @param vertexBuffer the vertex buffer to update
  13555. * @param data the data used to update the vertex buffer
  13556. * @param byteOffset the byte offset of the data
  13557. * @param byteLength the byte length of the data
  13558. */
  13559. Engine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, data, byteOffset, byteLength) {
  13560. this.bindArrayBuffer(vertexBuffer);
  13561. if (byteOffset === undefined) {
  13562. byteOffset = 0;
  13563. }
  13564. if (byteLength === undefined) {
  13565. if (data instanceof Array) {
  13566. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, new Float32Array(data));
  13567. }
  13568. else {
  13569. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, byteOffset, data);
  13570. }
  13571. }
  13572. else {
  13573. if (data instanceof Array) {
  13574. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, new Float32Array(data).subarray(byteOffset, byteOffset + byteLength));
  13575. }
  13576. else {
  13577. if (data instanceof ArrayBuffer) {
  13578. data = new Uint8Array(data, byteOffset, byteLength);
  13579. }
  13580. else {
  13581. data = new Uint8Array(data.buffer, data.byteOffset + byteOffset, byteLength);
  13582. }
  13583. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13584. }
  13585. }
  13586. this._resetVertexBufferBinding();
  13587. };
  13588. Engine.prototype._resetIndexBufferBinding = function () {
  13589. this.bindIndexBuffer(null);
  13590. this._cachedIndexBuffer = null;
  13591. };
  13592. /**
  13593. * Creates a new index buffer
  13594. * @param indices defines the content of the index buffer
  13595. * @param updatable defines if the index buffer must be updatable
  13596. * @returns a new webGL buffer
  13597. */
  13598. Engine.prototype.createIndexBuffer = function (indices, updatable) {
  13599. var vbo = this._gl.createBuffer();
  13600. if (!vbo) {
  13601. throw new Error("Unable to create index buffer");
  13602. }
  13603. this.bindIndexBuffer(vbo);
  13604. // Check for 32 bits indices
  13605. var arrayBuffer;
  13606. var need32Bits = false;
  13607. if (indices instanceof Uint16Array) {
  13608. arrayBuffer = indices;
  13609. }
  13610. else {
  13611. //check 32 bit support
  13612. if (this._caps.uintIndices) {
  13613. if (indices instanceof Uint32Array) {
  13614. arrayBuffer = indices;
  13615. need32Bits = true;
  13616. }
  13617. else {
  13618. //number[] or Int32Array, check if 32 bit is necessary
  13619. for (var index = 0; index < indices.length; index++) {
  13620. if (indices[index] > 65535) {
  13621. need32Bits = true;
  13622. break;
  13623. }
  13624. }
  13625. arrayBuffer = need32Bits ? new Uint32Array(indices) : new Uint16Array(indices);
  13626. }
  13627. }
  13628. else {
  13629. //no 32 bit support, force conversion to 16 bit (values greater 16 bit are lost)
  13630. arrayBuffer = new Uint16Array(indices);
  13631. }
  13632. }
  13633. this._gl.bufferData(this._gl.ELEMENT_ARRAY_BUFFER, arrayBuffer, updatable ? this._gl.DYNAMIC_DRAW : this._gl.STATIC_DRAW);
  13634. this._resetIndexBufferBinding();
  13635. vbo.references = 1;
  13636. vbo.is32Bits = need32Bits;
  13637. return vbo;
  13638. };
  13639. /**
  13640. * Bind a webGL buffer to the webGL context
  13641. * @param buffer defines the buffer to bind
  13642. */
  13643. Engine.prototype.bindArrayBuffer = function (buffer) {
  13644. if (!this._vaoRecordInProgress) {
  13645. this._unbindVertexArrayObject();
  13646. }
  13647. this.bindBuffer(buffer, this._gl.ARRAY_BUFFER);
  13648. };
  13649. /**
  13650. * Bind an uniform buffer to the current webGL context
  13651. * @param buffer defines the buffer to bind
  13652. */
  13653. Engine.prototype.bindUniformBuffer = function (buffer) {
  13654. this._gl.bindBuffer(this._gl.UNIFORM_BUFFER, buffer);
  13655. };
  13656. /**
  13657. * Bind a buffer to the current webGL context at a given location
  13658. * @param buffer defines the buffer to bind
  13659. * @param location defines the index where to bind the buffer
  13660. */
  13661. Engine.prototype.bindUniformBufferBase = function (buffer, location) {
  13662. this._gl.bindBufferBase(this._gl.UNIFORM_BUFFER, location, buffer);
  13663. };
  13664. /**
  13665. * Bind a specific block at a given index in a specific shader program
  13666. * @param shaderProgram defines the shader program
  13667. * @param blockName defines the block name
  13668. * @param index defines the index where to bind the block
  13669. */
  13670. Engine.prototype.bindUniformBlock = function (shaderProgram, blockName, index) {
  13671. var uniformLocation = this._gl.getUniformBlockIndex(shaderProgram, blockName);
  13672. this._gl.uniformBlockBinding(shaderProgram, uniformLocation, index);
  13673. };
  13674. ;
  13675. Engine.prototype.bindIndexBuffer = function (buffer) {
  13676. if (!this._vaoRecordInProgress) {
  13677. this._unbindVertexArrayObject();
  13678. }
  13679. this.bindBuffer(buffer, this._gl.ELEMENT_ARRAY_BUFFER);
  13680. };
  13681. Engine.prototype.bindBuffer = function (buffer, target) {
  13682. if (this._vaoRecordInProgress || this._currentBoundBuffer[target] !== buffer) {
  13683. this._gl.bindBuffer(target, buffer);
  13684. this._currentBoundBuffer[target] = buffer;
  13685. }
  13686. };
  13687. /**
  13688. * update the bound buffer with the given data
  13689. * @param data defines the data to update
  13690. */
  13691. Engine.prototype.updateArrayBuffer = function (data) {
  13692. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13693. };
  13694. Engine.prototype._vertexAttribPointer = function (buffer, indx, size, type, normalized, stride, offset) {
  13695. var pointer = this._currentBufferPointers[indx];
  13696. var changed = false;
  13697. if (!pointer.active) {
  13698. changed = true;
  13699. pointer.active = true;
  13700. pointer.index = indx;
  13701. pointer.size = size;
  13702. pointer.type = type;
  13703. pointer.normalized = normalized;
  13704. pointer.stride = stride;
  13705. pointer.offset = offset;
  13706. pointer.buffer = buffer;
  13707. }
  13708. else {
  13709. if (pointer.buffer !== buffer) {
  13710. pointer.buffer = buffer;
  13711. changed = true;
  13712. }
  13713. if (pointer.size !== size) {
  13714. pointer.size = size;
  13715. changed = true;
  13716. }
  13717. if (pointer.type !== type) {
  13718. pointer.type = type;
  13719. changed = true;
  13720. }
  13721. if (pointer.normalized !== normalized) {
  13722. pointer.normalized = normalized;
  13723. changed = true;
  13724. }
  13725. if (pointer.stride !== stride) {
  13726. pointer.stride = stride;
  13727. changed = true;
  13728. }
  13729. if (pointer.offset !== offset) {
  13730. pointer.offset = offset;
  13731. changed = true;
  13732. }
  13733. }
  13734. if (changed || this._vaoRecordInProgress) {
  13735. this.bindArrayBuffer(buffer);
  13736. this._gl.vertexAttribPointer(indx, size, type, normalized, stride, offset);
  13737. }
  13738. };
  13739. Engine.prototype._bindIndexBufferWithCache = function (indexBuffer) {
  13740. if (indexBuffer == null) {
  13741. return;
  13742. }
  13743. if (this._cachedIndexBuffer !== indexBuffer) {
  13744. this._cachedIndexBuffer = indexBuffer;
  13745. this.bindIndexBuffer(indexBuffer);
  13746. this._uintIndicesCurrentlySet = indexBuffer.is32Bits;
  13747. }
  13748. };
  13749. Engine.prototype._bindVertexBuffersAttributes = function (vertexBuffers, effect) {
  13750. var attributes = effect.getAttributesNames();
  13751. if (!this._vaoRecordInProgress) {
  13752. this._unbindVertexArrayObject();
  13753. }
  13754. this.unbindAllAttributes();
  13755. for (var index = 0; index < attributes.length; index++) {
  13756. var order = effect.getAttributeLocation(index);
  13757. if (order >= 0) {
  13758. var vertexBuffer = vertexBuffers[attributes[index]];
  13759. if (!vertexBuffer) {
  13760. continue;
  13761. }
  13762. this._gl.enableVertexAttribArray(order);
  13763. if (!this._vaoRecordInProgress) {
  13764. this._vertexAttribArraysEnabled[order] = true;
  13765. }
  13766. var buffer = vertexBuffer.getBuffer();
  13767. if (buffer) {
  13768. this._vertexAttribPointer(buffer, order, vertexBuffer.getSize(), vertexBuffer.type, vertexBuffer.normalized, vertexBuffer.byteStride, vertexBuffer.byteOffset);
  13769. if (vertexBuffer.getIsInstanced()) {
  13770. this._gl.vertexAttribDivisor(order, vertexBuffer.getInstanceDivisor());
  13771. if (!this._vaoRecordInProgress) {
  13772. this._currentInstanceLocations.push(order);
  13773. this._currentInstanceBuffers.push(buffer);
  13774. }
  13775. }
  13776. }
  13777. }
  13778. }
  13779. };
  13780. /**
  13781. * Records a vertex array object
  13782. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13783. * @param vertexBuffers defines the list of vertex buffers to store
  13784. * @param indexBuffer defines the index buffer to store
  13785. * @param effect defines the effect to store
  13786. * @returns the new vertex array object
  13787. */
  13788. Engine.prototype.recordVertexArrayObject = function (vertexBuffers, indexBuffer, effect) {
  13789. var vao = this._gl.createVertexArray();
  13790. this._vaoRecordInProgress = true;
  13791. this._gl.bindVertexArray(vao);
  13792. this._mustWipeVertexAttributes = true;
  13793. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13794. this.bindIndexBuffer(indexBuffer);
  13795. this._vaoRecordInProgress = false;
  13796. this._gl.bindVertexArray(null);
  13797. return vao;
  13798. };
  13799. /**
  13800. * Bind a specific vertex array object
  13801. * @see http://doc.babylonjs.com/features/webgl2#vertex-array-objects
  13802. * @param vertexArrayObject defines the vertex array object to bind
  13803. * @param indexBuffer defines the index buffer to bind
  13804. */
  13805. Engine.prototype.bindVertexArrayObject = function (vertexArrayObject, indexBuffer) {
  13806. if (this._cachedVertexArrayObject !== vertexArrayObject) {
  13807. this._cachedVertexArrayObject = vertexArrayObject;
  13808. this._gl.bindVertexArray(vertexArrayObject);
  13809. this._cachedVertexBuffers = null;
  13810. this._cachedIndexBuffer = null;
  13811. this._uintIndicesCurrentlySet = indexBuffer != null && indexBuffer.is32Bits;
  13812. this._mustWipeVertexAttributes = true;
  13813. }
  13814. };
  13815. /**
  13816. * Bind webGl buffers directly to the webGL context
  13817. * @param vertexBuffer defines the vertex buffer to bind
  13818. * @param indexBuffer defines the index buffer to bind
  13819. * @param vertexDeclaration defines the vertex declaration to use with the vertex buffer
  13820. * @param vertexStrideSize defines the vertex stride of the vertex buffer
  13821. * @param effect defines the effect associated with the vertex buffer
  13822. */
  13823. Engine.prototype.bindBuffersDirectly = function (vertexBuffer, indexBuffer, vertexDeclaration, vertexStrideSize, effect) {
  13824. if (this._cachedVertexBuffers !== vertexBuffer || this._cachedEffectForVertexBuffers !== effect) {
  13825. this._cachedVertexBuffers = vertexBuffer;
  13826. this._cachedEffectForVertexBuffers = effect;
  13827. var attributesCount = effect.getAttributesCount();
  13828. this._unbindVertexArrayObject();
  13829. this.unbindAllAttributes();
  13830. var offset = 0;
  13831. for (var index = 0; index < attributesCount; index++) {
  13832. if (index < vertexDeclaration.length) {
  13833. var order = effect.getAttributeLocation(index);
  13834. if (order >= 0) {
  13835. this._gl.enableVertexAttribArray(order);
  13836. this._vertexAttribArraysEnabled[order] = true;
  13837. this._vertexAttribPointer(vertexBuffer, order, vertexDeclaration[index], this._gl.FLOAT, false, vertexStrideSize, offset);
  13838. }
  13839. offset += vertexDeclaration[index] * 4;
  13840. }
  13841. }
  13842. }
  13843. this._bindIndexBufferWithCache(indexBuffer);
  13844. };
  13845. Engine.prototype._unbindVertexArrayObject = function () {
  13846. if (!this._cachedVertexArrayObject) {
  13847. return;
  13848. }
  13849. this._cachedVertexArrayObject = null;
  13850. this._gl.bindVertexArray(null);
  13851. };
  13852. /**
  13853. * Bind a list of vertex buffers to the webGL context
  13854. * @param vertexBuffers defines the list of vertex buffers to bind
  13855. * @param indexBuffer defines the index buffer to bind
  13856. * @param effect defines the effect associated with the vertex buffers
  13857. */
  13858. Engine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  13859. if (this._cachedVertexBuffers !== vertexBuffers || this._cachedEffectForVertexBuffers !== effect) {
  13860. this._cachedVertexBuffers = vertexBuffers;
  13861. this._cachedEffectForVertexBuffers = effect;
  13862. this._bindVertexBuffersAttributes(vertexBuffers, effect);
  13863. }
  13864. this._bindIndexBufferWithCache(indexBuffer);
  13865. };
  13866. /**
  13867. * Unbind all instance attributes
  13868. */
  13869. Engine.prototype.unbindInstanceAttributes = function () {
  13870. var boundBuffer;
  13871. for (var i = 0, ul = this._currentInstanceLocations.length; i < ul; i++) {
  13872. var instancesBuffer = this._currentInstanceBuffers[i];
  13873. if (boundBuffer != instancesBuffer && instancesBuffer.references) {
  13874. boundBuffer = instancesBuffer;
  13875. this.bindArrayBuffer(instancesBuffer);
  13876. }
  13877. var offsetLocation = this._currentInstanceLocations[i];
  13878. this._gl.vertexAttribDivisor(offsetLocation, 0);
  13879. }
  13880. this._currentInstanceBuffers.length = 0;
  13881. this._currentInstanceLocations.length = 0;
  13882. };
  13883. /**
  13884. * Release and free the memory of a vertex array object
  13885. * @param vao defines the vertex array object to delete
  13886. */
  13887. Engine.prototype.releaseVertexArrayObject = function (vao) {
  13888. this._gl.deleteVertexArray(vao);
  13889. };
  13890. /** @hidden */
  13891. Engine.prototype._releaseBuffer = function (buffer) {
  13892. buffer.references--;
  13893. if (buffer.references === 0) {
  13894. this._gl.deleteBuffer(buffer);
  13895. return true;
  13896. }
  13897. return false;
  13898. };
  13899. /**
  13900. * Creates a webGL buffer to use with instanciation
  13901. * @param capacity defines the size of the buffer
  13902. * @returns the webGL buffer
  13903. */
  13904. Engine.prototype.createInstancesBuffer = function (capacity) {
  13905. var buffer = this._gl.createBuffer();
  13906. if (!buffer) {
  13907. throw new Error("Unable to create instance buffer");
  13908. }
  13909. buffer.capacity = capacity;
  13910. this.bindArrayBuffer(buffer);
  13911. this._gl.bufferData(this._gl.ARRAY_BUFFER, capacity, this._gl.DYNAMIC_DRAW);
  13912. return buffer;
  13913. };
  13914. /**
  13915. * Delete a webGL buffer used with instanciation
  13916. * @param buffer defines the webGL buffer to delete
  13917. */
  13918. Engine.prototype.deleteInstancesBuffer = function (buffer) {
  13919. this._gl.deleteBuffer(buffer);
  13920. };
  13921. /**
  13922. * Update the content of a webGL buffer used with instanciation and bind it to the webGL context
  13923. * @param instancesBuffer defines the webGL buffer to update and bind
  13924. * @param data defines the data to store in the buffer
  13925. * @param offsetLocations defines the offsets or attributes information used to determine where data must be stored in the buffer
  13926. */
  13927. Engine.prototype.updateAndBindInstancesBuffer = function (instancesBuffer, data, offsetLocations) {
  13928. this.bindArrayBuffer(instancesBuffer);
  13929. if (data) {
  13930. this._gl.bufferSubData(this._gl.ARRAY_BUFFER, 0, data);
  13931. }
  13932. if (offsetLocations[0].index !== undefined) {
  13933. var stride = 0;
  13934. for (var i = 0; i < offsetLocations.length; i++) {
  13935. var ai = offsetLocations[i];
  13936. stride += ai.attributeSize * 4;
  13937. }
  13938. for (var i = 0; i < offsetLocations.length; i++) {
  13939. var ai = offsetLocations[i];
  13940. if (!this._vertexAttribArraysEnabled[ai.index]) {
  13941. this._gl.enableVertexAttribArray(ai.index);
  13942. this._vertexAttribArraysEnabled[ai.index] = true;
  13943. }
  13944. this._vertexAttribPointer(instancesBuffer, ai.index, ai.attributeSize, ai.attribyteType || this._gl.FLOAT, ai.normalized || false, stride, ai.offset);
  13945. this._gl.vertexAttribDivisor(ai.index, 1);
  13946. this._currentInstanceLocations.push(ai.index);
  13947. this._currentInstanceBuffers.push(instancesBuffer);
  13948. }
  13949. }
  13950. else {
  13951. for (var index = 0; index < 4; index++) {
  13952. var offsetLocation = offsetLocations[index];
  13953. if (!this._vertexAttribArraysEnabled[offsetLocation]) {
  13954. this._gl.enableVertexAttribArray(offsetLocation);
  13955. this._vertexAttribArraysEnabled[offsetLocation] = true;
  13956. }
  13957. this._vertexAttribPointer(instancesBuffer, offsetLocation, 4, this._gl.FLOAT, false, 64, index * 16);
  13958. this._gl.vertexAttribDivisor(offsetLocation, 1);
  13959. this._currentInstanceLocations.push(offsetLocation);
  13960. this._currentInstanceBuffers.push(instancesBuffer);
  13961. }
  13962. }
  13963. };
  13964. /**
  13965. * Apply all cached states (depth, culling, stencil and alpha)
  13966. */
  13967. Engine.prototype.applyStates = function () {
  13968. this._depthCullingState.apply(this._gl);
  13969. this._stencilState.apply(this._gl);
  13970. this._alphaState.apply(this._gl);
  13971. };
  13972. /**
  13973. * Send a draw order
  13974. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13975. * @param indexStart defines the starting index
  13976. * @param indexCount defines the number of index to draw
  13977. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13978. */
  13979. Engine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  13980. this.drawElementsType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, indexStart, indexCount, instancesCount);
  13981. };
  13982. /**
  13983. * Draw a list of points
  13984. * @param verticesStart defines the index of first vertex to draw
  13985. * @param verticesCount defines the count of vertices to draw
  13986. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13987. */
  13988. Engine.prototype.drawPointClouds = function (verticesStart, verticesCount, instancesCount) {
  13989. this.drawArraysType(BABYLON.Material.PointFillMode, verticesStart, verticesCount, instancesCount);
  13990. };
  13991. /**
  13992. * Draw a list of unindexed primitives
  13993. * @param useTriangles defines if triangles must be used to draw (else wireframe will be used)
  13994. * @param verticesStart defines the index of first vertex to draw
  13995. * @param verticesCount defines the count of vertices to draw
  13996. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  13997. */
  13998. Engine.prototype.drawUnIndexed = function (useTriangles, verticesStart, verticesCount, instancesCount) {
  13999. this.drawArraysType(useTriangles ? BABYLON.Material.TriangleFillMode : BABYLON.Material.WireFrameFillMode, verticesStart, verticesCount, instancesCount);
  14000. };
  14001. /**
  14002. * Draw a list of indexed primitives
  14003. * @param fillMode defines the primitive to use
  14004. * @param indexStart defines the starting index
  14005. * @param indexCount defines the number of index to draw
  14006. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14007. */
  14008. Engine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  14009. // Apply states
  14010. this.applyStates();
  14011. this._drawCalls.addCount(1, false);
  14012. // Render
  14013. var drawMode = this._drawMode(fillMode);
  14014. var indexFormat = this._uintIndicesCurrentlySet ? this._gl.UNSIGNED_INT : this._gl.UNSIGNED_SHORT;
  14015. var mult = this._uintIndicesCurrentlySet ? 4 : 2;
  14016. if (instancesCount) {
  14017. this._gl.drawElementsInstanced(drawMode, indexCount, indexFormat, indexStart * mult, instancesCount);
  14018. }
  14019. else {
  14020. this._gl.drawElements(drawMode, indexCount, indexFormat, indexStart * mult);
  14021. }
  14022. };
  14023. /**
  14024. * Draw a list of unindexed primitives
  14025. * @param fillMode defines the primitive to use
  14026. * @param verticesStart defines the index of first vertex to draw
  14027. * @param verticesCount defines the count of vertices to draw
  14028. * @param instancesCount defines the number of instances to draw (if instanciation is enabled)
  14029. */
  14030. Engine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  14031. // Apply states
  14032. this.applyStates();
  14033. this._drawCalls.addCount(1, false);
  14034. var drawMode = this._drawMode(fillMode);
  14035. if (instancesCount) {
  14036. this._gl.drawArraysInstanced(drawMode, verticesStart, verticesCount, instancesCount);
  14037. }
  14038. else {
  14039. this._gl.drawArrays(drawMode, verticesStart, verticesCount);
  14040. }
  14041. };
  14042. Engine.prototype._drawMode = function (fillMode) {
  14043. switch (fillMode) {
  14044. // Triangle views
  14045. case BABYLON.Material.TriangleFillMode:
  14046. return this._gl.TRIANGLES;
  14047. case BABYLON.Material.PointFillMode:
  14048. return this._gl.POINTS;
  14049. case BABYLON.Material.WireFrameFillMode:
  14050. return this._gl.LINES;
  14051. // Draw modes
  14052. case BABYLON.Material.PointListDrawMode:
  14053. return this._gl.POINTS;
  14054. case BABYLON.Material.LineListDrawMode:
  14055. return this._gl.LINES;
  14056. case BABYLON.Material.LineLoopDrawMode:
  14057. return this._gl.LINE_LOOP;
  14058. case BABYLON.Material.LineStripDrawMode:
  14059. return this._gl.LINE_STRIP;
  14060. case BABYLON.Material.TriangleStripDrawMode:
  14061. return this._gl.TRIANGLE_STRIP;
  14062. case BABYLON.Material.TriangleFanDrawMode:
  14063. return this._gl.TRIANGLE_FAN;
  14064. default:
  14065. return this._gl.TRIANGLES;
  14066. }
  14067. };
  14068. // Shaders
  14069. /** @hidden */
  14070. Engine.prototype._releaseEffect = function (effect) {
  14071. if (this._compiledEffects[effect._key]) {
  14072. delete this._compiledEffects[effect._key];
  14073. this._deleteProgram(effect.getProgram());
  14074. }
  14075. };
  14076. /** @hidden */
  14077. Engine.prototype._deleteProgram = function (program) {
  14078. if (program) {
  14079. program.__SPECTOR_rebuildProgram = null;
  14080. if (program.transformFeedback) {
  14081. this.deleteTransformFeedback(program.transformFeedback);
  14082. program.transformFeedback = null;
  14083. }
  14084. this._gl.deleteProgram(program);
  14085. }
  14086. };
  14087. /**
  14088. * Create a new effect (used to store vertex/fragment shaders)
  14089. * @param baseName defines the base name of the effect (The name of file without .fragment.fx or .vertex.fx)
  14090. * @param attributesNamesOrOptions defines either a list of attribute names or an EffectCreationOptions object
  14091. * @param uniformsNamesOrEngine defines either a list of uniform names or the engine to use
  14092. * @param samplers defines an array of string used to represent textures
  14093. * @param defines defines the string containing the defines to use to compile the shaders
  14094. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14095. * @param onCompiled defines a function to call when the effect creation is successful
  14096. * @param onError defines a function to call when the effect creation has failed
  14097. * @param indexParameters defines an object containing the index values to use to compile shaders (like the maximum number of simultaneous lights)
  14098. * @returns the new Effect
  14099. */
  14100. Engine.prototype.createEffect = function (baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, defines, fallbacks, onCompiled, onError, indexParameters) {
  14101. var vertex = baseName.vertexElement || baseName.vertex || baseName;
  14102. var fragment = baseName.fragmentElement || baseName.fragment || baseName;
  14103. var name = vertex + "+" + fragment + "@" + (defines ? defines : attributesNamesOrOptions.defines);
  14104. if (this._compiledEffects[name]) {
  14105. var compiledEffect = this._compiledEffects[name];
  14106. if (onCompiled && compiledEffect.isReady()) {
  14107. onCompiled(compiledEffect);
  14108. }
  14109. return compiledEffect;
  14110. }
  14111. var effect = new BABYLON.Effect(baseName, attributesNamesOrOptions, uniformsNamesOrEngine, samplers, this, defines, fallbacks, onCompiled, onError, indexParameters);
  14112. effect._key = name;
  14113. this._compiledEffects[name] = effect;
  14114. return effect;
  14115. };
  14116. /**
  14117. * Create an effect to use with particle systems.
  14118. * Please note that some parameters like animation sheets or not being billboard are not supported in this configuration
  14119. * @param fragmentName defines the base name of the effect (The name of file without .fragment.fx)
  14120. * @param uniformsNames defines a list of attribute names
  14121. * @param samplers defines an array of string used to represent textures
  14122. * @param defines defines the string containing the defines to use to compile the shaders
  14123. * @param fallbacks defines the list of potential fallbacks to use if shader conmpilation fails
  14124. * @param onCompiled defines a function to call when the effect creation is successful
  14125. * @param onError defines a function to call when the effect creation has failed
  14126. * @returns the new Effect
  14127. */
  14128. Engine.prototype.createEffectForParticles = function (fragmentName, uniformsNames, samplers, defines, fallbacks, onCompiled, onError) {
  14129. if (uniformsNames === void 0) { uniformsNames = []; }
  14130. if (samplers === void 0) { samplers = []; }
  14131. if (defines === void 0) { defines = ""; }
  14132. var attributesNamesOrOptions = BABYLON.ParticleSystem._GetAttributeNamesOrOptions();
  14133. var effectCreationOption = BABYLON.ParticleSystem._GetEffectCreationOptions();
  14134. if (defines.indexOf(" BILLBOARD") === -1) {
  14135. defines += "\n#define BILLBOARD\n";
  14136. }
  14137. if (samplers.indexOf("diffuseSampler") === -1) {
  14138. samplers.push("diffuseSampler");
  14139. }
  14140. return this.createEffect({
  14141. vertex: "particles",
  14142. fragmentElement: fragmentName
  14143. }, attributesNamesOrOptions, effectCreationOption.concat(uniformsNames), samplers, defines, fallbacks, onCompiled, onError);
  14144. };
  14145. /**
  14146. * Directly creates a webGL program
  14147. * @param vertexCode defines the vertex shader code to use
  14148. * @param fragmentCode defines the fragment shader code to use
  14149. * @param context defines the webGL context to use (if not set, the current one will be used)
  14150. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14151. * @returns the new webGL program
  14152. */
  14153. Engine.prototype.createRawShaderProgram = function (vertexCode, fragmentCode, context, transformFeedbackVaryings) {
  14154. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14155. context = context || this._gl;
  14156. var vertexShader = compileRawShader(context, vertexCode, "vertex");
  14157. var fragmentShader = compileRawShader(context, fragmentCode, "fragment");
  14158. return this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14159. };
  14160. /**
  14161. * Creates a webGL program
  14162. * @param vertexCode defines the vertex shader code to use
  14163. * @param fragmentCode defines the fragment shader code to use
  14164. * @param defines defines the string containing the defines to use to compile the shaders
  14165. * @param context defines the webGL context to use (if not set, the current one will be used)
  14166. * @param transformFeedbackVaryings defines the list of transform feedback varyings to use
  14167. * @returns the new webGL program
  14168. */
  14169. Engine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context, transformFeedbackVaryings) {
  14170. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14171. context = context || this._gl;
  14172. this.onBeforeShaderCompilationObservable.notifyObservers(this);
  14173. var shaderVersion = (this._webGLVersion > 1) ? "#version 300 es\n#define WEBGL2 \n" : "";
  14174. var vertexShader = compileShader(context, vertexCode, "vertex", defines, shaderVersion);
  14175. var fragmentShader = compileShader(context, fragmentCode, "fragment", defines, shaderVersion);
  14176. var program = this._createShaderProgram(vertexShader, fragmentShader, context, transformFeedbackVaryings);
  14177. this.onAfterShaderCompilationObservable.notifyObservers(this);
  14178. return program;
  14179. };
  14180. Engine.prototype._createShaderProgram = function (vertexShader, fragmentShader, context, transformFeedbackVaryings) {
  14181. if (transformFeedbackVaryings === void 0) { transformFeedbackVaryings = null; }
  14182. var shaderProgram = context.createProgram();
  14183. if (!shaderProgram) {
  14184. throw new Error("Unable to create program");
  14185. }
  14186. context.attachShader(shaderProgram, vertexShader);
  14187. context.attachShader(shaderProgram, fragmentShader);
  14188. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14189. var transformFeedback = this.createTransformFeedback();
  14190. this.bindTransformFeedback(transformFeedback);
  14191. this.setTranformFeedbackVaryings(shaderProgram, transformFeedbackVaryings);
  14192. shaderProgram.transformFeedback = transformFeedback;
  14193. }
  14194. context.linkProgram(shaderProgram);
  14195. if (this.webGLVersion > 1 && transformFeedbackVaryings) {
  14196. this.bindTransformFeedback(null);
  14197. }
  14198. var linked = context.getProgramParameter(shaderProgram, context.LINK_STATUS);
  14199. if (!linked) {
  14200. var error = context.getProgramInfoLog(shaderProgram);
  14201. if (error) {
  14202. throw new Error(error);
  14203. }
  14204. }
  14205. context.validateProgram(shaderProgram);
  14206. var validated = context.getProgramParameter(shaderProgram, context.VALIDATE_STATUS);
  14207. if (!validated) {
  14208. var error = context.getProgramInfoLog(shaderProgram);
  14209. if (error) {
  14210. throw new Error(error);
  14211. }
  14212. }
  14213. context.deleteShader(vertexShader);
  14214. context.deleteShader(fragmentShader);
  14215. return shaderProgram;
  14216. };
  14217. /**
  14218. * Gets the list of webGL uniform locations associated with a specific program based on a list of uniform names
  14219. * @param shaderProgram defines the webGL program to use
  14220. * @param uniformsNames defines the list of uniform names
  14221. * @returns an array of webGL uniform locations
  14222. */
  14223. Engine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  14224. var results = new Array();
  14225. for (var index = 0; index < uniformsNames.length; index++) {
  14226. results.push(this._gl.getUniformLocation(shaderProgram, uniformsNames[index]));
  14227. }
  14228. return results;
  14229. };
  14230. /**
  14231. * Gets the lsit of active attributes for a given webGL program
  14232. * @param shaderProgram defines the webGL program to use
  14233. * @param attributesNames defines the list of attribute names to get
  14234. * @returns an array of indices indicating the offset of each attribute
  14235. */
  14236. Engine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  14237. var results = [];
  14238. for (var index = 0; index < attributesNames.length; index++) {
  14239. try {
  14240. results.push(this._gl.getAttribLocation(shaderProgram, attributesNames[index]));
  14241. }
  14242. catch (e) {
  14243. results.push(-1);
  14244. }
  14245. }
  14246. return results;
  14247. };
  14248. /**
  14249. * Activates an effect, mkaing it the current one (ie. the one used for rendering)
  14250. * @param effect defines the effect to activate
  14251. */
  14252. Engine.prototype.enableEffect = function (effect) {
  14253. if (!effect) {
  14254. return;
  14255. }
  14256. // Use program
  14257. this.bindSamplers(effect);
  14258. this._currentEffect = effect;
  14259. if (effect.onBind) {
  14260. effect.onBind(effect);
  14261. }
  14262. effect.onBindObservable.notifyObservers(effect);
  14263. };
  14264. /**
  14265. * Set the value of an uniform to an array of int32
  14266. * @param uniform defines the webGL uniform location where to store the value
  14267. * @param array defines the array of int32 to store
  14268. */
  14269. Engine.prototype.setIntArray = function (uniform, array) {
  14270. if (!uniform)
  14271. return;
  14272. this._gl.uniform1iv(uniform, array);
  14273. };
  14274. /**
  14275. * Set the value of an uniform to an array of int32 (stored as vec2)
  14276. * @param uniform defines the webGL uniform location where to store the value
  14277. * @param array defines the array of int32 to store
  14278. */
  14279. Engine.prototype.setIntArray2 = function (uniform, array) {
  14280. if (!uniform || array.length % 2 !== 0)
  14281. return;
  14282. this._gl.uniform2iv(uniform, array);
  14283. };
  14284. /**
  14285. * Set the value of an uniform to an array of int32 (stored as vec3)
  14286. * @param uniform defines the webGL uniform location where to store the value
  14287. * @param array defines the array of int32 to store
  14288. */
  14289. Engine.prototype.setIntArray3 = function (uniform, array) {
  14290. if (!uniform || array.length % 3 !== 0)
  14291. return;
  14292. this._gl.uniform3iv(uniform, array);
  14293. };
  14294. /**
  14295. * Set the value of an uniform to an array of int32 (stored as vec4)
  14296. * @param uniform defines the webGL uniform location where to store the value
  14297. * @param array defines the array of int32 to store
  14298. */
  14299. Engine.prototype.setIntArray4 = function (uniform, array) {
  14300. if (!uniform || array.length % 4 !== 0)
  14301. return;
  14302. this._gl.uniform4iv(uniform, array);
  14303. };
  14304. /**
  14305. * Set the value of an uniform to an array of float32
  14306. * @param uniform defines the webGL uniform location where to store the value
  14307. * @param array defines the array of float32 to store
  14308. */
  14309. Engine.prototype.setFloatArray = function (uniform, array) {
  14310. if (!uniform)
  14311. return;
  14312. this._gl.uniform1fv(uniform, array);
  14313. };
  14314. /**
  14315. * Set the value of an uniform to an array of float32 (stored as vec2)
  14316. * @param uniform defines the webGL uniform location where to store the value
  14317. * @param array defines the array of float32 to store
  14318. */
  14319. Engine.prototype.setFloatArray2 = function (uniform, array) {
  14320. if (!uniform || array.length % 2 !== 0)
  14321. return;
  14322. this._gl.uniform2fv(uniform, array);
  14323. };
  14324. /**
  14325. * Set the value of an uniform to an array of float32 (stored as vec3)
  14326. * @param uniform defines the webGL uniform location where to store the value
  14327. * @param array defines the array of float32 to store
  14328. */
  14329. Engine.prototype.setFloatArray3 = function (uniform, array) {
  14330. if (!uniform || array.length % 3 !== 0)
  14331. return;
  14332. this._gl.uniform3fv(uniform, array);
  14333. };
  14334. /**
  14335. * Set the value of an uniform to an array of float32 (stored as vec4)
  14336. * @param uniform defines the webGL uniform location where to store the value
  14337. * @param array defines the array of float32 to store
  14338. */
  14339. Engine.prototype.setFloatArray4 = function (uniform, array) {
  14340. if (!uniform || array.length % 4 !== 0)
  14341. return;
  14342. this._gl.uniform4fv(uniform, array);
  14343. };
  14344. /**
  14345. * Set the value of an uniform to an array of number
  14346. * @param uniform defines the webGL uniform location where to store the value
  14347. * @param array defines the array of number to store
  14348. */
  14349. Engine.prototype.setArray = function (uniform, array) {
  14350. if (!uniform)
  14351. return;
  14352. this._gl.uniform1fv(uniform, array);
  14353. };
  14354. /**
  14355. * Set the value of an uniform to an array of number (stored as vec2)
  14356. * @param uniform defines the webGL uniform location where to store the value
  14357. * @param array defines the array of number to store
  14358. */
  14359. Engine.prototype.setArray2 = function (uniform, array) {
  14360. if (!uniform || array.length % 2 !== 0)
  14361. return;
  14362. this._gl.uniform2fv(uniform, array);
  14363. };
  14364. /**
  14365. * Set the value of an uniform to an array of number (stored as vec3)
  14366. * @param uniform defines the webGL uniform location where to store the value
  14367. * @param array defines the array of number to store
  14368. */
  14369. Engine.prototype.setArray3 = function (uniform, array) {
  14370. if (!uniform || array.length % 3 !== 0)
  14371. return;
  14372. this._gl.uniform3fv(uniform, array);
  14373. };
  14374. /**
  14375. * Set the value of an uniform to an array of number (stored as vec4)
  14376. * @param uniform defines the webGL uniform location where to store the value
  14377. * @param array defines the array of number to store
  14378. */
  14379. Engine.prototype.setArray4 = function (uniform, array) {
  14380. if (!uniform || array.length % 4 !== 0)
  14381. return;
  14382. this._gl.uniform4fv(uniform, array);
  14383. };
  14384. /**
  14385. * Set the value of an uniform to an array of float32 (stored as matrices)
  14386. * @param uniform defines the webGL uniform location where to store the value
  14387. * @param matrices defines the array of float32 to store
  14388. */
  14389. Engine.prototype.setMatrices = function (uniform, matrices) {
  14390. if (!uniform)
  14391. return;
  14392. this._gl.uniformMatrix4fv(uniform, false, matrices);
  14393. };
  14394. /**
  14395. * Set the value of an uniform to a matrix
  14396. * @param uniform defines the webGL uniform location where to store the value
  14397. * @param matrix defines the matrix to store
  14398. */
  14399. Engine.prototype.setMatrix = function (uniform, matrix) {
  14400. if (!uniform)
  14401. return;
  14402. this._gl.uniformMatrix4fv(uniform, false, matrix.toArray());
  14403. };
  14404. /**
  14405. * Set the value of an uniform to a matrix (3x3)
  14406. * @param uniform defines the webGL uniform location where to store the value
  14407. * @param matrix defines the Float32Array representing the 3x3 matrix to store
  14408. */
  14409. Engine.prototype.setMatrix3x3 = function (uniform, matrix) {
  14410. if (!uniform)
  14411. return;
  14412. this._gl.uniformMatrix3fv(uniform, false, matrix);
  14413. };
  14414. /**
  14415. * Set the value of an uniform to a matrix (2x2)
  14416. * @param uniform defines the webGL uniform location where to store the value
  14417. * @param matrix defines the Float32Array representing the 2x2 matrix to store
  14418. */
  14419. Engine.prototype.setMatrix2x2 = function (uniform, matrix) {
  14420. if (!uniform)
  14421. return;
  14422. this._gl.uniformMatrix2fv(uniform, false, matrix);
  14423. };
  14424. /**
  14425. * Set the value of an uniform to a number (int)
  14426. * @param uniform defines the webGL uniform location where to store the value
  14427. * @param value defines the int number to store
  14428. */
  14429. Engine.prototype.setInt = function (uniform, value) {
  14430. if (!uniform)
  14431. return;
  14432. this._gl.uniform1i(uniform, value);
  14433. };
  14434. /**
  14435. * Set the value of an uniform to a number (float)
  14436. * @param uniform defines the webGL uniform location where to store the value
  14437. * @param value defines the float number to store
  14438. */
  14439. Engine.prototype.setFloat = function (uniform, value) {
  14440. if (!uniform)
  14441. return;
  14442. this._gl.uniform1f(uniform, value);
  14443. };
  14444. /**
  14445. * Set the value of an uniform to a vec2
  14446. * @param uniform defines the webGL uniform location where to store the value
  14447. * @param x defines the 1st component of the value
  14448. * @param y defines the 2nd component of the value
  14449. */
  14450. Engine.prototype.setFloat2 = function (uniform, x, y) {
  14451. if (!uniform)
  14452. return;
  14453. this._gl.uniform2f(uniform, x, y);
  14454. };
  14455. /**
  14456. * Set the value of an uniform to a vec3
  14457. * @param uniform defines the webGL uniform location where to store the value
  14458. * @param x defines the 1st component of the value
  14459. * @param y defines the 2nd component of the value
  14460. * @param z defines the 3rd component of the value
  14461. */
  14462. Engine.prototype.setFloat3 = function (uniform, x, y, z) {
  14463. if (!uniform)
  14464. return;
  14465. this._gl.uniform3f(uniform, x, y, z);
  14466. };
  14467. /**
  14468. * Set the value of an uniform to a boolean
  14469. * @param uniform defines the webGL uniform location where to store the value
  14470. * @param bool defines the boolean to store
  14471. */
  14472. Engine.prototype.setBool = function (uniform, bool) {
  14473. if (!uniform)
  14474. return;
  14475. this._gl.uniform1i(uniform, bool);
  14476. };
  14477. /**
  14478. * Set the value of an uniform to a vec4
  14479. * @param uniform defines the webGL uniform location where to store the value
  14480. * @param x defines the 1st component of the value
  14481. * @param y defines the 2nd component of the value
  14482. * @param z defines the 3rd component of the value
  14483. * @param w defines the 4th component of the value
  14484. */
  14485. Engine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  14486. if (!uniform)
  14487. return;
  14488. this._gl.uniform4f(uniform, x, y, z, w);
  14489. };
  14490. /**
  14491. * Set the value of an uniform to a Color3
  14492. * @param uniform defines the webGL uniform location where to store the value
  14493. * @param color3 defines the color to store
  14494. */
  14495. Engine.prototype.setColor3 = function (uniform, color3) {
  14496. if (!uniform)
  14497. return;
  14498. this._gl.uniform3f(uniform, color3.r, color3.g, color3.b);
  14499. };
  14500. /**
  14501. * Set the value of an uniform to a Color3 and an alpha value
  14502. * @param uniform defines the webGL uniform location where to store the value
  14503. * @param color3 defines the color to store
  14504. * @param alpha defines the alpha component to store
  14505. */
  14506. Engine.prototype.setColor4 = function (uniform, color3, alpha) {
  14507. if (!uniform)
  14508. return;
  14509. this._gl.uniform4f(uniform, color3.r, color3.g, color3.b, alpha);
  14510. };
  14511. /**
  14512. * Sets a Color4 on a uniform variable
  14513. * @param uniform defines the uniform location
  14514. * @param color4 defines the value to be set
  14515. */
  14516. Engine.prototype.setDirectColor4 = function (uniform, color4) {
  14517. if (!uniform)
  14518. return;
  14519. this._gl.uniform4f(uniform, color4.r, color4.g, color4.b, color4.a);
  14520. };
  14521. // States
  14522. /**
  14523. * Set various states to the webGL context
  14524. * @param culling defines backface culling state
  14525. * @param zOffset defines the value to apply to zOffset (0 by default)
  14526. * @param force defines if states must be applied even if cache is up to date
  14527. * @param reverseSide defines if culling must be reversed (CCW instead of CW and CW instead of CCW)
  14528. */
  14529. Engine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  14530. if (zOffset === void 0) { zOffset = 0; }
  14531. if (reverseSide === void 0) { reverseSide = false; }
  14532. // Culling
  14533. if (this._depthCullingState.cull !== culling || force) {
  14534. this._depthCullingState.cull = culling;
  14535. }
  14536. // Cull face
  14537. var cullFace = this.cullBackFaces ? this._gl.BACK : this._gl.FRONT;
  14538. if (this._depthCullingState.cullFace !== cullFace || force) {
  14539. this._depthCullingState.cullFace = cullFace;
  14540. }
  14541. // Z offset
  14542. this.setZOffset(zOffset);
  14543. // Front face
  14544. var frontFace = reverseSide ? this._gl.CW : this._gl.CCW;
  14545. if (this._depthCullingState.frontFace !== frontFace || force) {
  14546. this._depthCullingState.frontFace = frontFace;
  14547. }
  14548. };
  14549. /**
  14550. * Set the z offset to apply to current rendering
  14551. * @param value defines the offset to apply
  14552. */
  14553. Engine.prototype.setZOffset = function (value) {
  14554. this._depthCullingState.zOffset = value;
  14555. };
  14556. /**
  14557. * Gets the current value of the zOffset
  14558. * @returns the current zOffset state
  14559. */
  14560. Engine.prototype.getZOffset = function () {
  14561. return this._depthCullingState.zOffset;
  14562. };
  14563. /**
  14564. * Enable or disable depth buffering
  14565. * @param enable defines the state to set
  14566. */
  14567. Engine.prototype.setDepthBuffer = function (enable) {
  14568. this._depthCullingState.depthTest = enable;
  14569. };
  14570. /**
  14571. * Gets a boolean indicating if depth writing is enabled
  14572. * @returns the current depth writing state
  14573. */
  14574. Engine.prototype.getDepthWrite = function () {
  14575. return this._depthCullingState.depthMask;
  14576. };
  14577. /**
  14578. * Enable or disable depth writing
  14579. * @param enable defines the state to set
  14580. */
  14581. Engine.prototype.setDepthWrite = function (enable) {
  14582. this._depthCullingState.depthMask = enable;
  14583. };
  14584. /**
  14585. * Enable or disable color writing
  14586. * @param enable defines the state to set
  14587. */
  14588. Engine.prototype.setColorWrite = function (enable) {
  14589. this._gl.colorMask(enable, enable, enable, enable);
  14590. this._colorWrite = enable;
  14591. };
  14592. /**
  14593. * Gets a boolean indicating if color writing is enabled
  14594. * @returns the current color writing state
  14595. */
  14596. Engine.prototype.getColorWrite = function () {
  14597. return this._colorWrite;
  14598. };
  14599. /**
  14600. * Sets alpha constants used by some alpha blending modes
  14601. * @param r defines the red component
  14602. * @param g defines the green component
  14603. * @param b defines the blue component
  14604. * @param a defines the alpha component
  14605. */
  14606. Engine.prototype.setAlphaConstants = function (r, g, b, a) {
  14607. this._alphaState.setAlphaBlendConstants(r, g, b, a);
  14608. };
  14609. /**
  14610. * Sets the current alpha mode
  14611. * @param mode defines the mode to use (one of the BABYLON.Engine.ALPHA_XXX)
  14612. * @param noDepthWriteChange defines if depth writing state should remains unchanged (false by default)
  14613. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14614. */
  14615. Engine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  14616. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  14617. if (this._alphaMode === mode) {
  14618. return;
  14619. }
  14620. switch (mode) {
  14621. case Engine.ALPHA_DISABLE:
  14622. this._alphaState.alphaBlend = false;
  14623. break;
  14624. case Engine.ALPHA_PREMULTIPLIED:
  14625. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14626. this._alphaState.alphaBlend = true;
  14627. break;
  14628. case Engine.ALPHA_PREMULTIPLIED_PORTERDUFF:
  14629. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14630. this._alphaState.alphaBlend = true;
  14631. break;
  14632. case Engine.ALPHA_COMBINE:
  14633. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_ALPHA, this._gl.ONE, this._gl.ONE);
  14634. this._alphaState.alphaBlend = true;
  14635. break;
  14636. case Engine.ALPHA_ONEONE:
  14637. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14638. this._alphaState.alphaBlend = true;
  14639. break;
  14640. case Engine.ALPHA_ADD:
  14641. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE, this._gl.ZERO, this._gl.ONE);
  14642. this._alphaState.alphaBlend = true;
  14643. break;
  14644. case Engine.ALPHA_SUBTRACT:
  14645. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ZERO, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14646. this._alphaState.alphaBlend = true;
  14647. break;
  14648. case Engine.ALPHA_MULTIPLY:
  14649. this._alphaState.setAlphaBlendFunctionParameters(this._gl.DST_COLOR, this._gl.ZERO, this._gl.ONE, this._gl.ONE);
  14650. this._alphaState.alphaBlend = true;
  14651. break;
  14652. case Engine.ALPHA_MAXIMIZED:
  14653. this._alphaState.setAlphaBlendFunctionParameters(this._gl.SRC_ALPHA, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE);
  14654. this._alphaState.alphaBlend = true;
  14655. break;
  14656. case Engine.ALPHA_INTERPOLATE:
  14657. this._alphaState.setAlphaBlendFunctionParameters(this._gl.CONSTANT_COLOR, this._gl.ONE_MINUS_CONSTANT_COLOR, this._gl.CONSTANT_ALPHA, this._gl.ONE_MINUS_CONSTANT_ALPHA);
  14658. this._alphaState.alphaBlend = true;
  14659. break;
  14660. case Engine.ALPHA_SCREENMODE:
  14661. this._alphaState.setAlphaBlendFunctionParameters(this._gl.ONE, this._gl.ONE_MINUS_SRC_COLOR, this._gl.ONE, this._gl.ONE_MINUS_SRC_ALPHA);
  14662. this._alphaState.alphaBlend = true;
  14663. break;
  14664. }
  14665. if (!noDepthWriteChange) {
  14666. this.setDepthWrite(mode === Engine.ALPHA_DISABLE);
  14667. }
  14668. this._alphaMode = mode;
  14669. };
  14670. /**
  14671. * Gets the current alpha mode
  14672. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered
  14673. * @returns the current alpha mode
  14674. */
  14675. Engine.prototype.getAlphaMode = function () {
  14676. return this._alphaMode;
  14677. };
  14678. // Textures
  14679. /**
  14680. * Clears the list of texture accessible through engine.
  14681. * This can help preventing texture load conflict due to name collision.
  14682. */
  14683. Engine.prototype.clearInternalTexturesCache = function () {
  14684. this._internalTexturesCache = [];
  14685. };
  14686. /**
  14687. * Force the entire cache to be cleared
  14688. * You should not have to use this function unless your engine needs to share the webGL context with another engine
  14689. * @param bruteForce defines a boolean to force clearing ALL caches (including stencil, detoh and alpha states)
  14690. */
  14691. Engine.prototype.wipeCaches = function (bruteForce) {
  14692. if (this.preventCacheWipeBetweenFrames && !bruteForce) {
  14693. return;
  14694. }
  14695. this._currentEffect = null;
  14696. this._unpackFlipYCached = null;
  14697. this._viewportCached.x = 0;
  14698. this._viewportCached.y = 0;
  14699. this._viewportCached.z = 0;
  14700. this._viewportCached.w = 0;
  14701. if (bruteForce) {
  14702. this.resetTextureCache();
  14703. this._currentProgram = null;
  14704. this._stencilState.reset();
  14705. this._depthCullingState.reset();
  14706. this.setDepthFunctionToLessOrEqual();
  14707. this._alphaState.reset();
  14708. }
  14709. this._resetVertexBufferBinding();
  14710. this._cachedIndexBuffer = null;
  14711. this._cachedEffectForVertexBuffers = null;
  14712. this._unbindVertexArrayObject();
  14713. this.bindIndexBuffer(null);
  14714. };
  14715. /**
  14716. * Set the compressed texture format to use, based on the formats you have, and the formats
  14717. * supported by the hardware / browser.
  14718. *
  14719. * Khronos Texture Container (.ktx) files are used to support this. This format has the
  14720. * advantage of being specifically designed for OpenGL. Header elements directly correspond
  14721. * to API arguments needed to compressed textures. This puts the burden on the container
  14722. * generator to house the arcane code for determining these for current & future formats.
  14723. *
  14724. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  14725. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  14726. *
  14727. * Note: The result of this call is not taken into account when a texture is base64.
  14728. *
  14729. * @param formatsAvailable defines the list of those format families you have created
  14730. * on your server. Syntax: '-' + format family + '.ktx'. (Case and order do not matter.)
  14731. *
  14732. * Current families are astc, dxt, pvrtc, etc2, & etc1.
  14733. * @returns The extension selected.
  14734. */
  14735. Engine.prototype.setTextureFormatToUse = function (formatsAvailable) {
  14736. for (var i = 0, len1 = this.texturesSupported.length; i < len1; i++) {
  14737. for (var j = 0, len2 = formatsAvailable.length; j < len2; j++) {
  14738. if (this._texturesSupported[i] === formatsAvailable[j].toLowerCase()) {
  14739. return this._textureFormatInUse = this._texturesSupported[i];
  14740. }
  14741. }
  14742. }
  14743. // actively set format to nothing, to allow this to be called more than once
  14744. // and possibly fail the 2nd time
  14745. this._textureFormatInUse = null;
  14746. return null;
  14747. };
  14748. /** @hidden */
  14749. Engine.prototype._createTexture = function () {
  14750. var texture = this._gl.createTexture();
  14751. if (!texture) {
  14752. throw new Error("Unable to create texture");
  14753. }
  14754. return texture;
  14755. };
  14756. /**
  14757. * Usually called from BABYLON.Texture.ts.
  14758. * Passed information to create a WebGLTexture
  14759. * @param urlArg defines a value which contains one of the following:
  14760. * * A conventional http URL, e.g. 'http://...' or 'file://...'
  14761. * * A base64 string of in-line texture data, e.g. 'data:image/jpg;base64,/...'
  14762. * * An indicator that data being passed using the buffer parameter, e.g. 'data:mytexture.jpg'
  14763. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated. Ignored for compressed textures. They must be in the file
  14764. * @param invertY when true, image is flipped when loaded. You probably want true. Ignored for compressed textures. Must be flipped in the file
  14765. * @param scene needed for loading to the correct scene
  14766. * @param samplingMode mode with should be used sample / access the texture (Default: BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  14767. * @param onLoad optional callback to be called upon successful completion
  14768. * @param onError optional callback to be called upon failure
  14769. * @param buffer a source of a file previously fetched as either a base64 string, an ArrayBuffer (compressed or image format), HTMLImageElement (image format), or a Blob
  14770. * @param fallback an internal argument in case the function must be called again, due to etc1 not having alpha capabilities
  14771. * @param format internal format. Default: RGB when extension is '.jpg' else RGBA. Ignored for compressed textures
  14772. * @returns a InternalTexture for assignment back into BABYLON.Texture
  14773. */
  14774. Engine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallback, format) {
  14775. var _this = this;
  14776. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  14777. if (onLoad === void 0) { onLoad = null; }
  14778. if (onError === void 0) { onError = null; }
  14779. if (buffer === void 0) { buffer = null; }
  14780. if (fallback === void 0) { fallback = null; }
  14781. if (format === void 0) { format = null; }
  14782. var url = String(urlArg); // assign a new string, so that the original is still available in case of fallback
  14783. var fromData = url.substr(0, 5) === "data:";
  14784. var fromBlob = url.substr(0, 5) === "blob:";
  14785. var isBase64 = fromData && url.indexOf("base64") !== -1;
  14786. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  14787. // establish the file extension, if possible
  14788. var lastDot = url.lastIndexOf('.');
  14789. var extension = (lastDot > 0) ? url.substring(lastDot).toLowerCase() : "";
  14790. var isDDS = this.getCaps().s3tc && (extension.indexOf(".dds") === 0);
  14791. var isTGA = (extension.indexOf(".tga") === 0);
  14792. // determine if a ktx file should be substituted
  14793. var isKTX = false;
  14794. if (this._textureFormatInUse && !isBase64 && !fallback && !buffer) {
  14795. url = url.substring(0, lastDot) + this._textureFormatInUse;
  14796. isKTX = true;
  14797. }
  14798. if (scene) {
  14799. scene._addPendingData(texture);
  14800. }
  14801. texture.url = url;
  14802. texture.generateMipMaps = !noMipmap;
  14803. texture.samplingMode = samplingMode;
  14804. texture.invertY = invertY;
  14805. if (!this._doNotHandleContextLost) {
  14806. // Keep a link to the buffer only if we plan to handle context lost
  14807. texture._buffer = buffer;
  14808. }
  14809. var onLoadObserver = null;
  14810. if (onLoad && !fallback) {
  14811. onLoadObserver = texture.onLoadedObservable.add(onLoad);
  14812. }
  14813. if (!fallback)
  14814. this._internalTexturesCache.push(texture);
  14815. var onerror = function (message, exception) {
  14816. if (scene) {
  14817. scene._removePendingData(texture);
  14818. }
  14819. if (onLoadObserver && !isKTX) {
  14820. //dont remove the observer if its a ktx file, since the fallback createTexture call will require it.
  14821. texture.onLoadedObservable.remove(onLoadObserver);
  14822. }
  14823. // fallback for when compressed file not found to try again. For instance, etc1 does not have an alpha capable type
  14824. if (isKTX) {
  14825. _this.createTexture(urlArg, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14826. }
  14827. else if (BABYLON.Tools.UseFallbackTexture) {
  14828. _this.createTexture(BABYLON.Tools.fallbackTexture, noMipmap, invertY, scene, samplingMode, null, onError, buffer, texture);
  14829. }
  14830. if (onError) {
  14831. onError(message || "Unknown error", exception);
  14832. }
  14833. };
  14834. var callback = null;
  14835. // processing for non-image formats
  14836. if (isKTX || isTGA || isDDS) {
  14837. if (isKTX) {
  14838. callback = function (data) {
  14839. var ktx = new BABYLON.KhronosTextureContainer(data, 1);
  14840. _this._prepareWebGLTexture(texture, scene, ktx.pixelWidth, ktx.pixelHeight, invertY, false, true, function () {
  14841. ktx.uploadLevels(_this._gl, !noMipmap);
  14842. return false;
  14843. }, samplingMode);
  14844. };
  14845. }
  14846. else if (isTGA) {
  14847. callback = function (arrayBuffer) {
  14848. var data = new Uint8Array(arrayBuffer);
  14849. var header = BABYLON.TGATools.GetTGAHeader(data);
  14850. _this._prepareWebGLTexture(texture, scene, header.width, header.height, invertY, noMipmap, false, function () {
  14851. BABYLON.TGATools.UploadContent(_this._gl, data);
  14852. return false;
  14853. }, samplingMode);
  14854. };
  14855. }
  14856. else if (isDDS) {
  14857. callback = function (data) {
  14858. var info = BABYLON.DDSTools.GetDDSInfo(data);
  14859. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap && ((info.width >> (info.mipmapCount - 1)) === 1);
  14860. _this._prepareWebGLTexture(texture, scene, info.width, info.height, invertY, !loadMipmap, info.isFourCC, function () {
  14861. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 1);
  14862. return false;
  14863. }, samplingMode);
  14864. };
  14865. }
  14866. if (!buffer) {
  14867. this._loadFile(url, function (data) {
  14868. if (callback) {
  14869. callback(data);
  14870. }
  14871. }, undefined, scene ? scene.database : undefined, true, function (request, exception) {
  14872. onerror("Unable to load " + (request ? request.responseURL : url, exception));
  14873. });
  14874. }
  14875. else {
  14876. if (callback) {
  14877. callback(buffer);
  14878. }
  14879. }
  14880. // image format processing
  14881. }
  14882. else {
  14883. var onload = function (img) {
  14884. if (fromBlob && !_this._doNotHandleContextLost) {
  14885. // We need to store the image if we need to rebuild the texture
  14886. // in case of a webgl context lost
  14887. texture._buffer = img;
  14888. }
  14889. _this._prepareWebGLTexture(texture, scene, img.width, img.height, invertY, noMipmap, false, function (potWidth, potHeight, continuationCallback) {
  14890. var gl = _this._gl;
  14891. var isPot = (img.width === potWidth && img.height === potHeight);
  14892. var internalFormat = format ? _this._getInternalFormat(format) : ((extension === ".jpg") ? gl.RGB : gl.RGBA);
  14893. if (isPot) {
  14894. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14895. return false;
  14896. }
  14897. var maxTextureSize = _this._caps.maxTextureSize;
  14898. if (img.width > maxTextureSize || img.height > maxTextureSize) {
  14899. _this._prepareWorkingCanvas();
  14900. if (!_this._workingCanvas || !_this._workingContext) {
  14901. return false;
  14902. }
  14903. _this._workingCanvas.width = potWidth;
  14904. _this._workingCanvas.height = potHeight;
  14905. _this._workingContext.drawImage(img, 0, 0, img.width, img.height, 0, 0, potWidth, potHeight);
  14906. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  14907. texture.width = potWidth;
  14908. texture.height = potHeight;
  14909. return false;
  14910. }
  14911. else {
  14912. // Using shaders when possible to rescale because canvas.drawImage is lossy
  14913. var source_1 = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  14914. _this._bindTextureDirectly(gl.TEXTURE_2D, source_1, true);
  14915. gl.texImage2D(gl.TEXTURE_2D, 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, img);
  14916. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  14917. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  14918. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  14919. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  14920. _this._rescaleTexture(source_1, texture, scene, internalFormat, function () {
  14921. _this._releaseTexture(source_1);
  14922. _this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  14923. continuationCallback();
  14924. });
  14925. }
  14926. return true;
  14927. }, samplingMode);
  14928. };
  14929. if (!fromData || isBase64) {
  14930. if (buffer instanceof HTMLImageElement) {
  14931. onload(buffer);
  14932. }
  14933. else {
  14934. BABYLON.Tools.LoadImage(url, onload, onerror, scene ? scene.database : null);
  14935. }
  14936. }
  14937. else if (typeof buffer === "string" || buffer instanceof ArrayBuffer || buffer instanceof Blob) {
  14938. BABYLON.Tools.LoadImage(buffer, onload, onerror, scene ? scene.database : null);
  14939. }
  14940. else {
  14941. onload(buffer);
  14942. }
  14943. }
  14944. return texture;
  14945. };
  14946. Engine.prototype._rescaleTexture = function (source, destination, scene, internalFormat, onComplete) {
  14947. var _this = this;
  14948. var rtt = this.createRenderTargetTexture({
  14949. width: destination.width,
  14950. height: destination.height,
  14951. }, {
  14952. generateMipMaps: false,
  14953. type: Engine.TEXTURETYPE_UNSIGNED_INT,
  14954. samplingMode: BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  14955. generateDepthBuffer: false,
  14956. generateStencilBuffer: false
  14957. });
  14958. if (!this._rescalePostProcess) {
  14959. this._rescalePostProcess = new BABYLON.PassPostProcess("rescale", 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this, false, Engine.TEXTURETYPE_UNSIGNED_INT);
  14960. }
  14961. this._rescalePostProcess.getEffect().executeWhenCompiled(function () {
  14962. _this._rescalePostProcess.onApply = function (effect) {
  14963. effect._bindTexture("textureSampler", source);
  14964. };
  14965. var hostingScene = scene;
  14966. if (!hostingScene) {
  14967. hostingScene = _this.scenes[_this.scenes.length - 1];
  14968. }
  14969. hostingScene.postProcessManager.directRender([_this._rescalePostProcess], rtt, true);
  14970. _this._bindTextureDirectly(_this._gl.TEXTURE_2D, destination, true);
  14971. _this._gl.copyTexImage2D(_this._gl.TEXTURE_2D, 0, internalFormat, 0, 0, destination.width, destination.height, 0);
  14972. _this.unBindFramebuffer(rtt);
  14973. _this._releaseTexture(rtt);
  14974. if (onComplete) {
  14975. onComplete();
  14976. }
  14977. });
  14978. };
  14979. /**
  14980. * Update a raw texture
  14981. * @param texture defines the texture to update
  14982. * @param data defines the data to store in the texture
  14983. * @param format defines the format of the data
  14984. * @param invertY defines if data must be stored with Y axis inverted
  14985. * @param compression defines the compression used (null by default)
  14986. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  14987. */
  14988. Engine.prototype.updateRawTexture = function (texture, data, format, invertY, compression, type) {
  14989. if (compression === void 0) { compression = null; }
  14990. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  14991. if (!texture) {
  14992. return;
  14993. }
  14994. // babylon's internalSizedFomat but gl's texImage2D internalFormat
  14995. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type, format);
  14996. // babylon's internalFormat but gl's texImage2D format
  14997. var internalFormat = this._getInternalFormat(format);
  14998. var textureType = this._getWebGLTextureType(type);
  14999. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15000. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  15001. if (!this._doNotHandleContextLost) {
  15002. texture._bufferView = data;
  15003. texture.format = format;
  15004. texture.type = type;
  15005. texture.invertY = invertY;
  15006. texture._compression = compression;
  15007. }
  15008. if (texture.width % 4 !== 0) {
  15009. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  15010. }
  15011. if (compression && data) {
  15012. this._gl.compressedTexImage2D(this._gl.TEXTURE_2D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, 0, data);
  15013. }
  15014. else {
  15015. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, data);
  15016. }
  15017. if (texture.generateMipMaps) {
  15018. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15019. }
  15020. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15021. // this.resetTextureCache();
  15022. texture.isReady = true;
  15023. };
  15024. /**
  15025. * Creates a raw texture
  15026. * @param data defines the data to store in the texture
  15027. * @param width defines the width of the texture
  15028. * @param height defines the height of the texture
  15029. * @param format defines the format of the data
  15030. * @param generateMipMaps defines if the engine should generate the mip levels
  15031. * @param invertY defines if data must be stored with Y axis inverted
  15032. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15033. * @param compression defines the compression used (null by default)
  15034. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  15035. * @returns the raw texture inside an InternalTexture
  15036. */
  15037. Engine.prototype.createRawTexture = function (data, width, height, format, generateMipMaps, invertY, samplingMode, compression, type) {
  15038. if (compression === void 0) { compression = null; }
  15039. if (type === void 0) { type = Engine.TEXTURETYPE_UNSIGNED_INT; }
  15040. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW);
  15041. texture.baseWidth = width;
  15042. texture.baseHeight = height;
  15043. texture.width = width;
  15044. texture.height = height;
  15045. texture.format = format;
  15046. texture.generateMipMaps = generateMipMaps;
  15047. texture.samplingMode = samplingMode;
  15048. texture.invertY = invertY;
  15049. texture._compression = compression;
  15050. texture.type = type;
  15051. if (!this._doNotHandleContextLost) {
  15052. texture._bufferView = data;
  15053. }
  15054. this.updateRawTexture(texture, data, format, invertY, compression, type);
  15055. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15056. // Filters
  15057. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  15058. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  15059. this._gl.texParameteri(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15060. if (generateMipMaps) {
  15061. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15062. }
  15063. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15064. this._internalTexturesCache.push(texture);
  15065. return texture;
  15066. };
  15067. /** @hidden */
  15068. Engine.prototype._unpackFlipY = function (value) {
  15069. if (this._unpackFlipYCached !== value) {
  15070. this._unpackFlipYCached = value;
  15071. this._gl.pixelStorei(this._gl.UNPACK_FLIP_Y_WEBGL, value ? 1 : 0);
  15072. }
  15073. };
  15074. /**
  15075. * Creates a dynamic texture
  15076. * @param width defines the width of the texture
  15077. * @param height defines the height of the texture
  15078. * @param generateMipMaps defines if the engine should generate the mip levels
  15079. * @param samplingMode defines the required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  15080. * @returns the dynamic texture inside an InternalTexture
  15081. */
  15082. Engine.prototype.createDynamicTexture = function (width, height, generateMipMaps, samplingMode) {
  15083. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DYNAMIC);
  15084. texture.baseWidth = width;
  15085. texture.baseHeight = height;
  15086. if (generateMipMaps) {
  15087. width = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, this._caps.maxTextureSize) : width;
  15088. height = this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, this._caps.maxTextureSize) : height;
  15089. }
  15090. // this.resetTextureCache();
  15091. texture.width = width;
  15092. texture.height = height;
  15093. texture.isReady = false;
  15094. texture.generateMipMaps = generateMipMaps;
  15095. texture.samplingMode = samplingMode;
  15096. this.updateTextureSamplingMode(samplingMode, texture);
  15097. this._internalTexturesCache.push(texture);
  15098. return texture;
  15099. };
  15100. /**
  15101. * Update the sampling mode of a given texture
  15102. * @param samplingMode defines the required sampling mode
  15103. * @param texture defines the texture to update
  15104. */
  15105. Engine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  15106. var filters = getSamplingParameters(samplingMode, texture.generateMipMaps, this._gl);
  15107. if (texture.isCube) {
  15108. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15109. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15110. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15111. }
  15112. else if (texture.is3D) {
  15113. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15114. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15115. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  15116. }
  15117. else {
  15118. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MAG_FILTER, filters.mag, texture);
  15119. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  15120. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15121. }
  15122. texture.samplingMode = samplingMode;
  15123. };
  15124. /**
  15125. * Update the content of a dynamic texture
  15126. * @param texture defines the texture to update
  15127. * @param canvas defines the canvas containing the source
  15128. * @param invertY defines if data must be stored with Y axis inverted
  15129. * @param premulAlpha defines if alpha is stored as premultiplied
  15130. * @param format defines the format of the data
  15131. */
  15132. Engine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  15133. if (premulAlpha === void 0) { premulAlpha = false; }
  15134. if (!texture) {
  15135. return;
  15136. }
  15137. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15138. this._unpackFlipY(invertY);
  15139. if (premulAlpha) {
  15140. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 1);
  15141. }
  15142. var internalFormat = format ? this._getInternalFormat(format) : this._gl.RGBA;
  15143. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, internalFormat, internalFormat, this._gl.UNSIGNED_BYTE, canvas);
  15144. if (texture.generateMipMaps) {
  15145. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15146. }
  15147. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15148. if (premulAlpha) {
  15149. this._gl.pixelStorei(this._gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, 0);
  15150. }
  15151. texture.isReady = true;
  15152. };
  15153. /**
  15154. * Update a video texture
  15155. * @param texture defines the texture to update
  15156. * @param video defines the video element to use
  15157. * @param invertY defines if data must be stored with Y axis inverted
  15158. */
  15159. Engine.prototype.updateVideoTexture = function (texture, video, invertY) {
  15160. if (!texture || texture._isDisabled) {
  15161. return;
  15162. }
  15163. var wasPreviouslyBound = this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15164. this._unpackFlipY(!invertY); // Video are upside down by default
  15165. try {
  15166. // Testing video texture support
  15167. if (this._videoTextureSupported === undefined) {
  15168. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15169. if (this._gl.getError() !== 0) {
  15170. this._videoTextureSupported = false;
  15171. }
  15172. else {
  15173. this._videoTextureSupported = true;
  15174. }
  15175. }
  15176. // Copy video through the current working canvas if video texture is not supported
  15177. if (!this._videoTextureSupported) {
  15178. if (!texture._workingCanvas) {
  15179. texture._workingCanvas = document.createElement("canvas");
  15180. var context = texture._workingCanvas.getContext("2d");
  15181. if (!context) {
  15182. throw new Error("Unable to get 2d context");
  15183. }
  15184. texture._workingContext = context;
  15185. texture._workingCanvas.width = texture.width;
  15186. texture._workingCanvas.height = texture.height;
  15187. }
  15188. texture._workingContext.drawImage(video, 0, 0, video.videoWidth, video.videoHeight, 0, 0, texture.width, texture.height);
  15189. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, texture._workingCanvas);
  15190. }
  15191. else {
  15192. this._gl.texImage2D(this._gl.TEXTURE_2D, 0, this._gl.RGBA, this._gl.RGBA, this._gl.UNSIGNED_BYTE, video);
  15193. }
  15194. if (texture.generateMipMaps) {
  15195. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15196. }
  15197. if (!wasPreviouslyBound) {
  15198. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15199. }
  15200. // this.resetTextureCache();
  15201. texture.isReady = true;
  15202. }
  15203. catch (ex) {
  15204. // Something unexpected
  15205. // Let's disable the texture
  15206. texture._isDisabled = true;
  15207. }
  15208. };
  15209. /**
  15210. * Updates a depth texture Comparison Mode and Function.
  15211. * If the comparison Function is equal to 0, the mode will be set to none.
  15212. * Otherwise, this only works in webgl 2 and requires a shadow sampler in the shader.
  15213. * @param texture The texture to set the comparison function for
  15214. * @param comparisonFunction The comparison function to set, 0 if no comparison required
  15215. */
  15216. Engine.prototype.updateTextureComparisonFunction = function (texture, comparisonFunction) {
  15217. if (this.webGLVersion === 1) {
  15218. BABYLON.Tools.Error("WebGL 1 does not support texture comparison.");
  15219. return;
  15220. }
  15221. var gl = this._gl;
  15222. if (texture.isCube) {
  15223. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  15224. if (comparisonFunction === 0) {
  15225. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15226. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15227. }
  15228. else {
  15229. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15230. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15231. }
  15232. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  15233. }
  15234. else {
  15235. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture, true);
  15236. if (comparisonFunction === 0) {
  15237. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15238. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15239. }
  15240. else {
  15241. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15242. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15243. }
  15244. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  15245. }
  15246. texture._comparisonFunction = comparisonFunction;
  15247. };
  15248. Engine.prototype._setupDepthStencilTexture = function (internalTexture, size, generateStencil, bilinearFiltering, comparisonFunction) {
  15249. var width = size.width || size;
  15250. var height = size.height || size;
  15251. internalTexture.baseWidth = width;
  15252. internalTexture.baseHeight = height;
  15253. internalTexture.width = width;
  15254. internalTexture.height = height;
  15255. internalTexture.isReady = true;
  15256. internalTexture.samples = 1;
  15257. internalTexture.generateMipMaps = false;
  15258. internalTexture._generateDepthBuffer = true;
  15259. internalTexture._generateStencilBuffer = generateStencil;
  15260. internalTexture.samplingMode = bilinearFiltering ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15261. internalTexture.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15262. internalTexture._comparisonFunction = comparisonFunction;
  15263. var gl = this._gl;
  15264. var target = internalTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15265. var samplingParameters = getSamplingParameters(internalTexture.samplingMode, false, gl);
  15266. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, samplingParameters.mag);
  15267. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, samplingParameters.min);
  15268. gl.texParameteri(target, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15269. gl.texParameteri(target, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15270. if (comparisonFunction === 0) {
  15271. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, Engine.LEQUAL);
  15272. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.NONE);
  15273. }
  15274. else {
  15275. gl.texParameteri(target, gl.TEXTURE_COMPARE_FUNC, comparisonFunction);
  15276. gl.texParameteri(target, gl.TEXTURE_COMPARE_MODE, gl.COMPARE_REF_TO_TEXTURE);
  15277. }
  15278. };
  15279. /**
  15280. * Creates a depth stencil texture.
  15281. * This is only available in WebGL 2 or with the depth texture extension available.
  15282. * @param size The size of face edge in the texture.
  15283. * @param options The options defining the texture.
  15284. * @returns The texture
  15285. */
  15286. Engine.prototype.createDepthStencilTexture = function (size, options) {
  15287. if (options.isCube) {
  15288. var width = size.width || size;
  15289. return this._createDepthStencilCubeTexture(width, options);
  15290. }
  15291. else {
  15292. return this._createDepthStencilTexture(size, options);
  15293. }
  15294. };
  15295. /**
  15296. * Creates a depth stencil texture.
  15297. * This is only available in WebGL 2 or with the depth texture extension available.
  15298. * @param size The size of face edge in the texture.
  15299. * @param options The options defining the texture.
  15300. * @returns The texture
  15301. */
  15302. Engine.prototype._createDepthStencilTexture = function (size, options) {
  15303. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_DEPTHTEXTURE);
  15304. if (!this._caps.depthTextureExtension) {
  15305. BABYLON.Tools.Error("Depth texture is not supported by your browser or hardware.");
  15306. return internalTexture;
  15307. }
  15308. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15309. var gl = this._gl;
  15310. this._bindTextureDirectly(gl.TEXTURE_2D, internalTexture, true);
  15311. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15312. if (this.webGLVersion > 1) {
  15313. if (internalOptions.generateStencil) {
  15314. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH24_STENCIL8, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15315. }
  15316. else {
  15317. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT24, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15318. }
  15319. }
  15320. else {
  15321. if (internalOptions.generateStencil) {
  15322. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_STENCIL, internalTexture.width, internalTexture.height, 0, gl.DEPTH_STENCIL, gl.UNSIGNED_INT_24_8, null);
  15323. }
  15324. else {
  15325. gl.texImage2D(gl.TEXTURE_2D, 0, gl.DEPTH_COMPONENT, internalTexture.width, internalTexture.height, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15326. }
  15327. }
  15328. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15329. return internalTexture;
  15330. };
  15331. /**
  15332. * Creates a depth stencil cube texture.
  15333. * This is only available in WebGL 2.
  15334. * @param size The size of face edge in the cube texture.
  15335. * @param options The options defining the cube texture.
  15336. * @returns The cube texture
  15337. */
  15338. Engine.prototype._createDepthStencilCubeTexture = function (size, options) {
  15339. var internalTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_UNKNOWN);
  15340. internalTexture.isCube = true;
  15341. if (this.webGLVersion === 1) {
  15342. BABYLON.Tools.Error("Depth cube texture is not supported by WebGL 1.");
  15343. return internalTexture;
  15344. }
  15345. var internalOptions = __assign({ bilinearFiltering: false, comparisonFunction: 0, generateStencil: false }, options);
  15346. var gl = this._gl;
  15347. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, internalTexture, true);
  15348. this._setupDepthStencilTexture(internalTexture, size, internalOptions.generateStencil, internalOptions.bilinearFiltering, internalOptions.comparisonFunction);
  15349. // Create the depth/stencil buffer
  15350. for (var face = 0; face < 6; face++) {
  15351. if (internalOptions.generateStencil) {
  15352. 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);
  15353. }
  15354. else {
  15355. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + face, 0, gl.DEPTH_COMPONENT24, size, size, 0, gl.DEPTH_COMPONENT, gl.UNSIGNED_INT, null);
  15356. }
  15357. }
  15358. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15359. return internalTexture;
  15360. };
  15361. /**
  15362. * Sets the frame buffer Depth / Stencil attachement of the render target to the defined depth stencil texture.
  15363. * @param renderTarget The render target to set the frame buffer for
  15364. */
  15365. Engine.prototype.setFrameBufferDepthStencilTexture = function (renderTarget) {
  15366. // Create the framebuffer
  15367. var internalTexture = renderTarget.getInternalTexture();
  15368. if (!internalTexture || !internalTexture._framebuffer || !renderTarget.depthStencilTexture) {
  15369. return;
  15370. }
  15371. var gl = this._gl;
  15372. var depthStencilTexture = renderTarget.depthStencilTexture;
  15373. this.bindUnboundFramebuffer(internalTexture._framebuffer);
  15374. if (depthStencilTexture.isCube) {
  15375. if (depthStencilTexture._generateStencilBuffer) {
  15376. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15377. }
  15378. else {
  15379. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_CUBE_MAP_POSITIVE_X, depthStencilTexture._webGLTexture, 0);
  15380. }
  15381. }
  15382. else {
  15383. if (depthStencilTexture._generateStencilBuffer) {
  15384. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15385. }
  15386. else {
  15387. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthStencilTexture._webGLTexture, 0);
  15388. }
  15389. }
  15390. this.bindUnboundFramebuffer(null);
  15391. };
  15392. /**
  15393. * Creates a new render target texture
  15394. * @param size defines the size of the texture
  15395. * @param options defines the options used to create the texture
  15396. * @returns a new render target texture stored in an InternalTexture
  15397. */
  15398. Engine.prototype.createRenderTargetTexture = function (size, options) {
  15399. var fullOptions = new RenderTargetCreationOptions();
  15400. if (options !== undefined && typeof options === "object") {
  15401. fullOptions.generateMipMaps = options.generateMipMaps;
  15402. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15403. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  15404. fullOptions.type = options.type === undefined ? Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  15405. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  15406. fullOptions.format = options.format === undefined ? Engine.TEXTUREFORMAT_RGBA : options.format;
  15407. }
  15408. else {
  15409. fullOptions.generateMipMaps = options;
  15410. fullOptions.generateDepthBuffer = true;
  15411. fullOptions.generateStencilBuffer = false;
  15412. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15413. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15414. fullOptions.format = Engine.TEXTUREFORMAT_RGBA;
  15415. }
  15416. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15417. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15418. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15419. }
  15420. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15421. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15422. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15423. }
  15424. var gl = this._gl;
  15425. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15426. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  15427. var width = size.width || size;
  15428. var height = size.height || size;
  15429. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps ? true : false, gl);
  15430. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15431. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15432. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15433. }
  15434. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15435. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15436. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15437. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15438. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(fullOptions.type, fullOptions.format), width, height, 0, this._getInternalFormat(fullOptions.format), this._getWebGLTextureType(fullOptions.type), null);
  15439. // Create the framebuffer
  15440. var currentFrameBuffer = this._currentFramebuffer;
  15441. var framebuffer = gl.createFramebuffer();
  15442. this.bindUnboundFramebuffer(framebuffer);
  15443. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15444. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer ? true : false, fullOptions.generateDepthBuffer, width, height);
  15445. if (fullOptions.generateMipMaps) {
  15446. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15447. }
  15448. // Unbind
  15449. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15450. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15451. this.bindUnboundFramebuffer(currentFrameBuffer);
  15452. texture._framebuffer = framebuffer;
  15453. texture.baseWidth = width;
  15454. texture.baseHeight = height;
  15455. texture.width = width;
  15456. texture.height = height;
  15457. texture.isReady = true;
  15458. texture.samples = 1;
  15459. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  15460. texture.samplingMode = fullOptions.samplingMode;
  15461. texture.type = fullOptions.type;
  15462. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15463. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  15464. // this.resetTextureCache();
  15465. this._internalTexturesCache.push(texture);
  15466. return texture;
  15467. };
  15468. /**
  15469. * Create a multi render target texture
  15470. * @see http://doc.babylonjs.com/features/webgl2#multiple-render-target
  15471. * @param size defines the size of the texture
  15472. * @param options defines the creation options
  15473. * @returns the cube texture as an InternalTexture
  15474. */
  15475. Engine.prototype.createMultipleRenderTarget = function (size, options) {
  15476. var generateMipMaps = false;
  15477. var generateDepthBuffer = true;
  15478. var generateStencilBuffer = false;
  15479. var generateDepthTexture = false;
  15480. var textureCount = 1;
  15481. var defaultType = Engine.TEXTURETYPE_UNSIGNED_INT;
  15482. var defaultSamplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  15483. var types = new Array();
  15484. var samplingModes = new Array();
  15485. if (options !== undefined) {
  15486. generateMipMaps = options.generateMipMaps === undefined ? false : options.generateMipMaps;
  15487. generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  15488. generateStencilBuffer = options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  15489. generateDepthTexture = options.generateDepthTexture === undefined ? false : options.generateDepthTexture;
  15490. textureCount = options.textureCount || 1;
  15491. if (options.types) {
  15492. types = options.types;
  15493. }
  15494. if (options.samplingModes) {
  15495. samplingModes = options.samplingModes;
  15496. }
  15497. }
  15498. var gl = this._gl;
  15499. // Create the framebuffer
  15500. var framebuffer = gl.createFramebuffer();
  15501. this.bindUnboundFramebuffer(framebuffer);
  15502. var width = size.width || size;
  15503. var height = size.height || size;
  15504. var textures = [];
  15505. var attachments = [];
  15506. var depthStencilBuffer = this._setupFramebufferDepthAttachments(generateStencilBuffer, generateDepthBuffer, width, height);
  15507. for (var i = 0; i < textureCount; i++) {
  15508. var samplingMode = samplingModes[i] || defaultSamplingMode;
  15509. var type = types[i] || defaultType;
  15510. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15511. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15512. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15513. }
  15514. else if (type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15515. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15516. samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15517. }
  15518. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  15519. if (type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15520. type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15521. BABYLON.Tools.Warn("Float textures are not supported. Render target forced to TEXTURETYPE_UNSIGNED_BYTE type");
  15522. }
  15523. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15524. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15525. textures.push(texture);
  15526. attachments.push(attachment);
  15527. gl.activeTexture(gl["TEXTURE" + i]);
  15528. gl.bindTexture(gl.TEXTURE_2D, texture._webGLTexture);
  15529. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  15530. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  15531. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15532. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15533. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), width, height, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  15534. gl.framebufferTexture2D(gl.DRAW_FRAMEBUFFER, attachment, gl.TEXTURE_2D, texture._webGLTexture, 0);
  15535. if (generateMipMaps) {
  15536. this._gl.generateMipmap(this._gl.TEXTURE_2D);
  15537. }
  15538. // Unbind
  15539. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  15540. texture._framebuffer = framebuffer;
  15541. texture._depthStencilBuffer = depthStencilBuffer;
  15542. texture.baseWidth = width;
  15543. texture.baseHeight = height;
  15544. texture.width = width;
  15545. texture.height = height;
  15546. texture.isReady = true;
  15547. texture.samples = 1;
  15548. texture.generateMipMaps = generateMipMaps;
  15549. texture.samplingMode = samplingMode;
  15550. texture.type = type;
  15551. texture._generateDepthBuffer = generateDepthBuffer;
  15552. texture._generateStencilBuffer = generateStencilBuffer;
  15553. texture._attachments = attachments;
  15554. this._internalTexturesCache.push(texture);
  15555. }
  15556. if (generateDepthTexture && this._caps.depthTextureExtension) {
  15557. // Depth texture
  15558. var depthTexture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_MULTIRENDERTARGET);
  15559. gl.activeTexture(gl.TEXTURE0);
  15560. gl.bindTexture(gl.TEXTURE_2D, depthTexture._webGLTexture);
  15561. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  15562. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  15563. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15564. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15565. 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);
  15566. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.TEXTURE_2D, depthTexture._webGLTexture, 0);
  15567. depthTexture._framebuffer = framebuffer;
  15568. depthTexture.baseWidth = width;
  15569. depthTexture.baseHeight = height;
  15570. depthTexture.width = width;
  15571. depthTexture.height = height;
  15572. depthTexture.isReady = true;
  15573. depthTexture.samples = 1;
  15574. depthTexture.generateMipMaps = generateMipMaps;
  15575. depthTexture.samplingMode = gl.NEAREST;
  15576. depthTexture._generateDepthBuffer = generateDepthBuffer;
  15577. depthTexture._generateStencilBuffer = generateStencilBuffer;
  15578. textures.push(depthTexture);
  15579. this._internalTexturesCache.push(depthTexture);
  15580. }
  15581. gl.drawBuffers(attachments);
  15582. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15583. this.bindUnboundFramebuffer(null);
  15584. this.resetTextureCache();
  15585. return textures;
  15586. };
  15587. Engine.prototype._setupFramebufferDepthAttachments = function (generateStencilBuffer, generateDepthBuffer, width, height, samples) {
  15588. if (samples === void 0) { samples = 1; }
  15589. var depthStencilBuffer = null;
  15590. var gl = this._gl;
  15591. // Create the depth/stencil buffer
  15592. if (generateStencilBuffer) {
  15593. depthStencilBuffer = gl.createRenderbuffer();
  15594. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15595. if (samples > 1) {
  15596. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH24_STENCIL8, width, height);
  15597. }
  15598. else {
  15599. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_STENCIL, width, height);
  15600. }
  15601. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_STENCIL_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15602. }
  15603. else if (generateDepthBuffer) {
  15604. depthStencilBuffer = gl.createRenderbuffer();
  15605. gl.bindRenderbuffer(gl.RENDERBUFFER, depthStencilBuffer);
  15606. if (samples > 1) {
  15607. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, gl.DEPTH_COMPONENT16, width, height);
  15608. }
  15609. else {
  15610. gl.renderbufferStorage(gl.RENDERBUFFER, gl.DEPTH_COMPONENT16, width, height);
  15611. }
  15612. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.DEPTH_ATTACHMENT, gl.RENDERBUFFER, depthStencilBuffer);
  15613. }
  15614. return depthStencilBuffer;
  15615. };
  15616. /**
  15617. * Updates the sample count of a render target texture
  15618. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15619. * @param texture defines the texture to update
  15620. * @param samples defines the sample count to set
  15621. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15622. */
  15623. Engine.prototype.updateRenderTargetTextureSampleCount = function (texture, samples) {
  15624. if (this.webGLVersion < 2 || !texture) {
  15625. return 1;
  15626. }
  15627. if (texture.samples === samples) {
  15628. return samples;
  15629. }
  15630. var gl = this._gl;
  15631. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15632. // Dispose previous render buffers
  15633. if (texture._depthStencilBuffer) {
  15634. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  15635. texture._depthStencilBuffer = null;
  15636. }
  15637. if (texture._MSAAFramebuffer) {
  15638. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  15639. texture._MSAAFramebuffer = null;
  15640. }
  15641. if (texture._MSAARenderBuffer) {
  15642. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  15643. texture._MSAARenderBuffer = null;
  15644. }
  15645. if (samples > 1) {
  15646. var framebuffer = gl.createFramebuffer();
  15647. if (!framebuffer) {
  15648. throw new Error("Unable to create multi sampled framebuffer");
  15649. }
  15650. texture._MSAAFramebuffer = framebuffer;
  15651. this.bindUnboundFramebuffer(texture._MSAAFramebuffer);
  15652. var colorRenderbuffer = gl.createRenderbuffer();
  15653. if (!colorRenderbuffer) {
  15654. throw new Error("Unable to create multi sampled framebuffer");
  15655. }
  15656. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15657. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15658. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.RENDERBUFFER, colorRenderbuffer);
  15659. texture._MSAARenderBuffer = colorRenderbuffer;
  15660. }
  15661. else {
  15662. this.bindUnboundFramebuffer(texture._framebuffer);
  15663. }
  15664. texture.samples = samples;
  15665. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(texture._generateStencilBuffer, texture._generateDepthBuffer, texture.width, texture.height, samples);
  15666. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15667. this.bindUnboundFramebuffer(null);
  15668. return samples;
  15669. };
  15670. /**
  15671. * Update the sample count for a given multiple render target texture
  15672. * @see http://doc.babylonjs.com/features/webgl2#multisample-render-targets
  15673. * @param textures defines the textures to update
  15674. * @param samples defines the sample count to set
  15675. * @returns the effective sample count (could be 0 if multisample render targets are not supported)
  15676. */
  15677. Engine.prototype.updateMultipleRenderTargetTextureSampleCount = function (textures, samples) {
  15678. if (this.webGLVersion < 2 || !textures || textures.length == 0) {
  15679. return 1;
  15680. }
  15681. if (textures[0].samples === samples) {
  15682. return samples;
  15683. }
  15684. var gl = this._gl;
  15685. samples = Math.min(samples, gl.getParameter(gl.MAX_SAMPLES));
  15686. // Dispose previous render buffers
  15687. if (textures[0]._depthStencilBuffer) {
  15688. gl.deleteRenderbuffer(textures[0]._depthStencilBuffer);
  15689. textures[0]._depthStencilBuffer = null;
  15690. }
  15691. if (textures[0]._MSAAFramebuffer) {
  15692. gl.deleteFramebuffer(textures[0]._MSAAFramebuffer);
  15693. textures[0]._MSAAFramebuffer = null;
  15694. }
  15695. for (var i = 0; i < textures.length; i++) {
  15696. if (textures[i]._MSAARenderBuffer) {
  15697. gl.deleteRenderbuffer(textures[i]._MSAARenderBuffer);
  15698. textures[i]._MSAARenderBuffer = null;
  15699. }
  15700. }
  15701. if (samples > 1) {
  15702. var framebuffer = gl.createFramebuffer();
  15703. if (!framebuffer) {
  15704. throw new Error("Unable to create multi sampled framebuffer");
  15705. }
  15706. this.bindUnboundFramebuffer(framebuffer);
  15707. var depthStencilBuffer = this._setupFramebufferDepthAttachments(textures[0]._generateStencilBuffer, textures[0]._generateDepthBuffer, textures[0].width, textures[0].height, samples);
  15708. var attachments = [];
  15709. for (var i = 0; i < textures.length; i++) {
  15710. var texture = textures[i];
  15711. var attachment = gl[this.webGLVersion > 1 ? "COLOR_ATTACHMENT" + i : "COLOR_ATTACHMENT" + i + "_WEBGL"];
  15712. var colorRenderbuffer = gl.createRenderbuffer();
  15713. if (!colorRenderbuffer) {
  15714. throw new Error("Unable to create multi sampled framebuffer");
  15715. }
  15716. gl.bindRenderbuffer(gl.RENDERBUFFER, colorRenderbuffer);
  15717. gl.renderbufferStorageMultisample(gl.RENDERBUFFER, samples, this._getRGBAMultiSampleBufferFormat(texture.type), texture.width, texture.height);
  15718. gl.framebufferRenderbuffer(gl.FRAMEBUFFER, attachment, gl.RENDERBUFFER, colorRenderbuffer);
  15719. texture._MSAAFramebuffer = framebuffer;
  15720. texture._MSAARenderBuffer = colorRenderbuffer;
  15721. texture.samples = samples;
  15722. texture._depthStencilBuffer = depthStencilBuffer;
  15723. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15724. attachments.push(attachment);
  15725. }
  15726. gl.drawBuffers(attachments);
  15727. }
  15728. else {
  15729. this.bindUnboundFramebuffer(textures[0]._framebuffer);
  15730. }
  15731. this.bindUnboundFramebuffer(null);
  15732. return samples;
  15733. };
  15734. /** @hidden */
  15735. Engine.prototype._uploadDataToTexture = function (target, lod, internalFormat, width, height, format, type, data) {
  15736. this._gl.texImage2D(target, lod, internalFormat, width, height, 0, format, type, data);
  15737. };
  15738. /** @hidden */
  15739. Engine.prototype._uploadCompressedDataToTexture = function (target, lod, internalFormat, width, height, data) {
  15740. this._gl.compressedTexImage2D(target, lod, internalFormat, width, height, 0, data);
  15741. };
  15742. /** @hidden */
  15743. Engine.prototype._uploadImageToTexture = function (texture, faceIndex, lod, image) {
  15744. var gl = this._gl;
  15745. var textureType = this._getWebGLTextureType(texture.type);
  15746. var format = this._getInternalFormat(texture.format);
  15747. var internalFormat = this._getRGBABufferInternalSizedFormat(texture.type, format);
  15748. var bindTarget = texture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  15749. this._bindTextureDirectly(bindTarget, texture, true);
  15750. this._unpackFlipY(texture.invertY);
  15751. var target = gl.TEXTURE_2D;
  15752. if (texture.isCube) {
  15753. var target = gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex;
  15754. }
  15755. gl.texImage2D(target, lod, internalFormat, format, textureType, image);
  15756. this._bindTextureDirectly(bindTarget, null, true);
  15757. };
  15758. /**
  15759. * Creates a new render target cube texture
  15760. * @param size defines the size of the texture
  15761. * @param options defines the options used to create the texture
  15762. * @returns a new render target cube texture stored in an InternalTexture
  15763. */
  15764. Engine.prototype.createRenderTargetCubeTexture = function (size, options) {
  15765. var fullOptions = __assign({ generateMipMaps: true, generateDepthBuffer: true, generateStencilBuffer: false, type: Engine.TEXTURETYPE_UNSIGNED_INT, samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE, format: Engine.TEXTUREFORMAT_RGBA }, options);
  15766. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && fullOptions.generateStencilBuffer;
  15767. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloatLinearFiltering) {
  15768. // if floating point linear (gl.FLOAT) then force to NEAREST_SAMPLINGMODE
  15769. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15770. }
  15771. else if (fullOptions.type === Engine.TEXTURETYPE_HALF_FLOAT && !this._caps.textureHalfFloatLinearFiltering) {
  15772. // if floating point linear (HALF_FLOAT) then force to NEAREST_SAMPLINGMODE
  15773. fullOptions.samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE;
  15774. }
  15775. var gl = this._gl;
  15776. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  15777. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15778. var filters = getSamplingParameters(fullOptions.samplingMode, fullOptions.generateMipMaps, gl);
  15779. if (fullOptions.type === Engine.TEXTURETYPE_FLOAT && !this._caps.textureFloat) {
  15780. fullOptions.type = Engine.TEXTURETYPE_UNSIGNED_INT;
  15781. BABYLON.Tools.Warn("Float textures are not supported. Cube render target forced to TEXTURETYPE_UNESIGNED_BYTE type");
  15782. }
  15783. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  15784. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  15785. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15786. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15787. for (var face = 0; face < 6; face++) {
  15788. 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);
  15789. }
  15790. // Create the framebuffer
  15791. var framebuffer = gl.createFramebuffer();
  15792. this.bindUnboundFramebuffer(framebuffer);
  15793. texture._depthStencilBuffer = this._setupFramebufferDepthAttachments(fullOptions.generateStencilBuffer, fullOptions.generateDepthBuffer, size, size);
  15794. // MipMaps
  15795. if (fullOptions.generateMipMaps) {
  15796. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  15797. }
  15798. // Unbind
  15799. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15800. gl.bindRenderbuffer(gl.RENDERBUFFER, null);
  15801. this.bindUnboundFramebuffer(null);
  15802. texture._framebuffer = framebuffer;
  15803. texture.width = size;
  15804. texture.height = size;
  15805. texture.isReady = true;
  15806. texture.isCube = true;
  15807. texture.samples = 1;
  15808. texture.generateMipMaps = fullOptions.generateMipMaps;
  15809. texture.samplingMode = fullOptions.samplingMode;
  15810. texture.type = fullOptions.type;
  15811. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  15812. texture._generateStencilBuffer = fullOptions.generateStencilBuffer;
  15813. this._internalTexturesCache.push(texture);
  15814. return texture;
  15815. };
  15816. /**
  15817. * Create a cube texture from prefiltered data (ie. the mipmaps contain ready to use data for PBR reflection)
  15818. * @param rootUrl defines the url where the file to load is located
  15819. * @param scene defines the current scene
  15820. * @param lodScale defines scale to apply to the mip map selection
  15821. * @param lodOffset defines offset to apply to the mip map selection
  15822. * @param onLoad defines an optional callback raised when the texture is loaded
  15823. * @param onError defines an optional callback raised if there is an issue to load the texture
  15824. * @param format defines the format of the data
  15825. * @param forcedExtension defines the extension to use to pick the right loader
  15826. * @param createPolynomials defines wheter or not to create polynomails harmonics for the texture
  15827. * @returns the cube texture as an InternalTexture
  15828. */
  15829. Engine.prototype.createPrefilteredCubeTexture = function (rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, createPolynomials) {
  15830. var _this = this;
  15831. if (onLoad === void 0) { onLoad = null; }
  15832. if (onError === void 0) { onError = null; }
  15833. if (forcedExtension === void 0) { forcedExtension = null; }
  15834. if (createPolynomials === void 0) { createPolynomials = true; }
  15835. var callback = function (loadData) {
  15836. if (!loadData) {
  15837. if (onLoad) {
  15838. onLoad(null);
  15839. }
  15840. return;
  15841. }
  15842. var texture = loadData.texture;
  15843. if (!createPolynomials) {
  15844. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  15845. }
  15846. else if (loadData.info.sphericalPolynomial) {
  15847. texture._sphericalPolynomial = loadData.info.sphericalPolynomial;
  15848. }
  15849. texture._dataSource = BABYLON.InternalTexture.DATASOURCE_CUBEPREFILTERED;
  15850. if (_this._caps.textureLOD) {
  15851. // Do not add extra process if texture lod is supported.
  15852. if (onLoad) {
  15853. onLoad(texture);
  15854. }
  15855. return;
  15856. }
  15857. var mipSlices = 3;
  15858. var gl = _this._gl;
  15859. var width = loadData.width;
  15860. if (!width) {
  15861. return;
  15862. }
  15863. var textures = [];
  15864. for (var i = 0; i < mipSlices; i++) {
  15865. //compute LOD from even spacing in smoothness (matching shader calculation)
  15866. var smoothness = i / (mipSlices - 1);
  15867. var roughness = 1 - smoothness;
  15868. var minLODIndex = lodOffset; // roughness = 0
  15869. var maxLODIndex = BABYLON.Scalar.Log2(width) * lodScale + lodOffset; // roughness = 1
  15870. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  15871. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  15872. var glTextureFromLod = new BABYLON.InternalTexture(_this, BABYLON.InternalTexture.DATASOURCE_TEMP);
  15873. glTextureFromLod.isCube = true;
  15874. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, glTextureFromLod, true);
  15875. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  15876. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.LINEAR);
  15877. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  15878. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  15879. if (loadData.isDDS) {
  15880. var info = loadData.info;
  15881. var data = loadData.data;
  15882. _this._unpackFlipY(info.isCompressed);
  15883. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, true, 6, mipmapIndex);
  15884. }
  15885. else {
  15886. BABYLON.Tools.Warn("DDS is the only prefiltered cube map supported so far.");
  15887. }
  15888. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  15889. // Wrap in a base texture for easy binding.
  15890. var lodTexture = new BABYLON.BaseTexture(scene);
  15891. lodTexture.isCube = true;
  15892. lodTexture._texture = glTextureFromLod;
  15893. glTextureFromLod.isReady = true;
  15894. textures.push(lodTexture);
  15895. }
  15896. texture._lodTextureHigh = textures[2];
  15897. texture._lodTextureMid = textures[1];
  15898. texture._lodTextureLow = textures[0];
  15899. if (onLoad) {
  15900. onLoad(texture);
  15901. }
  15902. };
  15903. return this.createCubeTexture(rootUrl, scene, null, false, callback, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset);
  15904. };
  15905. /**
  15906. * Creates a cube texture
  15907. * @param rootUrl defines the url where the files to load is located
  15908. * @param scene defines the current scene
  15909. * @param files defines the list of files to load (1 per face)
  15910. * @param noMipmap defines a boolean indicating that no mipmaps shall be generated (false by default)
  15911. * @param onLoad defines an optional callback raised when the texture is loaded
  15912. * @param onError defines an optional callback raised if there is an issue to load the texture
  15913. * @param format defines the format of the data
  15914. * @param forcedExtension defines the extension to use to pick the right loader
  15915. * @param createPolynomials if a polynomial sphere should be created for the cube texture
  15916. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  15917. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  15918. * @param fallback defines texture to use while falling back when (compressed) texture file not found.
  15919. * @returns the cube texture as an InternalTexture
  15920. */
  15921. Engine.prototype.createCubeTexture = function (rootUrl, scene, files, noMipmap, onLoad, onError, format, forcedExtension, createPolynomials, lodScale, lodOffset, fallback) {
  15922. var _this = this;
  15923. if (onLoad === void 0) { onLoad = null; }
  15924. if (onError === void 0) { onError = null; }
  15925. if (forcedExtension === void 0) { forcedExtension = null; }
  15926. if (createPolynomials === void 0) { createPolynomials = false; }
  15927. if (lodScale === void 0) { lodScale = 0; }
  15928. if (lodOffset === void 0) { lodOffset = 0; }
  15929. if (fallback === void 0) { fallback = null; }
  15930. var gl = this._gl;
  15931. var texture = fallback ? fallback : new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBE);
  15932. texture.isCube = true;
  15933. texture.url = rootUrl;
  15934. texture.generateMipMaps = !noMipmap;
  15935. texture._lodGenerationScale = lodScale;
  15936. texture._lodGenerationOffset = lodOffset;
  15937. if (!this._doNotHandleContextLost) {
  15938. texture._extension = forcedExtension;
  15939. texture._files = files;
  15940. }
  15941. var isKTX = false;
  15942. var isDDS = false;
  15943. var isEnv = false;
  15944. var lastDot = rootUrl.lastIndexOf('.');
  15945. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  15946. if (this._textureFormatInUse && !fallback) {
  15947. rootUrl = (lastDot > -1 ? rootUrl.substring(0, lastDot) : rootUrl) + this._textureFormatInUse;
  15948. isKTX = true;
  15949. }
  15950. else {
  15951. isDDS = (extension === ".dds");
  15952. isEnv = (extension === ".env");
  15953. }
  15954. var onerror = function (request, exception) {
  15955. if (isKTX) {
  15956. //remove the format appended to the rootUrl in the original createCubeTexture call.
  15957. var exp = new RegExp("" + _this._textureFormatInUse + "$");
  15958. _this.createCubeTexture(rootUrl.replace(exp, ""), scene, files, noMipmap, onLoad, onError, format, extension, createPolynomials, lodScale, lodOffset, texture);
  15959. }
  15960. if (onError && request) {
  15961. onError(request.status + " " + request.statusText, exception);
  15962. }
  15963. };
  15964. if (isKTX) {
  15965. this._loadFile(rootUrl, function (data) {
  15966. var ktx = new BABYLON.KhronosTextureContainer(data, 6);
  15967. var loadMipmap = ktx.numberOfMipmapLevels > 1 && !noMipmap;
  15968. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  15969. _this._unpackFlipY(true);
  15970. ktx.uploadLevels(_this._gl, !noMipmap);
  15971. _this.setCubeMapTextureParams(gl, loadMipmap);
  15972. texture.width = ktx.pixelWidth;
  15973. texture.height = ktx.pixelHeight;
  15974. texture.isReady = true;
  15975. }, undefined, undefined, true, onerror);
  15976. }
  15977. else if (isEnv) {
  15978. this._loadFile(rootUrl, function (data) {
  15979. data = data;
  15980. var info = BABYLON.EnvironmentTextureTools.GetEnvInfo(data);
  15981. if (info) {
  15982. texture.width = info.width;
  15983. texture.height = info.width;
  15984. BABYLON.EnvironmentTextureTools.UploadPolynomials(texture, data, info);
  15985. BABYLON.EnvironmentTextureTools.UploadLevelsAsync(texture, data, info).then(function () {
  15986. texture.isReady = true;
  15987. if (onLoad) {
  15988. onLoad();
  15989. }
  15990. });
  15991. }
  15992. else if (onError) {
  15993. onError("Can not parse the environment file", null);
  15994. }
  15995. }, undefined, undefined, true, onerror);
  15996. }
  15997. else if (isDDS) {
  15998. if (files && files.length === 6) {
  15999. this._cascadeLoadFiles(scene, function (imgs) {
  16000. var info;
  16001. var loadMipmap = false;
  16002. var width = 0;
  16003. for (var index = 0; index < imgs.length; index++) {
  16004. var data = imgs[index];
  16005. info = BABYLON.DDSTools.GetDDSInfo(data);
  16006. loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  16007. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16008. _this._unpackFlipY(info.isCompressed);
  16009. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6, -1, index);
  16010. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  16011. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16012. }
  16013. texture.width = info.width;
  16014. texture.height = info.height;
  16015. texture.type = info.textureType;
  16016. width = info.width;
  16017. }
  16018. _this.setCubeMapTextureParams(gl, loadMipmap);
  16019. texture.isReady = true;
  16020. if (onLoad) {
  16021. onLoad({ isDDS: true, width: width, info: info, imgs: imgs, texture: texture });
  16022. }
  16023. }, files, onError);
  16024. }
  16025. else {
  16026. this._loadFile(rootUrl, function (data) {
  16027. var info = BABYLON.DDSTools.GetDDSInfo(data);
  16028. if (createPolynomials) {
  16029. info.sphericalPolynomial = new BABYLON.SphericalPolynomial();
  16030. }
  16031. var loadMipmap = (info.isRGB || info.isLuminance || info.mipmapCount > 1) && !noMipmap;
  16032. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16033. _this._unpackFlipY(info.isCompressed);
  16034. BABYLON.DDSTools.UploadDDSLevels(_this, _this._gl, data, info, loadMipmap, 6);
  16035. if (!noMipmap && !info.isFourCC && info.mipmapCount === 1) {
  16036. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16037. }
  16038. _this.setCubeMapTextureParams(gl, loadMipmap);
  16039. texture.width = info.width;
  16040. texture.height = info.height;
  16041. texture.isReady = true;
  16042. texture.type = info.textureType;
  16043. if (onLoad) {
  16044. onLoad({ isDDS: true, width: info.width, info: info, data: data, texture: texture });
  16045. }
  16046. }, undefined, undefined, true, onerror);
  16047. }
  16048. }
  16049. else {
  16050. if (!files) {
  16051. throw new Error("Cannot load cubemap because files were not defined");
  16052. }
  16053. cascadeLoadImgs(rootUrl, scene, function (imgs) {
  16054. var width = _this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(imgs[0].width, _this._caps.maxCubemapTextureSize) : imgs[0].width;
  16055. var height = width;
  16056. _this._prepareWorkingCanvas();
  16057. if (!_this._workingCanvas || !_this._workingContext) {
  16058. return;
  16059. }
  16060. _this._workingCanvas.width = width;
  16061. _this._workingCanvas.height = height;
  16062. var faces = [
  16063. gl.TEXTURE_CUBE_MAP_POSITIVE_X, gl.TEXTURE_CUBE_MAP_POSITIVE_Y, gl.TEXTURE_CUBE_MAP_POSITIVE_Z,
  16064. gl.TEXTURE_CUBE_MAP_NEGATIVE_X, gl.TEXTURE_CUBE_MAP_NEGATIVE_Y, gl.TEXTURE_CUBE_MAP_NEGATIVE_Z
  16065. ];
  16066. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16067. _this._unpackFlipY(false);
  16068. var internalFormat = format ? _this._getInternalFormat(format) : _this._gl.RGBA;
  16069. for (var index = 0; index < faces.length; index++) {
  16070. _this._workingContext.drawImage(imgs[index], 0, 0, imgs[index].width, imgs[index].height, 0, 0, width, height);
  16071. gl.texImage2D(faces[index], 0, internalFormat, internalFormat, gl.UNSIGNED_BYTE, _this._workingCanvas);
  16072. }
  16073. if (!noMipmap) {
  16074. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  16075. }
  16076. _this.setCubeMapTextureParams(gl, !noMipmap);
  16077. texture.width = width;
  16078. texture.height = height;
  16079. texture.isReady = true;
  16080. if (format) {
  16081. texture.format = format;
  16082. }
  16083. texture.onLoadedObservable.notifyObservers(texture);
  16084. texture.onLoadedObservable.clear();
  16085. if (onLoad) {
  16086. onLoad();
  16087. }
  16088. }, files, onError);
  16089. }
  16090. this._internalTexturesCache.push(texture);
  16091. return texture;
  16092. };
  16093. Engine.prototype.setCubeMapTextureParams = function (gl, loadMipmap) {
  16094. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.LINEAR);
  16095. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, loadMipmap ? gl.LINEAR_MIPMAP_LINEAR : gl.LINEAR);
  16096. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16097. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16098. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16099. // this.resetTextureCache();
  16100. };
  16101. /**
  16102. * Update a raw cube texture
  16103. * @param texture defines the texture to udpdate
  16104. * @param data defines the data to store
  16105. * @param format defines the data format
  16106. * @param type defines the type fo the data (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  16107. * @param invertY defines if data must be stored with Y axis inverted
  16108. * @param compression defines the compression used (null by default)
  16109. * @param level defines which level of the texture to update
  16110. */
  16111. Engine.prototype.updateRawCubeTexture = function (texture, data, format, type, invertY, compression, level) {
  16112. if (compression === void 0) { compression = null; }
  16113. if (level === void 0) { level = 0; }
  16114. texture._bufferViewArray = data;
  16115. texture.format = format;
  16116. texture.type = type;
  16117. texture.invertY = invertY;
  16118. texture._compression = compression;
  16119. var gl = this._gl;
  16120. var textureType = this._getWebGLTextureType(type);
  16121. var internalFormat = this._getInternalFormat(format);
  16122. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(type);
  16123. var needConversion = false;
  16124. if (internalFormat === gl.RGB) {
  16125. internalFormat = gl.RGBA;
  16126. needConversion = true;
  16127. }
  16128. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16129. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16130. if (texture.width % 4 !== 0) {
  16131. gl.pixelStorei(gl.UNPACK_ALIGNMENT, 1);
  16132. }
  16133. // Data are known to be in +X +Y +Z -X -Y -Z
  16134. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16135. var faceData = data[faceIndex];
  16136. if (compression) {
  16137. gl.compressedTexImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, (this.getCaps().s3tc)[compression], texture.width, texture.height, 0, faceData);
  16138. }
  16139. else {
  16140. if (needConversion) {
  16141. faceData = this._convertRGBtoRGBATextureData(faceData, texture.width, texture.height, type);
  16142. }
  16143. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, level, internalSizedFomat, texture.width, texture.height, 0, internalFormat, textureType, faceData);
  16144. }
  16145. }
  16146. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16147. if (isPot && texture.generateMipMaps && level === 0) {
  16148. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16149. }
  16150. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16151. // this.resetTextureCache();
  16152. texture.isReady = true;
  16153. };
  16154. /**
  16155. * Creates a new raw cube texture
  16156. * @param data defines the array of data to use to create each face
  16157. * @param size defines the size of the textures
  16158. * @param format defines the format of the data
  16159. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16160. * @param generateMipMaps defines if the engine should generate the mip levels
  16161. * @param invertY defines if data must be stored with Y axis inverted
  16162. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16163. * @param compression defines the compression used (null by default)
  16164. * @returns the cube texture as an InternalTexture
  16165. */
  16166. Engine.prototype.createRawCubeTexture = function (data, size, format, type, generateMipMaps, invertY, samplingMode, compression) {
  16167. if (compression === void 0) { compression = null; }
  16168. var gl = this._gl;
  16169. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_CUBERAW);
  16170. texture.isCube = true;
  16171. texture.generateMipMaps = generateMipMaps;
  16172. texture.format = format;
  16173. texture.type = type;
  16174. if (!this._doNotHandleContextLost) {
  16175. texture._bufferViewArray = data;
  16176. }
  16177. var textureType = this._getWebGLTextureType(type);
  16178. var internalFormat = this._getInternalFormat(format);
  16179. if (internalFormat === gl.RGB) {
  16180. internalFormat = gl.RGBA;
  16181. }
  16182. var width = size;
  16183. var height = width;
  16184. texture.width = width;
  16185. texture.height = height;
  16186. // Double check on POT to generate Mips.
  16187. var isPot = !this.needPOTTextures || (BABYLON.Tools.IsExponentOfTwo(texture.width) && BABYLON.Tools.IsExponentOfTwo(texture.height));
  16188. if (!isPot) {
  16189. generateMipMaps = false;
  16190. }
  16191. // Upload data if needed. The texture won't be ready until then.
  16192. if (data) {
  16193. this.updateRawCubeTexture(texture, data, format, type, invertY, compression);
  16194. }
  16195. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, texture, true);
  16196. // Filters
  16197. if (data && generateMipMaps) {
  16198. this._gl.generateMipmap(this._gl.TEXTURE_CUBE_MAP);
  16199. }
  16200. if (textureType === gl.FLOAT && !this._caps.textureFloatLinearFiltering) {
  16201. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16202. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16203. }
  16204. else if (textureType === this._gl.HALF_FLOAT_OES && !this._caps.textureHalfFloatLinearFiltering) {
  16205. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  16206. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  16207. }
  16208. else {
  16209. var filters = getSamplingParameters(samplingMode, generateMipMaps, gl);
  16210. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MAG_FILTER, filters.mag);
  16211. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_MIN_FILTER, filters.min);
  16212. }
  16213. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE);
  16214. gl.texParameteri(gl.TEXTURE_CUBE_MAP, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE);
  16215. this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16216. return texture;
  16217. };
  16218. /**
  16219. * Creates a new raw cube texture from a specified url
  16220. * @param url defines the url where the data is located
  16221. * @param scene defines the current scene
  16222. * @param size defines the size of the textures
  16223. * @param format defines the format of the data
  16224. * @param type defines the type fo the data (like BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT)
  16225. * @param noMipmap defines if the engine should avoid generating the mip levels
  16226. * @param callback defines a callback used to extract texture data from loaded data
  16227. * @param mipmapGenerator defines to provide an optional tool to generate mip levels
  16228. * @param onLoad defines a callback called when texture is loaded
  16229. * @param onError defines a callback called if there is an error
  16230. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16231. * @param invertY defines if data must be stored with Y axis inverted
  16232. * @returns the cube texture as an InternalTexture
  16233. */
  16234. Engine.prototype.createRawCubeTextureFromUrl = function (url, scene, size, format, type, noMipmap, callback, mipmapGenerator, onLoad, onError, samplingMode, invertY) {
  16235. var _this = this;
  16236. if (onLoad === void 0) { onLoad = null; }
  16237. if (onError === void 0) { onError = null; }
  16238. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16239. if (invertY === void 0) { invertY = false; }
  16240. var gl = this._gl;
  16241. var texture = this.createRawCubeTexture(null, size, format, type, !noMipmap, invertY, samplingMode);
  16242. scene._addPendingData(texture);
  16243. texture.url = url;
  16244. this._internalTexturesCache.push(texture);
  16245. var onerror = function (request, exception) {
  16246. scene._removePendingData(texture);
  16247. if (onError && request) {
  16248. onError(request.status + " " + request.statusText, exception);
  16249. }
  16250. };
  16251. var internalCallback = function (data) {
  16252. var width = texture.width;
  16253. var faceDataArrays = callback(data);
  16254. if (!faceDataArrays) {
  16255. return;
  16256. }
  16257. if (mipmapGenerator) {
  16258. var textureType = _this._getWebGLTextureType(type);
  16259. var internalFormat = _this._getInternalFormat(format);
  16260. var internalSizedFomat = _this._getRGBABufferInternalSizedFormat(type);
  16261. var needConversion = false;
  16262. if (internalFormat === gl.RGB) {
  16263. internalFormat = gl.RGBA;
  16264. needConversion = true;
  16265. }
  16266. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, texture, true);
  16267. _this._unpackFlipY(false);
  16268. var mipData = mipmapGenerator(faceDataArrays);
  16269. for (var level = 0; level < mipData.length; level++) {
  16270. var mipSize = width >> level;
  16271. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  16272. var mipFaceData = mipData[level][faceIndex];
  16273. if (needConversion) {
  16274. mipFaceData = _this._convertRGBtoRGBATextureData(mipFaceData, mipSize, mipSize, type);
  16275. }
  16276. gl.texImage2D(faceIndex, level, internalSizedFomat, mipSize, mipSize, 0, internalFormat, textureType, mipFaceData);
  16277. }
  16278. }
  16279. _this._bindTextureDirectly(gl.TEXTURE_CUBE_MAP, null);
  16280. }
  16281. else {
  16282. texture.generateMipMaps = !noMipmap;
  16283. _this.updateRawCubeTexture(texture, faceDataArrays, format, type, invertY);
  16284. }
  16285. texture.isReady = true;
  16286. // this.resetTextureCache();
  16287. scene._removePendingData(texture);
  16288. if (onLoad) {
  16289. onLoad();
  16290. }
  16291. };
  16292. this._loadFile(url, function (data) {
  16293. internalCallback(data);
  16294. }, undefined, scene.database, true, onerror);
  16295. return texture;
  16296. };
  16297. ;
  16298. /**
  16299. * Update a raw 3D texture
  16300. * @param texture defines the texture to update
  16301. * @param data defines the data to store
  16302. * @param format defines the data format
  16303. * @param invertY defines if data must be stored with Y axis inverted
  16304. * @param compression defines the used compression (can be null)
  16305. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  16306. */
  16307. Engine.prototype.updateRawTexture3D = function (texture, data, format, invertY, compression, textureType) {
  16308. if (compression === void 0) { compression = null; }
  16309. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16310. var internalType = this._getWebGLTextureType(textureType);
  16311. var internalFormat = this._getInternalFormat(format);
  16312. var internalSizedFomat = this._getRGBABufferInternalSizedFormat(textureType, format);
  16313. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16314. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16315. if (!this._doNotHandleContextLost) {
  16316. texture._bufferView = data;
  16317. texture.format = format;
  16318. texture.invertY = invertY;
  16319. texture._compression = compression;
  16320. }
  16321. if (texture.width % 4 !== 0) {
  16322. this._gl.pixelStorei(this._gl.UNPACK_ALIGNMENT, 1);
  16323. }
  16324. if (compression && data) {
  16325. this._gl.compressedTexImage3D(this._gl.TEXTURE_3D, 0, this.getCaps().s3tc[compression], texture.width, texture.height, texture.depth, 0, data);
  16326. }
  16327. else {
  16328. this._gl.texImage3D(this._gl.TEXTURE_3D, 0, internalSizedFomat, texture.width, texture.height, texture.depth, 0, internalFormat, internalType, data);
  16329. }
  16330. if (texture.generateMipMaps) {
  16331. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16332. }
  16333. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16334. // this.resetTextureCache();
  16335. texture.isReady = true;
  16336. };
  16337. /**
  16338. * Creates a new raw 3D texture
  16339. * @param data defines the data used to create the texture
  16340. * @param width defines the width of the texture
  16341. * @param height defines the height of the texture
  16342. * @param depth defines the depth of the texture
  16343. * @param format defines the format of the texture
  16344. * @param generateMipMaps defines if the engine must generate mip levels
  16345. * @param invertY defines if data must be stored with Y axis inverted
  16346. * @param samplingMode defines the required sampling mode (like BABYLON.Texture.NEAREST_SAMPLINGMODE)
  16347. * @param compression defines the compressed used (can be null)
  16348. * @param textureType defines the compressed used (can be null)
  16349. * @returns a new raw 3D texture (stored in an InternalTexture)
  16350. */
  16351. Engine.prototype.createRawTexture3D = function (data, width, height, depth, format, generateMipMaps, invertY, samplingMode, compression, textureType) {
  16352. if (compression === void 0) { compression = null; }
  16353. if (textureType === void 0) { textureType = Engine.TEXTURETYPE_UNSIGNED_INT; }
  16354. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RAW3D);
  16355. texture.baseWidth = width;
  16356. texture.baseHeight = height;
  16357. texture.baseDepth = depth;
  16358. texture.width = width;
  16359. texture.height = height;
  16360. texture.depth = depth;
  16361. texture.format = format;
  16362. texture.type = textureType;
  16363. texture.generateMipMaps = generateMipMaps;
  16364. texture.samplingMode = samplingMode;
  16365. texture.is3D = true;
  16366. if (!this._doNotHandleContextLost) {
  16367. texture._bufferView = data;
  16368. }
  16369. this.updateRawTexture3D(texture, data, format, invertY, compression, textureType);
  16370. this._bindTextureDirectly(this._gl.TEXTURE_3D, texture, true);
  16371. // Filters
  16372. var filters = getSamplingParameters(samplingMode, generateMipMaps, this._gl);
  16373. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MAG_FILTER, filters.mag);
  16374. this._gl.texParameteri(this._gl.TEXTURE_3D, this._gl.TEXTURE_MIN_FILTER, filters.min);
  16375. if (generateMipMaps) {
  16376. this._gl.generateMipmap(this._gl.TEXTURE_3D);
  16377. }
  16378. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16379. this._internalTexturesCache.push(texture);
  16380. return texture;
  16381. };
  16382. Engine.prototype._prepareWebGLTextureContinuation = function (texture, scene, noMipmap, isCompressed, samplingMode) {
  16383. var gl = this._gl;
  16384. if (!gl) {
  16385. return;
  16386. }
  16387. var filters = getSamplingParameters(samplingMode, !noMipmap, gl);
  16388. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, filters.mag);
  16389. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, filters.min);
  16390. if (!noMipmap && !isCompressed) {
  16391. gl.generateMipmap(gl.TEXTURE_2D);
  16392. }
  16393. this._bindTextureDirectly(gl.TEXTURE_2D, null);
  16394. // this.resetTextureCache();
  16395. if (scene) {
  16396. scene._removePendingData(texture);
  16397. }
  16398. texture.onLoadedObservable.notifyObservers(texture);
  16399. texture.onLoadedObservable.clear();
  16400. };
  16401. Engine.prototype._prepareWebGLTexture = function (texture, scene, width, height, invertY, noMipmap, isCompressed, processFunction, samplingMode) {
  16402. var _this = this;
  16403. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  16404. var maxTextureSize = this.getCaps().maxTextureSize;
  16405. var potWidth = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(width, maxTextureSize) : width);
  16406. var potHeight = Math.min(maxTextureSize, this.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(height, maxTextureSize) : height);
  16407. var gl = this._gl;
  16408. if (!gl) {
  16409. return;
  16410. }
  16411. if (!texture._webGLTexture) {
  16412. // this.resetTextureCache();
  16413. if (scene) {
  16414. scene._removePendingData(texture);
  16415. }
  16416. return;
  16417. }
  16418. this._bindTextureDirectly(gl.TEXTURE_2D, texture, true);
  16419. this._unpackFlipY(invertY === undefined ? true : (invertY ? true : false));
  16420. texture.baseWidth = width;
  16421. texture.baseHeight = height;
  16422. texture.width = potWidth;
  16423. texture.height = potHeight;
  16424. texture.isReady = true;
  16425. if (processFunction(potWidth, potHeight, function () {
  16426. _this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16427. })) {
  16428. // Returning as texture needs extra async steps
  16429. return;
  16430. }
  16431. this._prepareWebGLTextureContinuation(texture, scene, noMipmap, isCompressed, samplingMode);
  16432. };
  16433. Engine.prototype._convertRGBtoRGBATextureData = function (rgbData, width, height, textureType) {
  16434. // Create new RGBA data container.
  16435. var rgbaData;
  16436. if (textureType === Engine.TEXTURETYPE_FLOAT) {
  16437. rgbaData = new Float32Array(width * height * 4);
  16438. }
  16439. else {
  16440. rgbaData = new Uint32Array(width * height * 4);
  16441. }
  16442. // Convert each pixel.
  16443. for (var x = 0; x < width; x++) {
  16444. for (var y = 0; y < height; y++) {
  16445. var index = (y * width + x) * 3;
  16446. var newIndex = (y * width + x) * 4;
  16447. // Map Old Value to new value.
  16448. rgbaData[newIndex + 0] = rgbData[index + 0];
  16449. rgbaData[newIndex + 1] = rgbData[index + 1];
  16450. rgbaData[newIndex + 2] = rgbData[index + 2];
  16451. // Add fully opaque alpha channel.
  16452. rgbaData[newIndex + 3] = 1;
  16453. }
  16454. }
  16455. return rgbaData;
  16456. };
  16457. /** @hidden */
  16458. Engine.prototype._releaseFramebufferObjects = function (texture) {
  16459. var gl = this._gl;
  16460. if (texture._framebuffer) {
  16461. gl.deleteFramebuffer(texture._framebuffer);
  16462. texture._framebuffer = null;
  16463. }
  16464. if (texture._depthStencilBuffer) {
  16465. gl.deleteRenderbuffer(texture._depthStencilBuffer);
  16466. texture._depthStencilBuffer = null;
  16467. }
  16468. if (texture._MSAAFramebuffer) {
  16469. gl.deleteFramebuffer(texture._MSAAFramebuffer);
  16470. texture._MSAAFramebuffer = null;
  16471. }
  16472. if (texture._MSAARenderBuffer) {
  16473. gl.deleteRenderbuffer(texture._MSAARenderBuffer);
  16474. texture._MSAARenderBuffer = null;
  16475. }
  16476. };
  16477. /** @hidden */
  16478. Engine.prototype._releaseTexture = function (texture) {
  16479. var gl = this._gl;
  16480. this._releaseFramebufferObjects(texture);
  16481. gl.deleteTexture(texture._webGLTexture);
  16482. // Unbind channels
  16483. this.unbindAllTextures();
  16484. var index = this._internalTexturesCache.indexOf(texture);
  16485. if (index !== -1) {
  16486. this._internalTexturesCache.splice(index, 1);
  16487. }
  16488. // Integrated fixed lod samplers.
  16489. if (texture._lodTextureHigh) {
  16490. texture._lodTextureHigh.dispose();
  16491. }
  16492. if (texture._lodTextureMid) {
  16493. texture._lodTextureMid.dispose();
  16494. }
  16495. if (texture._lodTextureLow) {
  16496. texture._lodTextureLow.dispose();
  16497. }
  16498. // Set output texture of post process to null if the texture has been released/disposed
  16499. this.scenes.forEach(function (scene) {
  16500. scene.postProcesses.forEach(function (postProcess) {
  16501. if (postProcess._outputTexture == texture) {
  16502. postProcess._outputTexture = null;
  16503. }
  16504. });
  16505. scene.cameras.forEach(function (camera) {
  16506. camera._postProcesses.forEach(function (postProcess) {
  16507. if (postProcess) {
  16508. if (postProcess._outputTexture == texture) {
  16509. postProcess._outputTexture = null;
  16510. }
  16511. }
  16512. });
  16513. });
  16514. });
  16515. };
  16516. Engine.prototype.setProgram = function (program) {
  16517. if (this._currentProgram !== program) {
  16518. this._gl.useProgram(program);
  16519. this._currentProgram = program;
  16520. }
  16521. };
  16522. /**
  16523. * Binds an effect to the webGL context
  16524. * @param effect defines the effect to bind
  16525. */
  16526. Engine.prototype.bindSamplers = function (effect) {
  16527. this.setProgram(effect.getProgram());
  16528. var samplers = effect.getSamplers();
  16529. for (var index = 0; index < samplers.length; index++) {
  16530. var uniform = effect.getUniform(samplers[index]);
  16531. if (uniform) {
  16532. this._boundUniforms[index] = uniform;
  16533. }
  16534. }
  16535. this._currentEffect = null;
  16536. };
  16537. Engine.prototype._moveBoundTextureOnTop = function (internalTexture) {
  16538. if (this.disableTextureBindingOptimization || this._lastBoundInternalTextureTracker.previous === internalTexture) {
  16539. return;
  16540. }
  16541. // Remove
  16542. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16543. // Bind last to it
  16544. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, internalTexture);
  16545. // Bind to dummy
  16546. this._linkTrackers(internalTexture, this._lastBoundInternalTextureTracker);
  16547. };
  16548. Engine.prototype._getCorrectTextureChannel = function (channel, internalTexture) {
  16549. if (!internalTexture) {
  16550. return -1;
  16551. }
  16552. internalTexture._initialSlot = channel;
  16553. if (this.disableTextureBindingOptimization) { // We want texture sampler ID === texture channel
  16554. if (channel !== internalTexture._designatedSlot) {
  16555. this._textureCollisions.addCount(1, false);
  16556. }
  16557. }
  16558. else {
  16559. if (channel !== internalTexture._designatedSlot) {
  16560. if (internalTexture._designatedSlot > -1) { // Texture is already assigned to a slot
  16561. return internalTexture._designatedSlot;
  16562. }
  16563. else {
  16564. // No slot for this texture, let's pick a new one (if we find a free slot)
  16565. if (this._nextFreeTextureSlots.length) {
  16566. return this._nextFreeTextureSlots[0];
  16567. }
  16568. // We need to recycle the oldest bound texture, sorry.
  16569. this._textureCollisions.addCount(1, false);
  16570. return this._removeDesignatedSlot(this._firstBoundInternalTextureTracker.next);
  16571. }
  16572. }
  16573. }
  16574. return channel;
  16575. };
  16576. Engine.prototype._linkTrackers = function (previous, next) {
  16577. previous.next = next;
  16578. next.previous = previous;
  16579. };
  16580. Engine.prototype._removeDesignatedSlot = function (internalTexture) {
  16581. var currentSlot = internalTexture._designatedSlot;
  16582. if (currentSlot === -1) {
  16583. return -1;
  16584. }
  16585. internalTexture._designatedSlot = -1;
  16586. if (this.disableTextureBindingOptimization) {
  16587. return -1;
  16588. }
  16589. // Remove from bound list
  16590. this._linkTrackers(internalTexture.previous, internalTexture.next);
  16591. // Free the slot
  16592. this._boundTexturesCache[currentSlot] = null;
  16593. this._nextFreeTextureSlots.push(currentSlot);
  16594. return currentSlot;
  16595. };
  16596. Engine.prototype._activateCurrentTexture = function () {
  16597. if (this._currentTextureChannel !== this._activeChannel) {
  16598. this._gl.activeTexture(this._gl.TEXTURE0 + this._activeChannel);
  16599. this._currentTextureChannel = this._activeChannel;
  16600. }
  16601. };
  16602. /** @hidden */
  16603. Engine.prototype._bindTextureDirectly = function (target, texture, forTextureDataUpdate, force) {
  16604. if (forTextureDataUpdate === void 0) { forTextureDataUpdate = false; }
  16605. if (force === void 0) { force = false; }
  16606. var wasPreviouslyBound = false;
  16607. if (forTextureDataUpdate && texture && texture._designatedSlot > -1) {
  16608. this._activeChannel = texture._designatedSlot;
  16609. }
  16610. var currentTextureBound = this._boundTexturesCache[this._activeChannel];
  16611. var isTextureForRendering = texture && texture._initialSlot > -1;
  16612. if (currentTextureBound !== texture || force) {
  16613. if (currentTextureBound) {
  16614. this._removeDesignatedSlot(currentTextureBound);
  16615. }
  16616. this._activateCurrentTexture();
  16617. this._gl.bindTexture(target, texture ? texture._webGLTexture : null);
  16618. this._boundTexturesCache[this._activeChannel] = texture;
  16619. if (texture) {
  16620. if (!this.disableTextureBindingOptimization) {
  16621. var slotIndex = this._nextFreeTextureSlots.indexOf(this._activeChannel);
  16622. if (slotIndex > -1) {
  16623. this._nextFreeTextureSlots.splice(slotIndex, 1);
  16624. }
  16625. this._linkTrackers(this._lastBoundInternalTextureTracker.previous, texture);
  16626. this._linkTrackers(texture, this._lastBoundInternalTextureTracker);
  16627. }
  16628. texture._designatedSlot = this._activeChannel;
  16629. }
  16630. }
  16631. else if (forTextureDataUpdate) {
  16632. wasPreviouslyBound = true;
  16633. this._activateCurrentTexture();
  16634. }
  16635. if (isTextureForRendering && !forTextureDataUpdate) {
  16636. this._bindSamplerUniformToChannel(texture._initialSlot, this._activeChannel);
  16637. }
  16638. return wasPreviouslyBound;
  16639. };
  16640. /** @hidden */
  16641. Engine.prototype._bindTexture = function (channel, texture) {
  16642. if (channel < 0) {
  16643. return;
  16644. }
  16645. if (texture) {
  16646. channel = this._getCorrectTextureChannel(channel, texture);
  16647. }
  16648. this._activeChannel = channel;
  16649. this._bindTextureDirectly(this._gl.TEXTURE_2D, texture);
  16650. };
  16651. /**
  16652. * Sets a texture to the webGL context from a postprocess
  16653. * @param channel defines the channel to use
  16654. * @param postProcess defines the source postprocess
  16655. */
  16656. Engine.prototype.setTextureFromPostProcess = function (channel, postProcess) {
  16657. this._bindTexture(channel, postProcess ? postProcess._textures.data[postProcess._currentRenderTextureInd] : null);
  16658. };
  16659. /**
  16660. * Binds the output of the passed in post process to the texture channel specified
  16661. * @param channel The channel the texture should be bound to
  16662. * @param postProcess The post process which's output should be bound
  16663. */
  16664. Engine.prototype.setTextureFromPostProcessOutput = function (channel, postProcess) {
  16665. this._bindTexture(channel, postProcess ? postProcess._outputTexture : null);
  16666. };
  16667. /**
  16668. * Unbind all textures from the webGL context
  16669. */
  16670. Engine.prototype.unbindAllTextures = function () {
  16671. for (var channel = 0; channel < this._maxSimultaneousTextures; channel++) {
  16672. this._activeChannel = channel;
  16673. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16674. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16675. if (this.webGLVersion > 1) {
  16676. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16677. }
  16678. }
  16679. };
  16680. /**
  16681. * Sets a texture to the according uniform.
  16682. * @param channel The texture channel
  16683. * @param uniform The uniform to set
  16684. * @param texture The texture to apply
  16685. */
  16686. Engine.prototype.setTexture = function (channel, uniform, texture) {
  16687. if (channel < 0) {
  16688. return;
  16689. }
  16690. if (uniform) {
  16691. this._boundUniforms[channel] = uniform;
  16692. }
  16693. this._setTexture(channel, texture);
  16694. };
  16695. /**
  16696. * Sets a depth stencil texture from a render target to the according uniform.
  16697. * @param channel The texture channel
  16698. * @param uniform The uniform to set
  16699. * @param texture The render target texture containing the depth stencil texture to apply
  16700. */
  16701. Engine.prototype.setDepthStencilTexture = function (channel, uniform, texture) {
  16702. if (channel < 0) {
  16703. return;
  16704. }
  16705. if (uniform) {
  16706. this._boundUniforms[channel] = uniform;
  16707. }
  16708. if (!texture || !texture.depthStencilTexture) {
  16709. this._setTexture(channel, null);
  16710. }
  16711. else {
  16712. this._setTexture(channel, texture, false, true);
  16713. }
  16714. };
  16715. Engine.prototype._bindSamplerUniformToChannel = function (sourceSlot, destination) {
  16716. var uniform = this._boundUniforms[sourceSlot];
  16717. if (uniform._currentState === destination) {
  16718. return;
  16719. }
  16720. this._gl.uniform1i(uniform, destination);
  16721. uniform._currentState = destination;
  16722. };
  16723. Engine.prototype._getTextureWrapMode = function (mode) {
  16724. switch (mode) {
  16725. case BABYLON.Texture.WRAP_ADDRESSMODE:
  16726. return this._gl.REPEAT;
  16727. case BABYLON.Texture.CLAMP_ADDRESSMODE:
  16728. return this._gl.CLAMP_TO_EDGE;
  16729. case BABYLON.Texture.MIRROR_ADDRESSMODE:
  16730. return this._gl.MIRRORED_REPEAT;
  16731. }
  16732. return this._gl.REPEAT;
  16733. };
  16734. Engine.prototype._setTexture = function (channel, texture, isPartOfTextureArray, depthStencilTexture) {
  16735. if (isPartOfTextureArray === void 0) { isPartOfTextureArray = false; }
  16736. if (depthStencilTexture === void 0) { depthStencilTexture = false; }
  16737. // Not ready?
  16738. if (!texture) {
  16739. if (this._boundTexturesCache[channel] != null) {
  16740. this._activeChannel = channel;
  16741. this._bindTextureDirectly(this._gl.TEXTURE_2D, null);
  16742. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, null);
  16743. if (this.webGLVersion > 1) {
  16744. this._bindTextureDirectly(this._gl.TEXTURE_3D, null);
  16745. }
  16746. }
  16747. return false;
  16748. }
  16749. // Video
  16750. if (texture.video) {
  16751. this._activeChannel = channel;
  16752. texture.update();
  16753. }
  16754. else if (texture.delayLoadState === Engine.DELAYLOADSTATE_NOTLOADED) { // Delay loading
  16755. texture.delayLoad();
  16756. return false;
  16757. }
  16758. var internalTexture;
  16759. if (depthStencilTexture) {
  16760. internalTexture = texture.depthStencilTexture;
  16761. }
  16762. else if (texture.isReady()) {
  16763. internalTexture = texture.getInternalTexture();
  16764. }
  16765. else if (texture.isCube) {
  16766. internalTexture = this.emptyCubeTexture;
  16767. }
  16768. else if (texture.is3D) {
  16769. internalTexture = this.emptyTexture3D;
  16770. }
  16771. else {
  16772. internalTexture = this.emptyTexture;
  16773. }
  16774. if (!isPartOfTextureArray) {
  16775. channel = this._getCorrectTextureChannel(channel, internalTexture);
  16776. }
  16777. var needToBind = true;
  16778. if (this._boundTexturesCache[channel] === internalTexture) {
  16779. this._moveBoundTextureOnTop(internalTexture);
  16780. if (!isPartOfTextureArray) {
  16781. this._bindSamplerUniformToChannel(internalTexture._initialSlot, channel);
  16782. }
  16783. needToBind = false;
  16784. }
  16785. this._activeChannel = channel;
  16786. if (internalTexture && internalTexture.is3D) {
  16787. if (needToBind) {
  16788. this._bindTextureDirectly(this._gl.TEXTURE_3D, internalTexture, isPartOfTextureArray);
  16789. }
  16790. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16791. internalTexture._cachedWrapU = texture.wrapU;
  16792. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16793. }
  16794. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16795. internalTexture._cachedWrapV = texture.wrapV;
  16796. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16797. }
  16798. if (internalTexture && internalTexture._cachedWrapR !== texture.wrapR) {
  16799. internalTexture._cachedWrapR = texture.wrapR;
  16800. this._setTextureParameterInteger(this._gl.TEXTURE_3D, this._gl.TEXTURE_WRAP_R, this._getTextureWrapMode(texture.wrapR), internalTexture);
  16801. }
  16802. this._setAnisotropicLevel(this._gl.TEXTURE_3D, texture);
  16803. }
  16804. else if (internalTexture && internalTexture.isCube) {
  16805. if (needToBind) {
  16806. this._bindTextureDirectly(this._gl.TEXTURE_CUBE_MAP, internalTexture, isPartOfTextureArray);
  16807. }
  16808. if (internalTexture._cachedCoordinatesMode !== texture.coordinatesMode) {
  16809. internalTexture._cachedCoordinatesMode = texture.coordinatesMode;
  16810. // CUBIC_MODE and SKYBOX_MODE both require CLAMP_TO_EDGE. All other modes use REPEAT.
  16811. var textureWrapMode = (texture.coordinatesMode !== BABYLON.Texture.CUBIC_MODE && texture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) ? this._gl.REPEAT : this._gl.CLAMP_TO_EDGE;
  16812. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_S, textureWrapMode, internalTexture);
  16813. this._setTextureParameterInteger(this._gl.TEXTURE_CUBE_MAP, this._gl.TEXTURE_WRAP_T, textureWrapMode);
  16814. }
  16815. this._setAnisotropicLevel(this._gl.TEXTURE_CUBE_MAP, texture);
  16816. }
  16817. else {
  16818. if (needToBind) {
  16819. this._bindTextureDirectly(this._gl.TEXTURE_2D, internalTexture, isPartOfTextureArray);
  16820. }
  16821. if (internalTexture && internalTexture._cachedWrapU !== texture.wrapU) {
  16822. internalTexture._cachedWrapU = texture.wrapU;
  16823. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_S, this._getTextureWrapMode(texture.wrapU), internalTexture);
  16824. }
  16825. if (internalTexture && internalTexture._cachedWrapV !== texture.wrapV) {
  16826. internalTexture._cachedWrapV = texture.wrapV;
  16827. this._setTextureParameterInteger(this._gl.TEXTURE_2D, this._gl.TEXTURE_WRAP_T, this._getTextureWrapMode(texture.wrapV), internalTexture);
  16828. }
  16829. this._setAnisotropicLevel(this._gl.TEXTURE_2D, texture);
  16830. }
  16831. return true;
  16832. };
  16833. /**
  16834. * Sets an array of texture to the webGL context
  16835. * @param channel defines the channel where the texture array must be set
  16836. * @param uniform defines the associated uniform location
  16837. * @param textures defines the array of textures to bind
  16838. */
  16839. Engine.prototype.setTextureArray = function (channel, uniform, textures) {
  16840. if (channel < 0 || !uniform) {
  16841. return;
  16842. }
  16843. if (!this._textureUnits || this._textureUnits.length !== textures.length) {
  16844. this._textureUnits = new Int32Array(textures.length);
  16845. }
  16846. for (var i = 0; i < textures.length; i++) {
  16847. this._textureUnits[i] = this._getCorrectTextureChannel(channel + i, textures[i].getInternalTexture());
  16848. }
  16849. this._gl.uniform1iv(uniform, this._textureUnits);
  16850. for (var index = 0; index < textures.length; index++) {
  16851. this._setTexture(this._textureUnits[index], textures[index], true);
  16852. }
  16853. };
  16854. /** @hidden */
  16855. Engine.prototype._setAnisotropicLevel = function (target, texture) {
  16856. var internalTexture = texture.getInternalTexture();
  16857. if (!internalTexture) {
  16858. return;
  16859. }
  16860. var anisotropicFilterExtension = this._caps.textureAnisotropicFilterExtension;
  16861. var value = texture.anisotropicFilteringLevel;
  16862. if (internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST
  16863. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR
  16864. && internalTexture.samplingMode !== BABYLON.Texture.LINEAR_LINEAR) {
  16865. value = 1; // Forcing the anisotropic to 1 because else webgl will force filters to linear
  16866. }
  16867. if (anisotropicFilterExtension && internalTexture._cachedAnisotropicFilteringLevel !== value) {
  16868. this._setTextureParameterFloat(target, anisotropicFilterExtension.TEXTURE_MAX_ANISOTROPY_EXT, Math.min(value, this._caps.maxAnisotropy), internalTexture);
  16869. internalTexture._cachedAnisotropicFilteringLevel = value;
  16870. }
  16871. };
  16872. Engine.prototype._setTextureParameterFloat = function (target, parameter, value, texture) {
  16873. this._bindTextureDirectly(target, texture, true, true);
  16874. this._gl.texParameterf(target, parameter, value);
  16875. };
  16876. Engine.prototype._setTextureParameterInteger = function (target, parameter, value, texture) {
  16877. if (texture) {
  16878. this._bindTextureDirectly(target, texture, true, true);
  16879. }
  16880. this._gl.texParameteri(target, parameter, value);
  16881. };
  16882. /**
  16883. * Reads pixels from the current frame buffer. Please note that this function can be slow
  16884. * @param x defines the x coordinate of the rectangle where pixels must be read
  16885. * @param y defines the y coordinate of the rectangle where pixels must be read
  16886. * @param width defines the width of the rectangle where pixels must be read
  16887. * @param height defines the height of the rectangle where pixels must be read
  16888. * @returns a Uint8Array containing RGBA colors
  16889. */
  16890. Engine.prototype.readPixels = function (x, y, width, height) {
  16891. var data = new Uint8Array(height * width * 4);
  16892. this._gl.readPixels(x, y, width, height, this._gl.RGBA, this._gl.UNSIGNED_BYTE, data);
  16893. return data;
  16894. };
  16895. /**
  16896. * Add an externaly attached data from its key.
  16897. * This method call will fail and return false, if such key already exists.
  16898. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  16899. * @param key the unique key that identifies the data
  16900. * @param data the data object to associate to the key for this Engine instance
  16901. * @return true if no such key were already present and the data was added successfully, false otherwise
  16902. */
  16903. Engine.prototype.addExternalData = function (key, data) {
  16904. if (!this._externalData) {
  16905. this._externalData = new BABYLON.StringDictionary();
  16906. }
  16907. return this._externalData.add(key, data);
  16908. };
  16909. /**
  16910. * Get an externaly attached data from its key
  16911. * @param key the unique key that identifies the data
  16912. * @return the associated data, if present (can be null), or undefined if not present
  16913. */
  16914. Engine.prototype.getExternalData = function (key) {
  16915. if (!this._externalData) {
  16916. this._externalData = new BABYLON.StringDictionary();
  16917. }
  16918. return this._externalData.get(key);
  16919. };
  16920. /**
  16921. * Get an externaly attached data from its key, create it using a factory if it's not already present
  16922. * @param key the unique key that identifies the data
  16923. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  16924. * @return the associated data, can be null if the factory returned null.
  16925. */
  16926. Engine.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  16927. if (!this._externalData) {
  16928. this._externalData = new BABYLON.StringDictionary();
  16929. }
  16930. return this._externalData.getOrAddWithFactory(key, factory);
  16931. };
  16932. /**
  16933. * Remove an externaly attached data from the Engine instance
  16934. * @param key the unique key that identifies the data
  16935. * @return true if the data was successfully removed, false if it doesn't exist
  16936. */
  16937. Engine.prototype.removeExternalData = function (key) {
  16938. if (!this._externalData) {
  16939. this._externalData = new BABYLON.StringDictionary();
  16940. }
  16941. return this._externalData.remove(key);
  16942. };
  16943. /**
  16944. * Unbind all vertex attributes from the webGL context
  16945. */
  16946. Engine.prototype.unbindAllAttributes = function () {
  16947. if (this._mustWipeVertexAttributes) {
  16948. this._mustWipeVertexAttributes = false;
  16949. for (var i = 0; i < this._caps.maxVertexAttribs; i++) {
  16950. this._gl.disableVertexAttribArray(i);
  16951. this._vertexAttribArraysEnabled[i] = false;
  16952. this._currentBufferPointers[i].active = false;
  16953. }
  16954. return;
  16955. }
  16956. for (var i = 0, ul = this._vertexAttribArraysEnabled.length; i < ul; i++) {
  16957. if (i >= this._caps.maxVertexAttribs || !this._vertexAttribArraysEnabled[i]) {
  16958. continue;
  16959. }
  16960. this._gl.disableVertexAttribArray(i);
  16961. this._vertexAttribArraysEnabled[i] = false;
  16962. this._currentBufferPointers[i].active = false;
  16963. }
  16964. };
  16965. /**
  16966. * 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
  16967. */
  16968. Engine.prototype.releaseEffects = function () {
  16969. for (var name in this._compiledEffects) {
  16970. this._deleteProgram(this._compiledEffects[name]._program);
  16971. }
  16972. this._compiledEffects = {};
  16973. };
  16974. /**
  16975. * Dispose and release all associated resources
  16976. */
  16977. Engine.prototype.dispose = function () {
  16978. this.hideLoadingUI();
  16979. this.stopRenderLoop();
  16980. // Release postProcesses
  16981. while (this.postProcesses.length) {
  16982. this.postProcesses[0].dispose();
  16983. }
  16984. // Empty texture
  16985. if (this._emptyTexture) {
  16986. this._releaseTexture(this._emptyTexture);
  16987. this._emptyTexture = null;
  16988. }
  16989. if (this._emptyCubeTexture) {
  16990. this._releaseTexture(this._emptyCubeTexture);
  16991. this._emptyCubeTexture = null;
  16992. }
  16993. // Rescale PP
  16994. if (this._rescalePostProcess) {
  16995. this._rescalePostProcess.dispose();
  16996. }
  16997. // Release scenes
  16998. while (this.scenes.length) {
  16999. this.scenes[0].dispose();
  17000. }
  17001. // Release audio engine
  17002. if (Engine.audioEngine) {
  17003. Engine.audioEngine.dispose();
  17004. }
  17005. // Release effects
  17006. this.releaseEffects();
  17007. // Unbind
  17008. this.unbindAllAttributes();
  17009. this._boundUniforms = [];
  17010. if (this._dummyFramebuffer) {
  17011. this._gl.deleteFramebuffer(this._dummyFramebuffer);
  17012. }
  17013. //WebVR
  17014. this.disableVR();
  17015. // Events
  17016. if (BABYLON.Tools.IsWindowObjectExist()) {
  17017. window.removeEventListener("blur", this._onBlur);
  17018. window.removeEventListener("focus", this._onFocus);
  17019. window.removeEventListener('vrdisplaypointerrestricted', this._onVRDisplayPointerRestricted);
  17020. window.removeEventListener('vrdisplaypointerunrestricted', this._onVRDisplayPointerUnrestricted);
  17021. if (this._renderingCanvas) {
  17022. this._renderingCanvas.removeEventListener("focus", this._onCanvasFocus);
  17023. this._renderingCanvas.removeEventListener("blur", this._onCanvasBlur);
  17024. this._renderingCanvas.removeEventListener("pointerout", this._onCanvasPointerOut);
  17025. if (!this._doNotHandleContextLost) {
  17026. this._renderingCanvas.removeEventListener("webglcontextlost", this._onContextLost);
  17027. this._renderingCanvas.removeEventListener("webglcontextrestored", this._onContextRestored);
  17028. }
  17029. }
  17030. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  17031. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  17032. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  17033. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  17034. document.removeEventListener("pointerlockchange", this._onPointerLockChange);
  17035. document.removeEventListener("mspointerlockchange", this._onPointerLockChange);
  17036. document.removeEventListener("mozpointerlockchange", this._onPointerLockChange);
  17037. document.removeEventListener("webkitpointerlockchange", this._onPointerLockChange);
  17038. if (this._onVrDisplayConnect) {
  17039. window.removeEventListener('vrdisplayconnect', this._onVrDisplayConnect);
  17040. if (this._onVrDisplayDisconnect) {
  17041. window.removeEventListener('vrdisplaydisconnect', this._onVrDisplayDisconnect);
  17042. }
  17043. if (this._onVrDisplayPresentChange) {
  17044. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  17045. }
  17046. this._onVrDisplayConnect = null;
  17047. this._onVrDisplayDisconnect = null;
  17048. }
  17049. }
  17050. // Remove from Instances
  17051. var index = Engine.Instances.indexOf(this);
  17052. if (index >= 0) {
  17053. Engine.Instances.splice(index, 1);
  17054. }
  17055. this._workingCanvas = null;
  17056. this._workingContext = null;
  17057. this._currentBufferPointers = [];
  17058. this._renderingCanvas = null;
  17059. this._currentProgram = null;
  17060. this._bindedRenderFunction = null;
  17061. this.onResizeObservable.clear();
  17062. this.onCanvasBlurObservable.clear();
  17063. this.onCanvasFocusObservable.clear();
  17064. this.onCanvasPointerOutObservable.clear();
  17065. this.onBeginFrameObservable.clear();
  17066. this.onEndFrameObservable.clear();
  17067. BABYLON.Effect.ResetCache();
  17068. // Abort active requests
  17069. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  17070. var request = _a[_i];
  17071. request.abort();
  17072. }
  17073. };
  17074. // Loading screen
  17075. /**
  17076. * Display the loading screen
  17077. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17078. */
  17079. Engine.prototype.displayLoadingUI = function () {
  17080. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17081. return;
  17082. }
  17083. var loadingScreen = this.loadingScreen;
  17084. if (loadingScreen) {
  17085. loadingScreen.displayLoadingUI();
  17086. }
  17087. };
  17088. /**
  17089. * Hide the loading screen
  17090. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17091. */
  17092. Engine.prototype.hideLoadingUI = function () {
  17093. if (!BABYLON.Tools.IsWindowObjectExist()) {
  17094. return;
  17095. }
  17096. var loadingScreen = this.loadingScreen;
  17097. if (loadingScreen) {
  17098. loadingScreen.hideLoadingUI();
  17099. }
  17100. };
  17101. Object.defineProperty(Engine.prototype, "loadingScreen", {
  17102. /**
  17103. * Gets the current loading screen object
  17104. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17105. */
  17106. get: function () {
  17107. if (!this._loadingScreen && BABYLON.DefaultLoadingScreen && this._renderingCanvas)
  17108. this._loadingScreen = new BABYLON.DefaultLoadingScreen(this._renderingCanvas);
  17109. return this._loadingScreen;
  17110. },
  17111. /**
  17112. * Sets the current loading screen object
  17113. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17114. */
  17115. set: function (loadingScreen) {
  17116. this._loadingScreen = loadingScreen;
  17117. },
  17118. enumerable: true,
  17119. configurable: true
  17120. });
  17121. Object.defineProperty(Engine.prototype, "loadingUIText", {
  17122. /**
  17123. * Sets the current loading screen text
  17124. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17125. */
  17126. set: function (text) {
  17127. this.loadingScreen.loadingUIText = text;
  17128. },
  17129. enumerable: true,
  17130. configurable: true
  17131. });
  17132. Object.defineProperty(Engine.prototype, "loadingUIBackgroundColor", {
  17133. /**
  17134. * Sets the current loading screen background color
  17135. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  17136. */
  17137. set: function (color) {
  17138. this.loadingScreen.loadingUIBackgroundColor = color;
  17139. },
  17140. enumerable: true,
  17141. configurable: true
  17142. });
  17143. /**
  17144. * Attach a new callback raised when context lost event is fired
  17145. * @param callback defines the callback to call
  17146. */
  17147. Engine.prototype.attachContextLostEvent = function (callback) {
  17148. if (this._renderingCanvas) {
  17149. this._renderingCanvas.addEventListener("webglcontextlost", callback, false);
  17150. }
  17151. };
  17152. /**
  17153. * Attach a new callback raised when context restored event is fired
  17154. * @param callback defines the callback to call
  17155. */
  17156. Engine.prototype.attachContextRestoredEvent = function (callback) {
  17157. if (this._renderingCanvas) {
  17158. this._renderingCanvas.addEventListener("webglcontextrestored", callback, false);
  17159. }
  17160. };
  17161. /**
  17162. * Gets the source code of the vertex shader associated with a specific webGL program
  17163. * @param program defines the program to use
  17164. * @returns a string containing the source code of the vertex shader associated with the program
  17165. */
  17166. Engine.prototype.getVertexShaderSource = function (program) {
  17167. var shaders = this._gl.getAttachedShaders(program);
  17168. if (!shaders) {
  17169. return null;
  17170. }
  17171. return this._gl.getShaderSource(shaders[0]);
  17172. };
  17173. /**
  17174. * Gets the source code of the fragment shader associated with a specific webGL program
  17175. * @param program defines the program to use
  17176. * @returns a string containing the source code of the fragment shader associated with the program
  17177. */
  17178. Engine.prototype.getFragmentShaderSource = function (program) {
  17179. var shaders = this._gl.getAttachedShaders(program);
  17180. if (!shaders) {
  17181. return null;
  17182. }
  17183. return this._gl.getShaderSource(shaders[1]);
  17184. };
  17185. /**
  17186. * Get the current error code of the webGL context
  17187. * @returns the error code
  17188. * @see https://developer.mozilla.org/en-US/docs/Web/API/WebGLRenderingContext/getError
  17189. */
  17190. Engine.prototype.getError = function () {
  17191. return this._gl.getError();
  17192. };
  17193. // FPS
  17194. /**
  17195. * Gets the current framerate
  17196. * @returns a number representing the framerate
  17197. */
  17198. Engine.prototype.getFps = function () {
  17199. return this._fps;
  17200. };
  17201. /**
  17202. * Gets the time spent between current and previous frame
  17203. * @returns a number representing the delta time in ms
  17204. */
  17205. Engine.prototype.getDeltaTime = function () {
  17206. return this._deltaTime;
  17207. };
  17208. Engine.prototype._measureFps = function () {
  17209. this._performanceMonitor.sampleFrame();
  17210. this._fps = this._performanceMonitor.averageFPS;
  17211. this._deltaTime = this._performanceMonitor.instantaneousFrameTime || 0;
  17212. };
  17213. /** @hidden */
  17214. Engine.prototype._readTexturePixels = function (texture, width, height, faceIndex, level) {
  17215. if (faceIndex === void 0) { faceIndex = -1; }
  17216. if (level === void 0) { level = 0; }
  17217. var gl = this._gl;
  17218. if (!this._dummyFramebuffer) {
  17219. var dummy = gl.createFramebuffer();
  17220. if (!dummy) {
  17221. throw new Error("Unable to create dummy framebuffer");
  17222. }
  17223. this._dummyFramebuffer = dummy;
  17224. }
  17225. gl.bindFramebuffer(gl.FRAMEBUFFER, this._dummyFramebuffer);
  17226. if (faceIndex > -1) {
  17227. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_CUBE_MAP_POSITIVE_X + faceIndex, texture._webGLTexture, level);
  17228. }
  17229. else {
  17230. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture._webGLTexture, level);
  17231. }
  17232. var readType = (texture.type !== undefined) ? this._getWebGLTextureType(texture.type) : gl.UNSIGNED_BYTE;
  17233. var buffer;
  17234. switch (readType) {
  17235. case gl.UNSIGNED_BYTE:
  17236. buffer = new Uint8Array(4 * width * height);
  17237. readType = gl.UNSIGNED_BYTE;
  17238. break;
  17239. default:
  17240. buffer = new Float32Array(4 * width * height);
  17241. readType = gl.FLOAT;
  17242. break;
  17243. }
  17244. gl.readPixels(0, 0, width, height, gl.RGBA, readType, buffer);
  17245. gl.bindFramebuffer(gl.FRAMEBUFFER, this._currentFramebuffer);
  17246. return buffer;
  17247. };
  17248. Engine.prototype._canRenderToFloatFramebuffer = function () {
  17249. if (this._webGLVersion > 1) {
  17250. return this._caps.colorBufferFloat;
  17251. }
  17252. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_FLOAT);
  17253. };
  17254. Engine.prototype._canRenderToHalfFloatFramebuffer = function () {
  17255. if (this._webGLVersion > 1) {
  17256. return this._caps.colorBufferFloat;
  17257. }
  17258. return this._canRenderToFramebuffer(Engine.TEXTURETYPE_HALF_FLOAT);
  17259. };
  17260. // Thank you : http://stackoverflow.com/questions/28827511/webgl-ios-render-to-floating-point-texture
  17261. Engine.prototype._canRenderToFramebuffer = function (type) {
  17262. var gl = this._gl;
  17263. //clear existing errors
  17264. while (gl.getError() !== gl.NO_ERROR) { }
  17265. var successful = true;
  17266. var texture = gl.createTexture();
  17267. gl.bindTexture(gl.TEXTURE_2D, texture);
  17268. gl.texImage2D(gl.TEXTURE_2D, 0, this._getRGBABufferInternalSizedFormat(type), 1, 1, 0, gl.RGBA, this._getWebGLTextureType(type), null);
  17269. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST);
  17270. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST);
  17271. var fb = gl.createFramebuffer();
  17272. gl.bindFramebuffer(gl.FRAMEBUFFER, fb);
  17273. gl.framebufferTexture2D(gl.FRAMEBUFFER, gl.COLOR_ATTACHMENT0, gl.TEXTURE_2D, texture, 0);
  17274. var status = gl.checkFramebufferStatus(gl.FRAMEBUFFER);
  17275. successful = successful && (status === gl.FRAMEBUFFER_COMPLETE);
  17276. successful = successful && (gl.getError() === gl.NO_ERROR);
  17277. //try render by clearing frame buffer's color buffer
  17278. if (successful) {
  17279. gl.clear(gl.COLOR_BUFFER_BIT);
  17280. successful = successful && (gl.getError() === gl.NO_ERROR);
  17281. }
  17282. //try reading from frame to ensure render occurs (just creating the FBO is not sufficient to determine if rendering is supported)
  17283. if (successful) {
  17284. //in practice it's sufficient to just read from the backbuffer rather than handle potentially issues reading from the texture
  17285. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17286. var readFormat = gl.RGBA;
  17287. var readType = gl.UNSIGNED_BYTE;
  17288. var buffer = new Uint8Array(4);
  17289. gl.readPixels(0, 0, 1, 1, readFormat, readType, buffer);
  17290. successful = successful && (gl.getError() === gl.NO_ERROR);
  17291. }
  17292. //clean up
  17293. gl.deleteTexture(texture);
  17294. gl.deleteFramebuffer(fb);
  17295. gl.bindFramebuffer(gl.FRAMEBUFFER, null);
  17296. //clear accumulated errors
  17297. while (!successful && (gl.getError() !== gl.NO_ERROR)) { }
  17298. return successful;
  17299. };
  17300. /** @hidden */
  17301. Engine.prototype._getWebGLTextureType = function (type) {
  17302. if (type === Engine.TEXTURETYPE_FLOAT) {
  17303. return this._gl.FLOAT;
  17304. }
  17305. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17306. // Add Half Float Constant.
  17307. return this._gl.HALF_FLOAT_OES;
  17308. }
  17309. return this._gl.UNSIGNED_BYTE;
  17310. };
  17311. ;
  17312. Engine.prototype._getInternalFormat = function (format) {
  17313. var internalFormat = this._gl.RGBA;
  17314. switch (format) {
  17315. case Engine.TEXTUREFORMAT_ALPHA:
  17316. internalFormat = this._gl.ALPHA;
  17317. break;
  17318. case Engine.TEXTUREFORMAT_LUMINANCE:
  17319. internalFormat = this._gl.LUMINANCE;
  17320. break;
  17321. case Engine.TEXTUREFORMAT_LUMINANCE_ALPHA:
  17322. internalFormat = this._gl.LUMINANCE_ALPHA;
  17323. break;
  17324. case Engine.TEXTUREFORMAT_RGB:
  17325. internalFormat = this._gl.RGB;
  17326. break;
  17327. case Engine.TEXTUREFORMAT_RGBA:
  17328. internalFormat = this._gl.RGBA;
  17329. break;
  17330. case Engine.TEXTUREFORMAT_R:
  17331. internalFormat = this._gl.RED;
  17332. break;
  17333. case Engine.TEXTUREFORMAT_RG:
  17334. internalFormat = this._gl.RG;
  17335. break;
  17336. }
  17337. return internalFormat;
  17338. };
  17339. /** @hidden */
  17340. Engine.prototype._getRGBABufferInternalSizedFormat = function (type, format) {
  17341. if (this._webGLVersion === 1) {
  17342. if (format !== undefined) {
  17343. switch (format) {
  17344. case Engine.TEXTUREFORMAT_LUMINANCE:
  17345. return this._gl.LUMINANCE;
  17346. case Engine.TEXTUREFORMAT_ALPHA:
  17347. return this._gl.ALPHA;
  17348. }
  17349. }
  17350. return this._gl.RGBA;
  17351. }
  17352. if (type === Engine.TEXTURETYPE_FLOAT) {
  17353. if (format !== undefined) {
  17354. switch (format) {
  17355. case Engine.TEXTUREFORMAT_R:
  17356. return this._gl.R32F;
  17357. case Engine.TEXTUREFORMAT_RG:
  17358. return this._gl.RG32F;
  17359. case Engine.TEXTUREFORMAT_RGB:
  17360. return this._gl.RGB32F;
  17361. }
  17362. }
  17363. return this._gl.RGBA32F;
  17364. }
  17365. if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17366. if (format) {
  17367. switch (format) {
  17368. case Engine.TEXTUREFORMAT_R:
  17369. return this._gl.R16F;
  17370. case Engine.TEXTUREFORMAT_RG:
  17371. return this._gl.RG16F;
  17372. case Engine.TEXTUREFORMAT_RGB:
  17373. return this._gl.RGB16F;
  17374. }
  17375. }
  17376. return this._gl.RGBA16F;
  17377. }
  17378. if (format !== undefined) {
  17379. switch (format) {
  17380. case Engine.TEXTUREFORMAT_LUMINANCE:
  17381. return this._gl.LUMINANCE;
  17382. case Engine.TEXTUREFORMAT_RGB:
  17383. return this._gl.RGB;
  17384. case Engine.TEXTUREFORMAT_R:
  17385. return this._gl.R8;
  17386. case Engine.TEXTUREFORMAT_RG:
  17387. return this._gl.RG8;
  17388. case Engine.TEXTUREFORMAT_ALPHA:
  17389. return this._gl.ALPHA;
  17390. }
  17391. }
  17392. return this._gl.RGBA;
  17393. };
  17394. ;
  17395. /** @hidden */
  17396. Engine.prototype._getRGBAMultiSampleBufferFormat = function (type) {
  17397. if (type === Engine.TEXTURETYPE_FLOAT) {
  17398. return this._gl.RGBA32F;
  17399. }
  17400. else if (type === Engine.TEXTURETYPE_HALF_FLOAT) {
  17401. return this._gl.RGBA16F;
  17402. }
  17403. return this._gl.RGBA8;
  17404. };
  17405. ;
  17406. /**
  17407. * Create a new webGL query (you must be sure that queries are supported by checking getCaps() function)
  17408. * @return the new query
  17409. */
  17410. Engine.prototype.createQuery = function () {
  17411. return this._gl.createQuery();
  17412. };
  17413. /**
  17414. * Delete and release a webGL query
  17415. * @param query defines the query to delete
  17416. * @return the current engine
  17417. */
  17418. Engine.prototype.deleteQuery = function (query) {
  17419. this._gl.deleteQuery(query);
  17420. return this;
  17421. };
  17422. /**
  17423. * Check if a given query has resolved and got its value
  17424. * @param query defines the query to check
  17425. * @returns true if the query got its value
  17426. */
  17427. Engine.prototype.isQueryResultAvailable = function (query) {
  17428. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT_AVAILABLE);
  17429. };
  17430. /**
  17431. * Gets the value of a given query
  17432. * @param query defines the query to check
  17433. * @returns the value of the query
  17434. */
  17435. Engine.prototype.getQueryResult = function (query) {
  17436. return this._gl.getQueryParameter(query, this._gl.QUERY_RESULT);
  17437. };
  17438. /**
  17439. * Initiates an occlusion query
  17440. * @param algorithmType defines the algorithm to use
  17441. * @param query defines the query to use
  17442. * @returns the current engine
  17443. * @see http://doc.babylonjs.com/features/occlusionquery
  17444. */
  17445. Engine.prototype.beginOcclusionQuery = function (algorithmType, query) {
  17446. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17447. this._gl.beginQuery(glAlgorithm, query);
  17448. return this;
  17449. };
  17450. /**
  17451. * Ends an occlusion query
  17452. * @see http://doc.babylonjs.com/features/occlusionquery
  17453. * @param algorithmType defines the algorithm to use
  17454. * @returns the current engine
  17455. */
  17456. Engine.prototype.endOcclusionQuery = function (algorithmType) {
  17457. var glAlgorithm = this.getGlAlgorithmType(algorithmType);
  17458. this._gl.endQuery(glAlgorithm);
  17459. return this;
  17460. };
  17461. /* Time queries */
  17462. Engine.prototype._createTimeQuery = function () {
  17463. var timerQuery = this._caps.timerQuery;
  17464. if (timerQuery.createQueryEXT) {
  17465. return timerQuery.createQueryEXT();
  17466. }
  17467. return this.createQuery();
  17468. };
  17469. Engine.prototype._deleteTimeQuery = function (query) {
  17470. var timerQuery = this._caps.timerQuery;
  17471. if (timerQuery.deleteQueryEXT) {
  17472. timerQuery.deleteQueryEXT(query);
  17473. return;
  17474. }
  17475. this.deleteQuery(query);
  17476. };
  17477. Engine.prototype._getTimeQueryResult = function (query) {
  17478. var timerQuery = this._caps.timerQuery;
  17479. if (timerQuery.getQueryObjectEXT) {
  17480. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_EXT);
  17481. }
  17482. return this.getQueryResult(query);
  17483. };
  17484. Engine.prototype._getTimeQueryAvailability = function (query) {
  17485. var timerQuery = this._caps.timerQuery;
  17486. if (timerQuery.getQueryObjectEXT) {
  17487. return timerQuery.getQueryObjectEXT(query, timerQuery.QUERY_RESULT_AVAILABLE_EXT);
  17488. }
  17489. return this.isQueryResultAvailable(query);
  17490. };
  17491. /**
  17492. * Starts a time query (used to measure time spent by the GPU on a specific frame)
  17493. * Please note that only one query can be issued at a time
  17494. * @returns a time token used to track the time span
  17495. */
  17496. Engine.prototype.startTimeQuery = function () {
  17497. var timerQuery = this._caps.timerQuery;
  17498. if (!timerQuery) {
  17499. return null;
  17500. }
  17501. var token = new BABYLON._TimeToken();
  17502. this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17503. if (this._caps.canUseTimestampForTimerQuery) {
  17504. token._startTimeQuery = this._createTimeQuery();
  17505. timerQuery.queryCounterEXT(token._startTimeQuery, timerQuery.TIMESTAMP_EXT);
  17506. }
  17507. else {
  17508. if (this._currentNonTimestampToken) {
  17509. return this._currentNonTimestampToken;
  17510. }
  17511. token._timeElapsedQuery = this._createTimeQuery();
  17512. if (timerQuery.beginQueryEXT) {
  17513. timerQuery.beginQueryEXT(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17514. }
  17515. else {
  17516. this._gl.beginQuery(timerQuery.TIME_ELAPSED_EXT, token._timeElapsedQuery);
  17517. }
  17518. this._currentNonTimestampToken = token;
  17519. }
  17520. return token;
  17521. };
  17522. /**
  17523. * Ends a time query
  17524. * @param token defines the token used to measure the time span
  17525. * @returns the time spent (in ns)
  17526. */
  17527. Engine.prototype.endTimeQuery = function (token) {
  17528. var timerQuery = this._caps.timerQuery;
  17529. if (!timerQuery || !token) {
  17530. return -1;
  17531. }
  17532. if (this._caps.canUseTimestampForTimerQuery) {
  17533. if (!token._startTimeQuery) {
  17534. return -1;
  17535. }
  17536. if (!token._endTimeQuery) {
  17537. token._endTimeQuery = this._createTimeQuery();
  17538. timerQuery.queryCounterEXT(token._endTimeQuery, timerQuery.TIMESTAMP_EXT);
  17539. }
  17540. }
  17541. else if (!token._timeElapsedQueryEnded) {
  17542. if (!token._timeElapsedQuery) {
  17543. return -1;
  17544. }
  17545. if (timerQuery.endQueryEXT) {
  17546. timerQuery.endQueryEXT(timerQuery.TIME_ELAPSED_EXT);
  17547. }
  17548. else {
  17549. this._gl.endQuery(timerQuery.TIME_ELAPSED_EXT);
  17550. }
  17551. token._timeElapsedQueryEnded = true;
  17552. }
  17553. var disjoint = this._gl.getParameter(timerQuery.GPU_DISJOINT_EXT);
  17554. var available = false;
  17555. if (token._endTimeQuery) {
  17556. available = this._getTimeQueryAvailability(token._endTimeQuery);
  17557. }
  17558. else if (token._timeElapsedQuery) {
  17559. available = this._getTimeQueryAvailability(token._timeElapsedQuery);
  17560. }
  17561. if (available && !disjoint) {
  17562. var result = 0;
  17563. if (this._caps.canUseTimestampForTimerQuery) {
  17564. if (!token._startTimeQuery || !token._endTimeQuery) {
  17565. return -1;
  17566. }
  17567. var timeStart = this._getTimeQueryResult(token._startTimeQuery);
  17568. var timeEnd = this._getTimeQueryResult(token._endTimeQuery);
  17569. result = timeEnd - timeStart;
  17570. this._deleteTimeQuery(token._startTimeQuery);
  17571. this._deleteTimeQuery(token._endTimeQuery);
  17572. token._startTimeQuery = null;
  17573. token._endTimeQuery = null;
  17574. }
  17575. else {
  17576. if (!token._timeElapsedQuery) {
  17577. return -1;
  17578. }
  17579. result = this._getTimeQueryResult(token._timeElapsedQuery);
  17580. this._deleteTimeQuery(token._timeElapsedQuery);
  17581. token._timeElapsedQuery = null;
  17582. token._timeElapsedQueryEnded = false;
  17583. this._currentNonTimestampToken = null;
  17584. }
  17585. return result;
  17586. }
  17587. return -1;
  17588. };
  17589. Engine.prototype.getGlAlgorithmType = function (algorithmType) {
  17590. return algorithmType === BABYLON.AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE ? this._gl.ANY_SAMPLES_PASSED_CONSERVATIVE : this._gl.ANY_SAMPLES_PASSED;
  17591. };
  17592. // Transform feedback
  17593. /**
  17594. * Creates a webGL transform feedback object
  17595. * Please makes sure to check webGLVersion property to check if you are running webGL 2+
  17596. * @returns the webGL transform feedback object
  17597. */
  17598. Engine.prototype.createTransformFeedback = function () {
  17599. return this._gl.createTransformFeedback();
  17600. };
  17601. /**
  17602. * Delete a webGL transform feedback object
  17603. * @param value defines the webGL transform feedback object to delete
  17604. */
  17605. Engine.prototype.deleteTransformFeedback = function (value) {
  17606. this._gl.deleteTransformFeedback(value);
  17607. };
  17608. /**
  17609. * Bind a webGL transform feedback object to the webgl context
  17610. * @param value defines the webGL transform feedback object to bind
  17611. */
  17612. Engine.prototype.bindTransformFeedback = function (value) {
  17613. this._gl.bindTransformFeedback(this._gl.TRANSFORM_FEEDBACK, value);
  17614. };
  17615. /**
  17616. * Begins a transform feedback operation
  17617. * @param usePoints defines if points or triangles must be used
  17618. */
  17619. Engine.prototype.beginTransformFeedback = function (usePoints) {
  17620. if (usePoints === void 0) { usePoints = true; }
  17621. this._gl.beginTransformFeedback(usePoints ? this._gl.POINTS : this._gl.TRIANGLES);
  17622. };
  17623. /**
  17624. * Ends a transform feedback operation
  17625. */
  17626. Engine.prototype.endTransformFeedback = function () {
  17627. this._gl.endTransformFeedback();
  17628. };
  17629. /**
  17630. * Specify the varyings to use with transform feedback
  17631. * @param program defines the associated webGL program
  17632. * @param value defines the list of strings representing the varying names
  17633. */
  17634. Engine.prototype.setTranformFeedbackVaryings = function (program, value) {
  17635. this._gl.transformFeedbackVaryings(program, value, this._gl.INTERLEAVED_ATTRIBS);
  17636. };
  17637. /**
  17638. * Bind a webGL buffer for a transform feedback operation
  17639. * @param value defines the webGL buffer to bind
  17640. */
  17641. Engine.prototype.bindTransformFeedbackBuffer = function (value) {
  17642. this._gl.bindBufferBase(this._gl.TRANSFORM_FEEDBACK_BUFFER, 0, value);
  17643. };
  17644. /** @hidden */
  17645. Engine.prototype._loadFile = function (url, onSuccess, onProgress, database, useArrayBuffer, onError) {
  17646. var _this = this;
  17647. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, database, useArrayBuffer, onError);
  17648. this._activeRequests.push(request);
  17649. request.onCompleteObservable.add(function (request) {
  17650. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  17651. });
  17652. return request;
  17653. };
  17654. /** @hidden */
  17655. Engine.prototype._loadFileAsync = function (url, database, useArrayBuffer) {
  17656. var _this = this;
  17657. return new Promise(function (resolve, reject) {
  17658. _this._loadFile(url, function (data) {
  17659. resolve(data);
  17660. }, undefined, database, useArrayBuffer, function (request, exception) {
  17661. reject(exception);
  17662. });
  17663. });
  17664. };
  17665. Engine.prototype._partialLoadFile = function (url, index, loadedFiles, scene, onfinish, onErrorCallBack) {
  17666. if (onErrorCallBack === void 0) { onErrorCallBack = null; }
  17667. var onload = function (data) {
  17668. loadedFiles[index] = data;
  17669. loadedFiles._internalCount++;
  17670. if (loadedFiles._internalCount === 6) {
  17671. onfinish(loadedFiles);
  17672. }
  17673. };
  17674. var onerror = function (request, exception) {
  17675. if (onErrorCallBack && request) {
  17676. onErrorCallBack(request.status + " " + request.statusText, exception);
  17677. }
  17678. };
  17679. this._loadFile(url, onload, undefined, undefined, true, onerror);
  17680. };
  17681. Engine.prototype._cascadeLoadFiles = function (scene, onfinish, files, onError) {
  17682. if (onError === void 0) { onError = null; }
  17683. var loadedFiles = [];
  17684. loadedFiles._internalCount = 0;
  17685. for (var index = 0; index < 6; index++) {
  17686. this._partialLoadFile(files[index], index, loadedFiles, scene, onfinish, onError);
  17687. }
  17688. };
  17689. // Statics
  17690. /**
  17691. * Gets a boolean indicating if the engine can be instanciated (ie. if a webGL context can be found)
  17692. * @returns true if the engine can be created
  17693. * @ignorenaming
  17694. */
  17695. Engine.isSupported = function () {
  17696. try {
  17697. var tempcanvas = document.createElement("canvas");
  17698. var gl = tempcanvas.getContext("webgl") || tempcanvas.getContext("experimental-webgl");
  17699. return gl != null && !!window.WebGLRenderingContext;
  17700. }
  17701. catch (e) {
  17702. return false;
  17703. }
  17704. };
  17705. /** Use this array to turn off some WebGL2 features on known buggy browsers version */
  17706. Engine.ExceptionList = [
  17707. { key: "Chrome/63.0", capture: "63\\.0\\.3239\\.(\\d+)", captureConstraint: 108, targets: ["uniformBuffer"] },
  17708. { key: "Firefox/58", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17709. { key: "Firefox/59", capture: null, captureConstraint: null, targets: ["uniformBuffer"] },
  17710. { key: "Macintosh", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17711. { key: "iPhone", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] },
  17712. { key: "iPad", capture: null, captureConstraint: null, targets: ["textureBindingOptimization"] }
  17713. ];
  17714. /** Gets the list of created engines */
  17715. Engine.Instances = new Array();
  17716. // Const statics
  17717. Engine._ALPHA_DISABLE = 0;
  17718. Engine._ALPHA_ADD = 1;
  17719. Engine._ALPHA_COMBINE = 2;
  17720. Engine._ALPHA_SUBTRACT = 3;
  17721. Engine._ALPHA_MULTIPLY = 4;
  17722. Engine._ALPHA_MAXIMIZED = 5;
  17723. Engine._ALPHA_ONEONE = 6;
  17724. Engine._ALPHA_PREMULTIPLIED = 7;
  17725. Engine._ALPHA_PREMULTIPLIED_PORTERDUFF = 8;
  17726. Engine._ALPHA_INTERPOLATE = 9;
  17727. Engine._ALPHA_SCREENMODE = 10;
  17728. Engine._DELAYLOADSTATE_NONE = 0;
  17729. Engine._DELAYLOADSTATE_LOADED = 1;
  17730. Engine._DELAYLOADSTATE_LOADING = 2;
  17731. Engine._DELAYLOADSTATE_NOTLOADED = 4;
  17732. Engine._TEXTUREFORMAT_ALPHA = 0;
  17733. Engine._TEXTUREFORMAT_LUMINANCE = 1;
  17734. Engine._TEXTUREFORMAT_LUMINANCE_ALPHA = 2;
  17735. Engine._TEXTUREFORMAT_RGB = 4;
  17736. Engine._TEXTUREFORMAT_RGBA = 5;
  17737. Engine._TEXTUREFORMAT_R = 6;
  17738. Engine._TEXTUREFORMAT_RG = 7;
  17739. Engine._TEXTURETYPE_UNSIGNED_INT = 0;
  17740. Engine._TEXTURETYPE_FLOAT = 1;
  17741. Engine._TEXTURETYPE_HALF_FLOAT = 2;
  17742. // Depht or Stencil test Constants.
  17743. Engine._NEVER = 0x0200; // Passed to depthFunction or stencilFunction to specify depth or stencil tests will never pass. i.e. Nothing will be drawn.
  17744. 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.
  17745. 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.
  17746. 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.
  17747. 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.
  17748. 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.
  17749. 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.
  17750. 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.
  17751. // Stencil Actions Constants.
  17752. Engine._KEEP = 0x1E00;
  17753. Engine._REPLACE = 0x1E01;
  17754. Engine._INCR = 0x1E02;
  17755. Engine._DECR = 0x1E03;
  17756. Engine._INVERT = 0x150A;
  17757. Engine._INCR_WRAP = 0x8507;
  17758. Engine._DECR_WRAP = 0x8508;
  17759. // Texture rescaling mode
  17760. Engine._SCALEMODE_FLOOR = 1;
  17761. Engine._SCALEMODE_NEAREST = 2;
  17762. Engine._SCALEMODE_CEILING = 3;
  17763. // Updatable statics so stick with vars here
  17764. /**
  17765. * Gets or sets the epsilon value used by collision engine
  17766. */
  17767. Engine.CollisionsEpsilon = 0.001;
  17768. /**
  17769. * Gets or sets the relative url used to load code if using the engine in non-minified mode
  17770. */
  17771. Engine.CodeRepository = "src/";
  17772. /**
  17773. * Gets or sets the relative url used to load shaders if using the engine in non-minified mode
  17774. */
  17775. Engine.ShadersRepository = "src/Shaders/";
  17776. return Engine;
  17777. }());
  17778. BABYLON.Engine = Engine;
  17779. })(BABYLON || (BABYLON = {}));
  17780. //# sourceMappingURL=babylon.engine.js.map
  17781. var BABYLON;
  17782. (function (BABYLON) {
  17783. /**
  17784. * Node is the basic class for all scene objects (Mesh, Light Camera).
  17785. */
  17786. var Node = /** @class */ (function () {
  17787. /**
  17788. * Creates a new Node
  17789. * @param {string} name - the name and id to be given to this node
  17790. * @param {BABYLON.Scene} the scene this node will be added to
  17791. */
  17792. function Node(name, scene) {
  17793. if (scene === void 0) { scene = null; }
  17794. /**
  17795. * Gets or sets a string used to store user defined state for the node
  17796. */
  17797. this.state = "";
  17798. /**
  17799. * Gets or sets an object used to store user defined information for the node
  17800. */
  17801. this.metadata = null;
  17802. /**
  17803. * Gets or sets a boolean used to define if the node must be serialized
  17804. */
  17805. this.doNotSerialize = false;
  17806. /** @hidden */
  17807. this._isDisposed = false;
  17808. /**
  17809. * Gets a list of Animations associated with the node
  17810. */
  17811. this.animations = new Array();
  17812. this._ranges = {};
  17813. this._isEnabled = true;
  17814. this._isReady = true;
  17815. /** @hidden */
  17816. this._currentRenderId = -1;
  17817. this._parentRenderId = -1;
  17818. this._childRenderId = -1;
  17819. this._animationPropertiesOverride = null;
  17820. /**
  17821. * An event triggered when the mesh is disposed
  17822. */
  17823. this.onDisposeObservable = new BABYLON.Observable();
  17824. // Behaviors
  17825. this._behaviors = new Array();
  17826. this.name = name;
  17827. this.id = name;
  17828. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  17829. this.uniqueId = this._scene.getUniqueId();
  17830. this._initCache();
  17831. }
  17832. /**
  17833. * Gets a boolean indicating if the node has been disposed
  17834. * @returns true if the node was disposed
  17835. */
  17836. Node.prototype.isDisposed = function () {
  17837. return this._isDisposed;
  17838. };
  17839. Object.defineProperty(Node.prototype, "parent", {
  17840. get: function () {
  17841. return this._parentNode;
  17842. },
  17843. /**
  17844. * Gets or sets the parent of the node
  17845. */
  17846. set: function (parent) {
  17847. if (this._parentNode === parent) {
  17848. return;
  17849. }
  17850. // Remove self from list of children of parent
  17851. if (this._parentNode && this._parentNode._children !== undefined && this._parentNode._children !== null) {
  17852. var index = this._parentNode._children.indexOf(this);
  17853. if (index !== -1) {
  17854. this._parentNode._children.splice(index, 1);
  17855. }
  17856. }
  17857. // Store new parent
  17858. this._parentNode = parent;
  17859. // Add as child to new parent
  17860. if (this._parentNode) {
  17861. if (this._parentNode._children === undefined || this._parentNode._children === null) {
  17862. this._parentNode._children = new Array();
  17863. }
  17864. this._parentNode._children.push(this);
  17865. }
  17866. },
  17867. enumerable: true,
  17868. configurable: true
  17869. });
  17870. Object.defineProperty(Node.prototype, "animationPropertiesOverride", {
  17871. /**
  17872. * Gets or sets the animation properties override
  17873. */
  17874. get: function () {
  17875. if (!this._animationPropertiesOverride) {
  17876. return this._scene.animationPropertiesOverride;
  17877. }
  17878. return this._animationPropertiesOverride;
  17879. },
  17880. set: function (value) {
  17881. this._animationPropertiesOverride = value;
  17882. },
  17883. enumerable: true,
  17884. configurable: true
  17885. });
  17886. /**
  17887. * Gets a string idenfifying the name of the class
  17888. * @returns "Node" string
  17889. */
  17890. Node.prototype.getClassName = function () {
  17891. return "Node";
  17892. };
  17893. Object.defineProperty(Node.prototype, "onDispose", {
  17894. /**
  17895. * Sets a callback that will be raised when the node will be disposed
  17896. */
  17897. set: function (callback) {
  17898. if (this._onDisposeObserver) {
  17899. this.onDisposeObservable.remove(this._onDisposeObserver);
  17900. }
  17901. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  17902. },
  17903. enumerable: true,
  17904. configurable: true
  17905. });
  17906. /**
  17907. * Gets the scene of the node
  17908. * @returns a {BABYLON.Scene}
  17909. */
  17910. Node.prototype.getScene = function () {
  17911. return this._scene;
  17912. };
  17913. /**
  17914. * Gets the engine of the node
  17915. * @returns a {BABYLON.Engine}
  17916. */
  17917. Node.prototype.getEngine = function () {
  17918. return this._scene.getEngine();
  17919. };
  17920. /**
  17921. * Attach a behavior to the node
  17922. * @see http://doc.babylonjs.com/features/behaviour
  17923. * @param behavior defines the behavior to attach
  17924. * @returns the current Node
  17925. */
  17926. Node.prototype.addBehavior = function (behavior) {
  17927. var _this = this;
  17928. var index = this._behaviors.indexOf(behavior);
  17929. if (index !== -1) {
  17930. return this;
  17931. }
  17932. behavior.init();
  17933. if (this._scene.isLoading) {
  17934. // We defer the attach when the scene will be loaded
  17935. this._scene.onDataLoadedObservable.addOnce(function () {
  17936. behavior.attach(_this);
  17937. });
  17938. }
  17939. else {
  17940. behavior.attach(this);
  17941. }
  17942. this._behaviors.push(behavior);
  17943. return this;
  17944. };
  17945. /**
  17946. * Remove an attached behavior
  17947. * @see http://doc.babylonjs.com/features/behaviour
  17948. * @param behavior defines the behavior to attach
  17949. * @returns the current Node
  17950. */
  17951. Node.prototype.removeBehavior = function (behavior) {
  17952. var index = this._behaviors.indexOf(behavior);
  17953. if (index === -1) {
  17954. return this;
  17955. }
  17956. this._behaviors[index].detach();
  17957. this._behaviors.splice(index, 1);
  17958. return this;
  17959. };
  17960. Object.defineProperty(Node.prototype, "behaviors", {
  17961. /**
  17962. * Gets the list of attached behaviors
  17963. * @see http://doc.babylonjs.com/features/behaviour
  17964. */
  17965. get: function () {
  17966. return this._behaviors;
  17967. },
  17968. enumerable: true,
  17969. configurable: true
  17970. });
  17971. /**
  17972. * Gets an attached behavior by name
  17973. * @param name defines the name of the behavior to look for
  17974. * @see http://doc.babylonjs.com/features/behaviour
  17975. * @returns null if behavior was not found else the requested behavior
  17976. */
  17977. Node.prototype.getBehaviorByName = function (name) {
  17978. for (var _i = 0, _a = this._behaviors; _i < _a.length; _i++) {
  17979. var behavior = _a[_i];
  17980. if (behavior.name === name) {
  17981. return behavior;
  17982. }
  17983. }
  17984. return null;
  17985. };
  17986. /**
  17987. * Returns the world matrix of the node
  17988. * @returns a matrix containing the node's world matrix
  17989. */
  17990. Node.prototype.getWorldMatrix = function () {
  17991. return BABYLON.Matrix.Identity();
  17992. };
  17993. /** @hidden */
  17994. Node.prototype._getWorldMatrixDeterminant = function () {
  17995. return 1;
  17996. };
  17997. // override it in derived class if you add new variables to the cache
  17998. // and call the parent class method
  17999. /** @hidden */
  18000. Node.prototype._initCache = function () {
  18001. this._cache = {};
  18002. this._cache.parent = undefined;
  18003. };
  18004. /** @hidden */
  18005. Node.prototype.updateCache = function (force) {
  18006. if (!force && this.isSynchronized())
  18007. return;
  18008. this._cache.parent = this.parent;
  18009. this._updateCache();
  18010. };
  18011. // override it in derived class if you add new variables to the cache
  18012. // and call the parent class method if !ignoreParentClass
  18013. /** @hidden */
  18014. Node.prototype._updateCache = function (ignoreParentClass) {
  18015. };
  18016. // override it in derived class if you add new variables to the cache
  18017. /** @hidden */
  18018. Node.prototype._isSynchronized = function () {
  18019. return true;
  18020. };
  18021. /** @hidden */
  18022. Node.prototype._markSyncedWithParent = function () {
  18023. if (this.parent) {
  18024. this._parentRenderId = this.parent._childRenderId;
  18025. }
  18026. };
  18027. /** @hidden */
  18028. Node.prototype.isSynchronizedWithParent = function () {
  18029. if (!this.parent) {
  18030. return true;
  18031. }
  18032. if (this._parentRenderId !== this.parent._childRenderId) {
  18033. return false;
  18034. }
  18035. return this.parent.isSynchronized();
  18036. };
  18037. /** @hidden */
  18038. Node.prototype.isSynchronized = function (updateCache) {
  18039. var check = this.hasNewParent();
  18040. check = check || !this.isSynchronizedWithParent();
  18041. check = check || !this._isSynchronized();
  18042. if (updateCache)
  18043. this.updateCache(true);
  18044. return !check;
  18045. };
  18046. /** @hidden */
  18047. Node.prototype.hasNewParent = function (update) {
  18048. if (this._cache.parent === this.parent)
  18049. return false;
  18050. if (update)
  18051. this._cache.parent = this.parent;
  18052. return true;
  18053. };
  18054. /**
  18055. * Is this node ready to be used/rendered
  18056. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  18057. * @return true if the node is ready
  18058. */
  18059. Node.prototype.isReady = function (completeCheck) {
  18060. if (completeCheck === void 0) { completeCheck = false; }
  18061. return this._isReady;
  18062. };
  18063. /**
  18064. * Is this node enabled?
  18065. * 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
  18066. * @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
  18067. * @return whether this node (and its parent) is enabled
  18068. */
  18069. Node.prototype.isEnabled = function (checkAncestors) {
  18070. if (checkAncestors === void 0) { checkAncestors = true; }
  18071. if (checkAncestors === false) {
  18072. return this._isEnabled;
  18073. }
  18074. if (this._isEnabled === false) {
  18075. return false;
  18076. }
  18077. if (this.parent !== undefined && this.parent !== null) {
  18078. return this.parent.isEnabled(checkAncestors);
  18079. }
  18080. return true;
  18081. };
  18082. /**
  18083. * Set the enabled state of this node
  18084. * @param value defines the new enabled state
  18085. */
  18086. Node.prototype.setEnabled = function (value) {
  18087. this._isEnabled = value;
  18088. };
  18089. /**
  18090. * Is this node a descendant of the given node?
  18091. * The function will iterate up the hierarchy until the ancestor was found or no more parents defined
  18092. * @param ancestor defines the parent node to inspect
  18093. * @returns a boolean indicating if this node is a descendant of the given node
  18094. */
  18095. Node.prototype.isDescendantOf = function (ancestor) {
  18096. if (this.parent) {
  18097. if (this.parent === ancestor) {
  18098. return true;
  18099. }
  18100. return this.parent.isDescendantOf(ancestor);
  18101. }
  18102. return false;
  18103. };
  18104. /** @hidden */
  18105. Node.prototype._getDescendants = function (results, directDescendantsOnly, predicate) {
  18106. if (directDescendantsOnly === void 0) { directDescendantsOnly = false; }
  18107. if (!this._children) {
  18108. return;
  18109. }
  18110. for (var index = 0; index < this._children.length; index++) {
  18111. var item = this._children[index];
  18112. if (!predicate || predicate(item)) {
  18113. results.push(item);
  18114. }
  18115. if (!directDescendantsOnly) {
  18116. item._getDescendants(results, false, predicate);
  18117. }
  18118. }
  18119. };
  18120. /**
  18121. * Will return all nodes that have this node as ascendant
  18122. * @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
  18123. * @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
  18124. * @return all children nodes of all types
  18125. */
  18126. Node.prototype.getDescendants = function (directDescendantsOnly, predicate) {
  18127. var results = new Array();
  18128. this._getDescendants(results, directDescendantsOnly, predicate);
  18129. return results;
  18130. };
  18131. /**
  18132. * Get all child-meshes of this node
  18133. * @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
  18134. * @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
  18135. * @returns an array of {BABYLON.AbstractMesh}
  18136. */
  18137. Node.prototype.getChildMeshes = function (directDescendantsOnly, predicate) {
  18138. var results = [];
  18139. this._getDescendants(results, directDescendantsOnly, function (node) {
  18140. return ((!predicate || predicate(node)) && (node instanceof BABYLON.AbstractMesh));
  18141. });
  18142. return results;
  18143. };
  18144. /**
  18145. * Get all child-transformNodes of this node
  18146. * @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
  18147. * @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
  18148. * @returns an array of {BABYLON.TransformNode}
  18149. */
  18150. Node.prototype.getChildTransformNodes = function (directDescendantsOnly, predicate) {
  18151. var results = [];
  18152. this._getDescendants(results, directDescendantsOnly, function (node) {
  18153. return ((!predicate || predicate(node)) && (node instanceof BABYLON.TransformNode));
  18154. });
  18155. return results;
  18156. };
  18157. /**
  18158. * Get all direct children of this node
  18159. * @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
  18160. * @returns an array of {BABYLON.Node}
  18161. */
  18162. Node.prototype.getChildren = function (predicate) {
  18163. return this.getDescendants(true, predicate);
  18164. };
  18165. /** @hidden */
  18166. Node.prototype._setReady = function (state) {
  18167. if (state === this._isReady) {
  18168. return;
  18169. }
  18170. if (!state) {
  18171. this._isReady = false;
  18172. return;
  18173. }
  18174. if (this.onReady) {
  18175. this.onReady(this);
  18176. }
  18177. this._isReady = true;
  18178. };
  18179. /**
  18180. * Get an animation by name
  18181. * @param name defines the name of the animation to look for
  18182. * @returns null if not found else the requested animation
  18183. */
  18184. Node.prototype.getAnimationByName = function (name) {
  18185. for (var i = 0; i < this.animations.length; i++) {
  18186. var animation = this.animations[i];
  18187. if (animation.name === name) {
  18188. return animation;
  18189. }
  18190. }
  18191. return null;
  18192. };
  18193. /**
  18194. * Creates an animation range for this node
  18195. * @param name defines the name of the range
  18196. * @param from defines the starting key
  18197. * @param to defines the end key
  18198. */
  18199. Node.prototype.createAnimationRange = function (name, from, to) {
  18200. // check name not already in use
  18201. if (!this._ranges[name]) {
  18202. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  18203. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18204. if (this.animations[i]) {
  18205. this.animations[i].createRange(name, from, to);
  18206. }
  18207. }
  18208. }
  18209. };
  18210. /**
  18211. * Delete a specific animation range
  18212. * @param name defines the name of the range to delete
  18213. * @param deleteFrames defines if animation frames from the range must be deleted as well
  18214. */
  18215. Node.prototype.deleteAnimationRange = function (name, deleteFrames) {
  18216. if (deleteFrames === void 0) { deleteFrames = true; }
  18217. for (var i = 0, nAnimations = this.animations.length; i < nAnimations; i++) {
  18218. if (this.animations[i]) {
  18219. this.animations[i].deleteRange(name, deleteFrames);
  18220. }
  18221. }
  18222. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  18223. };
  18224. /**
  18225. * Get an animation range by name
  18226. * @param name defines the name of the animation range to look for
  18227. * @returns null if not found else the requested animation range
  18228. */
  18229. Node.prototype.getAnimationRange = function (name) {
  18230. return this._ranges[name];
  18231. };
  18232. /**
  18233. * Will start the animation sequence
  18234. * @param name defines the range frames for animation sequence
  18235. * @param loop defines if the animation should loop (false by default)
  18236. * @param speedRatio defines the speed factor in which to run the animation (1 by default)
  18237. * @param onAnimationEnd defines a function to be executed when the animation ended (undefined by default)
  18238. * @returns the object created for this animation. If range does not exist, it will return null
  18239. */
  18240. Node.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  18241. var range = this.getAnimationRange(name);
  18242. if (!range) {
  18243. return null;
  18244. }
  18245. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  18246. };
  18247. /**
  18248. * Serialize animation ranges into a JSON compatible object
  18249. * @returns serialization object
  18250. */
  18251. Node.prototype.serializeAnimationRanges = function () {
  18252. var serializationRanges = [];
  18253. for (var name in this._ranges) {
  18254. var localRange = this._ranges[name];
  18255. if (!localRange) {
  18256. continue;
  18257. }
  18258. var range = {};
  18259. range.name = name;
  18260. range.from = localRange.from;
  18261. range.to = localRange.to;
  18262. serializationRanges.push(range);
  18263. }
  18264. return serializationRanges;
  18265. };
  18266. /**
  18267. * Computes the world matrix of the node
  18268. * @param force defines if the cache version should be invalidated forcing the world matrix to be created from scratch
  18269. * @returns the world matrix
  18270. */
  18271. Node.prototype.computeWorldMatrix = function (force) {
  18272. return BABYLON.Matrix.Identity();
  18273. };
  18274. /**
  18275. * Releases resources associated with this node.
  18276. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  18277. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  18278. */
  18279. Node.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  18280. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  18281. if (!doNotRecurse) {
  18282. var nodes = this.getDescendants(true);
  18283. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  18284. var node = nodes_1[_i];
  18285. node.dispose(doNotRecurse, disposeMaterialAndTextures);
  18286. }
  18287. }
  18288. else {
  18289. var transformNodes = this.getChildTransformNodes(true);
  18290. for (var _a = 0, transformNodes_1 = transformNodes; _a < transformNodes_1.length; _a++) {
  18291. var transformNode = transformNodes_1[_a];
  18292. transformNode.parent = null;
  18293. transformNode.computeWorldMatrix(true);
  18294. }
  18295. }
  18296. this.parent = null;
  18297. // Callback
  18298. this.onDisposeObservable.notifyObservers(this);
  18299. this.onDisposeObservable.clear();
  18300. // Behaviors
  18301. for (var _b = 0, _c = this._behaviors; _b < _c.length; _b++) {
  18302. var behavior = _c[_b];
  18303. behavior.detach();
  18304. }
  18305. this._behaviors = [];
  18306. this._isDisposed = true;
  18307. };
  18308. /**
  18309. * Parse animation range data from a serialization object and store them into a given node
  18310. * @param node defines where to store the animation ranges
  18311. * @param parsedNode defines the serialization object to read data from
  18312. * @param scene defines the hosting scene
  18313. */
  18314. Node.ParseAnimationRanges = function (node, parsedNode, scene) {
  18315. if (parsedNode.ranges) {
  18316. for (var index = 0; index < parsedNode.ranges.length; index++) {
  18317. var data = parsedNode.ranges[index];
  18318. node.createAnimationRange(data.name, data.from, data.to);
  18319. }
  18320. }
  18321. };
  18322. __decorate([
  18323. BABYLON.serialize()
  18324. ], Node.prototype, "name", void 0);
  18325. __decorate([
  18326. BABYLON.serialize()
  18327. ], Node.prototype, "id", void 0);
  18328. __decorate([
  18329. BABYLON.serialize()
  18330. ], Node.prototype, "uniqueId", void 0);
  18331. __decorate([
  18332. BABYLON.serialize()
  18333. ], Node.prototype, "state", void 0);
  18334. __decorate([
  18335. BABYLON.serialize()
  18336. ], Node.prototype, "metadata", void 0);
  18337. return Node;
  18338. }());
  18339. BABYLON.Node = Node;
  18340. })(BABYLON || (BABYLON = {}));
  18341. //# sourceMappingURL=babylon.node.js.map
  18342. var BABYLON;
  18343. (function (BABYLON) {
  18344. var BoundingSphere = /** @class */ (function () {
  18345. /**
  18346. * Creates a new bounding sphere
  18347. * @param min defines the minimum vector (in local space)
  18348. * @param max defines the maximum vector (in local space)
  18349. */
  18350. function BoundingSphere(min, max) {
  18351. this._tempRadiusVector = BABYLON.Vector3.Zero();
  18352. this.reConstruct(min, max);
  18353. }
  18354. /**
  18355. * Recreates the entire bounding sphere from scratch
  18356. * @param min defines the new minimum vector (in local space)
  18357. * @param max defines the new maximum vector (in local space)
  18358. */
  18359. BoundingSphere.prototype.reConstruct = function (min, max) {
  18360. this.minimum = min.clone();
  18361. this.maximum = max.clone();
  18362. var distance = BABYLON.Vector3.Distance(min, max);
  18363. this.center = BABYLON.Vector3.Lerp(min, max, 0.5);
  18364. this.radius = distance * 0.5;
  18365. this.centerWorld = BABYLON.Vector3.Zero();
  18366. this._update(BABYLON.Matrix.Identity());
  18367. };
  18368. // Methods
  18369. BoundingSphere.prototype._update = function (world) {
  18370. BABYLON.Vector3.TransformCoordinatesToRef(this.center, world, this.centerWorld);
  18371. BABYLON.Vector3.TransformNormalFromFloatsToRef(1.0, 1.0, 1.0, world, this._tempRadiusVector);
  18372. this.radiusWorld = Math.max(Math.abs(this._tempRadiusVector.x), Math.abs(this._tempRadiusVector.y), Math.abs(this._tempRadiusVector.z)) * this.radius;
  18373. };
  18374. BoundingSphere.prototype.isInFrustum = function (frustumPlanes) {
  18375. for (var i = 0; i < 6; i++) {
  18376. if (frustumPlanes[i].dotCoordinate(this.centerWorld) <= -this.radiusWorld)
  18377. return false;
  18378. }
  18379. return true;
  18380. };
  18381. BoundingSphere.prototype.intersectsPoint = function (point) {
  18382. var x = this.centerWorld.x - point.x;
  18383. var y = this.centerWorld.y - point.y;
  18384. var z = this.centerWorld.z - point.z;
  18385. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18386. if (Math.abs(this.radiusWorld - distance) < BABYLON.Epsilon)
  18387. return false;
  18388. return true;
  18389. };
  18390. // Statics
  18391. BoundingSphere.Intersects = function (sphere0, sphere1) {
  18392. var x = sphere0.centerWorld.x - sphere1.centerWorld.x;
  18393. var y = sphere0.centerWorld.y - sphere1.centerWorld.y;
  18394. var z = sphere0.centerWorld.z - sphere1.centerWorld.z;
  18395. var distance = Math.sqrt((x * x) + (y * y) + (z * z));
  18396. if (sphere0.radiusWorld + sphere1.radiusWorld < distance)
  18397. return false;
  18398. return true;
  18399. };
  18400. return BoundingSphere;
  18401. }());
  18402. BABYLON.BoundingSphere = BoundingSphere;
  18403. })(BABYLON || (BABYLON = {}));
  18404. //# sourceMappingURL=babylon.boundingSphere.js.map
  18405. var BABYLON;
  18406. (function (BABYLON) {
  18407. var BoundingBox = /** @class */ (function () {
  18408. /**
  18409. * Creates a new bounding box
  18410. * @param min defines the minimum vector (in local space)
  18411. * @param max defines the maximum vector (in local space)
  18412. */
  18413. function BoundingBox(min, max) {
  18414. this.vectorsWorld = new Array();
  18415. this.reConstruct(min, max);
  18416. }
  18417. // Methods
  18418. /**
  18419. * Recreates the entire bounding box from scratch
  18420. * @param min defines the new minimum vector (in local space)
  18421. * @param max defines the new maximum vector (in local space)
  18422. */
  18423. BoundingBox.prototype.reConstruct = function (min, max) {
  18424. this.minimum = min.clone();
  18425. this.maximum = max.clone();
  18426. // Bounding vectors
  18427. this.vectors = new Array();
  18428. this.vectors.push(this.minimum.clone());
  18429. this.vectors.push(this.maximum.clone());
  18430. this.vectors.push(this.minimum.clone());
  18431. this.vectors[2].x = this.maximum.x;
  18432. this.vectors.push(this.minimum.clone());
  18433. this.vectors[3].y = this.maximum.y;
  18434. this.vectors.push(this.minimum.clone());
  18435. this.vectors[4].z = this.maximum.z;
  18436. this.vectors.push(this.maximum.clone());
  18437. this.vectors[5].z = this.minimum.z;
  18438. this.vectors.push(this.maximum.clone());
  18439. this.vectors[6].x = this.minimum.x;
  18440. this.vectors.push(this.maximum.clone());
  18441. this.vectors[7].y = this.minimum.y;
  18442. // OBB
  18443. this.center = this.maximum.add(this.minimum).scale(0.5);
  18444. this.extendSize = this.maximum.subtract(this.minimum).scale(0.5);
  18445. this.directions = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  18446. // World
  18447. for (var index = 0; index < this.vectors.length; index++) {
  18448. this.vectorsWorld[index] = BABYLON.Vector3.Zero();
  18449. }
  18450. this.minimumWorld = BABYLON.Vector3.Zero();
  18451. this.maximumWorld = BABYLON.Vector3.Zero();
  18452. this.centerWorld = BABYLON.Vector3.Zero();
  18453. this.extendSizeWorld = BABYLON.Vector3.Zero();
  18454. this._update(this._worldMatrix || BABYLON.Matrix.Identity());
  18455. };
  18456. BoundingBox.prototype.getWorldMatrix = function () {
  18457. return this._worldMatrix;
  18458. };
  18459. BoundingBox.prototype.setWorldMatrix = function (matrix) {
  18460. this._worldMatrix.copyFrom(matrix);
  18461. return this;
  18462. };
  18463. BoundingBox.prototype._update = function (world) {
  18464. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this.minimumWorld);
  18465. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this.maximumWorld);
  18466. for (var index = 0; index < this.vectors.length; index++) {
  18467. var v = this.vectorsWorld[index];
  18468. BABYLON.Vector3.TransformCoordinatesToRef(this.vectors[index], world, v);
  18469. if (v.x < this.minimumWorld.x)
  18470. this.minimumWorld.x = v.x;
  18471. if (v.y < this.minimumWorld.y)
  18472. this.minimumWorld.y = v.y;
  18473. if (v.z < this.minimumWorld.z)
  18474. this.minimumWorld.z = v.z;
  18475. if (v.x > this.maximumWorld.x)
  18476. this.maximumWorld.x = v.x;
  18477. if (v.y > this.maximumWorld.y)
  18478. this.maximumWorld.y = v.y;
  18479. if (v.z > this.maximumWorld.z)
  18480. this.maximumWorld.z = v.z;
  18481. }
  18482. // Extend
  18483. this.maximumWorld.subtractToRef(this.minimumWorld, this.extendSizeWorld);
  18484. this.extendSizeWorld.scaleInPlace(0.5);
  18485. // OBB
  18486. this.maximumWorld.addToRef(this.minimumWorld, this.centerWorld);
  18487. this.centerWorld.scaleInPlace(0.5);
  18488. BABYLON.Vector3.FromFloatArrayToRef(world.m, 0, this.directions[0]);
  18489. BABYLON.Vector3.FromFloatArrayToRef(world.m, 4, this.directions[1]);
  18490. BABYLON.Vector3.FromFloatArrayToRef(world.m, 8, this.directions[2]);
  18491. this._worldMatrix = world;
  18492. };
  18493. BoundingBox.prototype.isInFrustum = function (frustumPlanes) {
  18494. return BoundingBox.IsInFrustum(this.vectorsWorld, frustumPlanes);
  18495. };
  18496. BoundingBox.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18497. return BoundingBox.IsCompletelyInFrustum(this.vectorsWorld, frustumPlanes);
  18498. };
  18499. BoundingBox.prototype.intersectsPoint = function (point) {
  18500. var delta = -BABYLON.Epsilon;
  18501. if (this.maximumWorld.x - point.x < delta || delta > point.x - this.minimumWorld.x)
  18502. return false;
  18503. if (this.maximumWorld.y - point.y < delta || delta > point.y - this.minimumWorld.y)
  18504. return false;
  18505. if (this.maximumWorld.z - point.z < delta || delta > point.z - this.minimumWorld.z)
  18506. return false;
  18507. return true;
  18508. };
  18509. BoundingBox.prototype.intersectsSphere = function (sphere) {
  18510. return BoundingBox.IntersectsSphere(this.minimumWorld, this.maximumWorld, sphere.centerWorld, sphere.radiusWorld);
  18511. };
  18512. BoundingBox.prototype.intersectsMinMax = function (min, max) {
  18513. if (this.maximumWorld.x < min.x || this.minimumWorld.x > max.x)
  18514. return false;
  18515. if (this.maximumWorld.y < min.y || this.minimumWorld.y > max.y)
  18516. return false;
  18517. if (this.maximumWorld.z < min.z || this.minimumWorld.z > max.z)
  18518. return false;
  18519. return true;
  18520. };
  18521. // Statics
  18522. BoundingBox.Intersects = function (box0, box1) {
  18523. if (box0.maximumWorld.x < box1.minimumWorld.x || box0.minimumWorld.x > box1.maximumWorld.x)
  18524. return false;
  18525. if (box0.maximumWorld.y < box1.minimumWorld.y || box0.minimumWorld.y > box1.maximumWorld.y)
  18526. return false;
  18527. if (box0.maximumWorld.z < box1.minimumWorld.z || box0.minimumWorld.z > box1.maximumWorld.z)
  18528. return false;
  18529. return true;
  18530. };
  18531. BoundingBox.IntersectsSphere = function (minPoint, maxPoint, sphereCenter, sphereRadius) {
  18532. var vector = BABYLON.Vector3.Clamp(sphereCenter, minPoint, maxPoint);
  18533. var num = BABYLON.Vector3.DistanceSquared(sphereCenter, vector);
  18534. return (num <= (sphereRadius * sphereRadius));
  18535. };
  18536. BoundingBox.IsCompletelyInFrustum = function (boundingVectors, frustumPlanes) {
  18537. for (var p = 0; p < 6; p++) {
  18538. for (var i = 0; i < 8; i++) {
  18539. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18540. return false;
  18541. }
  18542. }
  18543. }
  18544. return true;
  18545. };
  18546. BoundingBox.IsInFrustum = function (boundingVectors, frustumPlanes) {
  18547. for (var p = 0; p < 6; p++) {
  18548. var inCount = 8;
  18549. for (var i = 0; i < 8; i++) {
  18550. if (frustumPlanes[p].dotCoordinate(boundingVectors[i]) < 0) {
  18551. --inCount;
  18552. }
  18553. else {
  18554. break;
  18555. }
  18556. }
  18557. if (inCount === 0)
  18558. return false;
  18559. }
  18560. return true;
  18561. };
  18562. return BoundingBox;
  18563. }());
  18564. BABYLON.BoundingBox = BoundingBox;
  18565. })(BABYLON || (BABYLON = {}));
  18566. //# sourceMappingURL=babylon.boundingBox.js.map
  18567. var BABYLON;
  18568. (function (BABYLON) {
  18569. var computeBoxExtents = function (axis, box) {
  18570. var p = BABYLON.Vector3.Dot(box.centerWorld, axis);
  18571. var r0 = Math.abs(BABYLON.Vector3.Dot(box.directions[0], axis)) * box.extendSize.x;
  18572. var r1 = Math.abs(BABYLON.Vector3.Dot(box.directions[1], axis)) * box.extendSize.y;
  18573. var r2 = Math.abs(BABYLON.Vector3.Dot(box.directions[2], axis)) * box.extendSize.z;
  18574. var r = r0 + r1 + r2;
  18575. return {
  18576. min: p - r,
  18577. max: p + r
  18578. };
  18579. };
  18580. var extentsOverlap = function (min0, max0, min1, max1) { return !(min0 > max1 || min1 > max0); };
  18581. var axisOverlap = function (axis, box0, box1) {
  18582. var result0 = computeBoxExtents(axis, box0);
  18583. var result1 = computeBoxExtents(axis, box1);
  18584. return extentsOverlap(result0.min, result0.max, result1.min, result1.max);
  18585. };
  18586. var BoundingInfo = /** @class */ (function () {
  18587. function BoundingInfo(minimum, maximum) {
  18588. this.minimum = minimum;
  18589. this.maximum = maximum;
  18590. this._isLocked = false;
  18591. this.boundingBox = new BABYLON.BoundingBox(minimum, maximum);
  18592. this.boundingSphere = new BABYLON.BoundingSphere(minimum, maximum);
  18593. }
  18594. Object.defineProperty(BoundingInfo.prototype, "isLocked", {
  18595. get: function () {
  18596. return this._isLocked;
  18597. },
  18598. set: function (value) {
  18599. this._isLocked = value;
  18600. },
  18601. enumerable: true,
  18602. configurable: true
  18603. });
  18604. // Methods
  18605. BoundingInfo.prototype.update = function (world) {
  18606. if (this._isLocked) {
  18607. return;
  18608. }
  18609. this.boundingBox._update(world);
  18610. this.boundingSphere._update(world);
  18611. };
  18612. /**
  18613. * Recreate the bounding info to be centered around a specific point given a specific extend.
  18614. * @param center New center of the bounding info
  18615. * @param extend New extend of the bounding info
  18616. */
  18617. BoundingInfo.prototype.centerOn = function (center, extend) {
  18618. this.minimum = center.subtract(extend);
  18619. this.maximum = center.add(extend);
  18620. this.boundingBox = new BABYLON.BoundingBox(this.minimum, this.maximum);
  18621. this.boundingSphere = new BABYLON.BoundingSphere(this.minimum, this.maximum);
  18622. return this;
  18623. };
  18624. BoundingInfo.prototype.isInFrustum = function (frustumPlanes) {
  18625. if (!this.boundingSphere.isInFrustum(frustumPlanes))
  18626. return false;
  18627. return this.boundingBox.isInFrustum(frustumPlanes);
  18628. };
  18629. Object.defineProperty(BoundingInfo.prototype, "diagonalLength", {
  18630. /**
  18631. * Gets the world distance between the min and max points of the bounding box
  18632. */
  18633. get: function () {
  18634. var boundingBox = this.boundingBox;
  18635. var size = boundingBox.maximumWorld.subtract(boundingBox.minimumWorld);
  18636. return size.length();
  18637. },
  18638. enumerable: true,
  18639. configurable: true
  18640. });
  18641. BoundingInfo.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  18642. return this.boundingBox.isCompletelyInFrustum(frustumPlanes);
  18643. };
  18644. BoundingInfo.prototype._checkCollision = function (collider) {
  18645. return collider._canDoCollision(this.boundingSphere.centerWorld, this.boundingSphere.radiusWorld, this.boundingBox.minimumWorld, this.boundingBox.maximumWorld);
  18646. };
  18647. BoundingInfo.prototype.intersectsPoint = function (point) {
  18648. if (!this.boundingSphere.centerWorld) {
  18649. return false;
  18650. }
  18651. if (!this.boundingSphere.intersectsPoint(point)) {
  18652. return false;
  18653. }
  18654. if (!this.boundingBox.intersectsPoint(point)) {
  18655. return false;
  18656. }
  18657. return true;
  18658. };
  18659. BoundingInfo.prototype.intersects = function (boundingInfo, precise) {
  18660. if (!this.boundingSphere.centerWorld || !boundingInfo.boundingSphere.centerWorld) {
  18661. return false;
  18662. }
  18663. if (!BABYLON.BoundingSphere.Intersects(this.boundingSphere, boundingInfo.boundingSphere)) {
  18664. return false;
  18665. }
  18666. if (!BABYLON.BoundingBox.Intersects(this.boundingBox, boundingInfo.boundingBox)) {
  18667. return false;
  18668. }
  18669. if (!precise) {
  18670. return true;
  18671. }
  18672. var box0 = this.boundingBox;
  18673. var box1 = boundingInfo.boundingBox;
  18674. if (!axisOverlap(box0.directions[0], box0, box1))
  18675. return false;
  18676. if (!axisOverlap(box0.directions[1], box0, box1))
  18677. return false;
  18678. if (!axisOverlap(box0.directions[2], box0, box1))
  18679. return false;
  18680. if (!axisOverlap(box1.directions[0], box0, box1))
  18681. return false;
  18682. if (!axisOverlap(box1.directions[1], box0, box1))
  18683. return false;
  18684. if (!axisOverlap(box1.directions[2], box0, box1))
  18685. return false;
  18686. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[0]), box0, box1))
  18687. return false;
  18688. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[1]), box0, box1))
  18689. return false;
  18690. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[0], box1.directions[2]), box0, box1))
  18691. return false;
  18692. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[0]), box0, box1))
  18693. return false;
  18694. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[1]), box0, box1))
  18695. return false;
  18696. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[1], box1.directions[2]), box0, box1))
  18697. return false;
  18698. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[0]), box0, box1))
  18699. return false;
  18700. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[1]), box0, box1))
  18701. return false;
  18702. if (!axisOverlap(BABYLON.Vector3.Cross(box0.directions[2], box1.directions[2]), box0, box1))
  18703. return false;
  18704. return true;
  18705. };
  18706. return BoundingInfo;
  18707. }());
  18708. BABYLON.BoundingInfo = BoundingInfo;
  18709. })(BABYLON || (BABYLON = {}));
  18710. //# sourceMappingURL=babylon.boundingInfo.js.map
  18711. var BABYLON;
  18712. (function (BABYLON) {
  18713. var TransformNode = /** @class */ (function (_super) {
  18714. __extends(TransformNode, _super);
  18715. function TransformNode(name, scene, isPure) {
  18716. if (scene === void 0) { scene = null; }
  18717. if (isPure === void 0) { isPure = true; }
  18718. var _this = _super.call(this, name, scene) || this;
  18719. _this._forward = new BABYLON.Vector3(0, 0, 1);
  18720. _this._forwardInverted = new BABYLON.Vector3(0, 0, -1);
  18721. _this._up = new BABYLON.Vector3(0, 1, 0);
  18722. _this._right = new BABYLON.Vector3(1, 0, 0);
  18723. _this._rightInverted = new BABYLON.Vector3(-1, 0, 0);
  18724. // Properties
  18725. _this._rotation = BABYLON.Vector3.Zero();
  18726. _this._scaling = BABYLON.Vector3.One();
  18727. _this._isDirty = false;
  18728. /**
  18729. * Set the billboard mode. Default is 0.
  18730. *
  18731. * | Value | Type | Description |
  18732. * | --- | --- | --- |
  18733. * | 0 | BILLBOARDMODE_NONE | |
  18734. * | 1 | BILLBOARDMODE_X | |
  18735. * | 2 | BILLBOARDMODE_Y | |
  18736. * | 4 | BILLBOARDMODE_Z | |
  18737. * | 7 | BILLBOARDMODE_ALL | |
  18738. *
  18739. */
  18740. _this.billboardMode = TransformNode.BILLBOARDMODE_NONE;
  18741. _this.scalingDeterminant = 1;
  18742. _this.infiniteDistance = false;
  18743. /**
  18744. * Gets or sets a boolean indicating that non uniform scaling (when at least one component is different from others) should be ignored.
  18745. * By default the system will update normals to compensate
  18746. */
  18747. _this.ignoreNonUniformScaling = false;
  18748. _this.position = BABYLON.Vector3.Zero();
  18749. _this._localWorld = BABYLON.Matrix.Zero();
  18750. _this._worldMatrix = BABYLON.Matrix.Zero();
  18751. _this._worldMatrixDeterminant = 0;
  18752. _this._absolutePosition = BABYLON.Vector3.Zero();
  18753. _this._pivotMatrix = BABYLON.Matrix.Identity();
  18754. _this._postMultiplyPivotMatrix = false;
  18755. _this._isWorldMatrixFrozen = false;
  18756. /**
  18757. * An event triggered after the world matrix is updated
  18758. */
  18759. _this.onAfterWorldMatrixUpdateObservable = new BABYLON.Observable();
  18760. _this._nonUniformScaling = false;
  18761. if (isPure) {
  18762. _this.getScene().addTransformNode(_this);
  18763. }
  18764. return _this;
  18765. }
  18766. /**
  18767. * Gets a string idenfifying the name of the class
  18768. * @returns "TransformNode" string
  18769. */
  18770. TransformNode.prototype.getClassName = function () {
  18771. return "TransformNode";
  18772. };
  18773. Object.defineProperty(TransformNode.prototype, "rotation", {
  18774. /**
  18775. * Rotation property : a Vector3 depicting the rotation value in radians around each local axis X, Y, Z.
  18776. * If rotation quaternion is set, this Vector3 will (almost always) be the Zero vector!
  18777. * Default : (0.0, 0.0, 0.0)
  18778. */
  18779. get: function () {
  18780. return this._rotation;
  18781. },
  18782. set: function (newRotation) {
  18783. this._rotation = newRotation;
  18784. },
  18785. enumerable: true,
  18786. configurable: true
  18787. });
  18788. Object.defineProperty(TransformNode.prototype, "scaling", {
  18789. /**
  18790. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18791. * Default : (1.0, 1.0, 1.0)
  18792. */
  18793. get: function () {
  18794. return this._scaling;
  18795. },
  18796. /**
  18797. * Scaling property : a Vector3 depicting the mesh scaling along each local axis X, Y, Z.
  18798. * Default : (1.0, 1.0, 1.0)
  18799. */
  18800. set: function (newScaling) {
  18801. this._scaling = newScaling;
  18802. },
  18803. enumerable: true,
  18804. configurable: true
  18805. });
  18806. Object.defineProperty(TransformNode.prototype, "rotationQuaternion", {
  18807. /**
  18808. * Rotation Quaternion property : this a Quaternion object depicting the mesh rotation by using a unit quaternion.
  18809. * It's null by default.
  18810. * 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)
  18811. */
  18812. get: function () {
  18813. return this._rotationQuaternion;
  18814. },
  18815. set: function (quaternion) {
  18816. this._rotationQuaternion = quaternion;
  18817. //reset the rotation vector.
  18818. if (quaternion && this.rotation.length()) {
  18819. this.rotation.copyFromFloats(0.0, 0.0, 0.0);
  18820. }
  18821. },
  18822. enumerable: true,
  18823. configurable: true
  18824. });
  18825. Object.defineProperty(TransformNode.prototype, "forward", {
  18826. /**
  18827. * The forward direction of that transform in world space.
  18828. */
  18829. get: function () {
  18830. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._forwardInverted : this._forward, this.getWorldMatrix()));
  18831. },
  18832. enumerable: true,
  18833. configurable: true
  18834. });
  18835. Object.defineProperty(TransformNode.prototype, "up", {
  18836. /**
  18837. * The up direction of that transform in world space.
  18838. */
  18839. get: function () {
  18840. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this._up, this.getWorldMatrix()));
  18841. },
  18842. enumerable: true,
  18843. configurable: true
  18844. });
  18845. Object.defineProperty(TransformNode.prototype, "right", {
  18846. /**
  18847. * The right direction of that transform in world space.
  18848. */
  18849. get: function () {
  18850. return BABYLON.Vector3.Normalize(BABYLON.Vector3.TransformNormal(this.getScene().useRightHandedSystem ? this._rightInverted : this._right, this.getWorldMatrix()));
  18851. },
  18852. enumerable: true,
  18853. configurable: true
  18854. });
  18855. /**
  18856. * Returns the latest update of the World matrix
  18857. * Returns a Matrix.
  18858. */
  18859. TransformNode.prototype.getWorldMatrix = function () {
  18860. if (this._currentRenderId !== this.getScene().getRenderId()) {
  18861. this.computeWorldMatrix();
  18862. }
  18863. return this._worldMatrix;
  18864. };
  18865. /** @hidden */
  18866. TransformNode.prototype._getWorldMatrixDeterminant = function () {
  18867. return this._worldMatrixDeterminant;
  18868. };
  18869. Object.defineProperty(TransformNode.prototype, "worldMatrixFromCache", {
  18870. /**
  18871. * Returns directly the latest state of the mesh World matrix.
  18872. * A Matrix is returned.
  18873. */
  18874. get: function () {
  18875. return this._worldMatrix;
  18876. },
  18877. enumerable: true,
  18878. configurable: true
  18879. });
  18880. /**
  18881. * Copies the paramater passed Matrix into the mesh Pose matrix.
  18882. * Returns the TransformNode.
  18883. */
  18884. TransformNode.prototype.updatePoseMatrix = function (matrix) {
  18885. this._poseMatrix.copyFrom(matrix);
  18886. return this;
  18887. };
  18888. /**
  18889. * Returns the mesh Pose matrix.
  18890. * Returned object : Matrix
  18891. */
  18892. TransformNode.prototype.getPoseMatrix = function () {
  18893. return this._poseMatrix;
  18894. };
  18895. TransformNode.prototype._isSynchronized = function () {
  18896. if (this._isDirty) {
  18897. return false;
  18898. }
  18899. if (this.billboardMode !== this._cache.billboardMode || this.billboardMode !== TransformNode.BILLBOARDMODE_NONE)
  18900. return false;
  18901. if (this._cache.pivotMatrixUpdated) {
  18902. return false;
  18903. }
  18904. if (this.infiniteDistance) {
  18905. return false;
  18906. }
  18907. if (!this._cache.position.equals(this.position))
  18908. return false;
  18909. if (this.rotationQuaternion) {
  18910. if (!this._cache.rotationQuaternion.equals(this.rotationQuaternion))
  18911. return false;
  18912. }
  18913. if (!this._cache.rotation.equals(this.rotation))
  18914. return false;
  18915. if (!this._cache.scaling.equals(this.scaling))
  18916. return false;
  18917. return true;
  18918. };
  18919. TransformNode.prototype._initCache = function () {
  18920. _super.prototype._initCache.call(this);
  18921. this._cache.localMatrixUpdated = false;
  18922. this._cache.position = BABYLON.Vector3.Zero();
  18923. this._cache.scaling = BABYLON.Vector3.Zero();
  18924. this._cache.rotation = BABYLON.Vector3.Zero();
  18925. this._cache.rotationQuaternion = new BABYLON.Quaternion(0, 0, 0, 0);
  18926. this._cache.billboardMode = -1;
  18927. };
  18928. TransformNode.prototype.markAsDirty = function (property) {
  18929. if (property === "rotation") {
  18930. this.rotationQuaternion = null;
  18931. }
  18932. this._currentRenderId = Number.MAX_VALUE;
  18933. this._isDirty = true;
  18934. return this;
  18935. };
  18936. Object.defineProperty(TransformNode.prototype, "absolutePosition", {
  18937. /**
  18938. * Returns the current mesh absolute position.
  18939. * Retuns a Vector3.
  18940. */
  18941. get: function () {
  18942. return this._absolutePosition;
  18943. },
  18944. enumerable: true,
  18945. configurable: true
  18946. });
  18947. /**
  18948. * Sets a new matrix to apply before all other transformation
  18949. * @param matrix defines the transform matrix
  18950. * @returns the current TransformNode
  18951. */
  18952. TransformNode.prototype.setPreTransformMatrix = function (matrix) {
  18953. return this.setPivotMatrix(matrix, false);
  18954. };
  18955. /**
  18956. * Sets a new pivot matrix to the current node
  18957. * @param matrix defines the new pivot matrix to use
  18958. * @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
  18959. * @returns the current TransformNode
  18960. */
  18961. TransformNode.prototype.setPivotMatrix = function (matrix, postMultiplyPivotMatrix) {
  18962. if (postMultiplyPivotMatrix === void 0) { postMultiplyPivotMatrix = true; }
  18963. this._pivotMatrix = matrix.clone();
  18964. this._cache.pivotMatrixUpdated = true;
  18965. this._postMultiplyPivotMatrix = postMultiplyPivotMatrix;
  18966. if (this._postMultiplyPivotMatrix) {
  18967. if (!this._pivotMatrixInverse) {
  18968. this._pivotMatrixInverse = BABYLON.Matrix.Invert(this._pivotMatrix);
  18969. }
  18970. else {
  18971. this._pivotMatrix.invertToRef(this._pivotMatrixInverse);
  18972. }
  18973. }
  18974. return this;
  18975. };
  18976. /**
  18977. * Returns the mesh pivot matrix.
  18978. * Default : Identity.
  18979. * A Matrix is returned.
  18980. */
  18981. TransformNode.prototype.getPivotMatrix = function () {
  18982. return this._pivotMatrix;
  18983. };
  18984. /**
  18985. * Prevents the World matrix to be computed any longer.
  18986. * Returns the TransformNode.
  18987. */
  18988. TransformNode.prototype.freezeWorldMatrix = function () {
  18989. this._isWorldMatrixFrozen = false; // no guarantee world is not already frozen, switch off temporarily
  18990. this.computeWorldMatrix(true);
  18991. this._isWorldMatrixFrozen = true;
  18992. return this;
  18993. };
  18994. /**
  18995. * Allows back the World matrix computation.
  18996. * Returns the TransformNode.
  18997. */
  18998. TransformNode.prototype.unfreezeWorldMatrix = function () {
  18999. this._isWorldMatrixFrozen = false;
  19000. this.computeWorldMatrix(true);
  19001. return this;
  19002. };
  19003. Object.defineProperty(TransformNode.prototype, "isWorldMatrixFrozen", {
  19004. /**
  19005. * True if the World matrix has been frozen.
  19006. * Returns a boolean.
  19007. */
  19008. get: function () {
  19009. return this._isWorldMatrixFrozen;
  19010. },
  19011. enumerable: true,
  19012. configurable: true
  19013. });
  19014. /**
  19015. * Retuns the mesh absolute position in the World.
  19016. * Returns a Vector3.
  19017. */
  19018. TransformNode.prototype.getAbsolutePosition = function () {
  19019. this.computeWorldMatrix();
  19020. return this._absolutePosition;
  19021. };
  19022. /**
  19023. * Sets the mesh absolute position in the World from a Vector3 or an Array(3).
  19024. * Returns the TransformNode.
  19025. */
  19026. TransformNode.prototype.setAbsolutePosition = function (absolutePosition) {
  19027. if (!absolutePosition) {
  19028. return this;
  19029. }
  19030. var absolutePositionX;
  19031. var absolutePositionY;
  19032. var absolutePositionZ;
  19033. if (absolutePosition.x === undefined) {
  19034. if (arguments.length < 3) {
  19035. return this;
  19036. }
  19037. absolutePositionX = arguments[0];
  19038. absolutePositionY = arguments[1];
  19039. absolutePositionZ = arguments[2];
  19040. }
  19041. else {
  19042. absolutePositionX = absolutePosition.x;
  19043. absolutePositionY = absolutePosition.y;
  19044. absolutePositionZ = absolutePosition.z;
  19045. }
  19046. if (this.parent) {
  19047. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19048. invertParentWorldMatrix.invert();
  19049. var worldPosition = new BABYLON.Vector3(absolutePositionX, absolutePositionY, absolutePositionZ);
  19050. this.position = BABYLON.Vector3.TransformCoordinates(worldPosition, invertParentWorldMatrix);
  19051. }
  19052. else {
  19053. this.position.x = absolutePositionX;
  19054. this.position.y = absolutePositionY;
  19055. this.position.z = absolutePositionZ;
  19056. }
  19057. return this;
  19058. };
  19059. /**
  19060. * Sets the mesh position in its local space.
  19061. * Returns the TransformNode.
  19062. */
  19063. TransformNode.prototype.setPositionWithLocalVector = function (vector3) {
  19064. this.computeWorldMatrix();
  19065. this.position = BABYLON.Vector3.TransformNormal(vector3, this._localWorld);
  19066. return this;
  19067. };
  19068. /**
  19069. * Returns the mesh position in the local space from the current World matrix values.
  19070. * Returns a new Vector3.
  19071. */
  19072. TransformNode.prototype.getPositionExpressedInLocalSpace = function () {
  19073. this.computeWorldMatrix();
  19074. var invLocalWorldMatrix = this._localWorld.clone();
  19075. invLocalWorldMatrix.invert();
  19076. return BABYLON.Vector3.TransformNormal(this.position, invLocalWorldMatrix);
  19077. };
  19078. /**
  19079. * Translates the mesh along the passed Vector3 in its local space.
  19080. * Returns the TransformNode.
  19081. */
  19082. TransformNode.prototype.locallyTranslate = function (vector3) {
  19083. this.computeWorldMatrix(true);
  19084. this.position = BABYLON.Vector3.TransformCoordinates(vector3, this._localWorld);
  19085. return this;
  19086. };
  19087. /**
  19088. * Orients a mesh towards a target point. Mesh must be drawn facing user.
  19089. * @param targetPoint the position (must be in same space as current mesh) to look at
  19090. * @param yawCor optional yaw (y-axis) correction in radians
  19091. * @param pitchCor optional pitch (x-axis) correction in radians
  19092. * @param rollCor optional roll (z-axis) correction in radians
  19093. * @param space the choosen space of the target
  19094. * @returns the TransformNode.
  19095. */
  19096. TransformNode.prototype.lookAt = function (targetPoint, yawCor, pitchCor, rollCor, space) {
  19097. if (yawCor === void 0) { yawCor = 0; }
  19098. if (pitchCor === void 0) { pitchCor = 0; }
  19099. if (rollCor === void 0) { rollCor = 0; }
  19100. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19101. var dv = TransformNode._lookAtVectorCache;
  19102. var pos = space === BABYLON.Space.LOCAL ? this.position : this.getAbsolutePosition();
  19103. targetPoint.subtractToRef(pos, dv);
  19104. var yaw = -Math.atan2(dv.z, dv.x) - Math.PI / 2;
  19105. var len = Math.sqrt(dv.x * dv.x + dv.z * dv.z);
  19106. var pitch = Math.atan2(dv.y, len);
  19107. if (this.rotationQuaternion) {
  19108. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw + yawCor, pitch + pitchCor, rollCor, this.rotationQuaternion);
  19109. }
  19110. else {
  19111. this.rotation.x = pitch + pitchCor;
  19112. this.rotation.y = yaw + yawCor;
  19113. this.rotation.z = rollCor;
  19114. }
  19115. return this;
  19116. };
  19117. /**
  19118. * Returns a new Vector3 what is the localAxis, expressed in the mesh local space, rotated like the mesh.
  19119. * This Vector3 is expressed in the World space.
  19120. */
  19121. TransformNode.prototype.getDirection = function (localAxis) {
  19122. var result = BABYLON.Vector3.Zero();
  19123. this.getDirectionToRef(localAxis, result);
  19124. return result;
  19125. };
  19126. /**
  19127. * Sets the Vector3 "result" as the rotated Vector3 "localAxis" in the same rotation than the mesh.
  19128. * localAxis is expressed in the mesh local space.
  19129. * result is computed in the Wordl space from the mesh World matrix.
  19130. * Returns the TransformNode.
  19131. */
  19132. TransformNode.prototype.getDirectionToRef = function (localAxis, result) {
  19133. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  19134. return this;
  19135. };
  19136. /**
  19137. * Sets a new pivot point to the current node
  19138. * @param point defines the new pivot point to use
  19139. * @param space defines if the point is in world or local space (local by default)
  19140. * @returns the current TransformNode
  19141. */
  19142. TransformNode.prototype.setPivotPoint = function (point, space) {
  19143. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  19144. if (this.getScene().getRenderId() == 0) {
  19145. this.computeWorldMatrix(true);
  19146. }
  19147. var wm = this.getWorldMatrix();
  19148. if (space == BABYLON.Space.WORLD) {
  19149. var tmat = BABYLON.Tmp.Matrix[0];
  19150. wm.invertToRef(tmat);
  19151. point = BABYLON.Vector3.TransformCoordinates(point, tmat);
  19152. }
  19153. return this.setPivotMatrix(BABYLON.Matrix.Translation(-point.x, -point.y, -point.z), true);
  19154. };
  19155. /**
  19156. * Returns a new Vector3 set with the mesh pivot point coordinates in the local space.
  19157. */
  19158. TransformNode.prototype.getPivotPoint = function () {
  19159. var point = BABYLON.Vector3.Zero();
  19160. this.getPivotPointToRef(point);
  19161. return point;
  19162. };
  19163. /**
  19164. * Sets the passed Vector3 "result" with the coordinates of the mesh pivot point in the local space.
  19165. * Returns the TransformNode.
  19166. */
  19167. TransformNode.prototype.getPivotPointToRef = function (result) {
  19168. result.x = -this._pivotMatrix.m[12];
  19169. result.y = -this._pivotMatrix.m[13];
  19170. result.z = -this._pivotMatrix.m[14];
  19171. return this;
  19172. };
  19173. /**
  19174. * Returns a new Vector3 set with the mesh pivot point World coordinates.
  19175. */
  19176. TransformNode.prototype.getAbsolutePivotPoint = function () {
  19177. var point = BABYLON.Vector3.Zero();
  19178. this.getAbsolutePivotPointToRef(point);
  19179. return point;
  19180. };
  19181. /**
  19182. * Sets the Vector3 "result" coordinates with the mesh pivot point World coordinates.
  19183. * Returns the TransformNode.
  19184. */
  19185. TransformNode.prototype.getAbsolutePivotPointToRef = function (result) {
  19186. result.x = this._pivotMatrix.m[12];
  19187. result.y = this._pivotMatrix.m[13];
  19188. result.z = this._pivotMatrix.m[14];
  19189. this.getPivotPointToRef(result);
  19190. BABYLON.Vector3.TransformCoordinatesToRef(result, this.getWorldMatrix(), result);
  19191. return this;
  19192. };
  19193. /**
  19194. * Defines the passed node as the parent of the current node.
  19195. * The node will remain exactly where it is and its position / rotation will be updated accordingly
  19196. * Returns the TransformNode.
  19197. */
  19198. TransformNode.prototype.setParent = function (node) {
  19199. if (!node && !this.parent) {
  19200. return this;
  19201. }
  19202. if (!node) {
  19203. var rotation = BABYLON.Tmp.Quaternion[0];
  19204. var position = BABYLON.Tmp.Vector3[0];
  19205. var scale = BABYLON.Tmp.Vector3[1];
  19206. if (this.parent && this.parent.computeWorldMatrix) {
  19207. this.parent.computeWorldMatrix(true);
  19208. }
  19209. this.computeWorldMatrix(true);
  19210. this.getWorldMatrix().decompose(scale, rotation, position);
  19211. if (this.rotationQuaternion) {
  19212. this.rotationQuaternion.copyFrom(rotation);
  19213. }
  19214. else {
  19215. rotation.toEulerAnglesToRef(this.rotation);
  19216. }
  19217. this.scaling.x = scale.x;
  19218. this.scaling.y = scale.y;
  19219. this.scaling.z = scale.z;
  19220. this.position.x = position.x;
  19221. this.position.y = position.y;
  19222. this.position.z = position.z;
  19223. }
  19224. else {
  19225. var rotation = BABYLON.Tmp.Quaternion[0];
  19226. var position = BABYLON.Tmp.Vector3[0];
  19227. var scale = BABYLON.Tmp.Vector3[1];
  19228. var diffMatrix = BABYLON.Tmp.Matrix[0];
  19229. var invParentMatrix = BABYLON.Tmp.Matrix[1];
  19230. this.computeWorldMatrix(true);
  19231. node.computeWorldMatrix(true);
  19232. node.getWorldMatrix().invertToRef(invParentMatrix);
  19233. this.getWorldMatrix().multiplyToRef(invParentMatrix, diffMatrix);
  19234. diffMatrix.decompose(scale, rotation, position);
  19235. if (this.rotationQuaternion) {
  19236. this.rotationQuaternion.copyFrom(rotation);
  19237. }
  19238. else {
  19239. rotation.toEulerAnglesToRef(this.rotation);
  19240. }
  19241. this.position.x = position.x;
  19242. this.position.y = position.y;
  19243. this.position.z = position.z;
  19244. this.scaling.x = scale.x;
  19245. this.scaling.y = scale.y;
  19246. this.scaling.z = scale.z;
  19247. }
  19248. this.parent = node;
  19249. return this;
  19250. };
  19251. Object.defineProperty(TransformNode.prototype, "nonUniformScaling", {
  19252. get: function () {
  19253. return this._nonUniformScaling;
  19254. },
  19255. enumerable: true,
  19256. configurable: true
  19257. });
  19258. TransformNode.prototype._updateNonUniformScalingState = function (value) {
  19259. if (this._nonUniformScaling === value) {
  19260. return false;
  19261. }
  19262. this._nonUniformScaling = value;
  19263. return true;
  19264. };
  19265. /**
  19266. * Attach the current TransformNode to another TransformNode associated with a bone
  19267. * @param bone Bone affecting the TransformNode
  19268. * @param affectedTransformNode TransformNode associated with the bone
  19269. */
  19270. TransformNode.prototype.attachToBone = function (bone, affectedTransformNode) {
  19271. this._transformToBoneReferal = affectedTransformNode;
  19272. this.parent = bone;
  19273. if (bone.getWorldMatrix().determinant() < 0) {
  19274. this.scalingDeterminant *= -1;
  19275. }
  19276. return this;
  19277. };
  19278. TransformNode.prototype.detachFromBone = function () {
  19279. if (!this.parent) {
  19280. return this;
  19281. }
  19282. if (this.parent.getWorldMatrix().determinant() < 0) {
  19283. this.scalingDeterminant *= -1;
  19284. }
  19285. this._transformToBoneReferal = null;
  19286. this.parent = null;
  19287. return this;
  19288. };
  19289. /**
  19290. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in the given space.
  19291. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19292. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19293. * The passed axis is also normalized.
  19294. * Returns the TransformNode.
  19295. */
  19296. TransformNode.prototype.rotate = function (axis, amount, space) {
  19297. axis.normalize();
  19298. if (!this.rotationQuaternion) {
  19299. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19300. this.rotation = BABYLON.Vector3.Zero();
  19301. }
  19302. var rotationQuaternion;
  19303. if (!space || space === BABYLON.Space.LOCAL) {
  19304. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19305. this.rotationQuaternion.multiplyToRef(rotationQuaternion, this.rotationQuaternion);
  19306. }
  19307. else {
  19308. if (this.parent) {
  19309. var invertParentWorldMatrix = this.parent.getWorldMatrix().clone();
  19310. invertParentWorldMatrix.invert();
  19311. axis = BABYLON.Vector3.TransformNormal(axis, invertParentWorldMatrix);
  19312. }
  19313. rotationQuaternion = BABYLON.Quaternion.RotationAxisToRef(axis, amount, TransformNode._rotationAxisCache);
  19314. rotationQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19315. }
  19316. return this;
  19317. };
  19318. /**
  19319. * Rotates the mesh around the axis vector for the passed angle (amount) expressed in radians, in world space.
  19320. * Note that the property `rotationQuaternion` is then automatically updated and the property `rotation` is set to (0,0,0) and no longer used.
  19321. * The passed axis is also normalized.
  19322. * Returns the TransformNode.
  19323. * Method is based on http://www.euclideanspace.com/maths/geometry/affine/aroundPoint/index.htm
  19324. */
  19325. TransformNode.prototype.rotateAround = function (point, axis, amount) {
  19326. axis.normalize();
  19327. if (!this.rotationQuaternion) {
  19328. this.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  19329. this.rotation.copyFromFloats(0, 0, 0);
  19330. }
  19331. point.subtractToRef(this.position, BABYLON.Tmp.Vector3[0]);
  19332. BABYLON.Matrix.TranslationToRef(BABYLON.Tmp.Vector3[0].x, BABYLON.Tmp.Vector3[0].y, BABYLON.Tmp.Vector3[0].z, BABYLON.Tmp.Matrix[0]);
  19333. BABYLON.Tmp.Matrix[0].invertToRef(BABYLON.Tmp.Matrix[2]);
  19334. BABYLON.Matrix.RotationAxisToRef(axis, amount, BABYLON.Tmp.Matrix[1]);
  19335. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[2]);
  19336. BABYLON.Tmp.Matrix[2].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[2]);
  19337. BABYLON.Tmp.Matrix[2].decompose(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Quaternion[0], BABYLON.Tmp.Vector3[1]);
  19338. this.position.addInPlace(BABYLON.Tmp.Vector3[1]);
  19339. BABYLON.Tmp.Quaternion[0].multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  19340. return this;
  19341. };
  19342. /**
  19343. * Translates the mesh along the axis vector for the passed distance in the given space.
  19344. * space (default LOCAL) can be either BABYLON.Space.LOCAL, either BABYLON.Space.WORLD.
  19345. * Returns the TransformNode.
  19346. */
  19347. TransformNode.prototype.translate = function (axis, distance, space) {
  19348. var displacementVector = axis.scale(distance);
  19349. if (!space || space === BABYLON.Space.LOCAL) {
  19350. var tempV3 = this.getPositionExpressedInLocalSpace().add(displacementVector);
  19351. this.setPositionWithLocalVector(tempV3);
  19352. }
  19353. else {
  19354. this.setAbsolutePosition(this.getAbsolutePosition().add(displacementVector));
  19355. }
  19356. return this;
  19357. };
  19358. /**
  19359. * Adds a rotation step to the mesh current rotation.
  19360. * x, y, z are Euler angles expressed in radians.
  19361. * This methods updates the current mesh rotation, either mesh.rotation, either mesh.rotationQuaternion if it's set.
  19362. * This means this rotation is made in the mesh local space only.
  19363. * It's useful to set a custom rotation order different from the BJS standard one YXZ.
  19364. * Example : this rotates the mesh first around its local X axis, then around its local Z axis, finally around its local Y axis.
  19365. * ```javascript
  19366. * mesh.addRotation(x1, 0, 0).addRotation(0, 0, z2).addRotation(0, 0, y3);
  19367. * ```
  19368. * Note that `addRotation()` accumulates the passed rotation values to the current ones and computes the .rotation or .rotationQuaternion updated values.
  19369. * 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.
  19370. * Returns the TransformNode.
  19371. */
  19372. TransformNode.prototype.addRotation = function (x, y, z) {
  19373. var rotationQuaternion;
  19374. if (this.rotationQuaternion) {
  19375. rotationQuaternion = this.rotationQuaternion;
  19376. }
  19377. else {
  19378. rotationQuaternion = BABYLON.Tmp.Quaternion[1];
  19379. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, rotationQuaternion);
  19380. }
  19381. var accumulation = BABYLON.Tmp.Quaternion[0];
  19382. BABYLON.Quaternion.RotationYawPitchRollToRef(y, x, z, accumulation);
  19383. rotationQuaternion.multiplyInPlace(accumulation);
  19384. if (!this.rotationQuaternion) {
  19385. rotationQuaternion.toEulerAnglesToRef(this.rotation);
  19386. }
  19387. return this;
  19388. };
  19389. /**
  19390. * Computes the mesh World matrix and returns it.
  19391. * If the mesh world matrix is frozen, this computation does nothing more than returning the last frozen values.
  19392. * If the parameter `force` is let to `false` (default), the current cached World matrix is returned.
  19393. * If the parameter `force`is set to `true`, the actual computation is done.
  19394. * Returns the mesh World Matrix.
  19395. */
  19396. TransformNode.prototype.computeWorldMatrix = function (force) {
  19397. if (this._isWorldMatrixFrozen) {
  19398. return this._worldMatrix;
  19399. }
  19400. if (!force && this.isSynchronized(true)) {
  19401. this._currentRenderId = this.getScene().getRenderId();
  19402. return this._worldMatrix;
  19403. }
  19404. this._cache.position.copyFrom(this.position);
  19405. this._cache.scaling.copyFrom(this.scaling);
  19406. this._cache.pivotMatrixUpdated = false;
  19407. this._cache.billboardMode = this.billboardMode;
  19408. this._currentRenderId = this.getScene().getRenderId();
  19409. this._childRenderId = this.getScene().getRenderId();
  19410. this._isDirty = false;
  19411. // Scaling
  19412. BABYLON.Matrix.ScalingToRef(this.scaling.x * this.scalingDeterminant, this.scaling.y * this.scalingDeterminant, this.scaling.z * this.scalingDeterminant, BABYLON.Tmp.Matrix[1]);
  19413. // Rotation
  19414. //rotate, if quaternion is set and rotation was used
  19415. if (this.rotationQuaternion) {
  19416. var len = this.rotation.length();
  19417. if (len) {
  19418. this.rotationQuaternion.multiplyInPlace(BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z));
  19419. this.rotation.copyFromFloats(0, 0, 0);
  19420. }
  19421. }
  19422. if (this.rotationQuaternion) {
  19423. this.rotationQuaternion.toRotationMatrix(BABYLON.Tmp.Matrix[0]);
  19424. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  19425. }
  19426. else {
  19427. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, BABYLON.Tmp.Matrix[0]);
  19428. this._cache.rotation.copyFrom(this.rotation);
  19429. }
  19430. // Translation
  19431. var camera = this.getScene().activeCamera;
  19432. if (this.infiniteDistance && !this.parent && camera) {
  19433. var cameraWorldMatrix = camera.getWorldMatrix();
  19434. var cameraGlobalPosition = new BABYLON.Vector3(cameraWorldMatrix.m[12], cameraWorldMatrix.m[13], cameraWorldMatrix.m[14]);
  19435. BABYLON.Matrix.TranslationToRef(this.position.x + cameraGlobalPosition.x, this.position.y + cameraGlobalPosition.y, this.position.z + cameraGlobalPosition.z, BABYLON.Tmp.Matrix[2]);
  19436. }
  19437. else {
  19438. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, BABYLON.Tmp.Matrix[2]);
  19439. }
  19440. // Composing transformations
  19441. this._pivotMatrix.multiplyToRef(BABYLON.Tmp.Matrix[1], BABYLON.Tmp.Matrix[4]);
  19442. BABYLON.Tmp.Matrix[4].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19443. // Billboarding (testing PG:http://www.babylonjs-playground.com/#UJEIL#13)
  19444. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE && camera) {
  19445. if ((this.billboardMode & TransformNode.BILLBOARDMODE_ALL) !== TransformNode.BILLBOARDMODE_ALL) {
  19446. // Need to decompose each rotation here
  19447. var currentPosition = BABYLON.Tmp.Vector3[3];
  19448. if (this.parent && this.parent.getWorldMatrix) {
  19449. if (this._transformToBoneReferal) {
  19450. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19451. BABYLON.Vector3.TransformCoordinatesToRef(this.position, BABYLON.Tmp.Matrix[6], currentPosition);
  19452. }
  19453. else {
  19454. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), currentPosition);
  19455. }
  19456. }
  19457. else {
  19458. currentPosition.copyFrom(this.position);
  19459. }
  19460. currentPosition.subtractInPlace(camera.globalPosition);
  19461. var finalEuler = BABYLON.Tmp.Vector3[4].copyFromFloats(0, 0, 0);
  19462. if ((this.billboardMode & TransformNode.BILLBOARDMODE_X) === TransformNode.BILLBOARDMODE_X) {
  19463. finalEuler.x = Math.atan2(-currentPosition.y, currentPosition.z);
  19464. }
  19465. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Y) === TransformNode.BILLBOARDMODE_Y) {
  19466. finalEuler.y = Math.atan2(currentPosition.x, currentPosition.z);
  19467. }
  19468. if ((this.billboardMode & TransformNode.BILLBOARDMODE_Z) === TransformNode.BILLBOARDMODE_Z) {
  19469. finalEuler.z = Math.atan2(currentPosition.y, currentPosition.x);
  19470. }
  19471. BABYLON.Matrix.RotationYawPitchRollToRef(finalEuler.y, finalEuler.x, finalEuler.z, BABYLON.Tmp.Matrix[0]);
  19472. }
  19473. else {
  19474. BABYLON.Tmp.Matrix[1].copyFrom(camera.getViewMatrix());
  19475. BABYLON.Tmp.Matrix[1].setTranslationFromFloats(0, 0, 0);
  19476. BABYLON.Tmp.Matrix[1].invertToRef(BABYLON.Tmp.Matrix[0]);
  19477. }
  19478. BABYLON.Tmp.Matrix[1].copyFrom(BABYLON.Tmp.Matrix[5]);
  19479. BABYLON.Tmp.Matrix[1].multiplyToRef(BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Matrix[5]);
  19480. }
  19481. // Local world
  19482. BABYLON.Tmp.Matrix[5].multiplyToRef(BABYLON.Tmp.Matrix[2], this._localWorld);
  19483. // Parent
  19484. if (this.parent && this.parent.getWorldMatrix) {
  19485. if (this.billboardMode !== TransformNode.BILLBOARDMODE_NONE) {
  19486. if (this._transformToBoneReferal) {
  19487. this.parent.getWorldMatrix().multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19488. BABYLON.Tmp.Matrix[5].copyFrom(BABYLON.Tmp.Matrix[6]);
  19489. }
  19490. else {
  19491. BABYLON.Tmp.Matrix[5].copyFrom(this.parent.getWorldMatrix());
  19492. }
  19493. this._localWorld.getTranslationToRef(BABYLON.Tmp.Vector3[5]);
  19494. BABYLON.Vector3.TransformCoordinatesToRef(BABYLON.Tmp.Vector3[5], BABYLON.Tmp.Matrix[5], BABYLON.Tmp.Vector3[5]);
  19495. this._worldMatrix.copyFrom(this._localWorld);
  19496. this._worldMatrix.setTranslation(BABYLON.Tmp.Vector3[5]);
  19497. }
  19498. else {
  19499. if (this._transformToBoneReferal) {
  19500. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), BABYLON.Tmp.Matrix[6]);
  19501. BABYLON.Tmp.Matrix[6].multiplyToRef(this._transformToBoneReferal.getWorldMatrix(), this._worldMatrix);
  19502. }
  19503. else {
  19504. this._localWorld.multiplyToRef(this.parent.getWorldMatrix(), this._worldMatrix);
  19505. }
  19506. }
  19507. this._markSyncedWithParent();
  19508. }
  19509. else {
  19510. this._worldMatrix.copyFrom(this._localWorld);
  19511. }
  19512. // Post multiply inverse of pivotMatrix
  19513. if (this._postMultiplyPivotMatrix) {
  19514. this._worldMatrix.multiplyToRef(this._pivotMatrixInverse, this._worldMatrix);
  19515. }
  19516. // Normal matrix
  19517. if (!this.ignoreNonUniformScaling) {
  19518. if (this.scaling.isNonUniform) {
  19519. this._updateNonUniformScalingState(true);
  19520. }
  19521. else if (this.parent && this.parent._nonUniformScaling) {
  19522. this._updateNonUniformScalingState(this.parent._nonUniformScaling);
  19523. }
  19524. else {
  19525. this._updateNonUniformScalingState(false);
  19526. }
  19527. }
  19528. else {
  19529. this._updateNonUniformScalingState(false);
  19530. }
  19531. this._afterComputeWorldMatrix();
  19532. // Absolute position
  19533. this._absolutePosition.copyFromFloats(this._worldMatrix.m[12], this._worldMatrix.m[13], this._worldMatrix.m[14]);
  19534. // Callbacks
  19535. this.onAfterWorldMatrixUpdateObservable.notifyObservers(this);
  19536. if (!this._poseMatrix) {
  19537. this._poseMatrix = BABYLON.Matrix.Invert(this._worldMatrix);
  19538. }
  19539. // Cache the determinant
  19540. this._worldMatrixDeterminant = this._worldMatrix.determinant();
  19541. return this._worldMatrix;
  19542. };
  19543. TransformNode.prototype._afterComputeWorldMatrix = function () {
  19544. };
  19545. /**
  19546. * If you'd like to be called back after the mesh position, rotation or scaling has been updated.
  19547. * @param func: callback function to add
  19548. *
  19549. * Returns the TransformNode.
  19550. */
  19551. TransformNode.prototype.registerAfterWorldMatrixUpdate = function (func) {
  19552. this.onAfterWorldMatrixUpdateObservable.add(func);
  19553. return this;
  19554. };
  19555. /**
  19556. * Removes a registered callback function.
  19557. * Returns the TransformNode.
  19558. */
  19559. TransformNode.prototype.unregisterAfterWorldMatrixUpdate = function (func) {
  19560. this.onAfterWorldMatrixUpdateObservable.removeCallback(func);
  19561. return this;
  19562. };
  19563. /**
  19564. * Clone the current transform node
  19565. * Returns the new transform node
  19566. * @param name Name of the new clone
  19567. * @param newParent New parent for the clone
  19568. * @param doNotCloneChildren Do not clone children hierarchy
  19569. */
  19570. TransformNode.prototype.clone = function (name, newParent, doNotCloneChildren) {
  19571. var _this = this;
  19572. var result = BABYLON.SerializationHelper.Clone(function () { return new TransformNode(name, _this.getScene()); }, this);
  19573. result.name = name;
  19574. result.id = name;
  19575. if (newParent) {
  19576. result.parent = newParent;
  19577. }
  19578. if (!doNotCloneChildren) {
  19579. // Children
  19580. var directDescendants = this.getDescendants(true);
  19581. for (var index = 0; index < directDescendants.length; index++) {
  19582. var child = directDescendants[index];
  19583. if (child.clone) {
  19584. child.clone(name + "." + child.name, result);
  19585. }
  19586. }
  19587. }
  19588. return result;
  19589. };
  19590. TransformNode.prototype.serialize = function (currentSerializationObject) {
  19591. var serializationObject = BABYLON.SerializationHelper.Serialize(this, currentSerializationObject);
  19592. serializationObject.type = this.getClassName();
  19593. // Parent
  19594. if (this.parent) {
  19595. serializationObject.parentId = this.parent.id;
  19596. }
  19597. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  19598. serializationObject.tags = BABYLON.Tags.GetTags(this);
  19599. }
  19600. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  19601. serializationObject.isEnabled = this.isEnabled();
  19602. // Parent
  19603. if (this.parent) {
  19604. serializationObject.parentId = this.parent.id;
  19605. }
  19606. return serializationObject;
  19607. };
  19608. // Statics
  19609. /**
  19610. * Returns a new TransformNode object parsed from the source provided.
  19611. * The parameter `parsedMesh` is the source.
  19612. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  19613. */
  19614. TransformNode.Parse = function (parsedTransformNode, scene, rootUrl) {
  19615. var transformNode = BABYLON.SerializationHelper.Parse(function () { return new TransformNode(parsedTransformNode.name, scene); }, parsedTransformNode, scene, rootUrl);
  19616. if (BABYLON.Tags) {
  19617. BABYLON.Tags.AddTagsTo(transformNode, parsedTransformNode.tags);
  19618. }
  19619. if (parsedTransformNode.localMatrix) {
  19620. transformNode.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.localMatrix));
  19621. }
  19622. else if (parsedTransformNode.pivotMatrix) {
  19623. transformNode.setPivotMatrix(BABYLON.Matrix.FromArray(parsedTransformNode.pivotMatrix));
  19624. }
  19625. transformNode.setEnabled(parsedTransformNode.isEnabled);
  19626. // Parent
  19627. if (parsedTransformNode.parentId) {
  19628. transformNode._waitingParentId = parsedTransformNode.parentId;
  19629. }
  19630. return transformNode;
  19631. };
  19632. /**
  19633. * Releases resources associated with this transform node.
  19634. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  19635. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  19636. */
  19637. TransformNode.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  19638. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  19639. // Animations
  19640. this.getScene().stopAnimation(this);
  19641. // Remove from scene
  19642. this.getScene().removeTransformNode(this);
  19643. this.onAfterWorldMatrixUpdateObservable.clear();
  19644. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  19645. };
  19646. // Statics
  19647. TransformNode.BILLBOARDMODE_NONE = 0;
  19648. TransformNode.BILLBOARDMODE_X = 1;
  19649. TransformNode.BILLBOARDMODE_Y = 2;
  19650. TransformNode.BILLBOARDMODE_Z = 4;
  19651. TransformNode.BILLBOARDMODE_ALL = 7;
  19652. TransformNode._lookAtVectorCache = new BABYLON.Vector3(0, 0, 0);
  19653. TransformNode._rotationAxisCache = new BABYLON.Quaternion();
  19654. __decorate([
  19655. BABYLON.serializeAsVector3()
  19656. ], TransformNode.prototype, "_rotation", void 0);
  19657. __decorate([
  19658. BABYLON.serializeAsQuaternion()
  19659. ], TransformNode.prototype, "_rotationQuaternion", void 0);
  19660. __decorate([
  19661. BABYLON.serializeAsVector3()
  19662. ], TransformNode.prototype, "_scaling", void 0);
  19663. __decorate([
  19664. BABYLON.serialize()
  19665. ], TransformNode.prototype, "billboardMode", void 0);
  19666. __decorate([
  19667. BABYLON.serialize()
  19668. ], TransformNode.prototype, "scalingDeterminant", void 0);
  19669. __decorate([
  19670. BABYLON.serialize()
  19671. ], TransformNode.prototype, "infiniteDistance", void 0);
  19672. __decorate([
  19673. BABYLON.serialize()
  19674. ], TransformNode.prototype, "ignoreNonUniformScaling", void 0);
  19675. __decorate([
  19676. BABYLON.serializeAsVector3()
  19677. ], TransformNode.prototype, "position", void 0);
  19678. return TransformNode;
  19679. }(BABYLON.Node));
  19680. BABYLON.TransformNode = TransformNode;
  19681. })(BABYLON || (BABYLON = {}));
  19682. //# sourceMappingURL=babylon.transformNode.js.map
  19683. var BABYLON;
  19684. (function (BABYLON) {
  19685. /**
  19686. * Class used to store all common mesh properties
  19687. */
  19688. var AbstractMesh = /** @class */ (function (_super) {
  19689. __extends(AbstractMesh, _super);
  19690. // Constructor
  19691. /**
  19692. * Creates a new AbstractMesh
  19693. * @param name defines the name of the mesh
  19694. * @param scene defines the hosting scene
  19695. */
  19696. function AbstractMesh(name, scene) {
  19697. if (scene === void 0) { scene = null; }
  19698. var _this = _super.call(this, name, scene, false) || this;
  19699. _this._facetNb = 0; // facet number
  19700. _this._partitioningSubdivisions = 10; // number of subdivisions per axis in the partioning space
  19701. _this._partitioningBBoxRatio = 1.01; // the partioning array space is by default 1% bigger than the bounding box
  19702. _this._facetDataEnabled = false; // is the facet data feature enabled on this mesh ?
  19703. _this._facetParameters = {}; // keep a reference to the object parameters to avoid memory re-allocation
  19704. _this._bbSize = BABYLON.Vector3.Zero(); // bbox size approximated for facet data
  19705. _this._subDiv = {
  19706. max: 1,
  19707. X: 1,
  19708. Y: 1,
  19709. Z: 1
  19710. };
  19711. _this._facetDepthSort = false; // is the facet depth sort to be computed
  19712. _this._facetDepthSortEnabled = false; // is the facet depth sort initialized
  19713. // Events
  19714. /**
  19715. * An event triggered when this mesh collides with another one
  19716. */
  19717. _this.onCollideObservable = new BABYLON.Observable();
  19718. /**
  19719. * An event triggered when the collision's position changes
  19720. */
  19721. _this.onCollisionPositionChangeObservable = new BABYLON.Observable();
  19722. /**
  19723. * An event triggered when material is changed
  19724. */
  19725. _this.onMaterialChangedObservable = new BABYLON.Observable();
  19726. // Properties
  19727. /**
  19728. * Gets or sets the orientation for POV movement & rotation
  19729. */
  19730. _this.definedFacingForward = true;
  19731. /**
  19732. * This property determines the type of occlusion query algorithm to run in WebGl, you can use:
  19733. * * AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE which is mapped to GL_ANY_SAMPLES_PASSED.
  19734. * * 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.
  19735. * @see http://doc.babylonjs.com/features/occlusionquery
  19736. */
  19737. _this.occlusionQueryAlgorithmType = AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE;
  19738. /**
  19739. * 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:
  19740. * * OCCLUSION_TYPE_NONE (Default Value): this option means no occlusion query whith the Mesh.
  19741. * * OCCLUSION_TYPE_OPTIMISTIC: this option is means use occlusion query and if occlusionRetryCount is reached and the query is broken show the mesh.
  19742. * * 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.
  19743. * @see http://doc.babylonjs.com/features/occlusionquery
  19744. */
  19745. _this.occlusionType = AbstractMesh.OCCLUSION_TYPE_NONE;
  19746. /**
  19747. * 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.
  19748. * The default value is -1 which means don't break the query and wait till the result
  19749. * @see http://doc.babylonjs.com/features/occlusionquery
  19750. */
  19751. _this.occlusionRetryCount = -1;
  19752. _this._occlusionInternalRetryCounter = 0;
  19753. _this._isOccluded = false;
  19754. _this._isOcclusionQueryInProgress = false;
  19755. _this._visibility = 1.0;
  19756. /** Gets or sets the alpha index used to sort transparent meshes
  19757. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#alpha-index
  19758. */
  19759. _this.alphaIndex = Number.MAX_VALUE;
  19760. /**
  19761. * Gets or sets a boolean indicating if the mesh is visible (renderable). Default is true
  19762. */
  19763. _this.isVisible = true;
  19764. /**
  19765. * Gets or sets a boolean indicating if the mesh can be picked (by scene.pick for instance or through actions). Default is true
  19766. */
  19767. _this.isPickable = true;
  19768. /**
  19769. * Gets or sets a boolean indicating if the bounding box must be rendered as well (false by default)
  19770. */
  19771. _this.showBoundingBox = false;
  19772. /** Gets or sets a boolean indicating that bounding boxes of subMeshes must be rendered as well (false by default) */
  19773. _this.showSubMeshesBoundingBox = false;
  19774. /** Gets or sets a boolean indicating if the mesh must be considered as a ray blocker for lens flares (false by default)
  19775. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  19776. */
  19777. _this.isBlocker = false;
  19778. /**
  19779. * Gets or sets a boolean indicating that pointer move events must be supported on this mesh (false by default)
  19780. */
  19781. _this.enablePointerMoveEvents = false;
  19782. /**
  19783. * Specifies the rendering group id for this mesh (0 by default)
  19784. * @see http://doc.babylonjs.com/resources/transparency_and_how_meshes_are_rendered#rendering-groups
  19785. */
  19786. _this.renderingGroupId = 0;
  19787. _this._receiveShadows = false;
  19788. /**
  19789. * Gets or sets a boolean indicating if the outline must be rendered as well
  19790. * @see https://www.babylonjs-playground.com/#10WJ5S#3
  19791. */
  19792. _this.renderOutline = false;
  19793. /** Defines color to use when rendering outline */
  19794. _this.outlineColor = BABYLON.Color3.Red();
  19795. /** Define width to use when rendering outline */
  19796. _this.outlineWidth = 0.02;
  19797. /**
  19798. * Gets or sets a boolean indicating if the overlay must be rendered as well
  19799. * @see https://www.babylonjs-playground.com/#10WJ5S#2
  19800. */
  19801. _this.renderOverlay = false;
  19802. /** Defines color to use when rendering overlay */
  19803. _this.overlayColor = BABYLON.Color3.Red();
  19804. /** Defines alpha to use when rendering overlay */
  19805. _this.overlayAlpha = 0.5;
  19806. _this._hasVertexAlpha = false;
  19807. _this._useVertexColors = true;
  19808. _this._computeBonesUsingShaders = true;
  19809. _this._numBoneInfluencers = 4;
  19810. _this._applyFog = true;
  19811. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes selection (true by default) */
  19812. _this.useOctreeForRenderingSelection = true;
  19813. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes picking (true by default) */
  19814. _this.useOctreeForPicking = true;
  19815. /** Gets or sets a boolean indicating that internal octree (if available) can be used to boost submeshes collision (true by default) */
  19816. _this.useOctreeForCollisions = true;
  19817. _this._layerMask = 0x0FFFFFFF;
  19818. /**
  19819. * True if the mesh must be rendered in any case (this will shortcut the frustum clipping phase)
  19820. */
  19821. _this.alwaysSelectAsActiveMesh = false;
  19822. /**
  19823. * Gets or sets the current action manager
  19824. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  19825. */
  19826. _this.actionManager = null;
  19827. /**
  19828. * Gets or sets impostor used for physic simulation
  19829. * @see http://doc.babylonjs.com/features/physics_engine
  19830. */
  19831. _this.physicsImpostor = null;
  19832. // Collisions
  19833. _this._checkCollisions = false;
  19834. _this._collisionMask = -1;
  19835. _this._collisionGroup = -1;
  19836. /**
  19837. * Gets or sets the ellipsoid used to impersonate this mesh when using collision engine (default is (0.5, 1, 0.5))
  19838. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19839. */
  19840. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  19841. /**
  19842. * Gets or sets the ellipsoid offset used to impersonate this mesh when using collision engine (default is (0, 0, 0))
  19843. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  19844. */
  19845. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  19846. _this._oldPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19847. _this._diffPositionForCollisions = new BABYLON.Vector3(0, 0, 0);
  19848. // Edges
  19849. /**
  19850. * Defines edge width used when edgesRenderer is enabled
  19851. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19852. */
  19853. _this.edgesWidth = 1;
  19854. /**
  19855. * Defines edge color used when edgesRenderer is enabled
  19856. * @see https://www.babylonjs-playground.com/#10OJSG#13
  19857. */
  19858. _this.edgesColor = new BABYLON.Color4(1, 0, 0, 1);
  19859. // Cache
  19860. _this._collisionsTransformMatrix = BABYLON.Matrix.Zero();
  19861. _this._collisionsScalingMatrix = BABYLON.Matrix.Zero();
  19862. /** @hidden */
  19863. _this._renderId = 0;
  19864. /** @hidden */
  19865. _this._intersectionsInProgress = new Array();
  19866. /** @hidden */
  19867. _this._unIndexed = false;
  19868. /** @hidden */
  19869. _this._lightSources = new Array();
  19870. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  19871. if (collidedMesh === void 0) { collidedMesh = null; }
  19872. //TODO move this to the collision coordinator!
  19873. if (_this.getScene().workerCollisions)
  19874. newPosition.multiplyInPlace(_this._collider._radius);
  19875. newPosition.subtractToRef(_this._oldPositionForCollisions, _this._diffPositionForCollisions);
  19876. if (_this._diffPositionForCollisions.length() > BABYLON.Engine.CollisionsEpsilon) {
  19877. _this.position.addInPlace(_this._diffPositionForCollisions);
  19878. }
  19879. if (collidedMesh) {
  19880. _this.onCollideObservable.notifyObservers(collidedMesh);
  19881. }
  19882. _this.onCollisionPositionChangeObservable.notifyObservers(_this.position);
  19883. };
  19884. _this.getScene().addMesh(_this);
  19885. _this._resyncLightSources();
  19886. return _this;
  19887. }
  19888. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_NONE", {
  19889. /**
  19890. * No billboard
  19891. */
  19892. get: function () {
  19893. return BABYLON.TransformNode.BILLBOARDMODE_NONE;
  19894. },
  19895. enumerable: true,
  19896. configurable: true
  19897. });
  19898. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_X", {
  19899. /** Billboard on X axis */
  19900. get: function () {
  19901. return BABYLON.TransformNode.BILLBOARDMODE_X;
  19902. },
  19903. enumerable: true,
  19904. configurable: true
  19905. });
  19906. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Y", {
  19907. /** Billboard on Y axis */
  19908. get: function () {
  19909. return BABYLON.TransformNode.BILLBOARDMODE_Y;
  19910. },
  19911. enumerable: true,
  19912. configurable: true
  19913. });
  19914. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_Z", {
  19915. /** Billboard on Z axis */
  19916. get: function () {
  19917. return BABYLON.TransformNode.BILLBOARDMODE_Z;
  19918. },
  19919. enumerable: true,
  19920. configurable: true
  19921. });
  19922. Object.defineProperty(AbstractMesh, "BILLBOARDMODE_ALL", {
  19923. /** Billboard on all axes */
  19924. get: function () {
  19925. return BABYLON.TransformNode.BILLBOARDMODE_ALL;
  19926. },
  19927. enumerable: true,
  19928. configurable: true
  19929. });
  19930. Object.defineProperty(AbstractMesh.prototype, "facetNb", {
  19931. /**
  19932. * Gets the number of facets in the mesh
  19933. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  19934. */
  19935. get: function () {
  19936. return this._facetNb;
  19937. },
  19938. enumerable: true,
  19939. configurable: true
  19940. });
  19941. Object.defineProperty(AbstractMesh.prototype, "partitioningSubdivisions", {
  19942. /**
  19943. * Gets or set the number (integer) of subdivisions per axis in the partioning space
  19944. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19945. */
  19946. get: function () {
  19947. return this._partitioningSubdivisions;
  19948. },
  19949. set: function (nb) {
  19950. this._partitioningSubdivisions = nb;
  19951. },
  19952. enumerable: true,
  19953. configurable: true
  19954. });
  19955. Object.defineProperty(AbstractMesh.prototype, "partitioningBBoxRatio", {
  19956. /**
  19957. * The ratio (float) to apply to the bouding box size to set to the partioning space.
  19958. * Ex : 1.01 (default) the partioning space is 1% bigger than the bounding box
  19959. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#tweaking-the-partitioning
  19960. */
  19961. get: function () {
  19962. return this._partitioningBBoxRatio;
  19963. },
  19964. set: function (ratio) {
  19965. this._partitioningBBoxRatio = ratio;
  19966. },
  19967. enumerable: true,
  19968. configurable: true
  19969. });
  19970. Object.defineProperty(AbstractMesh.prototype, "mustDepthSortFacets", {
  19971. /**
  19972. * Gets or sets a boolean indicating that the facets must be depth sorted on next call to `updateFacetData()`.
  19973. * Works only for updatable meshes.
  19974. * Doesn't work with multi-materials
  19975. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19976. */
  19977. get: function () {
  19978. return this._facetDepthSort;
  19979. },
  19980. set: function (sort) {
  19981. this._facetDepthSort = sort;
  19982. },
  19983. enumerable: true,
  19984. configurable: true
  19985. });
  19986. Object.defineProperty(AbstractMesh.prototype, "facetDepthSortFrom", {
  19987. /**
  19988. * The location (Vector3) where the facet depth sort must be computed from.
  19989. * By default, the active camera position.
  19990. * Used only when facet depth sort is enabled
  19991. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#facet-depth-sort
  19992. */
  19993. get: function () {
  19994. return this._facetDepthSortFrom;
  19995. },
  19996. set: function (location) {
  19997. this._facetDepthSortFrom = location;
  19998. },
  19999. enumerable: true,
  20000. configurable: true
  20001. });
  20002. Object.defineProperty(AbstractMesh.prototype, "isFacetDataEnabled", {
  20003. /**
  20004. * gets a boolean indicating if facetData is enabled
  20005. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata#what-is-a-mesh-facet
  20006. */
  20007. get: function () {
  20008. return this._facetDataEnabled;
  20009. },
  20010. enumerable: true,
  20011. configurable: true
  20012. });
  20013. /** @hidden */
  20014. AbstractMesh.prototype._updateNonUniformScalingState = function (value) {
  20015. if (!_super.prototype._updateNonUniformScalingState.call(this, value)) {
  20016. return false;
  20017. }
  20018. this._markSubMeshesAsMiscDirty();
  20019. return true;
  20020. };
  20021. Object.defineProperty(AbstractMesh.prototype, "onCollide", {
  20022. /** Set a function to call when this mesh collides with another one */
  20023. set: function (callback) {
  20024. if (this._onCollideObserver) {
  20025. this.onCollideObservable.remove(this._onCollideObserver);
  20026. }
  20027. this._onCollideObserver = this.onCollideObservable.add(callback);
  20028. },
  20029. enumerable: true,
  20030. configurable: true
  20031. });
  20032. Object.defineProperty(AbstractMesh.prototype, "onCollisionPositionChange", {
  20033. /** Set a function to call when the collision's position changes */
  20034. set: function (callback) {
  20035. if (this._onCollisionPositionChangeObserver) {
  20036. this.onCollisionPositionChangeObservable.remove(this._onCollisionPositionChangeObserver);
  20037. }
  20038. this._onCollisionPositionChangeObserver = this.onCollisionPositionChangeObservable.add(callback);
  20039. },
  20040. enumerable: true,
  20041. configurable: true
  20042. });
  20043. Object.defineProperty(AbstractMesh.prototype, "isOccluded", {
  20044. /**
  20045. * 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
  20046. * @see http://doc.babylonjs.com/features/occlusionquery
  20047. */
  20048. get: function () {
  20049. return this._isOccluded;
  20050. },
  20051. set: function (value) {
  20052. this._isOccluded = value;
  20053. },
  20054. enumerable: true,
  20055. configurable: true
  20056. });
  20057. Object.defineProperty(AbstractMesh.prototype, "isOcclusionQueryInProgress", {
  20058. /**
  20059. * Flag to check the progress status of the query
  20060. * @see http://doc.babylonjs.com/features/occlusionquery
  20061. */
  20062. get: function () {
  20063. return this._isOcclusionQueryInProgress;
  20064. },
  20065. enumerable: true,
  20066. configurable: true
  20067. });
  20068. Object.defineProperty(AbstractMesh.prototype, "visibility", {
  20069. /**
  20070. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20071. */
  20072. get: function () {
  20073. return this._visibility;
  20074. },
  20075. /**
  20076. * Gets or sets mesh visibility between 0 and 1 (default is 1)
  20077. */
  20078. set: function (value) {
  20079. if (this._visibility === value) {
  20080. return;
  20081. }
  20082. this._visibility = value;
  20083. this._markSubMeshesAsMiscDirty();
  20084. },
  20085. enumerable: true,
  20086. configurable: true
  20087. });
  20088. Object.defineProperty(AbstractMesh.prototype, "material", {
  20089. /** Gets or sets current material */
  20090. get: function () {
  20091. return this._material;
  20092. },
  20093. set: function (value) {
  20094. if (this._material === value) {
  20095. return;
  20096. }
  20097. this._material = value;
  20098. if (this.onMaterialChangedObservable.hasObservers) {
  20099. this.onMaterialChangedObservable.notifyObservers(this);
  20100. }
  20101. if (!this.subMeshes) {
  20102. return;
  20103. }
  20104. this._unBindEffect();
  20105. },
  20106. enumerable: true,
  20107. configurable: true
  20108. });
  20109. Object.defineProperty(AbstractMesh.prototype, "receiveShadows", {
  20110. /**
  20111. * Gets or sets a boolean indicating that this mesh can receive realtime shadows
  20112. * @see http://doc.babylonjs.com/babylon101/shadows
  20113. */
  20114. get: function () {
  20115. return this._receiveShadows;
  20116. },
  20117. set: function (value) {
  20118. if (this._receiveShadows === value) {
  20119. return;
  20120. }
  20121. this._receiveShadows = value;
  20122. this._markSubMeshesAsLightDirty();
  20123. },
  20124. enumerable: true,
  20125. configurable: true
  20126. });
  20127. Object.defineProperty(AbstractMesh.prototype, "hasVertexAlpha", {
  20128. /** Gets or sets a boolean indicating that this mesh contains vertex color data with alpha values */
  20129. get: function () {
  20130. return this._hasVertexAlpha;
  20131. },
  20132. set: function (value) {
  20133. if (this._hasVertexAlpha === value) {
  20134. return;
  20135. }
  20136. this._hasVertexAlpha = value;
  20137. this._markSubMeshesAsAttributesDirty();
  20138. this._markSubMeshesAsMiscDirty();
  20139. },
  20140. enumerable: true,
  20141. configurable: true
  20142. });
  20143. Object.defineProperty(AbstractMesh.prototype, "useVertexColors", {
  20144. /** Gets or sets a boolean indicating that this mesh needs to use vertex color data to render (if this kind of vertex data is available in the geometry) */
  20145. get: function () {
  20146. return this._useVertexColors;
  20147. },
  20148. set: function (value) {
  20149. if (this._useVertexColors === value) {
  20150. return;
  20151. }
  20152. this._useVertexColors = value;
  20153. this._markSubMeshesAsAttributesDirty();
  20154. },
  20155. enumerable: true,
  20156. configurable: true
  20157. });
  20158. Object.defineProperty(AbstractMesh.prototype, "computeBonesUsingShaders", {
  20159. /**
  20160. * Gets or sets a boolean indicating that bone animations must be computed by the CPU (false by default)
  20161. */
  20162. get: function () {
  20163. return this._computeBonesUsingShaders;
  20164. },
  20165. set: function (value) {
  20166. if (this._computeBonesUsingShaders === value) {
  20167. return;
  20168. }
  20169. this._computeBonesUsingShaders = value;
  20170. this._markSubMeshesAsAttributesDirty();
  20171. },
  20172. enumerable: true,
  20173. configurable: true
  20174. });
  20175. Object.defineProperty(AbstractMesh.prototype, "numBoneInfluencers", {
  20176. /** Gets or sets the number of allowed bone influences per vertex (4 by default) */
  20177. get: function () {
  20178. return this._numBoneInfluencers;
  20179. },
  20180. set: function (value) {
  20181. if (this._numBoneInfluencers === value) {
  20182. return;
  20183. }
  20184. this._numBoneInfluencers = value;
  20185. this._markSubMeshesAsAttributesDirty();
  20186. },
  20187. enumerable: true,
  20188. configurable: true
  20189. });
  20190. Object.defineProperty(AbstractMesh.prototype, "applyFog", {
  20191. /** Gets or sets a boolean indicating that this mesh will allow fog to be rendered on it (true by default) */
  20192. get: function () {
  20193. return this._applyFog;
  20194. },
  20195. set: function (value) {
  20196. if (this._applyFog === value) {
  20197. return;
  20198. }
  20199. this._applyFog = value;
  20200. this._markSubMeshesAsMiscDirty();
  20201. },
  20202. enumerable: true,
  20203. configurable: true
  20204. });
  20205. Object.defineProperty(AbstractMesh.prototype, "layerMask", {
  20206. /**
  20207. * Gets or sets the current layer mask (default is 0x0FFFFFFF)
  20208. * @see http://doc.babylonjs.com/how_to/layermasks_and_multi-cam_textures
  20209. */
  20210. get: function () {
  20211. return this._layerMask;
  20212. },
  20213. set: function (value) {
  20214. if (value === this._layerMask) {
  20215. return;
  20216. }
  20217. this._layerMask = value;
  20218. this._resyncLightSources();
  20219. },
  20220. enumerable: true,
  20221. configurable: true
  20222. });
  20223. Object.defineProperty(AbstractMesh.prototype, "collisionMask", {
  20224. /**
  20225. * Gets or sets a collision mask used to mask collisions (default is -1).
  20226. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20227. */
  20228. get: function () {
  20229. return this._collisionMask;
  20230. },
  20231. set: function (mask) {
  20232. this._collisionMask = !isNaN(mask) ? mask : -1;
  20233. },
  20234. enumerable: true,
  20235. configurable: true
  20236. });
  20237. Object.defineProperty(AbstractMesh.prototype, "collisionGroup", {
  20238. /**
  20239. * Gets or sets the current collision group mask (-1 by default).
  20240. * A collision between A and B will happen if A.collisionGroup & b.collisionMask !== 0
  20241. */
  20242. get: function () {
  20243. return this._collisionGroup;
  20244. },
  20245. set: function (mask) {
  20246. this._collisionGroup = !isNaN(mask) ? mask : -1;
  20247. },
  20248. enumerable: true,
  20249. configurable: true
  20250. });
  20251. Object.defineProperty(AbstractMesh.prototype, "_positions", {
  20252. /** @hidden */
  20253. get: function () {
  20254. return null;
  20255. },
  20256. enumerable: true,
  20257. configurable: true
  20258. });
  20259. Object.defineProperty(AbstractMesh.prototype, "skeleton", {
  20260. get: function () {
  20261. return this._skeleton;
  20262. },
  20263. /**
  20264. * Gets or sets a skeleton to apply skining transformations
  20265. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  20266. */
  20267. set: function (value) {
  20268. if (this._skeleton && this._skeleton.needInitialSkinMatrix) {
  20269. this._skeleton._unregisterMeshWithPoseMatrix(this);
  20270. }
  20271. if (value && value.needInitialSkinMatrix) {
  20272. value._registerMeshWithPoseMatrix(this);
  20273. }
  20274. this._skeleton = value;
  20275. if (!this._skeleton) {
  20276. this._bonesTransformMatrices = null;
  20277. }
  20278. this._markSubMeshesAsAttributesDirty();
  20279. },
  20280. enumerable: true,
  20281. configurable: true
  20282. });
  20283. /**
  20284. * Returns the string "AbstractMesh"
  20285. * @returns "AbstractMesh"
  20286. */
  20287. AbstractMesh.prototype.getClassName = function () {
  20288. return "AbstractMesh";
  20289. };
  20290. /**
  20291. * Gets a string representation of the current mesh
  20292. * @param fullDetails defines a boolean indicating if full details must be included
  20293. * @returns a string representation of the current mesh
  20294. */
  20295. AbstractMesh.prototype.toString = function (fullDetails) {
  20296. var ret = "Name: " + this.name + ", isInstance: " + (this instanceof BABYLON.InstancedMesh ? "YES" : "NO");
  20297. ret += ", # of submeshes: " + (this.subMeshes ? this.subMeshes.length : 0);
  20298. if (this._skeleton) {
  20299. ret += ", skeleton: " + this._skeleton.name;
  20300. }
  20301. if (fullDetails) {
  20302. ret += ", billboard mode: " + (["NONE", "X", "Y", null, "Z", null, null, "ALL"])[this.billboardMode];
  20303. ret += ", freeze wrld mat: " + (this._isWorldMatrixFrozen || this._waitingFreezeWorldMatrix ? "YES" : "NO");
  20304. }
  20305. return ret;
  20306. };
  20307. /** @hidden */
  20308. AbstractMesh.prototype._rebuild = function () {
  20309. if (this._occlusionQuery) {
  20310. this._occlusionQuery = null;
  20311. }
  20312. if (this._edgesRenderer) {
  20313. this._edgesRenderer._rebuild();
  20314. }
  20315. if (!this.subMeshes) {
  20316. return;
  20317. }
  20318. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20319. var subMesh = _a[_i];
  20320. subMesh._rebuild();
  20321. }
  20322. };
  20323. /** @hidden */
  20324. AbstractMesh.prototype._resyncLightSources = function () {
  20325. this._lightSources.length = 0;
  20326. for (var _i = 0, _a = this.getScene().lights; _i < _a.length; _i++) {
  20327. var light = _a[_i];
  20328. if (!light.isEnabled()) {
  20329. continue;
  20330. }
  20331. if (light.canAffectMesh(this)) {
  20332. this._lightSources.push(light);
  20333. }
  20334. }
  20335. this._markSubMeshesAsLightDirty();
  20336. };
  20337. /** @hidden */
  20338. AbstractMesh.prototype._resyncLighSource = function (light) {
  20339. var isIn = light.isEnabled() && light.canAffectMesh(this);
  20340. var index = this._lightSources.indexOf(light);
  20341. if (index === -1) {
  20342. if (!isIn) {
  20343. return;
  20344. }
  20345. this._lightSources.push(light);
  20346. }
  20347. else {
  20348. if (isIn) {
  20349. return;
  20350. }
  20351. this._lightSources.splice(index, 1);
  20352. }
  20353. this._markSubMeshesAsLightDirty();
  20354. };
  20355. /** @hidden */
  20356. AbstractMesh.prototype._unBindEffect = function () {
  20357. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20358. var subMesh = _a[_i];
  20359. subMesh.setEffect(null);
  20360. }
  20361. };
  20362. /** @hidden */
  20363. AbstractMesh.prototype._removeLightSource = function (light) {
  20364. var index = this._lightSources.indexOf(light);
  20365. if (index === -1) {
  20366. return;
  20367. }
  20368. this._lightSources.splice(index, 1);
  20369. this._markSubMeshesAsLightDirty();
  20370. };
  20371. AbstractMesh.prototype._markSubMeshesAsDirty = function (func) {
  20372. if (!this.subMeshes) {
  20373. return;
  20374. }
  20375. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20376. var subMesh = _a[_i];
  20377. if (subMesh._materialDefines) {
  20378. func(subMesh._materialDefines);
  20379. }
  20380. }
  20381. };
  20382. /** @hidden */
  20383. AbstractMesh.prototype._markSubMeshesAsLightDirty = function () {
  20384. this._markSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  20385. };
  20386. /** @hidden */
  20387. AbstractMesh.prototype._markSubMeshesAsAttributesDirty = function () {
  20388. this._markSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  20389. };
  20390. /** @hidden */
  20391. AbstractMesh.prototype._markSubMeshesAsMiscDirty = function () {
  20392. if (!this.subMeshes) {
  20393. return;
  20394. }
  20395. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  20396. var subMesh = _a[_i];
  20397. var material = subMesh.getMaterial();
  20398. if (material) {
  20399. material.markAsDirty(BABYLON.Material.MiscDirtyFlag);
  20400. }
  20401. }
  20402. };
  20403. Object.defineProperty(AbstractMesh.prototype, "scaling", {
  20404. /**
  20405. * Gets or sets a Vector3 depicting the mesh scaling along each local axis X, Y, Z. Default is (1.0, 1.0, 1.0)
  20406. */
  20407. get: function () {
  20408. return this._scaling;
  20409. },
  20410. set: function (newScaling) {
  20411. this._scaling = newScaling;
  20412. if (this.physicsImpostor) {
  20413. this.physicsImpostor.forceUpdate();
  20414. }
  20415. },
  20416. enumerable: true,
  20417. configurable: true
  20418. });
  20419. // Methods
  20420. /**
  20421. * Disables the mesh edge rendering mode
  20422. * @returns the currentAbstractMesh
  20423. */
  20424. AbstractMesh.prototype.disableEdgesRendering = function () {
  20425. if (this._edgesRenderer) {
  20426. this._edgesRenderer.dispose();
  20427. this._edgesRenderer = null;
  20428. }
  20429. return this;
  20430. };
  20431. /**
  20432. * Enables the edge rendering mode on the mesh.
  20433. * This mode makes the mesh edges visible
  20434. * @param epsilon defines the maximal distance between two angles to detect a face
  20435. * @param checkVerticesInsteadOfIndices indicates that we should check vertex list directly instead of faces
  20436. * @returns the currentAbstractMesh
  20437. * @see https://www.babylonjs-playground.com/#19O9TU#0
  20438. */
  20439. AbstractMesh.prototype.enableEdgesRendering = function (epsilon, checkVerticesInsteadOfIndices) {
  20440. if (epsilon === void 0) { epsilon = 0.95; }
  20441. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  20442. this.disableEdgesRendering();
  20443. this._edgesRenderer = new BABYLON.EdgesRenderer(this, epsilon, checkVerticesInsteadOfIndices);
  20444. return this;
  20445. };
  20446. Object.defineProperty(AbstractMesh.prototype, "edgesRenderer", {
  20447. /**
  20448. * Gets the edgesRenderer associated with the mesh
  20449. */
  20450. get: function () {
  20451. return this._edgesRenderer;
  20452. },
  20453. enumerable: true,
  20454. configurable: true
  20455. });
  20456. Object.defineProperty(AbstractMesh.prototype, "isBlocked", {
  20457. /**
  20458. * Returns true if the mesh is blocked. Implemented by child classes
  20459. */
  20460. get: function () {
  20461. return false;
  20462. },
  20463. enumerable: true,
  20464. configurable: true
  20465. });
  20466. /**
  20467. * Returns the mesh itself by default. Implemented by child classes
  20468. * @param camera defines the camera to use to pick the right LOD level
  20469. * @returns the currentAbstractMesh
  20470. */
  20471. AbstractMesh.prototype.getLOD = function (camera) {
  20472. return this;
  20473. };
  20474. /**
  20475. * Returns 0 by default. Implemented by child classes
  20476. * @returns an integer
  20477. */
  20478. AbstractMesh.prototype.getTotalVertices = function () {
  20479. return 0;
  20480. };
  20481. /**
  20482. * Returns null by default. Implemented by child classes
  20483. * @returns null
  20484. */
  20485. AbstractMesh.prototype.getIndices = function () {
  20486. return null;
  20487. };
  20488. /**
  20489. * Returns the array of the requested vertex data kind. Implemented by child classes
  20490. * @param kind defines the vertex data kind to use
  20491. * @returns null
  20492. */
  20493. AbstractMesh.prototype.getVerticesData = function (kind) {
  20494. return null;
  20495. };
  20496. /**
  20497. * Sets the vertex data of the mesh geometry for the requested `kind`.
  20498. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  20499. * Note that a new underlying VertexBuffer object is created each call.
  20500. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  20501. * @param kind defines vertex data kind:
  20502. * * BABYLON.VertexBuffer.PositionKind
  20503. * * BABYLON.VertexBuffer.UVKind
  20504. * * BABYLON.VertexBuffer.UV2Kind
  20505. * * BABYLON.VertexBuffer.UV3Kind
  20506. * * BABYLON.VertexBuffer.UV4Kind
  20507. * * BABYLON.VertexBuffer.UV5Kind
  20508. * * BABYLON.VertexBuffer.UV6Kind
  20509. * * BABYLON.VertexBuffer.ColorKind
  20510. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20511. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20512. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20513. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20514. * @param data defines the data source
  20515. * @param updatable defines if the data must be flagged as updatable (or static)
  20516. * @param stride defines the vertex stride (size of an entire vertex). Can be null and in this case will be deduced from vertex data kind
  20517. * @returns the current mesh
  20518. */
  20519. AbstractMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  20520. return this;
  20521. };
  20522. /**
  20523. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  20524. * If the mesh has no geometry, it is simply returned as it is.
  20525. * @param kind defines vertex data kind:
  20526. * * BABYLON.VertexBuffer.PositionKind
  20527. * * BABYLON.VertexBuffer.UVKind
  20528. * * BABYLON.VertexBuffer.UV2Kind
  20529. * * BABYLON.VertexBuffer.UV3Kind
  20530. * * BABYLON.VertexBuffer.UV4Kind
  20531. * * BABYLON.VertexBuffer.UV5Kind
  20532. * * BABYLON.VertexBuffer.UV6Kind
  20533. * * BABYLON.VertexBuffer.ColorKind
  20534. * * BABYLON.VertexBuffer.MatricesIndicesKind
  20535. * * BABYLON.VertexBuffer.MatricesIndicesExtraKind
  20536. * * BABYLON.VertexBuffer.MatricesWeightsKind
  20537. * * BABYLON.VertexBuffer.MatricesWeightsExtraKind
  20538. * @param data defines the data source
  20539. * @param updateExtends If `kind` is `PositionKind` and if `updateExtends` is true, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed
  20540. * @param makeItUnique If true, a new global geometry is created from this data and is set to the mesh
  20541. * @returns the current mesh
  20542. */
  20543. AbstractMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  20544. return this;
  20545. };
  20546. /**
  20547. * Sets the mesh indices,
  20548. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  20549. * @param indices Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  20550. * @param totalVertices Defines the total number of vertices
  20551. * @returns the current mesh
  20552. */
  20553. AbstractMesh.prototype.setIndices = function (indices, totalVertices) {
  20554. return this;
  20555. };
  20556. /**
  20557. * Gets a boolean indicating if specific vertex data is present
  20558. * @param kind defines the vertex data kind to use
  20559. * @returns true is data kind is present
  20560. */
  20561. AbstractMesh.prototype.isVerticesDataPresent = function (kind) {
  20562. return false;
  20563. };
  20564. /**
  20565. * Returns the mesh BoundingInfo object or creates a new one and returns if it was undefined
  20566. * @returns a BoundingInfo
  20567. */
  20568. AbstractMesh.prototype.getBoundingInfo = function () {
  20569. if (this._masterMesh) {
  20570. return this._masterMesh.getBoundingInfo();
  20571. }
  20572. if (!this._boundingInfo) {
  20573. // this._boundingInfo is being created here
  20574. this._updateBoundingInfo();
  20575. }
  20576. // cannot be null.
  20577. return this._boundingInfo;
  20578. };
  20579. /**
  20580. * Uniformly scales the mesh to fit inside of a unit cube (1 X 1 X 1 units)
  20581. * @param includeDescendants Use the hierarchy's bounding box instead of the mesh's bounding box
  20582. * @returns the current mesh
  20583. */
  20584. AbstractMesh.prototype.normalizeToUnitCube = function (includeDescendants) {
  20585. if (includeDescendants === void 0) { includeDescendants = true; }
  20586. var boundingVectors = this.getHierarchyBoundingVectors(includeDescendants);
  20587. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  20588. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  20589. if (maxDimension === 0) {
  20590. return this;
  20591. }
  20592. var scale = 1 / maxDimension;
  20593. this.scaling.scaleInPlace(scale);
  20594. return this;
  20595. };
  20596. /**
  20597. * Overwrite the current bounding info
  20598. * @param boundingInfo defines the new bounding info
  20599. * @returns the current mesh
  20600. */
  20601. AbstractMesh.prototype.setBoundingInfo = function (boundingInfo) {
  20602. this._boundingInfo = boundingInfo;
  20603. return this;
  20604. };
  20605. Object.defineProperty(AbstractMesh.prototype, "useBones", {
  20606. /** Gets a boolean indicating if this mesh has skinning data and an attached skeleton */
  20607. get: function () {
  20608. return (this.skeleton && this.getScene().skeletonsEnabled && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind) && this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind));
  20609. },
  20610. enumerable: true,
  20611. configurable: true
  20612. });
  20613. /** @hidden */
  20614. AbstractMesh.prototype._preActivate = function () {
  20615. };
  20616. /** @hidden */
  20617. AbstractMesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  20618. };
  20619. /** @hidden */
  20620. AbstractMesh.prototype._activate = function (renderId) {
  20621. this._renderId = renderId;
  20622. };
  20623. /**
  20624. * Gets the current world matrix
  20625. * @returns a Matrix
  20626. */
  20627. AbstractMesh.prototype.getWorldMatrix = function () {
  20628. if (this._masterMesh) {
  20629. return this._masterMesh.getWorldMatrix();
  20630. }
  20631. return _super.prototype.getWorldMatrix.call(this);
  20632. };
  20633. /** @hidden */
  20634. AbstractMesh.prototype._getWorldMatrixDeterminant = function () {
  20635. if (this._masterMesh) {
  20636. return this._masterMesh._getWorldMatrixDeterminant();
  20637. }
  20638. return _super.prototype._getWorldMatrixDeterminant.call(this);
  20639. };
  20640. // ================================== Point of View Movement =================================
  20641. /**
  20642. * Perform relative position change from the point of view of behind the front of the mesh.
  20643. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20644. * Supports definition of mesh facing forward or backward
  20645. * @param amountRight defines the distance on the right axis
  20646. * @param amountUp defines the distance on the up axis
  20647. * @param amountForward defines the distance on the forward axis
  20648. * @returns the current mesh
  20649. */
  20650. AbstractMesh.prototype.movePOV = function (amountRight, amountUp, amountForward) {
  20651. this.position.addInPlace(this.calcMovePOV(amountRight, amountUp, amountForward));
  20652. return this;
  20653. };
  20654. /**
  20655. * Calculate relative position change from the point of view of behind the front of the mesh.
  20656. * This is performed taking into account the meshes current rotation, so you do not have to care.
  20657. * Supports definition of mesh facing forward or backward
  20658. * @param amountRight defines the distance on the right axis
  20659. * @param amountUp defines the distance on the up axis
  20660. * @param amountForward defines the distance on the forward axis
  20661. * @returns the new displacement vector
  20662. */
  20663. AbstractMesh.prototype.calcMovePOV = function (amountRight, amountUp, amountForward) {
  20664. var rotMatrix = new BABYLON.Matrix();
  20665. var rotQuaternion = (this.rotationQuaternion) ? this.rotationQuaternion : BABYLON.Quaternion.RotationYawPitchRoll(this.rotation.y, this.rotation.x, this.rotation.z);
  20666. rotQuaternion.toRotationMatrix(rotMatrix);
  20667. var translationDelta = BABYLON.Vector3.Zero();
  20668. var defForwardMult = this.definedFacingForward ? -1 : 1;
  20669. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(amountRight * defForwardMult, amountUp, amountForward * defForwardMult, rotMatrix, translationDelta);
  20670. return translationDelta;
  20671. };
  20672. // ================================== Point of View Rotation =================================
  20673. /**
  20674. * Perform relative rotation change from the point of view of behind the front of the mesh.
  20675. * Supports definition of mesh facing forward or backward
  20676. * @param flipBack defines the flip
  20677. * @param twirlClockwise defines the twirl
  20678. * @param tiltRight defines the tilt
  20679. * @returns the current mesh
  20680. */
  20681. AbstractMesh.prototype.rotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20682. this.rotation.addInPlace(this.calcRotatePOV(flipBack, twirlClockwise, tiltRight));
  20683. return this;
  20684. };
  20685. /**
  20686. * Calculate relative rotation change from the point of view of behind the front of the mesh.
  20687. * Supports definition of mesh facing forward or backward.
  20688. * @param flipBack defines the flip
  20689. * @param twirlClockwise defines the twirl
  20690. * @param tiltRight defines the tilt
  20691. * @returns the new rotation vector
  20692. */
  20693. AbstractMesh.prototype.calcRotatePOV = function (flipBack, twirlClockwise, tiltRight) {
  20694. var defForwardMult = this.definedFacingForward ? 1 : -1;
  20695. return new BABYLON.Vector3(flipBack * defForwardMult, twirlClockwise, tiltRight * defForwardMult);
  20696. };
  20697. /**
  20698. * Return the minimum and maximum world vectors of the entire hierarchy under current mesh
  20699. * @param includeDescendants Include bounding info from descendants as well (true by default)
  20700. * @param predicate defines a callback function that can be customize to filter what meshes should be included in the list used to compute the bounding vectors
  20701. * @returns the new bounding vectors
  20702. */
  20703. AbstractMesh.prototype.getHierarchyBoundingVectors = function (includeDescendants, predicate) {
  20704. if (includeDescendants === void 0) { includeDescendants = true; }
  20705. if (predicate === void 0) { predicate = null; }
  20706. // Ensures that all world matrix will be recomputed.
  20707. this.getScene().incrementRenderId();
  20708. this.computeWorldMatrix(true);
  20709. var min;
  20710. var max;
  20711. var boundingInfo = this.getBoundingInfo();
  20712. if (!this.subMeshes) {
  20713. min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  20714. max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  20715. }
  20716. else {
  20717. min = boundingInfo.boundingBox.minimumWorld;
  20718. max = boundingInfo.boundingBox.maximumWorld;
  20719. }
  20720. if (includeDescendants) {
  20721. var descendants = this.getDescendants(false);
  20722. for (var _i = 0, descendants_1 = descendants; _i < descendants_1.length; _i++) {
  20723. var descendant = descendants_1[_i];
  20724. var childMesh = descendant;
  20725. childMesh.computeWorldMatrix(true);
  20726. // Filters meshes based on custom predicate function.
  20727. if (predicate && !predicate(childMesh)) {
  20728. continue;
  20729. }
  20730. //make sure we have the needed params to get mix and max
  20731. if (!childMesh.getBoundingInfo || childMesh.getTotalVertices() === 0) {
  20732. continue;
  20733. }
  20734. var childBoundingInfo = childMesh.getBoundingInfo();
  20735. var boundingBox = childBoundingInfo.boundingBox;
  20736. var minBox = boundingBox.minimumWorld;
  20737. var maxBox = boundingBox.maximumWorld;
  20738. BABYLON.Tools.CheckExtends(minBox, min, max);
  20739. BABYLON.Tools.CheckExtends(maxBox, min, max);
  20740. }
  20741. }
  20742. return {
  20743. min: min,
  20744. max: max
  20745. };
  20746. };
  20747. /** @hidden */
  20748. AbstractMesh.prototype._updateBoundingInfo = function () {
  20749. this._boundingInfo = this._boundingInfo || new BABYLON.BoundingInfo(this.absolutePosition, this.absolutePosition);
  20750. this._boundingInfo.update(this.worldMatrixFromCache);
  20751. this._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  20752. return this;
  20753. };
  20754. /** @hidden */
  20755. AbstractMesh.prototype._updateSubMeshesBoundingInfo = function (matrix) {
  20756. if (!this.subMeshes) {
  20757. return this;
  20758. }
  20759. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  20760. var subMesh = this.subMeshes[subIndex];
  20761. if (!subMesh.IsGlobal) {
  20762. subMesh.updateBoundingInfo(matrix);
  20763. }
  20764. }
  20765. return this;
  20766. };
  20767. /** @hidden */
  20768. AbstractMesh.prototype._afterComputeWorldMatrix = function () {
  20769. // Bounding info
  20770. this._updateBoundingInfo();
  20771. };
  20772. /**
  20773. * Returns `true` if the mesh is within the frustum defined by the passed array of planes.
  20774. * A mesh is in the frustum if its bounding box intersects the frustum
  20775. * @param frustumPlanes defines the frustum to test
  20776. * @returns true if the mesh is in the frustum planes
  20777. */
  20778. AbstractMesh.prototype.isInFrustum = function (frustumPlanes) {
  20779. return this._boundingInfo !== null && this._boundingInfo.isInFrustum(frustumPlanes);
  20780. };
  20781. /**
  20782. * Returns `true` if the mesh is completely in the frustum defined be the passed array of planes.
  20783. * A mesh is completely in the frustum if its bounding box it completely inside the frustum.
  20784. * @param frustumPlanes defines the frustum to test
  20785. * @returns true if the mesh is completely in the frustum planes
  20786. */
  20787. AbstractMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  20788. return this._boundingInfo !== null && this._boundingInfo.isCompletelyInFrustum(frustumPlanes);
  20789. };
  20790. /**
  20791. * True if the mesh intersects another mesh or a SolidParticle object
  20792. * @param mesh defines a target mesh or SolidParticle to test
  20793. * @param precise Unless the parameter `precise` is set to `true` the intersection is computed according to Axis Aligned Bounding Boxes (AABB), else according to OBB (Oriented BBoxes)
  20794. * @param includeDescendants Can be set to true to test if the mesh defined in parameters intersects with the current mesh or any child meshes
  20795. * @returns true if there is an intersection
  20796. */
  20797. AbstractMesh.prototype.intersectsMesh = function (mesh, precise, includeDescendants) {
  20798. if (precise === void 0) { precise = false; }
  20799. if (!this._boundingInfo || !mesh._boundingInfo) {
  20800. return false;
  20801. }
  20802. if (this._boundingInfo.intersects(mesh._boundingInfo, precise)) {
  20803. return true;
  20804. }
  20805. if (includeDescendants) {
  20806. for (var _i = 0, _a = this.getChildMeshes(); _i < _a.length; _i++) {
  20807. var child = _a[_i];
  20808. if (child.intersectsMesh(mesh, precise, true)) {
  20809. return true;
  20810. }
  20811. }
  20812. }
  20813. return false;
  20814. };
  20815. /**
  20816. * Returns true if the passed point (Vector3) is inside the mesh bounding box
  20817. * @param point defines the point to test
  20818. * @returns true if there is an intersection
  20819. */
  20820. AbstractMesh.prototype.intersectsPoint = function (point) {
  20821. if (!this._boundingInfo) {
  20822. return false;
  20823. }
  20824. return this._boundingInfo.intersectsPoint(point);
  20825. };
  20826. /**
  20827. * Gets the current physics impostor
  20828. * @see http://doc.babylonjs.com/features/physics_engine
  20829. * @returns a physics impostor or null
  20830. */
  20831. AbstractMesh.prototype.getPhysicsImpostor = function () {
  20832. return this.physicsImpostor;
  20833. };
  20834. /**
  20835. * Gets the position of the current mesh in camera space
  20836. * @param camera defines the camera to use
  20837. * @returns a position
  20838. */
  20839. AbstractMesh.prototype.getPositionInCameraSpace = function (camera) {
  20840. if (camera === void 0) { camera = null; }
  20841. if (!camera) {
  20842. camera = this.getScene().activeCamera;
  20843. }
  20844. return BABYLON.Vector3.TransformCoordinates(this.absolutePosition, camera.getViewMatrix());
  20845. };
  20846. /**
  20847. * Returns the distance from the mesh to the active camera
  20848. * @param camera defines the camera to use
  20849. * @returns the distance
  20850. */
  20851. AbstractMesh.prototype.getDistanceToCamera = function (camera) {
  20852. if (camera === void 0) { camera = null; }
  20853. if (!camera) {
  20854. camera = this.getScene().activeCamera;
  20855. }
  20856. return this.absolutePosition.subtract(camera.position).length();
  20857. };
  20858. /**
  20859. * Apply a physic impulse to the mesh
  20860. * @param force defines the force to apply
  20861. * @param contactPoint defines where to apply the force
  20862. * @returns the current mesh
  20863. * @see http://doc.babylonjs.com/how_to/using_the_physics_engine
  20864. */
  20865. AbstractMesh.prototype.applyImpulse = function (force, contactPoint) {
  20866. if (!this.physicsImpostor) {
  20867. return this;
  20868. }
  20869. this.physicsImpostor.applyImpulse(force, contactPoint);
  20870. return this;
  20871. };
  20872. /**
  20873. * Creates a physic joint between two meshes
  20874. * @param otherMesh defines the other mesh to use
  20875. * @param pivot1 defines the pivot to use on this mesh
  20876. * @param pivot2 defines the pivot to use on the other mesh
  20877. * @param options defines additional options (can be plugin dependent)
  20878. * @returns the current mesh
  20879. * @see https://www.babylonjs-playground.com/#0BS5U0#0
  20880. */
  20881. AbstractMesh.prototype.setPhysicsLinkWith = function (otherMesh, pivot1, pivot2, options) {
  20882. if (!this.physicsImpostor || !otherMesh.physicsImpostor) {
  20883. return this;
  20884. }
  20885. this.physicsImpostor.createJoint(otherMesh.physicsImpostor, BABYLON.PhysicsJoint.HingeJoint, {
  20886. mainPivot: pivot1,
  20887. connectedPivot: pivot2,
  20888. nativeParams: options
  20889. });
  20890. return this;
  20891. };
  20892. Object.defineProperty(AbstractMesh.prototype, "checkCollisions", {
  20893. // Collisions
  20894. /**
  20895. * Gets or sets a boolean indicating that this mesh can be used in the collision engine
  20896. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20897. */
  20898. get: function () {
  20899. return this._checkCollisions;
  20900. },
  20901. set: function (collisionEnabled) {
  20902. this._checkCollisions = collisionEnabled;
  20903. if (this.getScene().workerCollisions) {
  20904. this.getScene().collisionCoordinator.onMeshUpdated(this);
  20905. }
  20906. },
  20907. enumerable: true,
  20908. configurable: true
  20909. });
  20910. Object.defineProperty(AbstractMesh.prototype, "collider", {
  20911. /**
  20912. * Gets Collider object used to compute collisions (not physics)
  20913. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20914. */
  20915. get: function () {
  20916. return this._collider;
  20917. },
  20918. enumerable: true,
  20919. configurable: true
  20920. });
  20921. /**
  20922. * Move the mesh using collision engine
  20923. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  20924. * @param displacement defines the requested displacement vector
  20925. * @returns the current mesh
  20926. */
  20927. AbstractMesh.prototype.moveWithCollisions = function (displacement) {
  20928. var globalPosition = this.getAbsolutePosition();
  20929. globalPosition.addToRef(this.ellipsoidOffset, this._oldPositionForCollisions);
  20930. if (!this._collider) {
  20931. this._collider = new BABYLON.Collider();
  20932. }
  20933. this._collider._radius = this.ellipsoid;
  20934. this.getScene().collisionCoordinator.getNewPosition(this._oldPositionForCollisions, displacement, this._collider, 3, this, this._onCollisionPositionChange, this.uniqueId);
  20935. return this;
  20936. };
  20937. // Submeshes octree
  20938. /**
  20939. * This function will create an octree to help to select the right submeshes for rendering, picking and collision computations.
  20940. * Please note that you must have a decent number of submeshes to get performance improvements when using an octree
  20941. * @param maxCapacity defines the maximum size of each block (64 by default)
  20942. * @param maxDepth defines the maximum depth to use (no more than 2 levels by default)
  20943. * @returns the new octree
  20944. * @see https://www.babylonjs-playground.com/#NA4OQ#12
  20945. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  20946. */
  20947. AbstractMesh.prototype.createOrUpdateSubmeshesOctree = function (maxCapacity, maxDepth) {
  20948. if (maxCapacity === void 0) { maxCapacity = 64; }
  20949. if (maxDepth === void 0) { maxDepth = 2; }
  20950. if (!this._submeshesOctree) {
  20951. this._submeshesOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForSubMeshes, maxCapacity, maxDepth);
  20952. }
  20953. this.computeWorldMatrix(true);
  20954. var boundingInfo = this.getBoundingInfo();
  20955. // Update octree
  20956. var bbox = boundingInfo.boundingBox;
  20957. this._submeshesOctree.update(bbox.minimumWorld, bbox.maximumWorld, this.subMeshes);
  20958. return this._submeshesOctree;
  20959. };
  20960. // Collisions
  20961. /** @hidden */
  20962. AbstractMesh.prototype._collideForSubMesh = function (subMesh, transformMatrix, collider) {
  20963. this._generatePointsArray();
  20964. if (!this._positions) {
  20965. return this;
  20966. }
  20967. // Transformation
  20968. if (!subMesh._lastColliderWorldVertices || !subMesh._lastColliderTransformMatrix.equals(transformMatrix)) {
  20969. subMesh._lastColliderTransformMatrix = transformMatrix.clone();
  20970. subMesh._lastColliderWorldVertices = [];
  20971. subMesh._trianglePlanes = [];
  20972. var start = subMesh.verticesStart;
  20973. var end = (subMesh.verticesStart + subMesh.verticesCount);
  20974. for (var i = start; i < end; i++) {
  20975. subMesh._lastColliderWorldVertices.push(BABYLON.Vector3.TransformCoordinates(this._positions[i], transformMatrix));
  20976. }
  20977. }
  20978. // Collide
  20979. collider._collide(subMesh._trianglePlanes, subMesh._lastColliderWorldVertices, this.getIndices(), subMesh.indexStart, subMesh.indexStart + subMesh.indexCount, subMesh.verticesStart, !!subMesh.getMaterial());
  20980. if (collider.collisionFound) {
  20981. collider.collidedMesh = this;
  20982. }
  20983. return this;
  20984. };
  20985. /** @hidden */
  20986. AbstractMesh.prototype._processCollisionsForSubMeshes = function (collider, transformMatrix) {
  20987. var subMeshes;
  20988. var len;
  20989. // Octrees
  20990. if (this._submeshesOctree && this.useOctreeForCollisions) {
  20991. var radius = collider._velocityWorldLength + Math.max(collider._radius.x, collider._radius.y, collider._radius.z);
  20992. var intersections = this._submeshesOctree.intersects(collider._basePointWorld, radius);
  20993. len = intersections.length;
  20994. subMeshes = intersections.data;
  20995. }
  20996. else {
  20997. subMeshes = this.subMeshes;
  20998. len = subMeshes.length;
  20999. }
  21000. for (var index = 0; index < len; index++) {
  21001. var subMesh = subMeshes[index];
  21002. // Bounding test
  21003. if (len > 1 && !subMesh._checkCollision(collider))
  21004. continue;
  21005. this._collideForSubMesh(subMesh, transformMatrix, collider);
  21006. }
  21007. return this;
  21008. };
  21009. /** @hidden */
  21010. AbstractMesh.prototype._checkCollision = function (collider) {
  21011. // Bounding box test
  21012. if (!this._boundingInfo || !this._boundingInfo._checkCollision(collider))
  21013. return this;
  21014. // Transformation matrix
  21015. BABYLON.Matrix.ScalingToRef(1.0 / collider._radius.x, 1.0 / collider._radius.y, 1.0 / collider._radius.z, this._collisionsScalingMatrix);
  21016. this.worldMatrixFromCache.multiplyToRef(this._collisionsScalingMatrix, this._collisionsTransformMatrix);
  21017. this._processCollisionsForSubMeshes(collider, this._collisionsTransformMatrix);
  21018. return this;
  21019. };
  21020. // Picking
  21021. /** @hidden */
  21022. AbstractMesh.prototype._generatePointsArray = function () {
  21023. return false;
  21024. };
  21025. /**
  21026. * Checks if the passed Ray intersects with the mesh
  21027. * @param ray defines the ray to use
  21028. * @param fastCheck defines if fast mode (but less precise) must be used (false by default)
  21029. * @returns the picking info
  21030. * @see http://doc.babylonjs.com/babylon101/intersect_collisions_-_mesh
  21031. */
  21032. AbstractMesh.prototype.intersects = function (ray, fastCheck) {
  21033. var pickingInfo = new BABYLON.PickingInfo();
  21034. if (!this.subMeshes || !this._boundingInfo || !ray.intersectsSphere(this._boundingInfo.boundingSphere) || !ray.intersectsBox(this._boundingInfo.boundingBox)) {
  21035. return pickingInfo;
  21036. }
  21037. if (!this._generatePointsArray()) {
  21038. return pickingInfo;
  21039. }
  21040. var intersectInfo = null;
  21041. // Octrees
  21042. var subMeshes;
  21043. var len;
  21044. if (this._submeshesOctree && this.useOctreeForPicking) {
  21045. var worldRay = BABYLON.Ray.Transform(ray, this.getWorldMatrix());
  21046. var intersections = this._submeshesOctree.intersectsRay(worldRay);
  21047. len = intersections.length;
  21048. subMeshes = intersections.data;
  21049. }
  21050. else {
  21051. subMeshes = this.subMeshes;
  21052. len = subMeshes.length;
  21053. }
  21054. for (var index = 0; index < len; index++) {
  21055. var subMesh = subMeshes[index];
  21056. // Bounding test
  21057. if (len > 1 && !subMesh.canIntersects(ray))
  21058. continue;
  21059. var currentIntersectInfo = subMesh.intersects(ray, this._positions, this.getIndices(), fastCheck);
  21060. if (currentIntersectInfo) {
  21061. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  21062. intersectInfo = currentIntersectInfo;
  21063. intersectInfo.subMeshId = index;
  21064. if (fastCheck) {
  21065. break;
  21066. }
  21067. }
  21068. }
  21069. }
  21070. if (intersectInfo) {
  21071. // Get picked point
  21072. var world = this.getWorldMatrix();
  21073. var worldOrigin = BABYLON.Vector3.TransformCoordinates(ray.origin, world);
  21074. var direction = ray.direction.clone();
  21075. direction = direction.scale(intersectInfo.distance);
  21076. var worldDirection = BABYLON.Vector3.TransformNormal(direction, world);
  21077. var pickedPoint = worldOrigin.add(worldDirection);
  21078. // Return result
  21079. pickingInfo.hit = true;
  21080. pickingInfo.distance = BABYLON.Vector3.Distance(worldOrigin, pickedPoint);
  21081. pickingInfo.pickedPoint = pickedPoint;
  21082. pickingInfo.pickedMesh = this;
  21083. pickingInfo.bu = intersectInfo.bu || 0;
  21084. pickingInfo.bv = intersectInfo.bv || 0;
  21085. pickingInfo.faceId = intersectInfo.faceId;
  21086. pickingInfo.subMeshId = intersectInfo.subMeshId;
  21087. return pickingInfo;
  21088. }
  21089. return pickingInfo;
  21090. };
  21091. /**
  21092. * Clones the current mesh
  21093. * @param name defines the mesh name
  21094. * @param newParent defines the new mesh parent
  21095. * @param doNotCloneChildren defines a boolean indicating that children must not be cloned (false by default)
  21096. * @returns the new mesh
  21097. */
  21098. AbstractMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  21099. return null;
  21100. };
  21101. /**
  21102. * Disposes all the submeshes of the current meshnp
  21103. * @returns the current mesh
  21104. */
  21105. AbstractMesh.prototype.releaseSubMeshes = function () {
  21106. if (this.subMeshes) {
  21107. while (this.subMeshes.length) {
  21108. this.subMeshes[0].dispose();
  21109. }
  21110. }
  21111. else {
  21112. this.subMeshes = new Array();
  21113. }
  21114. return this;
  21115. };
  21116. /**
  21117. * Releases resources associated with this abstract mesh.
  21118. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  21119. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  21120. */
  21121. AbstractMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  21122. var _this = this;
  21123. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  21124. var index;
  21125. // Smart Array Retainers.
  21126. this.getScene().freeActiveMeshes();
  21127. this.getScene().freeRenderingGroups();
  21128. // Action manager
  21129. if (this.actionManager !== undefined && this.actionManager !== null) {
  21130. this.actionManager.dispose();
  21131. this.actionManager = null;
  21132. }
  21133. // Skeleton
  21134. this._skeleton = null;
  21135. // Physics
  21136. if (this.physicsImpostor) {
  21137. this.physicsImpostor.dispose( /*!doNotRecurse*/);
  21138. }
  21139. // Intersections in progress
  21140. for (index = 0; index < this._intersectionsInProgress.length; index++) {
  21141. var other = this._intersectionsInProgress[index];
  21142. var pos = other._intersectionsInProgress.indexOf(this);
  21143. other._intersectionsInProgress.splice(pos, 1);
  21144. }
  21145. this._intersectionsInProgress = [];
  21146. // Lights
  21147. var lights = this.getScene().lights;
  21148. lights.forEach(function (light) {
  21149. var meshIndex = light.includedOnlyMeshes.indexOf(_this);
  21150. if (meshIndex !== -1) {
  21151. light.includedOnlyMeshes.splice(meshIndex, 1);
  21152. }
  21153. meshIndex = light.excludedMeshes.indexOf(_this);
  21154. if (meshIndex !== -1) {
  21155. light.excludedMeshes.splice(meshIndex, 1);
  21156. }
  21157. // Shadow generators
  21158. var generator = light.getShadowGenerator();
  21159. if (generator) {
  21160. var shadowMap = generator.getShadowMap();
  21161. if (shadowMap && shadowMap.renderList) {
  21162. meshIndex = shadowMap.renderList.indexOf(_this);
  21163. if (meshIndex !== -1) {
  21164. shadowMap.renderList.splice(meshIndex, 1);
  21165. }
  21166. }
  21167. }
  21168. });
  21169. // Edges
  21170. if (this._edgesRenderer) {
  21171. this._edgesRenderer.dispose();
  21172. this._edgesRenderer = null;
  21173. }
  21174. // SubMeshes
  21175. if (this.getClassName() !== "InstancedMesh") {
  21176. this.releaseSubMeshes();
  21177. }
  21178. // Octree
  21179. var sceneOctree = this.getScene().selectionOctree;
  21180. if (sceneOctree !== undefined && sceneOctree !== null) {
  21181. var index = sceneOctree.dynamicContent.indexOf(this);
  21182. if (index !== -1) {
  21183. sceneOctree.dynamicContent.splice(index, 1);
  21184. }
  21185. }
  21186. // Query
  21187. var engine = this.getScene().getEngine();
  21188. if (this._occlusionQuery) {
  21189. this._isOcclusionQueryInProgress = false;
  21190. engine.deleteQuery(this._occlusionQuery);
  21191. this._occlusionQuery = null;
  21192. }
  21193. // Engine
  21194. engine.wipeCaches();
  21195. // Remove from scene
  21196. this.getScene().removeMesh(this);
  21197. if (disposeMaterialAndTextures) {
  21198. if (this.material) {
  21199. this.material.dispose(false, true);
  21200. }
  21201. }
  21202. if (!doNotRecurse) {
  21203. // Particles
  21204. for (index = 0; index < this.getScene().particleSystems.length; index++) {
  21205. if (this.getScene().particleSystems[index].emitter === this) {
  21206. this.getScene().particleSystems[index].dispose();
  21207. index--;
  21208. }
  21209. }
  21210. }
  21211. // facet data
  21212. if (this._facetDataEnabled) {
  21213. this.disableFacetData();
  21214. }
  21215. this.onAfterWorldMatrixUpdateObservable.clear();
  21216. this.onCollideObservable.clear();
  21217. this.onCollisionPositionChangeObservable.clear();
  21218. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  21219. };
  21220. /**
  21221. * Adds the passed mesh as a child to the current mesh
  21222. * @param mesh defines the child mesh
  21223. * @returns the current mesh
  21224. */
  21225. AbstractMesh.prototype.addChild = function (mesh) {
  21226. mesh.setParent(this);
  21227. return this;
  21228. };
  21229. /**
  21230. * Removes the passed mesh from the current mesh children list
  21231. * @param mesh defines the child mesh
  21232. * @returns the current mesh
  21233. */
  21234. AbstractMesh.prototype.removeChild = function (mesh) {
  21235. mesh.setParent(null);
  21236. return this;
  21237. };
  21238. // Facet data
  21239. /** @hidden */
  21240. AbstractMesh.prototype._initFacetData = function () {
  21241. if (!this._facetNormals) {
  21242. this._facetNormals = new Array();
  21243. }
  21244. if (!this._facetPositions) {
  21245. this._facetPositions = new Array();
  21246. }
  21247. if (!this._facetPartitioning) {
  21248. this._facetPartitioning = new Array();
  21249. }
  21250. this._facetNb = (this.getIndices().length / 3) | 0;
  21251. this._partitioningSubdivisions = (this._partitioningSubdivisions) ? this._partitioningSubdivisions : 10; // default nb of partitioning subdivisions = 10
  21252. this._partitioningBBoxRatio = (this._partitioningBBoxRatio) ? this._partitioningBBoxRatio : 1.01; // default ratio 1.01 = the partitioning is 1% bigger than the bounding box
  21253. for (var f = 0; f < this._facetNb; f++) {
  21254. this._facetNormals[f] = BABYLON.Vector3.Zero();
  21255. this._facetPositions[f] = BABYLON.Vector3.Zero();
  21256. }
  21257. this._facetDataEnabled = true;
  21258. return this;
  21259. };
  21260. /**
  21261. * Updates the mesh facetData arrays and the internal partitioning when the mesh is morphed or updated.
  21262. * This method can be called within the render loop.
  21263. * 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
  21264. * @returns the current mesh
  21265. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21266. */
  21267. AbstractMesh.prototype.updateFacetData = function () {
  21268. if (!this._facetDataEnabled) {
  21269. this._initFacetData();
  21270. }
  21271. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21272. var indices = this.getIndices();
  21273. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21274. var bInfo = this.getBoundingInfo();
  21275. if (this._facetDepthSort && !this._facetDepthSortEnabled) {
  21276. // init arrays, matrix and sort function on first call
  21277. this._facetDepthSortEnabled = true;
  21278. if (indices instanceof Uint16Array) {
  21279. this._depthSortedIndices = new Uint16Array(indices);
  21280. }
  21281. else if (indices instanceof Uint32Array) {
  21282. this._depthSortedIndices = new Uint32Array(indices);
  21283. }
  21284. else {
  21285. var needs32bits = false;
  21286. for (var i = 0; i < indices.length; i++) {
  21287. if (indices[i] > 65535) {
  21288. needs32bits = true;
  21289. break;
  21290. }
  21291. }
  21292. if (needs32bits) {
  21293. this._depthSortedIndices = new Uint32Array(indices);
  21294. }
  21295. else {
  21296. this._depthSortedIndices = new Uint16Array(indices);
  21297. }
  21298. }
  21299. this._facetDepthSortFunction = function (f1, f2) {
  21300. return (f2.sqDistance - f1.sqDistance);
  21301. };
  21302. if (!this._facetDepthSortFrom) {
  21303. var camera = this.getScene().activeCamera;
  21304. this._facetDepthSortFrom = (camera) ? camera.position : BABYLON.Vector3.Zero();
  21305. }
  21306. this._depthSortedFacets = [];
  21307. for (var f = 0; f < this._facetNb; f++) {
  21308. var depthSortedFacet = { ind: f * 3, sqDistance: 0.0 };
  21309. this._depthSortedFacets.push(depthSortedFacet);
  21310. }
  21311. this._invertedMatrix = BABYLON.Matrix.Identity();
  21312. this._facetDepthSortOrigin = BABYLON.Vector3.Zero();
  21313. }
  21314. this._bbSize.x = (bInfo.maximum.x - bInfo.minimum.x > BABYLON.Epsilon) ? bInfo.maximum.x - bInfo.minimum.x : BABYLON.Epsilon;
  21315. this._bbSize.y = (bInfo.maximum.y - bInfo.minimum.y > BABYLON.Epsilon) ? bInfo.maximum.y - bInfo.minimum.y : BABYLON.Epsilon;
  21316. this._bbSize.z = (bInfo.maximum.z - bInfo.minimum.z > BABYLON.Epsilon) ? bInfo.maximum.z - bInfo.minimum.z : BABYLON.Epsilon;
  21317. var bbSizeMax = (this._bbSize.x > this._bbSize.y) ? this._bbSize.x : this._bbSize.y;
  21318. bbSizeMax = (bbSizeMax > this._bbSize.z) ? bbSizeMax : this._bbSize.z;
  21319. this._subDiv.max = this._partitioningSubdivisions;
  21320. this._subDiv.X = Math.floor(this._subDiv.max * this._bbSize.x / bbSizeMax); // adjust the number of subdivisions per axis
  21321. this._subDiv.Y = Math.floor(this._subDiv.max * this._bbSize.y / bbSizeMax); // according to each bbox size per axis
  21322. this._subDiv.Z = Math.floor(this._subDiv.max * this._bbSize.z / bbSizeMax);
  21323. this._subDiv.X = this._subDiv.X < 1 ? 1 : this._subDiv.X; // at least one subdivision
  21324. this._subDiv.Y = this._subDiv.Y < 1 ? 1 : this._subDiv.Y;
  21325. this._subDiv.Z = this._subDiv.Z < 1 ? 1 : this._subDiv.Z;
  21326. // set the parameters for ComputeNormals()
  21327. this._facetParameters.facetNormals = this.getFacetLocalNormals();
  21328. this._facetParameters.facetPositions = this.getFacetLocalPositions();
  21329. this._facetParameters.facetPartitioning = this.getFacetLocalPartitioning();
  21330. this._facetParameters.bInfo = bInfo;
  21331. this._facetParameters.bbSize = this._bbSize;
  21332. this._facetParameters.subDiv = this._subDiv;
  21333. this._facetParameters.ratio = this.partitioningBBoxRatio;
  21334. this._facetParameters.depthSort = this._facetDepthSort;
  21335. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21336. this.computeWorldMatrix(true);
  21337. this._worldMatrix.invertToRef(this._invertedMatrix);
  21338. BABYLON.Vector3.TransformCoordinatesToRef(this._facetDepthSortFrom, this._invertedMatrix, this._facetDepthSortOrigin);
  21339. this._facetParameters.distanceTo = this._facetDepthSortOrigin;
  21340. }
  21341. this._facetParameters.depthSortedFacets = this._depthSortedFacets;
  21342. BABYLON.VertexData.ComputeNormals(positions, indices, normals, this._facetParameters);
  21343. if (this._facetDepthSort && this._facetDepthSortEnabled) {
  21344. this._depthSortedFacets.sort(this._facetDepthSortFunction);
  21345. var l = (this._depthSortedIndices.length / 3) | 0;
  21346. for (var f = 0; f < l; f++) {
  21347. var sind = this._depthSortedFacets[f].ind;
  21348. this._depthSortedIndices[f * 3] = indices[sind];
  21349. this._depthSortedIndices[f * 3 + 1] = indices[sind + 1];
  21350. this._depthSortedIndices[f * 3 + 2] = indices[sind + 2];
  21351. }
  21352. this.updateIndices(this._depthSortedIndices);
  21353. }
  21354. return this;
  21355. };
  21356. /**
  21357. * Returns the facetLocalNormals array.
  21358. * The normals are expressed in the mesh local spac
  21359. * @returns an array of Vector3
  21360. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21361. */
  21362. AbstractMesh.prototype.getFacetLocalNormals = function () {
  21363. if (!this._facetNormals) {
  21364. this.updateFacetData();
  21365. }
  21366. return this._facetNormals;
  21367. };
  21368. /**
  21369. * Returns the facetLocalPositions array.
  21370. * The facet positions are expressed in the mesh local space
  21371. * @returns an array of Vector3
  21372. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21373. */
  21374. AbstractMesh.prototype.getFacetLocalPositions = function () {
  21375. if (!this._facetPositions) {
  21376. this.updateFacetData();
  21377. }
  21378. return this._facetPositions;
  21379. };
  21380. /**
  21381. * Returns the facetLocalPartioning array
  21382. * @returns an array of array of numbers
  21383. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21384. */
  21385. AbstractMesh.prototype.getFacetLocalPartitioning = function () {
  21386. if (!this._facetPartitioning) {
  21387. this.updateFacetData();
  21388. }
  21389. return this._facetPartitioning;
  21390. };
  21391. /**
  21392. * Returns the i-th facet position in the world system.
  21393. * This method allocates a new Vector3 per call
  21394. * @param i defines the facet index
  21395. * @returns a new Vector3
  21396. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21397. */
  21398. AbstractMesh.prototype.getFacetPosition = function (i) {
  21399. var pos = BABYLON.Vector3.Zero();
  21400. this.getFacetPositionToRef(i, pos);
  21401. return pos;
  21402. };
  21403. /**
  21404. * Sets the reference Vector3 with the i-th facet position in the world system
  21405. * @param i defines the facet index
  21406. * @param ref defines the target vector
  21407. * @returns the current mesh
  21408. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21409. */
  21410. AbstractMesh.prototype.getFacetPositionToRef = function (i, ref) {
  21411. var localPos = (this.getFacetLocalPositions())[i];
  21412. var world = this.getWorldMatrix();
  21413. BABYLON.Vector3.TransformCoordinatesToRef(localPos, world, ref);
  21414. return this;
  21415. };
  21416. /**
  21417. * Returns the i-th facet normal in the world system.
  21418. * This method allocates a new Vector3 per call
  21419. * @param i defines the facet index
  21420. * @returns a new Vector3
  21421. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21422. */
  21423. AbstractMesh.prototype.getFacetNormal = function (i) {
  21424. var norm = BABYLON.Vector3.Zero();
  21425. this.getFacetNormalToRef(i, norm);
  21426. return norm;
  21427. };
  21428. /**
  21429. * Sets the reference Vector3 with the i-th facet normal in the world system
  21430. * @param i defines the facet index
  21431. * @param ref defines the target vector
  21432. * @returns the current mesh
  21433. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21434. */
  21435. AbstractMesh.prototype.getFacetNormalToRef = function (i, ref) {
  21436. var localNorm = (this.getFacetLocalNormals())[i];
  21437. BABYLON.Vector3.TransformNormalToRef(localNorm, this.getWorldMatrix(), ref);
  21438. return this;
  21439. };
  21440. /**
  21441. * 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)
  21442. * @param x defines x coordinate
  21443. * @param y defines y coordinate
  21444. * @param z defines z coordinate
  21445. * @returns the array of facet indexes
  21446. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21447. */
  21448. AbstractMesh.prototype.getFacetsAtLocalCoordinates = function (x, y, z) {
  21449. var bInfo = this.getBoundingInfo();
  21450. var ox = Math.floor((x - bInfo.minimum.x * this._partitioningBBoxRatio) * this._subDiv.X * this._partitioningBBoxRatio / this._bbSize.x);
  21451. var oy = Math.floor((y - bInfo.minimum.y * this._partitioningBBoxRatio) * this._subDiv.Y * this._partitioningBBoxRatio / this._bbSize.y);
  21452. var oz = Math.floor((z - bInfo.minimum.z * this._partitioningBBoxRatio) * this._subDiv.Z * this._partitioningBBoxRatio / this._bbSize.z);
  21453. if (ox < 0 || ox > this._subDiv.max || oy < 0 || oy > this._subDiv.max || oz < 0 || oz > this._subDiv.max) {
  21454. return null;
  21455. }
  21456. return this._facetPartitioning[ox + this._subDiv.max * oy + this._subDiv.max * this._subDiv.max * oz];
  21457. };
  21458. /**
  21459. * Returns the closest mesh facet index at (x,y,z) World coordinates, null if not found
  21460. * @param projected sets as the (x,y,z) world projection on the facet
  21461. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21462. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21463. * @param x defines x coordinate
  21464. * @param y defines y coordinate
  21465. * @param z defines z coordinate
  21466. * @returns the face index if found (or null instead)
  21467. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21468. */
  21469. AbstractMesh.prototype.getClosestFacetAtCoordinates = function (x, y, z, projected, checkFace, facing) {
  21470. if (checkFace === void 0) { checkFace = false; }
  21471. if (facing === void 0) { facing = true; }
  21472. var world = this.getWorldMatrix();
  21473. var invMat = BABYLON.Tmp.Matrix[5];
  21474. world.invertToRef(invMat);
  21475. var invVect = BABYLON.Tmp.Vector3[8];
  21476. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, invMat, invVect); // transform (x,y,z) to coordinates in the mesh local space
  21477. var closest = this.getClosestFacetAtLocalCoordinates(invVect.x, invVect.y, invVect.z, projected, checkFace, facing);
  21478. if (projected) {
  21479. // tranform the local computed projected vector to world coordinates
  21480. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(projected.x, projected.y, projected.z, world, projected);
  21481. }
  21482. return closest;
  21483. };
  21484. /**
  21485. * Returns the closest mesh facet index at (x,y,z) local coordinates, null if not found
  21486. * @param projected sets as the (x,y,z) local projection on the facet
  21487. * @param checkFace if true (default false), only the facet "facing" to (x,y,z) or only the ones "turning their backs", according to the parameter "facing" are returned
  21488. * @param facing if facing and checkFace are true, only the facet "facing" to (x, y, z) are returned : positive dot (x, y, z) * facet position. If facing si false and checkFace is true, only the facet "turning their backs" to (x, y, z) are returned : negative dot (x, y, z) * facet position
  21489. * @param x defines x coordinate
  21490. * @param y defines y coordinate
  21491. * @param z defines z coordinate
  21492. * @returns the face index if found (or null instead)
  21493. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21494. */
  21495. AbstractMesh.prototype.getClosestFacetAtLocalCoordinates = function (x, y, z, projected, checkFace, facing) {
  21496. if (checkFace === void 0) { checkFace = false; }
  21497. if (facing === void 0) { facing = true; }
  21498. var closest = null;
  21499. var tmpx = 0.0;
  21500. var tmpy = 0.0;
  21501. var tmpz = 0.0;
  21502. var d = 0.0; // tmp dot facet normal * facet position
  21503. var t0 = 0.0;
  21504. var projx = 0.0;
  21505. var projy = 0.0;
  21506. var projz = 0.0;
  21507. // Get all the facets in the same partitioning block than (x, y, z)
  21508. var facetPositions = this.getFacetLocalPositions();
  21509. var facetNormals = this.getFacetLocalNormals();
  21510. var facetsInBlock = this.getFacetsAtLocalCoordinates(x, y, z);
  21511. if (!facetsInBlock) {
  21512. return null;
  21513. }
  21514. // Get the closest facet to (x, y, z)
  21515. var shortest = Number.MAX_VALUE; // init distance vars
  21516. var tmpDistance = shortest;
  21517. var fib; // current facet in the block
  21518. var norm; // current facet normal
  21519. var p0; // current facet barycenter position
  21520. // loop on all the facets in the current partitioning block
  21521. for (var idx = 0; idx < facetsInBlock.length; idx++) {
  21522. fib = facetsInBlock[idx];
  21523. norm = facetNormals[fib];
  21524. p0 = facetPositions[fib];
  21525. d = (x - p0.x) * norm.x + (y - p0.y) * norm.y + (z - p0.z) * norm.z;
  21526. if (!checkFace || (checkFace && facing && d >= 0.0) || (checkFace && !facing && d <= 0.0)) {
  21527. // compute (x,y,z) projection on the facet = (projx, projy, projz)
  21528. d = norm.x * p0.x + norm.y * p0.y + norm.z * p0.z;
  21529. t0 = -(norm.x * x + norm.y * y + norm.z * z - d) / (norm.x * norm.x + norm.y * norm.y + norm.z * norm.z);
  21530. projx = x + norm.x * t0;
  21531. projy = y + norm.y * t0;
  21532. projz = z + norm.z * t0;
  21533. tmpx = projx - x;
  21534. tmpy = projy - y;
  21535. tmpz = projz - z;
  21536. tmpDistance = tmpx * tmpx + tmpy * tmpy + tmpz * tmpz; // compute length between (x, y, z) and its projection on the facet
  21537. if (tmpDistance < shortest) { // just keep the closest facet to (x, y, z)
  21538. shortest = tmpDistance;
  21539. closest = fib;
  21540. if (projected) {
  21541. projected.x = projx;
  21542. projected.y = projy;
  21543. projected.z = projz;
  21544. }
  21545. }
  21546. }
  21547. }
  21548. return closest;
  21549. };
  21550. /**
  21551. * Returns the object "parameter" set with all the expected parameters for facetData computation by ComputeNormals()
  21552. * @returns the parameters
  21553. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21554. */
  21555. AbstractMesh.prototype.getFacetDataParameters = function () {
  21556. return this._facetParameters;
  21557. };
  21558. /**
  21559. * Disables the feature FacetData and frees the related memory
  21560. * @returns the current mesh
  21561. * @see http://doc.babylonjs.com/how_to/how_to_use_facetdata
  21562. */
  21563. AbstractMesh.prototype.disableFacetData = function () {
  21564. if (this._facetDataEnabled) {
  21565. this._facetDataEnabled = false;
  21566. this._facetPositions = new Array();
  21567. this._facetNormals = new Array();
  21568. this._facetPartitioning = new Array();
  21569. this._facetParameters = null;
  21570. this._depthSortedIndices = new Uint32Array(0);
  21571. }
  21572. return this;
  21573. };
  21574. /**
  21575. * Updates the AbstractMesh indices array
  21576. * @param indices defines the data source
  21577. * @returns the current mesh
  21578. */
  21579. AbstractMesh.prototype.updateIndices = function (indices) {
  21580. return this;
  21581. };
  21582. /**
  21583. * Creates new normals data for the mesh
  21584. * @param updatable defines if the normal vertex buffer must be flagged as updatable
  21585. * @returns the current mesh
  21586. */
  21587. AbstractMesh.prototype.createNormals = function (updatable) {
  21588. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  21589. var indices = this.getIndices();
  21590. var normals;
  21591. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  21592. normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  21593. }
  21594. else {
  21595. normals = [];
  21596. }
  21597. BABYLON.VertexData.ComputeNormals(positions, indices, normals, { useRightHandedSystem: this.getScene().useRightHandedSystem });
  21598. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  21599. return this;
  21600. };
  21601. /**
  21602. * Align the mesh with a normal
  21603. * @param normal defines the normal to use
  21604. * @param upDirection can be used to redefined the up vector to use (will use the (0, 1, 0) by default)
  21605. * @returns the current mesh
  21606. */
  21607. AbstractMesh.prototype.alignWithNormal = function (normal, upDirection) {
  21608. if (!upDirection) {
  21609. upDirection = BABYLON.Axis.Y;
  21610. }
  21611. var axisX = BABYLON.Tmp.Vector3[0];
  21612. var axisZ = BABYLON.Tmp.Vector3[1];
  21613. BABYLON.Vector3.CrossToRef(upDirection, normal, axisZ);
  21614. BABYLON.Vector3.CrossToRef(normal, axisZ, axisX);
  21615. if (this.rotationQuaternion) {
  21616. BABYLON.Quaternion.RotationQuaternionFromAxisToRef(axisX, normal, axisZ, this.rotationQuaternion);
  21617. }
  21618. else {
  21619. BABYLON.Vector3.RotationFromAxisToRef(axisX, normal, axisZ, this.rotation);
  21620. }
  21621. return this;
  21622. };
  21623. /** @hidden */
  21624. AbstractMesh.prototype._checkOcclusionQuery = function () {
  21625. var engine = this.getEngine();
  21626. if (engine.webGLVersion < 2 || this.occlusionType === AbstractMesh.OCCLUSION_TYPE_NONE) {
  21627. this._isOccluded = false;
  21628. return;
  21629. }
  21630. if (this.isOcclusionQueryInProgress && this._occlusionQuery) {
  21631. var isOcclusionQueryAvailable = engine.isQueryResultAvailable(this._occlusionQuery);
  21632. if (isOcclusionQueryAvailable) {
  21633. var occlusionQueryResult = engine.getQueryResult(this._occlusionQuery);
  21634. this._isOcclusionQueryInProgress = false;
  21635. this._occlusionInternalRetryCounter = 0;
  21636. this._isOccluded = occlusionQueryResult === 1 ? false : true;
  21637. }
  21638. else {
  21639. this._occlusionInternalRetryCounter++;
  21640. if (this.occlusionRetryCount !== -1 && this._occlusionInternalRetryCounter > this.occlusionRetryCount) {
  21641. this._isOcclusionQueryInProgress = false;
  21642. this._occlusionInternalRetryCounter = 0;
  21643. // if optimistic set isOccluded to false regardless of the status of isOccluded. (Render in the current render loop)
  21644. // if strict continue the last state of the object.
  21645. this._isOccluded = this.occlusionType === AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC ? false : this._isOccluded;
  21646. }
  21647. else {
  21648. return;
  21649. }
  21650. }
  21651. }
  21652. var scene = this.getScene();
  21653. var occlusionBoundingBoxRenderer = scene.getBoundingBoxRenderer();
  21654. if (!this._occlusionQuery) {
  21655. this._occlusionQuery = engine.createQuery();
  21656. }
  21657. engine.beginOcclusionQuery(this.occlusionQueryAlgorithmType, this._occlusionQuery);
  21658. occlusionBoundingBoxRenderer.renderOcclusionBoundingBox(this);
  21659. engine.endOcclusionQuery(this.occlusionQueryAlgorithmType);
  21660. this._isOcclusionQueryInProgress = true;
  21661. };
  21662. /** No occlusion */
  21663. AbstractMesh.OCCLUSION_TYPE_NONE = 0;
  21664. /** Occlusion set to optimisitic */
  21665. AbstractMesh.OCCLUSION_TYPE_OPTIMISTIC = 1;
  21666. /** Occlusion set to strict */
  21667. AbstractMesh.OCCLUSION_TYPE_STRICT = 2;
  21668. /** Use an accurante occlusion algorithm */
  21669. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_ACCURATE = 0;
  21670. /** Use a conservative occlusion algorithm */
  21671. AbstractMesh.OCCLUSION_ALGORITHM_TYPE_CONSERVATIVE = 1;
  21672. return AbstractMesh;
  21673. }(BABYLON.TransformNode));
  21674. BABYLON.AbstractMesh = AbstractMesh;
  21675. })(BABYLON || (BABYLON = {}));
  21676. //# sourceMappingURL=babylon.abstractMesh.js.map
  21677. var BABYLON;
  21678. (function (BABYLON) {
  21679. /**
  21680. * Base class of all the lights in Babylon. It groups all the generic information about lights.
  21681. * Lights are used, as you would expect, to affect how meshes are seen, in terms of both illumination and colour.
  21682. * 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.
  21683. */
  21684. var Light = /** @class */ (function (_super) {
  21685. __extends(Light, _super);
  21686. /**
  21687. * Creates a Light object in the scene.
  21688. * Documentation : http://doc.babylonjs.com/tutorials/lights
  21689. * @param name The firendly name of the light
  21690. * @param scene The scene the light belongs too
  21691. */
  21692. function Light(name, scene) {
  21693. var _this = _super.call(this, name, scene) || this;
  21694. /**
  21695. * Diffuse gives the basic color to an object.
  21696. */
  21697. _this.diffuse = new BABYLON.Color3(1.0, 1.0, 1.0);
  21698. /**
  21699. * Specular produces a highlight color on an object.
  21700. * Note: This is note affecting PBR materials.
  21701. */
  21702. _this.specular = new BABYLON.Color3(1.0, 1.0, 1.0);
  21703. /**
  21704. * Strength of the light.
  21705. * Note: By default it is define in the framework own unit.
  21706. * Note: In PBR materials the intensityMode can be use to chose what unit the intensity is defined in.
  21707. */
  21708. _this.intensity = 1.0;
  21709. /**
  21710. * Defines how far from the source the light is impacting in scene units.
  21711. * Note: Unused in PBR material as the distance light falloff is defined following the inverse squared falloff.
  21712. */
  21713. _this.range = Number.MAX_VALUE;
  21714. /**
  21715. * Cached photometric scale default to 1.0 as the automatic intensity mode defaults to 1.0 for every type
  21716. * of light.
  21717. */
  21718. _this._photometricScale = 1.0;
  21719. _this._intensityMode = Light.INTENSITYMODE_AUTOMATIC;
  21720. _this._radius = 0.00001;
  21721. /**
  21722. * Defines the rendering priority of the lights. It can help in case of fallback or number of lights
  21723. * exceeding the number allowed of the materials.
  21724. */
  21725. _this.renderPriority = 0;
  21726. _this._shadowEnabled = true;
  21727. _this._excludeWithLayerMask = 0;
  21728. _this._includeOnlyWithLayerMask = 0;
  21729. _this._lightmapMode = 0;
  21730. /**
  21731. * @hidden Internal use only.
  21732. */
  21733. _this._excludedMeshesIds = new Array();
  21734. /**
  21735. * @hidden Internal use only.
  21736. */
  21737. _this._includedOnlyMeshesIds = new Array();
  21738. _this.getScene().addLight(_this);
  21739. _this._uniformBuffer = new BABYLON.UniformBuffer(_this.getScene().getEngine());
  21740. _this._buildUniformLayout();
  21741. _this.includedOnlyMeshes = new Array();
  21742. _this.excludedMeshes = new Array();
  21743. _this._resyncMeshes();
  21744. return _this;
  21745. }
  21746. Object.defineProperty(Light, "LIGHTMAP_DEFAULT", {
  21747. /**
  21748. * If every light affecting the material is in this lightmapMode,
  21749. * material.lightmapTexture adds or multiplies
  21750. * (depends on material.useLightmapAsShadowmap)
  21751. * after every other light calculations.
  21752. */
  21753. get: function () {
  21754. return Light._LIGHTMAP_DEFAULT;
  21755. },
  21756. enumerable: true,
  21757. configurable: true
  21758. });
  21759. Object.defineProperty(Light, "LIGHTMAP_SPECULAR", {
  21760. /**
  21761. * material.lightmapTexture as only diffuse lighting from this light
  21762. * adds only specular lighting from this light
  21763. * adds dynamic shadows
  21764. */
  21765. get: function () {
  21766. return Light._LIGHTMAP_SPECULAR;
  21767. },
  21768. enumerable: true,
  21769. configurable: true
  21770. });
  21771. Object.defineProperty(Light, "LIGHTMAP_SHADOWSONLY", {
  21772. /**
  21773. * material.lightmapTexture as only lighting
  21774. * no light calculation from this light
  21775. * only adds dynamic shadows from this light
  21776. */
  21777. get: function () {
  21778. return Light._LIGHTMAP_SHADOWSONLY;
  21779. },
  21780. enumerable: true,
  21781. configurable: true
  21782. });
  21783. Object.defineProperty(Light, "INTENSITYMODE_AUTOMATIC", {
  21784. /**
  21785. * Each light type uses the default quantity according to its type:
  21786. * point/spot lights use luminous intensity
  21787. * directional lights use illuminance
  21788. */
  21789. get: function () {
  21790. return Light._INTENSITYMODE_AUTOMATIC;
  21791. },
  21792. enumerable: true,
  21793. configurable: true
  21794. });
  21795. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSPOWER", {
  21796. /**
  21797. * lumen (lm)
  21798. */
  21799. get: function () {
  21800. return Light._INTENSITYMODE_LUMINOUSPOWER;
  21801. },
  21802. enumerable: true,
  21803. configurable: true
  21804. });
  21805. Object.defineProperty(Light, "INTENSITYMODE_LUMINOUSINTENSITY", {
  21806. /**
  21807. * candela (lm/sr)
  21808. */
  21809. get: function () {
  21810. return Light._INTENSITYMODE_LUMINOUSINTENSITY;
  21811. },
  21812. enumerable: true,
  21813. configurable: true
  21814. });
  21815. Object.defineProperty(Light, "INTENSITYMODE_ILLUMINANCE", {
  21816. /**
  21817. * lux (lm/m^2)
  21818. */
  21819. get: function () {
  21820. return Light._INTENSITYMODE_ILLUMINANCE;
  21821. },
  21822. enumerable: true,
  21823. configurable: true
  21824. });
  21825. Object.defineProperty(Light, "INTENSITYMODE_LUMINANCE", {
  21826. /**
  21827. * nit (cd/m^2)
  21828. */
  21829. get: function () {
  21830. return Light._INTENSITYMODE_LUMINANCE;
  21831. },
  21832. enumerable: true,
  21833. configurable: true
  21834. });
  21835. Object.defineProperty(Light, "LIGHTTYPEID_POINTLIGHT", {
  21836. /**
  21837. * Light type const id of the point light.
  21838. */
  21839. get: function () {
  21840. return Light._LIGHTTYPEID_POINTLIGHT;
  21841. },
  21842. enumerable: true,
  21843. configurable: true
  21844. });
  21845. Object.defineProperty(Light, "LIGHTTYPEID_DIRECTIONALLIGHT", {
  21846. /**
  21847. * Light type const id of the directional light.
  21848. */
  21849. get: function () {
  21850. return Light._LIGHTTYPEID_DIRECTIONALLIGHT;
  21851. },
  21852. enumerable: true,
  21853. configurable: true
  21854. });
  21855. Object.defineProperty(Light, "LIGHTTYPEID_SPOTLIGHT", {
  21856. /**
  21857. * Light type const id of the spot light.
  21858. */
  21859. get: function () {
  21860. return Light._LIGHTTYPEID_SPOTLIGHT;
  21861. },
  21862. enumerable: true,
  21863. configurable: true
  21864. });
  21865. Object.defineProperty(Light, "LIGHTTYPEID_HEMISPHERICLIGHT", {
  21866. /**
  21867. * Light type const id of the hemispheric light.
  21868. */
  21869. get: function () {
  21870. return Light._LIGHTTYPEID_HEMISPHERICLIGHT;
  21871. },
  21872. enumerable: true,
  21873. configurable: true
  21874. });
  21875. Object.defineProperty(Light.prototype, "intensityMode", {
  21876. /**
  21877. * Gets the photometric scale used to interpret the intensity.
  21878. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21879. */
  21880. get: function () {
  21881. return this._intensityMode;
  21882. },
  21883. /**
  21884. * Sets the photometric scale used to interpret the intensity.
  21885. * This is only relevant with PBR Materials where the light intensity can be defined in a physical way.
  21886. */
  21887. set: function (value) {
  21888. this._intensityMode = value;
  21889. this._computePhotometricScale();
  21890. },
  21891. enumerable: true,
  21892. configurable: true
  21893. });
  21894. ;
  21895. ;
  21896. Object.defineProperty(Light.prototype, "radius", {
  21897. /**
  21898. * Gets the light radius used by PBR Materials to simulate soft area lights.
  21899. */
  21900. get: function () {
  21901. return this._radius;
  21902. },
  21903. /**
  21904. * sets the light radius used by PBR Materials to simulate soft area lights.
  21905. */
  21906. set: function (value) {
  21907. this._radius = value;
  21908. this._computePhotometricScale();
  21909. },
  21910. enumerable: true,
  21911. configurable: true
  21912. });
  21913. ;
  21914. ;
  21915. Object.defineProperty(Light.prototype, "shadowEnabled", {
  21916. /**
  21917. * Gets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21918. * the current shadow generator.
  21919. */
  21920. get: function () {
  21921. return this._shadowEnabled;
  21922. },
  21923. /**
  21924. * Sets wether or not the shadows are enabled for this light. This can help turning off/on shadow without detaching
  21925. * the current shadow generator.
  21926. */
  21927. set: function (value) {
  21928. if (this._shadowEnabled === value) {
  21929. return;
  21930. }
  21931. this._shadowEnabled = value;
  21932. this._markMeshesAsLightDirty();
  21933. },
  21934. enumerable: true,
  21935. configurable: true
  21936. });
  21937. Object.defineProperty(Light.prototype, "includedOnlyMeshes", {
  21938. /**
  21939. * Gets the only meshes impacted by this light.
  21940. */
  21941. get: function () {
  21942. return this._includedOnlyMeshes;
  21943. },
  21944. /**
  21945. * Sets the only meshes impacted by this light.
  21946. */
  21947. set: function (value) {
  21948. this._includedOnlyMeshes = value;
  21949. this._hookArrayForIncludedOnly(value);
  21950. },
  21951. enumerable: true,
  21952. configurable: true
  21953. });
  21954. Object.defineProperty(Light.prototype, "excludedMeshes", {
  21955. /**
  21956. * Gets the meshes not impacted by this light.
  21957. */
  21958. get: function () {
  21959. return this._excludedMeshes;
  21960. },
  21961. /**
  21962. * Sets the meshes not impacted by this light.
  21963. */
  21964. set: function (value) {
  21965. this._excludedMeshes = value;
  21966. this._hookArrayForExcluded(value);
  21967. },
  21968. enumerable: true,
  21969. configurable: true
  21970. });
  21971. Object.defineProperty(Light.prototype, "excludeWithLayerMask", {
  21972. /**
  21973. * Gets the layer id use to find what meshes are not impacted by the light.
  21974. * Inactive if 0
  21975. */
  21976. get: function () {
  21977. return this._excludeWithLayerMask;
  21978. },
  21979. /**
  21980. * Sets the layer id use to find what meshes are not impacted by the light.
  21981. * Inactive if 0
  21982. */
  21983. set: function (value) {
  21984. this._excludeWithLayerMask = value;
  21985. this._resyncMeshes();
  21986. },
  21987. enumerable: true,
  21988. configurable: true
  21989. });
  21990. Object.defineProperty(Light.prototype, "includeOnlyWithLayerMask", {
  21991. /**
  21992. * Gets the layer id use to find what meshes are impacted by the light.
  21993. * Inactive if 0
  21994. */
  21995. get: function () {
  21996. return this._includeOnlyWithLayerMask;
  21997. },
  21998. /**
  21999. * Sets the layer id use to find what meshes are impacted by the light.
  22000. * Inactive if 0
  22001. */
  22002. set: function (value) {
  22003. this._includeOnlyWithLayerMask = value;
  22004. this._resyncMeshes();
  22005. },
  22006. enumerable: true,
  22007. configurable: true
  22008. });
  22009. Object.defineProperty(Light.prototype, "lightmapMode", {
  22010. /**
  22011. * Gets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22012. */
  22013. get: function () {
  22014. return this._lightmapMode;
  22015. },
  22016. /**
  22017. * Sets the lightmap mode of this light (should be one of the constants defined by Light.LIGHTMAP_x)
  22018. */
  22019. set: function (value) {
  22020. if (this._lightmapMode === value) {
  22021. return;
  22022. }
  22023. this._lightmapMode = value;
  22024. this._markMeshesAsLightDirty();
  22025. },
  22026. enumerable: true,
  22027. configurable: true
  22028. });
  22029. /**
  22030. * Returns the string "Light".
  22031. * @returns the class name
  22032. */
  22033. Light.prototype.getClassName = function () {
  22034. return "Light";
  22035. };
  22036. /**
  22037. * Converts the light information to a readable string for debug purpose.
  22038. * @param fullDetails Supports for multiple levels of logging within scene loading
  22039. * @returns the human readable light info
  22040. */
  22041. Light.prototype.toString = function (fullDetails) {
  22042. var ret = "Name: " + this.name;
  22043. ret += ", type: " + (["Point", "Directional", "Spot", "Hemispheric"])[this.getTypeID()];
  22044. if (this.animations) {
  22045. for (var i = 0; i < this.animations.length; i++) {
  22046. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22047. }
  22048. }
  22049. if (fullDetails) {
  22050. }
  22051. return ret;
  22052. };
  22053. /**
  22054. * Set the enabled state of this node.
  22055. * @param value - the new enabled state
  22056. */
  22057. Light.prototype.setEnabled = function (value) {
  22058. _super.prototype.setEnabled.call(this, value);
  22059. this._resyncMeshes();
  22060. };
  22061. /**
  22062. * Returns the Light associated shadow generator if any.
  22063. * @return the associated shadow generator.
  22064. */
  22065. Light.prototype.getShadowGenerator = function () {
  22066. return this._shadowGenerator;
  22067. };
  22068. /**
  22069. * Returns a Vector3, the absolute light position in the World.
  22070. * @returns the world space position of the light
  22071. */
  22072. Light.prototype.getAbsolutePosition = function () {
  22073. return BABYLON.Vector3.Zero();
  22074. };
  22075. /**
  22076. * Specifies if the light will affect the passed mesh.
  22077. * @param mesh The mesh to test against the light
  22078. * @return true the mesh is affected otherwise, false.
  22079. */
  22080. Light.prototype.canAffectMesh = function (mesh) {
  22081. if (!mesh) {
  22082. return true;
  22083. }
  22084. if (this.includedOnlyMeshes && this.includedOnlyMeshes.length > 0 && this.includedOnlyMeshes.indexOf(mesh) === -1) {
  22085. return false;
  22086. }
  22087. if (this.excludedMeshes && this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  22088. return false;
  22089. }
  22090. if (this.includeOnlyWithLayerMask !== 0 && (this.includeOnlyWithLayerMask & mesh.layerMask) === 0) {
  22091. return false;
  22092. }
  22093. if (this.excludeWithLayerMask !== 0 && this.excludeWithLayerMask & mesh.layerMask) {
  22094. return false;
  22095. }
  22096. return true;
  22097. };
  22098. /**
  22099. * Computes and Returns the light World matrix.
  22100. * @returns the world matrix
  22101. */
  22102. Light.prototype.getWorldMatrix = function () {
  22103. this._currentRenderId = this.getScene().getRenderId();
  22104. this._childRenderId = this._currentRenderId;
  22105. var worldMatrix = this._getWorldMatrix();
  22106. if (this.parent && this.parent.getWorldMatrix) {
  22107. if (!this._parentedWorldMatrix) {
  22108. this._parentedWorldMatrix = BABYLON.Matrix.Identity();
  22109. }
  22110. worldMatrix.multiplyToRef(this.parent.getWorldMatrix(), this._parentedWorldMatrix);
  22111. this._markSyncedWithParent();
  22112. return this._parentedWorldMatrix;
  22113. }
  22114. return worldMatrix;
  22115. };
  22116. /**
  22117. * Sort function to order lights for rendering.
  22118. * @param a First Light object to compare to second.
  22119. * @param b Second Light object to compare first.
  22120. * @return -1 to reduce's a's index relative to be, 0 for no change, 1 to increase a's index relative to b.
  22121. */
  22122. Light.CompareLightsPriority = function (a, b) {
  22123. //shadow-casting lights have priority over non-shadow-casting lights
  22124. //the renderPrioirty is a secondary sort criterion
  22125. if (a.shadowEnabled !== b.shadowEnabled) {
  22126. return (b.shadowEnabled ? 1 : 0) - (a.shadowEnabled ? 1 : 0);
  22127. }
  22128. return b.renderPriority - a.renderPriority;
  22129. };
  22130. /**
  22131. * Releases resources associated with this node.
  22132. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22133. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22134. */
  22135. Light.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22136. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22137. if (this._shadowGenerator) {
  22138. this._shadowGenerator.dispose();
  22139. this._shadowGenerator = null;
  22140. }
  22141. // Animations
  22142. this.getScene().stopAnimation(this);
  22143. // Remove from meshes
  22144. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22145. var mesh = _a[_i];
  22146. mesh._removeLightSource(this);
  22147. }
  22148. this._uniformBuffer.dispose();
  22149. // Remove from scene
  22150. this.getScene().removeLight(this);
  22151. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  22152. };
  22153. /**
  22154. * Returns the light type ID (integer).
  22155. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  22156. */
  22157. Light.prototype.getTypeID = function () {
  22158. return 0;
  22159. };
  22160. /**
  22161. * Returns the intensity scaled by the Photometric Scale according to the light type and intensity mode.
  22162. * @returns the scaled intensity in intensity mode unit
  22163. */
  22164. Light.prototype.getScaledIntensity = function () {
  22165. return this._photometricScale * this.intensity;
  22166. };
  22167. /**
  22168. * Returns a new Light object, named "name", from the current one.
  22169. * @param name The name of the cloned light
  22170. * @returns the new created light
  22171. */
  22172. Light.prototype.clone = function (name) {
  22173. var constructor = Light.GetConstructorFromName(this.getTypeID(), name, this.getScene());
  22174. if (!constructor) {
  22175. return null;
  22176. }
  22177. return BABYLON.SerializationHelper.Clone(constructor, this);
  22178. };
  22179. /**
  22180. * Serializes the current light into a Serialization object.
  22181. * @returns the serialized object.
  22182. */
  22183. Light.prototype.serialize = function () {
  22184. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  22185. // Type
  22186. serializationObject.type = this.getTypeID();
  22187. // Parent
  22188. if (this.parent) {
  22189. serializationObject.parentId = this.parent.id;
  22190. }
  22191. // Inclusion / exclusions
  22192. if (this.excludedMeshes.length > 0) {
  22193. serializationObject.excludedMeshesIds = [];
  22194. this.excludedMeshes.forEach(function (mesh) {
  22195. serializationObject.excludedMeshesIds.push(mesh.id);
  22196. });
  22197. }
  22198. if (this.includedOnlyMeshes.length > 0) {
  22199. serializationObject.includedOnlyMeshesIds = [];
  22200. this.includedOnlyMeshes.forEach(function (mesh) {
  22201. serializationObject.includedOnlyMeshesIds.push(mesh.id);
  22202. });
  22203. }
  22204. // Animations
  22205. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  22206. serializationObject.ranges = this.serializeAnimationRanges();
  22207. return serializationObject;
  22208. };
  22209. /**
  22210. * Creates a new typed light from the passed type (integer) : point light = 0, directional light = 1, spot light = 2, hemispheric light = 3.
  22211. * This new light is named "name" and added to the passed scene.
  22212. * @param type Type according to the types available in Light.LIGHTTYPEID_x
  22213. * @param name The friendly name of the light
  22214. * @param scene The scene the new light will belong to
  22215. * @returns the constructor function
  22216. */
  22217. Light.GetConstructorFromName = function (type, name, scene) {
  22218. switch (type) {
  22219. case 0:
  22220. return function () { return new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), scene); };
  22221. case 1:
  22222. return function () { return new BABYLON.DirectionalLight(name, BABYLON.Vector3.Zero(), scene); };
  22223. case 2:
  22224. return function () { return new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, scene); };
  22225. case 3:
  22226. return function () { return new BABYLON.HemisphericLight(name, BABYLON.Vector3.Zero(), scene); };
  22227. }
  22228. return null;
  22229. };
  22230. /**
  22231. * Parses the passed "parsedLight" and returns a new instanced Light from this parsing.
  22232. * @param parsedLight The JSON representation of the light
  22233. * @param scene The scene to create the parsed light in
  22234. * @returns the created light after parsing
  22235. */
  22236. Light.Parse = function (parsedLight, scene) {
  22237. var constructor = Light.GetConstructorFromName(parsedLight.type, parsedLight.name, scene);
  22238. if (!constructor) {
  22239. return null;
  22240. }
  22241. var light = BABYLON.SerializationHelper.Parse(constructor, parsedLight, scene);
  22242. // Inclusion / exclusions
  22243. if (parsedLight.excludedMeshesIds) {
  22244. light._excludedMeshesIds = parsedLight.excludedMeshesIds;
  22245. }
  22246. if (parsedLight.includedOnlyMeshesIds) {
  22247. light._includedOnlyMeshesIds = parsedLight.includedOnlyMeshesIds;
  22248. }
  22249. // Parent
  22250. if (parsedLight.parentId) {
  22251. light._waitingParentId = parsedLight.parentId;
  22252. }
  22253. // Animations
  22254. if (parsedLight.animations) {
  22255. for (var animationIndex = 0; animationIndex < parsedLight.animations.length; animationIndex++) {
  22256. var parsedAnimation = parsedLight.animations[animationIndex];
  22257. light.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  22258. }
  22259. BABYLON.Node.ParseAnimationRanges(light, parsedLight, scene);
  22260. }
  22261. if (parsedLight.autoAnimate) {
  22262. scene.beginAnimation(light, parsedLight.autoAnimateFrom, parsedLight.autoAnimateTo, parsedLight.autoAnimateLoop, parsedLight.autoAnimateSpeed || 1.0);
  22263. }
  22264. return light;
  22265. };
  22266. Light.prototype._hookArrayForExcluded = function (array) {
  22267. var _this = this;
  22268. var oldPush = array.push;
  22269. array.push = function () {
  22270. var items = [];
  22271. for (var _i = 0; _i < arguments.length; _i++) {
  22272. items[_i] = arguments[_i];
  22273. }
  22274. var result = oldPush.apply(array, items);
  22275. for (var _a = 0, items_1 = items; _a < items_1.length; _a++) {
  22276. var item = items_1[_a];
  22277. item._resyncLighSource(_this);
  22278. }
  22279. return result;
  22280. };
  22281. var oldSplice = array.splice;
  22282. array.splice = function (index, deleteCount) {
  22283. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22284. for (var _i = 0, deleted_1 = deleted; _i < deleted_1.length; _i++) {
  22285. var item = deleted_1[_i];
  22286. item._resyncLighSource(_this);
  22287. }
  22288. return deleted;
  22289. };
  22290. for (var _i = 0, array_1 = array; _i < array_1.length; _i++) {
  22291. var item = array_1[_i];
  22292. item._resyncLighSource(this);
  22293. }
  22294. };
  22295. Light.prototype._hookArrayForIncludedOnly = function (array) {
  22296. var _this = this;
  22297. var oldPush = array.push;
  22298. array.push = function () {
  22299. var items = [];
  22300. for (var _i = 0; _i < arguments.length; _i++) {
  22301. items[_i] = arguments[_i];
  22302. }
  22303. var result = oldPush.apply(array, items);
  22304. _this._resyncMeshes();
  22305. return result;
  22306. };
  22307. var oldSplice = array.splice;
  22308. array.splice = function (index, deleteCount) {
  22309. var deleted = oldSplice.apply(array, [index, deleteCount]);
  22310. _this._resyncMeshes();
  22311. return deleted;
  22312. };
  22313. this._resyncMeshes();
  22314. };
  22315. Light.prototype._resyncMeshes = function () {
  22316. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22317. var mesh = _a[_i];
  22318. mesh._resyncLighSource(this);
  22319. }
  22320. };
  22321. /**
  22322. * Forces the meshes to update their light related information in their rendering used effects
  22323. * @hidden Internal Use Only
  22324. */
  22325. Light.prototype._markMeshesAsLightDirty = function () {
  22326. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  22327. var mesh = _a[_i];
  22328. if (mesh._lightSources.indexOf(this) !== -1) {
  22329. mesh._markSubMeshesAsLightDirty();
  22330. }
  22331. }
  22332. };
  22333. /**
  22334. * Recomputes the cached photometric scale if needed.
  22335. */
  22336. Light.prototype._computePhotometricScale = function () {
  22337. this._photometricScale = this._getPhotometricScale();
  22338. this.getScene().resetCachedMaterial();
  22339. };
  22340. /**
  22341. * Returns the Photometric Scale according to the light type and intensity mode.
  22342. */
  22343. Light.prototype._getPhotometricScale = function () {
  22344. var photometricScale = 0.0;
  22345. var lightTypeID = this.getTypeID();
  22346. //get photometric mode
  22347. var photometricMode = this.intensityMode;
  22348. if (photometricMode === Light.INTENSITYMODE_AUTOMATIC) {
  22349. if (lightTypeID === Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  22350. photometricMode = Light.INTENSITYMODE_ILLUMINANCE;
  22351. }
  22352. else {
  22353. photometricMode = Light.INTENSITYMODE_LUMINOUSINTENSITY;
  22354. }
  22355. }
  22356. //compute photometric scale
  22357. switch (lightTypeID) {
  22358. case Light.LIGHTTYPEID_POINTLIGHT:
  22359. case Light.LIGHTTYPEID_SPOTLIGHT:
  22360. switch (photometricMode) {
  22361. case Light.INTENSITYMODE_LUMINOUSPOWER:
  22362. photometricScale = 1.0 / (4.0 * Math.PI);
  22363. break;
  22364. case Light.INTENSITYMODE_LUMINOUSINTENSITY:
  22365. photometricScale = 1.0;
  22366. break;
  22367. case Light.INTENSITYMODE_LUMINANCE:
  22368. photometricScale = this.radius * this.radius;
  22369. break;
  22370. }
  22371. break;
  22372. case Light.LIGHTTYPEID_DIRECTIONALLIGHT:
  22373. switch (photometricMode) {
  22374. case Light.INTENSITYMODE_ILLUMINANCE:
  22375. photometricScale = 1.0;
  22376. break;
  22377. case Light.INTENSITYMODE_LUMINANCE:
  22378. // When radius (and therefore solid angle) is non-zero a directional lights brightness can be specified via central (peak) luminance.
  22379. // For a directional light the 'radius' defines the angular radius (in radians) rather than world-space radius (e.g. in metres).
  22380. var apexAngleRadians = this.radius;
  22381. // Impose a minimum light angular size to avoid the light becoming an infinitely small angular light source (i.e. a dirac delta function).
  22382. apexAngleRadians = Math.max(apexAngleRadians, 0.001);
  22383. var solidAngle = 2.0 * Math.PI * (1.0 - Math.cos(apexAngleRadians));
  22384. photometricScale = solidAngle;
  22385. break;
  22386. }
  22387. break;
  22388. case Light.LIGHTTYPEID_HEMISPHERICLIGHT:
  22389. // No fall off in hemisperic light.
  22390. photometricScale = 1.0;
  22391. break;
  22392. }
  22393. return photometricScale;
  22394. };
  22395. /**
  22396. * Reorder the light in the scene according to their defined priority.
  22397. * @hidden Internal Use Only
  22398. */
  22399. Light.prototype._reorderLightsInScene = function () {
  22400. var scene = this.getScene();
  22401. if (this._renderPriority != 0) {
  22402. scene.requireLightSorting = true;
  22403. }
  22404. this.getScene().sortLightsByPriority();
  22405. };
  22406. //lightmapMode Consts
  22407. Light._LIGHTMAP_DEFAULT = 0;
  22408. Light._LIGHTMAP_SPECULAR = 1;
  22409. Light._LIGHTMAP_SHADOWSONLY = 2;
  22410. // Intensity Mode Consts
  22411. Light._INTENSITYMODE_AUTOMATIC = 0;
  22412. Light._INTENSITYMODE_LUMINOUSPOWER = 1;
  22413. Light._INTENSITYMODE_LUMINOUSINTENSITY = 2;
  22414. Light._INTENSITYMODE_ILLUMINANCE = 3;
  22415. Light._INTENSITYMODE_LUMINANCE = 4;
  22416. // Light types ids const.
  22417. Light._LIGHTTYPEID_POINTLIGHT = 0;
  22418. Light._LIGHTTYPEID_DIRECTIONALLIGHT = 1;
  22419. Light._LIGHTTYPEID_SPOTLIGHT = 2;
  22420. Light._LIGHTTYPEID_HEMISPHERICLIGHT = 3;
  22421. __decorate([
  22422. BABYLON.serializeAsColor3()
  22423. ], Light.prototype, "diffuse", void 0);
  22424. __decorate([
  22425. BABYLON.serializeAsColor3()
  22426. ], Light.prototype, "specular", void 0);
  22427. __decorate([
  22428. BABYLON.serialize()
  22429. ], Light.prototype, "intensity", void 0);
  22430. __decorate([
  22431. BABYLON.serialize()
  22432. ], Light.prototype, "range", void 0);
  22433. __decorate([
  22434. BABYLON.serialize()
  22435. ], Light.prototype, "intensityMode", null);
  22436. __decorate([
  22437. BABYLON.serialize()
  22438. ], Light.prototype, "radius", null);
  22439. __decorate([
  22440. BABYLON.serialize()
  22441. ], Light.prototype, "_renderPriority", void 0);
  22442. __decorate([
  22443. BABYLON.expandToProperty("_reorderLightsInScene")
  22444. ], Light.prototype, "renderPriority", void 0);
  22445. __decorate([
  22446. BABYLON.serialize("shadowEnabled")
  22447. ], Light.prototype, "_shadowEnabled", void 0);
  22448. __decorate([
  22449. BABYLON.serialize("excludeWithLayerMask")
  22450. ], Light.prototype, "_excludeWithLayerMask", void 0);
  22451. __decorate([
  22452. BABYLON.serialize("includeOnlyWithLayerMask")
  22453. ], Light.prototype, "_includeOnlyWithLayerMask", void 0);
  22454. __decorate([
  22455. BABYLON.serialize("lightmapMode")
  22456. ], Light.prototype, "_lightmapMode", void 0);
  22457. return Light;
  22458. }(BABYLON.Node));
  22459. BABYLON.Light = Light;
  22460. })(BABYLON || (BABYLON = {}));
  22461. //# sourceMappingURL=babylon.light.js.map
  22462. var BABYLON;
  22463. (function (BABYLON) {
  22464. var Camera = /** @class */ (function (_super) {
  22465. __extends(Camera, _super);
  22466. function Camera(name, position, scene, setActiveOnSceneIfNoneActive) {
  22467. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  22468. var _this = _super.call(this, name, scene) || this;
  22469. /**
  22470. * The vector the camera should consider as up.
  22471. * (default is Vector3(0, 1, 0) aka Vector3.Up())
  22472. */
  22473. _this.upVector = BABYLON.Vector3.Up();
  22474. _this.orthoLeft = null;
  22475. _this.orthoRight = null;
  22476. _this.orthoBottom = null;
  22477. _this.orthoTop = null;
  22478. /**
  22479. * FOV is set in Radians. (default is 0.8)
  22480. */
  22481. _this.fov = 0.8;
  22482. _this.minZ = 1;
  22483. _this.maxZ = 10000.0;
  22484. _this.inertia = 0.9;
  22485. _this.mode = Camera.PERSPECTIVE_CAMERA;
  22486. _this.isIntermediate = false;
  22487. _this.viewport = new BABYLON.Viewport(0, 0, 1.0, 1.0);
  22488. /**
  22489. * Restricts the camera to viewing objects with the same layerMask.
  22490. * A camera with a layerMask of 1 will render mesh.layerMask & camera.layerMask!== 0
  22491. */
  22492. _this.layerMask = 0x0FFFFFFF;
  22493. /**
  22494. * fovMode sets the camera frustum bounds to the viewport bounds. (default is FOVMODE_VERTICAL_FIXED)
  22495. */
  22496. _this.fovMode = Camera.FOVMODE_VERTICAL_FIXED;
  22497. // Camera rig members
  22498. _this.cameraRigMode = Camera.RIG_MODE_NONE;
  22499. _this._rigCameras = new Array();
  22500. _this._webvrViewMatrix = BABYLON.Matrix.Identity();
  22501. _this._skipRendering = false;
  22502. _this.customRenderTargets = new Array();
  22503. // Observables
  22504. _this.onViewMatrixChangedObservable = new BABYLON.Observable();
  22505. _this.onProjectionMatrixChangedObservable = new BABYLON.Observable();
  22506. _this.onAfterCheckInputsObservable = new BABYLON.Observable();
  22507. _this.onRestoreStateObservable = new BABYLON.Observable();
  22508. // Cache
  22509. _this._computedViewMatrix = BABYLON.Matrix.Identity();
  22510. _this._projectionMatrix = new BABYLON.Matrix();
  22511. _this._doNotComputeProjectionMatrix = false;
  22512. _this._worldMatrix = BABYLON.Matrix.Identity();
  22513. _this._postProcesses = new Array();
  22514. _this._transformMatrix = BABYLON.Matrix.Zero();
  22515. _this._activeMeshes = new BABYLON.SmartArray(256);
  22516. _this._globalPosition = BABYLON.Vector3.Zero();
  22517. _this._refreshFrustumPlanes = true;
  22518. _this.getScene().addCamera(_this);
  22519. if (setActiveOnSceneIfNoneActive && !_this.getScene().activeCamera) {
  22520. _this.getScene().activeCamera = _this;
  22521. }
  22522. _this.position = position;
  22523. return _this;
  22524. }
  22525. Object.defineProperty(Camera, "PERSPECTIVE_CAMERA", {
  22526. get: function () {
  22527. return Camera._PERSPECTIVE_CAMERA;
  22528. },
  22529. enumerable: true,
  22530. configurable: true
  22531. });
  22532. Object.defineProperty(Camera, "ORTHOGRAPHIC_CAMERA", {
  22533. get: function () {
  22534. return Camera._ORTHOGRAPHIC_CAMERA;
  22535. },
  22536. enumerable: true,
  22537. configurable: true
  22538. });
  22539. Object.defineProperty(Camera, "FOVMODE_VERTICAL_FIXED", {
  22540. /**
  22541. * This is the default FOV mode for perspective cameras.
  22542. * This setting aligns the upper and lower bounds of the viewport to the upper and lower bounds of the camera frustum.
  22543. *
  22544. */
  22545. get: function () {
  22546. return Camera._FOVMODE_VERTICAL_FIXED;
  22547. },
  22548. enumerable: true,
  22549. configurable: true
  22550. });
  22551. Object.defineProperty(Camera, "FOVMODE_HORIZONTAL_FIXED", {
  22552. /**
  22553. * This setting aligns the left and right bounds of the viewport to the left and right bounds of the camera frustum.
  22554. *
  22555. */
  22556. get: function () {
  22557. return Camera._FOVMODE_HORIZONTAL_FIXED;
  22558. },
  22559. enumerable: true,
  22560. configurable: true
  22561. });
  22562. Object.defineProperty(Camera, "RIG_MODE_NONE", {
  22563. get: function () {
  22564. return Camera._RIG_MODE_NONE;
  22565. },
  22566. enumerable: true,
  22567. configurable: true
  22568. });
  22569. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_ANAGLYPH", {
  22570. get: function () {
  22571. return Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH;
  22572. },
  22573. enumerable: true,
  22574. configurable: true
  22575. });
  22576. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL", {
  22577. get: function () {
  22578. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL;
  22579. },
  22580. enumerable: true,
  22581. configurable: true
  22582. });
  22583. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED", {
  22584. get: function () {
  22585. return Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  22586. },
  22587. enumerable: true,
  22588. configurable: true
  22589. });
  22590. Object.defineProperty(Camera, "RIG_MODE_STEREOSCOPIC_OVERUNDER", {
  22591. get: function () {
  22592. return Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER;
  22593. },
  22594. enumerable: true,
  22595. configurable: true
  22596. });
  22597. Object.defineProperty(Camera, "RIG_MODE_VR", {
  22598. get: function () {
  22599. return Camera._RIG_MODE_VR;
  22600. },
  22601. enumerable: true,
  22602. configurable: true
  22603. });
  22604. Object.defineProperty(Camera, "RIG_MODE_WEBVR", {
  22605. get: function () {
  22606. return Camera._RIG_MODE_WEBVR;
  22607. },
  22608. enumerable: true,
  22609. configurable: true
  22610. });
  22611. /**
  22612. * Store current camera state (fov, position, etc..)
  22613. */
  22614. Camera.prototype.storeState = function () {
  22615. this._stateStored = true;
  22616. this._storedFov = this.fov;
  22617. return this;
  22618. };
  22619. /**
  22620. * Restores the camera state values if it has been stored. You must call storeState() first
  22621. */
  22622. Camera.prototype._restoreStateValues = function () {
  22623. if (!this._stateStored) {
  22624. return false;
  22625. }
  22626. this.fov = this._storedFov;
  22627. return true;
  22628. };
  22629. /**
  22630. * Restored camera state. You must call storeState() first
  22631. */
  22632. Camera.prototype.restoreState = function () {
  22633. if (this._restoreStateValues()) {
  22634. this.onRestoreStateObservable.notifyObservers(this);
  22635. return true;
  22636. }
  22637. return false;
  22638. };
  22639. Camera.prototype.getClassName = function () {
  22640. return "Camera";
  22641. };
  22642. /**
  22643. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  22644. */
  22645. Camera.prototype.toString = function (fullDetails) {
  22646. var ret = "Name: " + this.name;
  22647. ret += ", type: " + this.getClassName();
  22648. if (this.animations) {
  22649. for (var i = 0; i < this.animations.length; i++) {
  22650. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  22651. }
  22652. }
  22653. if (fullDetails) {
  22654. }
  22655. return ret;
  22656. };
  22657. Object.defineProperty(Camera.prototype, "globalPosition", {
  22658. get: function () {
  22659. return this._globalPosition;
  22660. },
  22661. enumerable: true,
  22662. configurable: true
  22663. });
  22664. Camera.prototype.getActiveMeshes = function () {
  22665. return this._activeMeshes;
  22666. };
  22667. Camera.prototype.isActiveMesh = function (mesh) {
  22668. return (this._activeMeshes.indexOf(mesh) !== -1);
  22669. };
  22670. /**
  22671. * Is this camera ready to be used/rendered
  22672. * @param completeCheck defines if a complete check (including post processes) has to be done (false by default)
  22673. * @return true if the camera is ready
  22674. */
  22675. Camera.prototype.isReady = function (completeCheck) {
  22676. if (completeCheck === void 0) { completeCheck = false; }
  22677. if (completeCheck) {
  22678. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  22679. var pp = _a[_i];
  22680. if (pp && !pp.isReady()) {
  22681. return false;
  22682. }
  22683. }
  22684. }
  22685. return _super.prototype.isReady.call(this, completeCheck);
  22686. };
  22687. //Cache
  22688. Camera.prototype._initCache = function () {
  22689. _super.prototype._initCache.call(this);
  22690. this._cache.position = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22691. this._cache.upVector = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  22692. this._cache.mode = undefined;
  22693. this._cache.minZ = undefined;
  22694. this._cache.maxZ = undefined;
  22695. this._cache.fov = undefined;
  22696. this._cache.fovMode = undefined;
  22697. this._cache.aspectRatio = undefined;
  22698. this._cache.orthoLeft = undefined;
  22699. this._cache.orthoRight = undefined;
  22700. this._cache.orthoBottom = undefined;
  22701. this._cache.orthoTop = undefined;
  22702. this._cache.renderWidth = undefined;
  22703. this._cache.renderHeight = undefined;
  22704. };
  22705. Camera.prototype._updateCache = function (ignoreParentClass) {
  22706. if (!ignoreParentClass) {
  22707. _super.prototype._updateCache.call(this);
  22708. }
  22709. this._cache.position.copyFrom(this.position);
  22710. this._cache.upVector.copyFrom(this.upVector);
  22711. };
  22712. // Synchronized
  22713. Camera.prototype._isSynchronized = function () {
  22714. return this._isSynchronizedViewMatrix() && this._isSynchronizedProjectionMatrix();
  22715. };
  22716. Camera.prototype._isSynchronizedViewMatrix = function () {
  22717. if (!_super.prototype._isSynchronized.call(this))
  22718. return false;
  22719. return this._cache.position.equals(this.position)
  22720. && this._cache.upVector.equals(this.upVector)
  22721. && this.isSynchronizedWithParent();
  22722. };
  22723. Camera.prototype._isSynchronizedProjectionMatrix = function () {
  22724. var check = this._cache.mode === this.mode
  22725. && this._cache.minZ === this.minZ
  22726. && this._cache.maxZ === this.maxZ;
  22727. if (!check) {
  22728. return false;
  22729. }
  22730. var engine = this.getEngine();
  22731. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22732. check = this._cache.fov === this.fov
  22733. && this._cache.fovMode === this.fovMode
  22734. && this._cache.aspectRatio === engine.getAspectRatio(this);
  22735. }
  22736. else {
  22737. check = this._cache.orthoLeft === this.orthoLeft
  22738. && this._cache.orthoRight === this.orthoRight
  22739. && this._cache.orthoBottom === this.orthoBottom
  22740. && this._cache.orthoTop === this.orthoTop
  22741. && this._cache.renderWidth === engine.getRenderWidth()
  22742. && this._cache.renderHeight === engine.getRenderHeight();
  22743. }
  22744. return check;
  22745. };
  22746. // Controls
  22747. Camera.prototype.attachControl = function (element, noPreventDefault) {
  22748. };
  22749. Camera.prototype.detachControl = function (element) {
  22750. };
  22751. Camera.prototype.update = function () {
  22752. this._checkInputs();
  22753. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22754. this._updateRigCameras();
  22755. }
  22756. };
  22757. Camera.prototype._checkInputs = function () {
  22758. this.onAfterCheckInputsObservable.notifyObservers(this);
  22759. };
  22760. Object.defineProperty(Camera.prototype, "rigCameras", {
  22761. get: function () {
  22762. return this._rigCameras;
  22763. },
  22764. enumerable: true,
  22765. configurable: true
  22766. });
  22767. Object.defineProperty(Camera.prototype, "rigPostProcess", {
  22768. get: function () {
  22769. return this._rigPostProcess;
  22770. },
  22771. enumerable: true,
  22772. configurable: true
  22773. });
  22774. /**
  22775. * Internal, gets the first post proces.
  22776. * @returns the first post process to be run on this camera.
  22777. */
  22778. Camera.prototype._getFirstPostProcess = function () {
  22779. for (var ppIndex = 0; ppIndex < this._postProcesses.length; ppIndex++) {
  22780. if (this._postProcesses[ppIndex] !== null) {
  22781. return this._postProcesses[ppIndex];
  22782. }
  22783. }
  22784. return null;
  22785. };
  22786. Camera.prototype._cascadePostProcessesToRigCams = function () {
  22787. // invalidate framebuffer
  22788. var firstPostProcess = this._getFirstPostProcess();
  22789. if (firstPostProcess) {
  22790. firstPostProcess.markTextureDirty();
  22791. }
  22792. // glue the rigPostProcess to the end of the user postprocesses & assign to each sub-camera
  22793. for (var i = 0, len = this._rigCameras.length; i < len; i++) {
  22794. var cam = this._rigCameras[i];
  22795. var rigPostProcess = cam._rigPostProcess;
  22796. // for VR rig, there does not have to be a post process
  22797. if (rigPostProcess) {
  22798. var isPass = rigPostProcess instanceof BABYLON.PassPostProcess;
  22799. if (isPass) {
  22800. // any rig which has a PassPostProcess for rig[0], cannot be isIntermediate when there are also user postProcesses
  22801. cam.isIntermediate = this._postProcesses.length === 0;
  22802. }
  22803. cam._postProcesses = this._postProcesses.slice(0).concat(rigPostProcess);
  22804. rigPostProcess.markTextureDirty();
  22805. }
  22806. else {
  22807. cam._postProcesses = this._postProcesses.slice(0);
  22808. }
  22809. }
  22810. };
  22811. Camera.prototype.attachPostProcess = function (postProcess, insertAt) {
  22812. if (insertAt === void 0) { insertAt = null; }
  22813. if (!postProcess.isReusable() && this._postProcesses.indexOf(postProcess) > -1) {
  22814. BABYLON.Tools.Error("You're trying to reuse a post process not defined as reusable.");
  22815. return 0;
  22816. }
  22817. if (insertAt == null || insertAt < 0) {
  22818. this._postProcesses.push(postProcess);
  22819. }
  22820. else if (this._postProcesses[insertAt] === null) {
  22821. this._postProcesses[insertAt] = postProcess;
  22822. }
  22823. else {
  22824. this._postProcesses.splice(insertAt, 0, postProcess);
  22825. }
  22826. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22827. return this._postProcesses.indexOf(postProcess);
  22828. };
  22829. Camera.prototype.detachPostProcess = function (postProcess) {
  22830. var idx = this._postProcesses.indexOf(postProcess);
  22831. if (idx !== -1) {
  22832. this._postProcesses[idx] = null;
  22833. }
  22834. this._cascadePostProcessesToRigCams(); // also ensures framebuffer invalidated
  22835. };
  22836. Camera.prototype.getWorldMatrix = function () {
  22837. if (this._isSynchronizedViewMatrix()) {
  22838. return this._worldMatrix;
  22839. }
  22840. // Getting the the view matrix will also compute the world matrix.
  22841. this.getViewMatrix();
  22842. return this._worldMatrix;
  22843. };
  22844. Camera.prototype._getViewMatrix = function () {
  22845. return BABYLON.Matrix.Identity();
  22846. };
  22847. Camera.prototype.getViewMatrix = function (force) {
  22848. if (!force && this._isSynchronizedViewMatrix()) {
  22849. return this._computedViewMatrix;
  22850. }
  22851. this.updateCache();
  22852. this._computedViewMatrix = this._getViewMatrix();
  22853. this._currentRenderId = this.getScene().getRenderId();
  22854. this._childRenderId = this._currentRenderId;
  22855. this._refreshFrustumPlanes = true;
  22856. if (this._cameraRigParams && this._cameraRigParams.vrPreViewMatrix) {
  22857. this._computedViewMatrix.multiplyToRef(this._cameraRigParams.vrPreViewMatrix, this._computedViewMatrix);
  22858. }
  22859. this.onViewMatrixChangedObservable.notifyObservers(this);
  22860. this._computedViewMatrix.invertToRef(this._worldMatrix);
  22861. return this._computedViewMatrix;
  22862. };
  22863. Camera.prototype.freezeProjectionMatrix = function (projection) {
  22864. this._doNotComputeProjectionMatrix = true;
  22865. if (projection !== undefined) {
  22866. this._projectionMatrix = projection;
  22867. }
  22868. };
  22869. ;
  22870. Camera.prototype.unfreezeProjectionMatrix = function () {
  22871. this._doNotComputeProjectionMatrix = false;
  22872. };
  22873. ;
  22874. Camera.prototype.getProjectionMatrix = function (force) {
  22875. if (this._doNotComputeProjectionMatrix || (!force && this._isSynchronizedProjectionMatrix())) {
  22876. return this._projectionMatrix;
  22877. }
  22878. // Cache
  22879. this._cache.mode = this.mode;
  22880. this._cache.minZ = this.minZ;
  22881. this._cache.maxZ = this.maxZ;
  22882. // Matrix
  22883. this._refreshFrustumPlanes = true;
  22884. var engine = this.getEngine();
  22885. var scene = this.getScene();
  22886. if (this.mode === Camera.PERSPECTIVE_CAMERA) {
  22887. this._cache.fov = this.fov;
  22888. this._cache.fovMode = this.fovMode;
  22889. this._cache.aspectRatio = engine.getAspectRatio(this);
  22890. if (this.minZ <= 0) {
  22891. this.minZ = 0.1;
  22892. }
  22893. if (scene.useRightHandedSystem) {
  22894. BABYLON.Matrix.PerspectiveFovRHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22895. }
  22896. else {
  22897. BABYLON.Matrix.PerspectiveFovLHToRef(this.fov, engine.getAspectRatio(this), this.minZ, this.maxZ, this._projectionMatrix, this.fovMode === Camera.FOVMODE_VERTICAL_FIXED);
  22898. }
  22899. }
  22900. else {
  22901. var halfWidth = engine.getRenderWidth() / 2.0;
  22902. var halfHeight = engine.getRenderHeight() / 2.0;
  22903. if (scene.useRightHandedSystem) {
  22904. BABYLON.Matrix.OrthoOffCenterRHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22905. }
  22906. else {
  22907. BABYLON.Matrix.OrthoOffCenterLHToRef(this.orthoLeft || -halfWidth, this.orthoRight || halfWidth, this.orthoBottom || -halfHeight, this.orthoTop || halfHeight, this.minZ, this.maxZ, this._projectionMatrix);
  22908. }
  22909. this._cache.orthoLeft = this.orthoLeft;
  22910. this._cache.orthoRight = this.orthoRight;
  22911. this._cache.orthoBottom = this.orthoBottom;
  22912. this._cache.orthoTop = this.orthoTop;
  22913. this._cache.renderWidth = engine.getRenderWidth();
  22914. this._cache.renderHeight = engine.getRenderHeight();
  22915. }
  22916. this.onProjectionMatrixChangedObservable.notifyObservers(this);
  22917. return this._projectionMatrix;
  22918. };
  22919. Camera.prototype.getTranformationMatrix = function () {
  22920. this._computedViewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  22921. return this._transformMatrix;
  22922. };
  22923. Camera.prototype.updateFrustumPlanes = function () {
  22924. if (!this._refreshFrustumPlanes) {
  22925. return;
  22926. }
  22927. this.getTranformationMatrix();
  22928. if (!this._frustumPlanes) {
  22929. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  22930. }
  22931. else {
  22932. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  22933. }
  22934. this._refreshFrustumPlanes = false;
  22935. };
  22936. Camera.prototype.isInFrustum = function (target) {
  22937. this.updateFrustumPlanes();
  22938. return target.isInFrustum(this._frustumPlanes);
  22939. };
  22940. Camera.prototype.isCompletelyInFrustum = function (target) {
  22941. this.updateFrustumPlanes();
  22942. return target.isCompletelyInFrustum(this._frustumPlanes);
  22943. };
  22944. Camera.prototype.getForwardRay = function (length, transform, origin) {
  22945. if (length === void 0) { length = 100; }
  22946. if (!transform) {
  22947. transform = this.getWorldMatrix();
  22948. }
  22949. if (!origin) {
  22950. origin = this.position;
  22951. }
  22952. var forward = new BABYLON.Vector3(0, 0, 1);
  22953. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, transform);
  22954. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  22955. return new BABYLON.Ray(origin, direction, length);
  22956. };
  22957. /**
  22958. * Releases resources associated with this node.
  22959. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  22960. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  22961. */
  22962. Camera.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  22963. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  22964. // Observables
  22965. this.onViewMatrixChangedObservable.clear();
  22966. this.onProjectionMatrixChangedObservable.clear();
  22967. this.onAfterCheckInputsObservable.clear();
  22968. this.onRestoreStateObservable.clear();
  22969. // Inputs
  22970. if (this.inputs) {
  22971. this.inputs.clear();
  22972. }
  22973. // Animations
  22974. this.getScene().stopAnimation(this);
  22975. // Remove from scene
  22976. this.getScene().removeCamera(this);
  22977. while (this._rigCameras.length > 0) {
  22978. var camera = this._rigCameras.pop();
  22979. if (camera) {
  22980. camera.dispose();
  22981. }
  22982. }
  22983. // Postprocesses
  22984. if (this._rigPostProcess) {
  22985. this._rigPostProcess.dispose(this);
  22986. this._rigPostProcess = null;
  22987. this._postProcesses = [];
  22988. }
  22989. else if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  22990. this._rigPostProcess = null;
  22991. this._postProcesses = [];
  22992. }
  22993. else {
  22994. var i = this._postProcesses.length;
  22995. while (--i >= 0) {
  22996. var postProcess = this._postProcesses[i];
  22997. if (postProcess) {
  22998. postProcess.dispose(this);
  22999. }
  23000. }
  23001. }
  23002. // Render targets
  23003. var i = this.customRenderTargets.length;
  23004. while (--i >= 0) {
  23005. this.customRenderTargets[i].dispose();
  23006. }
  23007. this.customRenderTargets = [];
  23008. // Active Meshes
  23009. this._activeMeshes.dispose();
  23010. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  23011. };
  23012. Object.defineProperty(Camera.prototype, "leftCamera", {
  23013. // ---- Camera rigs section ----
  23014. get: function () {
  23015. if (this._rigCameras.length < 1) {
  23016. return null;
  23017. }
  23018. return this._rigCameras[0];
  23019. },
  23020. enumerable: true,
  23021. configurable: true
  23022. });
  23023. Object.defineProperty(Camera.prototype, "rightCamera", {
  23024. get: function () {
  23025. if (this._rigCameras.length < 2) {
  23026. return null;
  23027. }
  23028. return this._rigCameras[1];
  23029. },
  23030. enumerable: true,
  23031. configurable: true
  23032. });
  23033. Camera.prototype.getLeftTarget = function () {
  23034. if (this._rigCameras.length < 1) {
  23035. return null;
  23036. }
  23037. return this._rigCameras[0].getTarget();
  23038. };
  23039. Camera.prototype.getRightTarget = function () {
  23040. if (this._rigCameras.length < 2) {
  23041. return null;
  23042. }
  23043. return this._rigCameras[1].getTarget();
  23044. };
  23045. Camera.prototype.setCameraRigMode = function (mode, rigParams) {
  23046. if (this.cameraRigMode === mode) {
  23047. return;
  23048. }
  23049. while (this._rigCameras.length > 0) {
  23050. var camera = this._rigCameras.pop();
  23051. if (camera) {
  23052. camera.dispose();
  23053. }
  23054. }
  23055. this.cameraRigMode = mode;
  23056. this._cameraRigParams = {};
  23057. //we have to implement stereo camera calcultating left and right viewpoints from interaxialDistance and target,
  23058. //not from a given angle as it is now, but until that complete code rewriting provisional stereoHalfAngle value is introduced
  23059. this._cameraRigParams.interaxialDistance = rigParams.interaxialDistance || 0.0637;
  23060. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(this._cameraRigParams.interaxialDistance / 0.0637);
  23061. // create the rig cameras, unless none
  23062. if (this.cameraRigMode !== Camera.RIG_MODE_NONE) {
  23063. var leftCamera = this.createRigCamera(this.name + "_L", 0);
  23064. var rightCamera = this.createRigCamera(this.name + "_R", 1);
  23065. if (leftCamera && rightCamera) {
  23066. this._rigCameras.push(leftCamera);
  23067. this._rigCameras.push(rightCamera);
  23068. }
  23069. }
  23070. switch (this.cameraRigMode) {
  23071. case Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  23072. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23073. this._rigCameras[1]._rigPostProcess = new BABYLON.AnaglyphPostProcess(this.name + "_anaglyph", 1.0, this._rigCameras);
  23074. break;
  23075. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  23076. case Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  23077. case Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  23078. var isStereoscopicHoriz = this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL || this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED;
  23079. this._rigCameras[0]._rigPostProcess = new BABYLON.PassPostProcess(this.name + "_passthru", 1.0, this._rigCameras[0]);
  23080. this._rigCameras[1]._rigPostProcess = new BABYLON.StereoscopicInterlacePostProcess(this.name + "_stereoInterlace", this._rigCameras, isStereoscopicHoriz);
  23081. break;
  23082. case Camera.RIG_MODE_VR:
  23083. var metrics = rigParams.vrCameraMetrics || BABYLON.VRCameraMetrics.GetDefault();
  23084. this._rigCameras[0]._cameraRigParams.vrMetrics = metrics;
  23085. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23086. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23087. this._rigCameras[0]._cameraRigParams.vrHMatrix = metrics.leftHMatrix;
  23088. this._rigCameras[0]._cameraRigParams.vrPreViewMatrix = metrics.leftPreViewMatrix;
  23089. this._rigCameras[0].getProjectionMatrix = this._rigCameras[0]._getVRProjectionMatrix;
  23090. this._rigCameras[1]._cameraRigParams.vrMetrics = metrics;
  23091. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23092. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23093. this._rigCameras[1]._cameraRigParams.vrHMatrix = metrics.rightHMatrix;
  23094. this._rigCameras[1]._cameraRigParams.vrPreViewMatrix = metrics.rightPreViewMatrix;
  23095. this._rigCameras[1].getProjectionMatrix = this._rigCameras[1]._getVRProjectionMatrix;
  23096. if (metrics.compensateDistortion) {
  23097. this._rigCameras[0]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Left", this._rigCameras[0], false, metrics);
  23098. this._rigCameras[1]._rigPostProcess = new BABYLON.VRDistortionCorrectionPostProcess("VR_Distort_Compensation_Right", this._rigCameras[1], true, metrics);
  23099. }
  23100. break;
  23101. case Camera.RIG_MODE_WEBVR:
  23102. if (rigParams.vrDisplay) {
  23103. var leftEye = rigParams.vrDisplay.getEyeParameters('left');
  23104. var rightEye = rigParams.vrDisplay.getEyeParameters('right');
  23105. //Left eye
  23106. this._rigCameras[0].viewport = new BABYLON.Viewport(0, 0, 0.5, 1.0);
  23107. this._rigCameras[0].setCameraRigParameter("left", true);
  23108. //leaving this for future reference
  23109. this._rigCameras[0].setCameraRigParameter("specs", rigParams.specs);
  23110. this._rigCameras[0].setCameraRigParameter("eyeParameters", leftEye);
  23111. this._rigCameras[0].setCameraRigParameter("frameData", rigParams.frameData);
  23112. this._rigCameras[0].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23113. this._rigCameras[0]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23114. this._rigCameras[0].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23115. this._rigCameras[0].parent = this;
  23116. this._rigCameras[0]._getViewMatrix = this._getWebVRViewMatrix;
  23117. //Right eye
  23118. this._rigCameras[1].viewport = new BABYLON.Viewport(0.5, 0, 0.5, 1.0);
  23119. this._rigCameras[1].setCameraRigParameter('eyeParameters', rightEye);
  23120. this._rigCameras[1].setCameraRigParameter("specs", rigParams.specs);
  23121. this._rigCameras[1].setCameraRigParameter("frameData", rigParams.frameData);
  23122. this._rigCameras[1].setCameraRigParameter("parentCamera", rigParams.parentCamera);
  23123. this._rigCameras[1]._cameraRigParams.vrWorkMatrix = new BABYLON.Matrix();
  23124. this._rigCameras[1].getProjectionMatrix = this._getWebVRProjectionMatrix;
  23125. this._rigCameras[1].parent = this;
  23126. this._rigCameras[1]._getViewMatrix = this._getWebVRViewMatrix;
  23127. if (Camera.UseAlternateWebVRRendering) {
  23128. this._rigCameras[1]._skipRendering = true;
  23129. this._rigCameras[0]._alternateCamera = this._rigCameras[1];
  23130. }
  23131. }
  23132. break;
  23133. }
  23134. this._cascadePostProcessesToRigCams();
  23135. this.update();
  23136. };
  23137. Camera.prototype._getVRProjectionMatrix = function () {
  23138. BABYLON.Matrix.PerspectiveFovLHToRef(this._cameraRigParams.vrMetrics.aspectRatioFov, this._cameraRigParams.vrMetrics.aspectRatio, this.minZ, this.maxZ, this._cameraRigParams.vrWorkMatrix);
  23139. this._cameraRigParams.vrWorkMatrix.multiplyToRef(this._cameraRigParams.vrHMatrix, this._projectionMatrix);
  23140. return this._projectionMatrix;
  23141. };
  23142. Camera.prototype._updateCameraRotationMatrix = function () {
  23143. //Here for WebVR
  23144. };
  23145. Camera.prototype._updateWebVRCameraRotationMatrix = function () {
  23146. //Here for WebVR
  23147. };
  23148. /**
  23149. * This function MUST be overwritten by the different WebVR cameras available.
  23150. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23151. */
  23152. Camera.prototype._getWebVRProjectionMatrix = function () {
  23153. return BABYLON.Matrix.Identity();
  23154. };
  23155. /**
  23156. * This function MUST be overwritten by the different WebVR cameras available.
  23157. * The context in which it is running is the RIG camera. So 'this' is the TargetCamera, left or right.
  23158. */
  23159. Camera.prototype._getWebVRViewMatrix = function () {
  23160. return BABYLON.Matrix.Identity();
  23161. };
  23162. Camera.prototype.setCameraRigParameter = function (name, value) {
  23163. if (!this._cameraRigParams) {
  23164. this._cameraRigParams = {};
  23165. }
  23166. this._cameraRigParams[name] = value;
  23167. //provisionnally:
  23168. if (name === "interaxialDistance") {
  23169. this._cameraRigParams.stereoHalfAngle = BABYLON.Tools.ToRadians(value / 0.0637);
  23170. }
  23171. };
  23172. /**
  23173. * needs to be overridden by children so sub has required properties to be copied
  23174. */
  23175. Camera.prototype.createRigCamera = function (name, cameraIndex) {
  23176. return null;
  23177. };
  23178. /**
  23179. * May need to be overridden by children
  23180. */
  23181. Camera.prototype._updateRigCameras = function () {
  23182. for (var i = 0; i < this._rigCameras.length; i++) {
  23183. this._rigCameras[i].minZ = this.minZ;
  23184. this._rigCameras[i].maxZ = this.maxZ;
  23185. this._rigCameras[i].fov = this.fov;
  23186. }
  23187. // only update viewport when ANAGLYPH
  23188. if (this.cameraRigMode === Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH) {
  23189. this._rigCameras[0].viewport = this._rigCameras[1].viewport = this.viewport;
  23190. }
  23191. };
  23192. Camera.prototype._setupInputs = function () {
  23193. };
  23194. Camera.prototype.serialize = function () {
  23195. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  23196. // Type
  23197. serializationObject.type = this.getClassName();
  23198. // Parent
  23199. if (this.parent) {
  23200. serializationObject.parentId = this.parent.id;
  23201. }
  23202. if (this.inputs) {
  23203. this.inputs.serialize(serializationObject);
  23204. }
  23205. // Animations
  23206. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  23207. serializationObject.ranges = this.serializeAnimationRanges();
  23208. return serializationObject;
  23209. };
  23210. Camera.prototype.clone = function (name) {
  23211. return BABYLON.SerializationHelper.Clone(Camera.GetConstructorFromName(this.getClassName(), name, this.getScene(), this.interaxialDistance, this.isStereoscopicSideBySide), this);
  23212. };
  23213. Camera.prototype.getDirection = function (localAxis) {
  23214. var result = BABYLON.Vector3.Zero();
  23215. this.getDirectionToRef(localAxis, result);
  23216. return result;
  23217. };
  23218. Camera.prototype.getDirectionToRef = function (localAxis, result) {
  23219. BABYLON.Vector3.TransformNormalToRef(localAxis, this.getWorldMatrix(), result);
  23220. };
  23221. Camera.GetConstructorFromName = function (type, name, scene, interaxial_distance, isStereoscopicSideBySide) {
  23222. if (interaxial_distance === void 0) { interaxial_distance = 0; }
  23223. if (isStereoscopicSideBySide === void 0) { isStereoscopicSideBySide = true; }
  23224. switch (type) {
  23225. case "ArcRotateCamera":
  23226. return function () { return new BABYLON.ArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), scene); };
  23227. case "DeviceOrientationCamera":
  23228. return function () { return new BABYLON.DeviceOrientationCamera(name, BABYLON.Vector3.Zero(), scene); };
  23229. case "FollowCamera":
  23230. return function () { return new BABYLON.FollowCamera(name, BABYLON.Vector3.Zero(), scene); };
  23231. case "ArcFollowCamera":
  23232. return function () { return new BABYLON.ArcFollowCamera(name, 0, 0, 1.0, null, scene); };
  23233. case "GamepadCamera":
  23234. return function () { return new BABYLON.GamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23235. case "TouchCamera":
  23236. return function () { return new BABYLON.TouchCamera(name, BABYLON.Vector3.Zero(), scene); };
  23237. case "VirtualJoysticksCamera":
  23238. return function () { return new BABYLON.VirtualJoysticksCamera(name, BABYLON.Vector3.Zero(), scene); };
  23239. case "WebVRFreeCamera":
  23240. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23241. case "WebVRGamepadCamera":
  23242. return function () { return new BABYLON.WebVRFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23243. case "VRDeviceOrientationFreeCamera":
  23244. return function () { return new BABYLON.VRDeviceOrientationFreeCamera(name, BABYLON.Vector3.Zero(), scene); };
  23245. case "VRDeviceOrientationGamepadCamera":
  23246. return function () { return new BABYLON.VRDeviceOrientationGamepadCamera(name, BABYLON.Vector3.Zero(), scene); };
  23247. case "AnaglyphArcRotateCamera":
  23248. return function () { return new BABYLON.AnaglyphArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23249. case "AnaglyphFreeCamera":
  23250. return function () { return new BABYLON.AnaglyphFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23251. case "AnaglyphGamepadCamera":
  23252. return function () { return new BABYLON.AnaglyphGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23253. case "AnaglyphUniversalCamera":
  23254. return function () { return new BABYLON.AnaglyphUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, scene); };
  23255. case "StereoscopicArcRotateCamera":
  23256. return function () { return new BABYLON.StereoscopicArcRotateCamera(name, 0, 0, 1.0, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23257. case "StereoscopicFreeCamera":
  23258. return function () { return new BABYLON.StereoscopicFreeCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23259. case "StereoscopicGamepadCamera":
  23260. return function () { return new BABYLON.StereoscopicGamepadCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23261. case "StereoscopicUniversalCamera":
  23262. return function () { return new BABYLON.StereoscopicUniversalCamera(name, BABYLON.Vector3.Zero(), interaxial_distance, isStereoscopicSideBySide, scene); };
  23263. case "FreeCamera": // Forcing Universal here
  23264. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23265. default: // Universal Camera is the default value
  23266. return function () { return new BABYLON.UniversalCamera(name, BABYLON.Vector3.Zero(), scene); };
  23267. }
  23268. };
  23269. Camera.prototype.computeWorldMatrix = function () {
  23270. return this.getWorldMatrix();
  23271. };
  23272. Camera.Parse = function (parsedCamera, scene) {
  23273. var type = parsedCamera.type;
  23274. var construct = Camera.GetConstructorFromName(type, parsedCamera.name, scene, parsedCamera.interaxial_distance, parsedCamera.isStereoscopicSideBySide);
  23275. var camera = BABYLON.SerializationHelper.Parse(construct, parsedCamera, scene);
  23276. // Parent
  23277. if (parsedCamera.parentId) {
  23278. camera._waitingParentId = parsedCamera.parentId;
  23279. }
  23280. //If camera has an input manager, let it parse inputs settings
  23281. if (camera.inputs) {
  23282. camera.inputs.parse(parsedCamera);
  23283. camera._setupInputs();
  23284. }
  23285. if (camera.setPosition) { // need to force position
  23286. camera.position.copyFromFloats(0, 0, 0);
  23287. camera.setPosition(BABYLON.Vector3.FromArray(parsedCamera.position));
  23288. }
  23289. // Target
  23290. if (parsedCamera.target) {
  23291. if (camera.setTarget) {
  23292. camera.setTarget(BABYLON.Vector3.FromArray(parsedCamera.target));
  23293. }
  23294. }
  23295. // Apply 3d rig, when found
  23296. if (parsedCamera.cameraRigMode) {
  23297. var rigParams = (parsedCamera.interaxial_distance) ? { interaxialDistance: parsedCamera.interaxial_distance } : {};
  23298. camera.setCameraRigMode(parsedCamera.cameraRigMode, rigParams);
  23299. }
  23300. // Animations
  23301. if (parsedCamera.animations) {
  23302. for (var animationIndex = 0; animationIndex < parsedCamera.animations.length; animationIndex++) {
  23303. var parsedAnimation = parsedCamera.animations[animationIndex];
  23304. camera.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  23305. }
  23306. BABYLON.Node.ParseAnimationRanges(camera, parsedCamera, scene);
  23307. }
  23308. if (parsedCamera.autoAnimate) {
  23309. scene.beginAnimation(camera, parsedCamera.autoAnimateFrom, parsedCamera.autoAnimateTo, parsedCamera.autoAnimateLoop, parsedCamera.autoAnimateSpeed || 1.0);
  23310. }
  23311. return camera;
  23312. };
  23313. // Statics
  23314. Camera._PERSPECTIVE_CAMERA = 0;
  23315. Camera._ORTHOGRAPHIC_CAMERA = 1;
  23316. Camera._FOVMODE_VERTICAL_FIXED = 0;
  23317. Camera._FOVMODE_HORIZONTAL_FIXED = 1;
  23318. Camera._RIG_MODE_NONE = 0;
  23319. Camera._RIG_MODE_STEREOSCOPIC_ANAGLYPH = 10;
  23320. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL = 11;
  23321. Camera._RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED = 12;
  23322. Camera._RIG_MODE_STEREOSCOPIC_OVERUNDER = 13;
  23323. Camera._RIG_MODE_VR = 20;
  23324. Camera._RIG_MODE_WEBVR = 21;
  23325. Camera.ForceAttachControlToAlwaysPreventDefault = false;
  23326. Camera.UseAlternateWebVRRendering = false;
  23327. __decorate([
  23328. BABYLON.serializeAsVector3()
  23329. ], Camera.prototype, "position", void 0);
  23330. __decorate([
  23331. BABYLON.serializeAsVector3()
  23332. ], Camera.prototype, "upVector", void 0);
  23333. __decorate([
  23334. BABYLON.serialize()
  23335. ], Camera.prototype, "orthoLeft", void 0);
  23336. __decorate([
  23337. BABYLON.serialize()
  23338. ], Camera.prototype, "orthoRight", void 0);
  23339. __decorate([
  23340. BABYLON.serialize()
  23341. ], Camera.prototype, "orthoBottom", void 0);
  23342. __decorate([
  23343. BABYLON.serialize()
  23344. ], Camera.prototype, "orthoTop", void 0);
  23345. __decorate([
  23346. BABYLON.serialize()
  23347. ], Camera.prototype, "fov", void 0);
  23348. __decorate([
  23349. BABYLON.serialize()
  23350. ], Camera.prototype, "minZ", void 0);
  23351. __decorate([
  23352. BABYLON.serialize()
  23353. ], Camera.prototype, "maxZ", void 0);
  23354. __decorate([
  23355. BABYLON.serialize()
  23356. ], Camera.prototype, "inertia", void 0);
  23357. __decorate([
  23358. BABYLON.serialize()
  23359. ], Camera.prototype, "mode", void 0);
  23360. __decorate([
  23361. BABYLON.serialize()
  23362. ], Camera.prototype, "layerMask", void 0);
  23363. __decorate([
  23364. BABYLON.serialize()
  23365. ], Camera.prototype, "fovMode", void 0);
  23366. __decorate([
  23367. BABYLON.serialize()
  23368. ], Camera.prototype, "cameraRigMode", void 0);
  23369. __decorate([
  23370. BABYLON.serialize()
  23371. ], Camera.prototype, "interaxialDistance", void 0);
  23372. __decorate([
  23373. BABYLON.serialize()
  23374. ], Camera.prototype, "isStereoscopicSideBySide", void 0);
  23375. return Camera;
  23376. }(BABYLON.Node));
  23377. BABYLON.Camera = Camera;
  23378. })(BABYLON || (BABYLON = {}));
  23379. //# sourceMappingURL=babylon.camera.js.map
  23380. var BABYLON;
  23381. (function (BABYLON) {
  23382. var RenderingManager = /** @class */ (function () {
  23383. function RenderingManager(scene) {
  23384. this._renderingGroups = new Array();
  23385. this._autoClearDepthStencil = {};
  23386. this._customOpaqueSortCompareFn = {};
  23387. this._customAlphaTestSortCompareFn = {};
  23388. this._customTransparentSortCompareFn = {};
  23389. this._renderinGroupInfo = null;
  23390. this._scene = scene;
  23391. for (var i = RenderingManager.MIN_RENDERINGGROUPS; i < RenderingManager.MAX_RENDERINGGROUPS; i++) {
  23392. this._autoClearDepthStencil[i] = { autoClear: true, depth: true, stencil: true };
  23393. }
  23394. }
  23395. RenderingManager.prototype._clearDepthStencilBuffer = function (depth, stencil) {
  23396. if (depth === void 0) { depth = true; }
  23397. if (stencil === void 0) { stencil = true; }
  23398. if (this._depthStencilBufferAlreadyCleaned) {
  23399. return;
  23400. }
  23401. this._scene.getEngine().clear(null, false, depth, stencil);
  23402. this._depthStencilBufferAlreadyCleaned = true;
  23403. };
  23404. RenderingManager.prototype.render = function (customRenderFunction, activeMeshes, renderParticles, renderSprites) {
  23405. // Check if there's at least on observer on the onRenderingGroupObservable and initialize things to fire it
  23406. var observable = this._scene.onRenderingGroupObservable.hasObservers() ? this._scene.onRenderingGroupObservable : null;
  23407. var info = null;
  23408. if (observable) {
  23409. if (!this._renderinGroupInfo) {
  23410. this._renderinGroupInfo = new BABYLON.RenderingGroupInfo();
  23411. }
  23412. info = this._renderinGroupInfo;
  23413. info.scene = this._scene;
  23414. info.camera = this._scene.activeCamera;
  23415. }
  23416. // Dispatch sprites
  23417. if (renderSprites) {
  23418. for (var index = 0; index < this._scene.spriteManagers.length; index++) {
  23419. var manager = this._scene.spriteManagers[index];
  23420. this.dispatchSprites(manager);
  23421. }
  23422. }
  23423. // Render
  23424. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23425. this._depthStencilBufferAlreadyCleaned = index === RenderingManager.MIN_RENDERINGGROUPS;
  23426. var renderingGroup = this._renderingGroups[index];
  23427. if (!renderingGroup && !observable)
  23428. continue;
  23429. var renderingGroupMask = 0;
  23430. // Fire PRECLEAR stage
  23431. if (observable && info) {
  23432. renderingGroupMask = Math.pow(2, index);
  23433. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRECLEAR;
  23434. info.renderingGroupId = index;
  23435. observable.notifyObservers(info, renderingGroupMask);
  23436. }
  23437. // Clear depth/stencil if needed
  23438. if (RenderingManager.AUTOCLEAR) {
  23439. var autoClear = this._autoClearDepthStencil[index];
  23440. if (autoClear && autoClear.autoClear) {
  23441. this._clearDepthStencilBuffer(autoClear.depth, autoClear.stencil);
  23442. }
  23443. }
  23444. if (observable && info) {
  23445. // Fire PREOPAQUE stage
  23446. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PREOPAQUE;
  23447. observable.notifyObservers(info, renderingGroupMask);
  23448. // Fire PRETRANSPARENT stage
  23449. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_PRETRANSPARENT;
  23450. observable.notifyObservers(info, renderingGroupMask);
  23451. }
  23452. if (renderingGroup)
  23453. renderingGroup.render(customRenderFunction, renderSprites, renderParticles, activeMeshes);
  23454. // Fire POSTTRANSPARENT stage
  23455. if (observable && info) {
  23456. info.renderStage = BABYLON.RenderingGroupInfo.STAGE_POSTTRANSPARENT;
  23457. observable.notifyObservers(info, renderingGroupMask);
  23458. }
  23459. }
  23460. };
  23461. RenderingManager.prototype.reset = function () {
  23462. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23463. var renderingGroup = this._renderingGroups[index];
  23464. if (renderingGroup) {
  23465. renderingGroup.prepare();
  23466. }
  23467. }
  23468. };
  23469. RenderingManager.prototype.dispose = function () {
  23470. this.freeRenderingGroups();
  23471. this._renderingGroups.length = 0;
  23472. };
  23473. /**
  23474. * Clear the info related to rendering groups preventing retention points during dispose.
  23475. */
  23476. RenderingManager.prototype.freeRenderingGroups = function () {
  23477. for (var index = RenderingManager.MIN_RENDERINGGROUPS; index < RenderingManager.MAX_RENDERINGGROUPS; index++) {
  23478. var renderingGroup = this._renderingGroups[index];
  23479. if (renderingGroup) {
  23480. renderingGroup.dispose();
  23481. }
  23482. }
  23483. };
  23484. RenderingManager.prototype._prepareRenderingGroup = function (renderingGroupId) {
  23485. if (this._renderingGroups[renderingGroupId] === undefined) {
  23486. this._renderingGroups[renderingGroupId] = new BABYLON.RenderingGroup(renderingGroupId, this._scene, this._customOpaqueSortCompareFn[renderingGroupId], this._customAlphaTestSortCompareFn[renderingGroupId], this._customTransparentSortCompareFn[renderingGroupId]);
  23487. }
  23488. };
  23489. RenderingManager.prototype.dispatchSprites = function (spriteManager) {
  23490. var renderingGroupId = spriteManager.renderingGroupId || 0;
  23491. this._prepareRenderingGroup(renderingGroupId);
  23492. this._renderingGroups[renderingGroupId].dispatchSprites(spriteManager);
  23493. };
  23494. RenderingManager.prototype.dispatchParticles = function (particleSystem) {
  23495. var renderingGroupId = particleSystem.renderingGroupId || 0;
  23496. this._prepareRenderingGroup(renderingGroupId);
  23497. this._renderingGroups[renderingGroupId].dispatchParticles(particleSystem);
  23498. };
  23499. /**
  23500. * @param subMesh The submesh to dispatch
  23501. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23502. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23503. */
  23504. RenderingManager.prototype.dispatch = function (subMesh, mesh, material) {
  23505. if (mesh === undefined) {
  23506. mesh = subMesh.getMesh();
  23507. }
  23508. var renderingGroupId = mesh.renderingGroupId || 0;
  23509. this._prepareRenderingGroup(renderingGroupId);
  23510. this._renderingGroups[renderingGroupId].dispatch(subMesh, mesh, material);
  23511. };
  23512. /**
  23513. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  23514. * This allowed control for front to back rendering or reversly depending of the special needs.
  23515. *
  23516. * @param renderingGroupId The rendering group id corresponding to its index
  23517. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  23518. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  23519. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  23520. */
  23521. RenderingManager.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23522. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23523. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23524. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23525. this._customOpaqueSortCompareFn[renderingGroupId] = opaqueSortCompareFn;
  23526. this._customAlphaTestSortCompareFn[renderingGroupId] = alphaTestSortCompareFn;
  23527. this._customTransparentSortCompareFn[renderingGroupId] = transparentSortCompareFn;
  23528. if (this._renderingGroups[renderingGroupId]) {
  23529. var group = this._renderingGroups[renderingGroupId];
  23530. group.opaqueSortCompareFn = this._customOpaqueSortCompareFn[renderingGroupId];
  23531. group.alphaTestSortCompareFn = this._customAlphaTestSortCompareFn[renderingGroupId];
  23532. group.transparentSortCompareFn = this._customTransparentSortCompareFn[renderingGroupId];
  23533. }
  23534. };
  23535. /**
  23536. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  23537. *
  23538. * @param renderingGroupId The rendering group id corresponding to its index
  23539. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  23540. * @param depth Automatically clears depth between groups if true and autoClear is true.
  23541. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  23542. */
  23543. RenderingManager.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  23544. if (depth === void 0) { depth = true; }
  23545. if (stencil === void 0) { stencil = true; }
  23546. this._autoClearDepthStencil[renderingGroupId] = {
  23547. autoClear: autoClearDepthStencil,
  23548. depth: depth,
  23549. stencil: stencil
  23550. };
  23551. };
  23552. /**
  23553. * The max id used for rendering groups (not included)
  23554. */
  23555. RenderingManager.MAX_RENDERINGGROUPS = 4;
  23556. /**
  23557. * The min id used for rendering groups (included)
  23558. */
  23559. RenderingManager.MIN_RENDERINGGROUPS = 0;
  23560. /**
  23561. * Used to globally prevent autoclearing scenes.
  23562. */
  23563. RenderingManager.AUTOCLEAR = true;
  23564. return RenderingManager;
  23565. }());
  23566. BABYLON.RenderingManager = RenderingManager;
  23567. })(BABYLON || (BABYLON = {}));
  23568. //# sourceMappingURL=babylon.renderingManager.js.map
  23569. var BABYLON;
  23570. (function (BABYLON) {
  23571. var RenderingGroup = /** @class */ (function () {
  23572. /**
  23573. * Creates a new rendering group.
  23574. * @param index The rendering group index
  23575. * @param opaqueSortCompareFn The opaque sort comparison function. If null no order is applied
  23576. * @param alphaTestSortCompareFn The alpha test sort comparison function. If null no order is applied
  23577. * @param transparentSortCompareFn The transparent sort comparison function. If null back to front + alpha index sort is applied
  23578. */
  23579. function RenderingGroup(index, scene, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  23580. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  23581. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  23582. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  23583. this.index = index;
  23584. this._opaqueSubMeshes = new BABYLON.SmartArray(256);
  23585. this._transparentSubMeshes = new BABYLON.SmartArray(256);
  23586. this._alphaTestSubMeshes = new BABYLON.SmartArray(256);
  23587. this._depthOnlySubMeshes = new BABYLON.SmartArray(256);
  23588. this._particleSystems = new BABYLON.SmartArray(256);
  23589. this._spriteManagers = new BABYLON.SmartArray(256);
  23590. this._edgesRenderers = new BABYLON.SmartArray(16);
  23591. this._scene = scene;
  23592. this.opaqueSortCompareFn = opaqueSortCompareFn;
  23593. this.alphaTestSortCompareFn = alphaTestSortCompareFn;
  23594. this.transparentSortCompareFn = transparentSortCompareFn;
  23595. }
  23596. Object.defineProperty(RenderingGroup.prototype, "opaqueSortCompareFn", {
  23597. /**
  23598. * Set the opaque sort comparison function.
  23599. * If null the sub meshes will be render in the order they were created
  23600. */
  23601. set: function (value) {
  23602. this._opaqueSortCompareFn = value;
  23603. if (value) {
  23604. this._renderOpaque = this.renderOpaqueSorted;
  23605. }
  23606. else {
  23607. this._renderOpaque = RenderingGroup.renderUnsorted;
  23608. }
  23609. },
  23610. enumerable: true,
  23611. configurable: true
  23612. });
  23613. Object.defineProperty(RenderingGroup.prototype, "alphaTestSortCompareFn", {
  23614. /**
  23615. * Set the alpha test sort comparison function.
  23616. * If null the sub meshes will be render in the order they were created
  23617. */
  23618. set: function (value) {
  23619. this._alphaTestSortCompareFn = value;
  23620. if (value) {
  23621. this._renderAlphaTest = this.renderAlphaTestSorted;
  23622. }
  23623. else {
  23624. this._renderAlphaTest = RenderingGroup.renderUnsorted;
  23625. }
  23626. },
  23627. enumerable: true,
  23628. configurable: true
  23629. });
  23630. Object.defineProperty(RenderingGroup.prototype, "transparentSortCompareFn", {
  23631. /**
  23632. * Set the transparent sort comparison function.
  23633. * If null the sub meshes will be render in the order they were created
  23634. */
  23635. set: function (value) {
  23636. if (value) {
  23637. this._transparentSortCompareFn = value;
  23638. }
  23639. else {
  23640. this._transparentSortCompareFn = RenderingGroup.defaultTransparentSortCompare;
  23641. }
  23642. this._renderTransparent = this.renderTransparentSorted;
  23643. },
  23644. enumerable: true,
  23645. configurable: true
  23646. });
  23647. /**
  23648. * Render all the sub meshes contained in the group.
  23649. * @param customRenderFunction Used to override the default render behaviour of the group.
  23650. * @returns true if rendered some submeshes.
  23651. */
  23652. RenderingGroup.prototype.render = function (customRenderFunction, renderSprites, renderParticles, activeMeshes) {
  23653. if (customRenderFunction) {
  23654. customRenderFunction(this._opaqueSubMeshes, this._alphaTestSubMeshes, this._transparentSubMeshes, this._depthOnlySubMeshes);
  23655. return;
  23656. }
  23657. var engine = this._scene.getEngine();
  23658. // Depth only
  23659. if (this._depthOnlySubMeshes.length !== 0) {
  23660. engine.setColorWrite(false);
  23661. this._renderAlphaTest(this._depthOnlySubMeshes);
  23662. engine.setColorWrite(true);
  23663. }
  23664. // Opaque
  23665. if (this._opaqueSubMeshes.length !== 0) {
  23666. this._renderOpaque(this._opaqueSubMeshes);
  23667. }
  23668. // Alpha test
  23669. if (this._alphaTestSubMeshes.length !== 0) {
  23670. this._renderAlphaTest(this._alphaTestSubMeshes);
  23671. }
  23672. var stencilState = engine.getStencilBuffer();
  23673. engine.setStencilBuffer(false);
  23674. // Sprites
  23675. if (renderSprites) {
  23676. this._renderSprites();
  23677. }
  23678. // Particles
  23679. if (renderParticles) {
  23680. this._renderParticles(activeMeshes);
  23681. }
  23682. if (this.onBeforeTransparentRendering) {
  23683. this.onBeforeTransparentRendering();
  23684. }
  23685. // Transparent
  23686. if (this._transparentSubMeshes.length !== 0) {
  23687. this._renderTransparent(this._transparentSubMeshes);
  23688. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23689. }
  23690. // Set back stencil to false in case it changes before the edge renderer.
  23691. engine.setStencilBuffer(false);
  23692. // Edges
  23693. for (var edgesRendererIndex = 0; edgesRendererIndex < this._edgesRenderers.length; edgesRendererIndex++) {
  23694. this._edgesRenderers.data[edgesRendererIndex].render();
  23695. }
  23696. // Restore Stencil state.
  23697. engine.setStencilBuffer(stencilState);
  23698. };
  23699. /**
  23700. * Renders the opaque submeshes in the order from the opaqueSortCompareFn.
  23701. * @param subMeshes The submeshes to render
  23702. */
  23703. RenderingGroup.prototype.renderOpaqueSorted = function (subMeshes) {
  23704. return RenderingGroup.renderSorted(subMeshes, this._opaqueSortCompareFn, this._scene.activeCamera, false);
  23705. };
  23706. /**
  23707. * Renders the opaque submeshes in the order from the alphatestSortCompareFn.
  23708. * @param subMeshes The submeshes to render
  23709. */
  23710. RenderingGroup.prototype.renderAlphaTestSorted = function (subMeshes) {
  23711. return RenderingGroup.renderSorted(subMeshes, this._alphaTestSortCompareFn, this._scene.activeCamera, false);
  23712. };
  23713. /**
  23714. * Renders the opaque submeshes in the order from the transparentSortCompareFn.
  23715. * @param subMeshes The submeshes to render
  23716. */
  23717. RenderingGroup.prototype.renderTransparentSorted = function (subMeshes) {
  23718. return RenderingGroup.renderSorted(subMeshes, this._transparentSortCompareFn, this._scene.activeCamera, true);
  23719. };
  23720. /**
  23721. * Renders the submeshes in a specified order.
  23722. * @param subMeshes The submeshes to sort before render
  23723. * @param sortCompareFn The comparison function use to sort
  23724. * @param cameraPosition The camera position use to preprocess the submeshes to help sorting
  23725. * @param transparent Specifies to activate blending if true
  23726. */
  23727. RenderingGroup.renderSorted = function (subMeshes, sortCompareFn, camera, transparent) {
  23728. var subIndex = 0;
  23729. var subMesh;
  23730. var cameraPosition = camera ? camera.globalPosition : BABYLON.Vector3.Zero();
  23731. for (; subIndex < subMeshes.length; subIndex++) {
  23732. subMesh = subMeshes.data[subIndex];
  23733. subMesh._alphaIndex = subMesh.getMesh().alphaIndex;
  23734. subMesh._distanceToCamera = subMesh.getBoundingInfo().boundingSphere.centerWorld.subtract(cameraPosition).length();
  23735. }
  23736. var sortedArray = subMeshes.data.slice(0, subMeshes.length);
  23737. if (sortCompareFn) {
  23738. sortedArray.sort(sortCompareFn);
  23739. }
  23740. for (subIndex = 0; subIndex < sortedArray.length; subIndex++) {
  23741. subMesh = sortedArray[subIndex];
  23742. if (transparent) {
  23743. var material = subMesh.getMaterial();
  23744. if (material && material.needDepthPrePass) {
  23745. var engine = material.getScene().getEngine();
  23746. engine.setColorWrite(false);
  23747. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  23748. subMesh.render(false);
  23749. engine.setColorWrite(true);
  23750. }
  23751. }
  23752. subMesh.render(transparent);
  23753. }
  23754. };
  23755. /**
  23756. * Renders the submeshes in the order they were dispatched (no sort applied).
  23757. * @param subMeshes The submeshes to render
  23758. */
  23759. RenderingGroup.renderUnsorted = function (subMeshes) {
  23760. for (var subIndex = 0; subIndex < subMeshes.length; subIndex++) {
  23761. var submesh = subMeshes.data[subIndex];
  23762. submesh.render(false);
  23763. }
  23764. };
  23765. /**
  23766. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23767. * are rendered back to front if in the same alpha index.
  23768. *
  23769. * @param a The first submesh
  23770. * @param b The second submesh
  23771. * @returns The result of the comparison
  23772. */
  23773. RenderingGroup.defaultTransparentSortCompare = function (a, b) {
  23774. // Alpha index first
  23775. if (a._alphaIndex > b._alphaIndex) {
  23776. return 1;
  23777. }
  23778. if (a._alphaIndex < b._alphaIndex) {
  23779. return -1;
  23780. }
  23781. // Then distance to camera
  23782. return RenderingGroup.backToFrontSortCompare(a, b);
  23783. };
  23784. /**
  23785. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23786. * are rendered back to front.
  23787. *
  23788. * @param a The first submesh
  23789. * @param b The second submesh
  23790. * @returns The result of the comparison
  23791. */
  23792. RenderingGroup.backToFrontSortCompare = function (a, b) {
  23793. // Then distance to camera
  23794. if (a._distanceToCamera < b._distanceToCamera) {
  23795. return 1;
  23796. }
  23797. if (a._distanceToCamera > b._distanceToCamera) {
  23798. return -1;
  23799. }
  23800. return 0;
  23801. };
  23802. /**
  23803. * Build in function which can be applied to ensure meshes of a special queue (opaque, alpha test, transparent)
  23804. * are rendered front to back (prevent overdraw).
  23805. *
  23806. * @param a The first submesh
  23807. * @param b The second submesh
  23808. * @returns The result of the comparison
  23809. */
  23810. RenderingGroup.frontToBackSortCompare = function (a, b) {
  23811. // Then distance to camera
  23812. if (a._distanceToCamera < b._distanceToCamera) {
  23813. return -1;
  23814. }
  23815. if (a._distanceToCamera > b._distanceToCamera) {
  23816. return 1;
  23817. }
  23818. return 0;
  23819. };
  23820. /**
  23821. * Resets the different lists of submeshes to prepare a new frame.
  23822. */
  23823. RenderingGroup.prototype.prepare = function () {
  23824. this._opaqueSubMeshes.reset();
  23825. this._transparentSubMeshes.reset();
  23826. this._alphaTestSubMeshes.reset();
  23827. this._depthOnlySubMeshes.reset();
  23828. this._particleSystems.reset();
  23829. this._spriteManagers.reset();
  23830. this._edgesRenderers.reset();
  23831. };
  23832. RenderingGroup.prototype.dispose = function () {
  23833. this._opaqueSubMeshes.dispose();
  23834. this._transparentSubMeshes.dispose();
  23835. this._alphaTestSubMeshes.dispose();
  23836. this._depthOnlySubMeshes.dispose();
  23837. this._particleSystems.dispose();
  23838. this._spriteManagers.dispose();
  23839. this._edgesRenderers.dispose();
  23840. };
  23841. /**
  23842. * Inserts the submesh in its correct queue depending on its material.
  23843. * @param subMesh The submesh to dispatch
  23844. * @param [mesh] Optional reference to the submeshes's mesh. Provide if you have an exiting reference to improve performance.
  23845. * @param [material] Optional reference to the submeshes's material. Provide if you have an exiting reference to improve performance.
  23846. */
  23847. RenderingGroup.prototype.dispatch = function (subMesh, mesh, material) {
  23848. // Get mesh and materials if not provided
  23849. if (mesh === undefined) {
  23850. mesh = subMesh.getMesh();
  23851. }
  23852. if (material === undefined) {
  23853. material = subMesh.getMaterial();
  23854. }
  23855. if (material === null || material === undefined) {
  23856. return;
  23857. }
  23858. if (material.needAlphaBlendingForMesh(mesh)) { // Transparent
  23859. this._transparentSubMeshes.push(subMesh);
  23860. }
  23861. else if (material.needAlphaTesting()) { // Alpha test
  23862. if (material.needDepthPrePass) {
  23863. this._depthOnlySubMeshes.push(subMesh);
  23864. }
  23865. this._alphaTestSubMeshes.push(subMesh);
  23866. }
  23867. else {
  23868. if (material.needDepthPrePass) {
  23869. this._depthOnlySubMeshes.push(subMesh);
  23870. }
  23871. this._opaqueSubMeshes.push(subMesh); // Opaque
  23872. }
  23873. if (mesh._edgesRenderer !== null && mesh._edgesRenderer !== undefined && mesh._edgesRenderer.isEnabled) {
  23874. this._edgesRenderers.push(mesh._edgesRenderer);
  23875. }
  23876. };
  23877. RenderingGroup.prototype.dispatchSprites = function (spriteManager) {
  23878. this._spriteManagers.push(spriteManager);
  23879. };
  23880. RenderingGroup.prototype.dispatchParticles = function (particleSystem) {
  23881. this._particleSystems.push(particleSystem);
  23882. };
  23883. RenderingGroup.prototype._renderParticles = function (activeMeshes) {
  23884. if (this._particleSystems.length === 0) {
  23885. return;
  23886. }
  23887. // Particles
  23888. var activeCamera = this._scene.activeCamera;
  23889. this._scene.onBeforeParticlesRenderingObservable.notifyObservers(this._scene);
  23890. for (var particleIndex = 0; particleIndex < this._particleSystems.length; particleIndex++) {
  23891. var particleSystem = this._particleSystems.data[particleIndex];
  23892. if ((activeCamera && activeCamera.layerMask & particleSystem.layerMask) === 0) {
  23893. continue;
  23894. }
  23895. var emitter = particleSystem.emitter;
  23896. if (!emitter.position || !activeMeshes || activeMeshes.indexOf(emitter) !== -1) {
  23897. this._scene._activeParticles.addCount(particleSystem.render(), false);
  23898. }
  23899. }
  23900. this._scene.onAfterParticlesRenderingObservable.notifyObservers(this._scene);
  23901. };
  23902. RenderingGroup.prototype._renderSprites = function () {
  23903. if (!this._scene.spritesEnabled || this._spriteManagers.length === 0) {
  23904. return;
  23905. }
  23906. // Sprites
  23907. var activeCamera = this._scene.activeCamera;
  23908. this._scene.onBeforeSpritesRenderingObservable.notifyObservers(this._scene);
  23909. for (var id = 0; id < this._spriteManagers.length; id++) {
  23910. var spriteManager = this._spriteManagers.data[id];
  23911. if (((activeCamera && activeCamera.layerMask & spriteManager.layerMask) !== 0)) {
  23912. spriteManager.render();
  23913. }
  23914. }
  23915. this._scene.onAfterSpritesRenderingObservable.notifyObservers(this._scene);
  23916. };
  23917. return RenderingGroup;
  23918. }());
  23919. BABYLON.RenderingGroup = RenderingGroup;
  23920. })(BABYLON || (BABYLON = {}));
  23921. //# sourceMappingURL=babylon.renderingGroup.js.map
  23922. var BABYLON;
  23923. (function (BABYLON) {
  23924. /** @hidden */
  23925. var ClickInfo = /** @class */ (function () {
  23926. function ClickInfo() {
  23927. this._singleClick = false;
  23928. this._doubleClick = false;
  23929. this._hasSwiped = false;
  23930. this._ignore = false;
  23931. }
  23932. Object.defineProperty(ClickInfo.prototype, "singleClick", {
  23933. get: function () {
  23934. return this._singleClick;
  23935. },
  23936. set: function (b) {
  23937. this._singleClick = b;
  23938. },
  23939. enumerable: true,
  23940. configurable: true
  23941. });
  23942. Object.defineProperty(ClickInfo.prototype, "doubleClick", {
  23943. get: function () {
  23944. return this._doubleClick;
  23945. },
  23946. set: function (b) {
  23947. this._doubleClick = b;
  23948. },
  23949. enumerable: true,
  23950. configurable: true
  23951. });
  23952. Object.defineProperty(ClickInfo.prototype, "hasSwiped", {
  23953. get: function () {
  23954. return this._hasSwiped;
  23955. },
  23956. set: function (b) {
  23957. this._hasSwiped = b;
  23958. },
  23959. enumerable: true,
  23960. configurable: true
  23961. });
  23962. Object.defineProperty(ClickInfo.prototype, "ignore", {
  23963. get: function () {
  23964. return this._ignore;
  23965. },
  23966. set: function (b) {
  23967. this._ignore = b;
  23968. },
  23969. enumerable: true,
  23970. configurable: true
  23971. });
  23972. return ClickInfo;
  23973. }());
  23974. /**
  23975. * This class is used by the onRenderingGroupObservable
  23976. */
  23977. var RenderingGroupInfo = /** @class */ (function () {
  23978. function RenderingGroupInfo() {
  23979. }
  23980. /**
  23981. * Stage corresponding to the very first hook in the renderingGroup phase: before the render buffer may be cleared
  23982. * This stage will be fired no matter what
  23983. */
  23984. RenderingGroupInfo.STAGE_PRECLEAR = 1;
  23985. /**
  23986. * Called before opaque object are rendered.
  23987. * This stage will be fired only if there's 3D Opaque content to render
  23988. */
  23989. RenderingGroupInfo.STAGE_PREOPAQUE = 2;
  23990. /**
  23991. * Called after the opaque objects are rendered and before the transparent ones
  23992. * This stage will be fired only if there's 3D transparent content to render
  23993. */
  23994. RenderingGroupInfo.STAGE_PRETRANSPARENT = 3;
  23995. /**
  23996. * Called after the transparent object are rendered, last hook of the renderingGroup phase
  23997. * This stage will be fired no matter what
  23998. */
  23999. RenderingGroupInfo.STAGE_POSTTRANSPARENT = 4;
  24000. return RenderingGroupInfo;
  24001. }());
  24002. BABYLON.RenderingGroupInfo = RenderingGroupInfo;
  24003. /**
  24004. * Represents a scene to be rendered by the engine.
  24005. * @see http://doc.babylonjs.com/features/scene
  24006. */
  24007. var Scene = /** @class */ (function () {
  24008. /**
  24009. * Creates a new Scene
  24010. * @param engine defines the engine to use to render this scene
  24011. */
  24012. function Scene(engine) {
  24013. // Members
  24014. /**
  24015. * Gets or sets a boolean that indicates if the scene must clear the render buffer before rendering a frame
  24016. */
  24017. this.autoClear = true;
  24018. /**
  24019. * Gets or sets a boolean that indicates if the scene must clear the depth and stencil buffers before rendering a frame
  24020. */
  24021. this.autoClearDepthAndStencil = true;
  24022. /**
  24023. * Defines the color used to clear the render buffer (Default is (0.2, 0.2, 0.3, 1.0))
  24024. */
  24025. this.clearColor = new BABYLON.Color4(0.2, 0.2, 0.3, 1.0);
  24026. /**
  24027. * Defines the color used to simulate the ambient color (Default is (0, 0, 0))
  24028. */
  24029. this.ambientColor = new BABYLON.Color3(0, 0, 0);
  24030. this._forceWireframe = false;
  24031. this._forcePointsCloud = false;
  24032. /**
  24033. * Gets or sets a boolean indicating if all bounding boxes must be rendered
  24034. */
  24035. this.forceShowBoundingBoxes = false;
  24036. /**
  24037. * Gets or sets a boolean indicating if animations are enabled
  24038. */
  24039. this.animationsEnabled = true;
  24040. this._animationPropertiesOverride = null;
  24041. /**
  24042. * Gets or sets a boolean indicating if a constant deltatime has to be used
  24043. * This is mostly useful for testing purposes when you do not want the animations to scale with the framerate
  24044. */
  24045. this.useConstantAnimationDeltaTime = false;
  24046. /**
  24047. * Gets or sets a boolean indicating if the scene must keep the meshUnderPointer property updated
  24048. * Please note that it requires to run a ray cast through the scene on every frame
  24049. */
  24050. this.constantlyUpdateMeshUnderPointer = false;
  24051. /**
  24052. * Defines the HTML cursor to use when hovering over interactive elements
  24053. */
  24054. this.hoverCursor = "pointer";
  24055. /**
  24056. * Defines the HTML default cursor to use (empty by default)
  24057. */
  24058. this.defaultCursor = "";
  24059. /**
  24060. * This is used to call preventDefault() on pointer down
  24061. * in order to block unwanted artifacts like system double clicks
  24062. */
  24063. this.preventDefaultOnPointerDown = true;
  24064. // Metadata
  24065. /**
  24066. * Gets or sets user defined metadata
  24067. */
  24068. this.metadata = null;
  24069. /**
  24070. * Use this array to add regular expressions used to disable offline support for specific urls
  24071. */
  24072. this.disableOfflineSupportExceptionRules = new Array();
  24073. /**
  24074. * An event triggered when the scene is disposed.
  24075. */
  24076. this.onDisposeObservable = new BABYLON.Observable();
  24077. this._onDisposeObserver = null;
  24078. /**
  24079. * An event triggered before rendering the scene (right after animations and physics)
  24080. */
  24081. this.onBeforeRenderObservable = new BABYLON.Observable();
  24082. this._onBeforeRenderObserver = null;
  24083. /**
  24084. * An event triggered after rendering the scene
  24085. */
  24086. this.onAfterRenderObservable = new BABYLON.Observable();
  24087. this._onAfterRenderObserver = null;
  24088. /**
  24089. * An event triggered before animating the scene
  24090. */
  24091. this.onBeforeAnimationsObservable = new BABYLON.Observable();
  24092. /**
  24093. * An event triggered after animations processing
  24094. */
  24095. this.onAfterAnimationsObservable = new BABYLON.Observable();
  24096. /**
  24097. * An event triggered before draw calls are ready to be sent
  24098. */
  24099. this.onBeforeDrawPhaseObservable = new BABYLON.Observable();
  24100. /**
  24101. * An event triggered after draw calls have been sent
  24102. */
  24103. this.onAfterDrawPhaseObservable = new BABYLON.Observable();
  24104. /**
  24105. * An event triggered when physic simulation is about to be run
  24106. */
  24107. this.onBeforePhysicsObservable = new BABYLON.Observable();
  24108. /**
  24109. * An event triggered when physic simulation has been done
  24110. */
  24111. this.onAfterPhysicsObservable = new BABYLON.Observable();
  24112. /**
  24113. * An event triggered when the scene is ready
  24114. */
  24115. this.onReadyObservable = new BABYLON.Observable();
  24116. /**
  24117. * An event triggered before rendering a camera
  24118. */
  24119. this.onBeforeCameraRenderObservable = new BABYLON.Observable();
  24120. this._onBeforeCameraRenderObserver = null;
  24121. /**
  24122. * An event triggered after rendering a camera
  24123. */
  24124. this.onAfterCameraRenderObservable = new BABYLON.Observable();
  24125. this._onAfterCameraRenderObserver = null;
  24126. /**
  24127. * An event triggered when active meshes evaluation is about to start
  24128. */
  24129. this.onBeforeActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24130. /**
  24131. * An event triggered when active meshes evaluation is done
  24132. */
  24133. this.onAfterActiveMeshesEvaluationObservable = new BABYLON.Observable();
  24134. /**
  24135. * An event triggered when particles rendering is about to start
  24136. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24137. */
  24138. this.onBeforeParticlesRenderingObservable = new BABYLON.Observable();
  24139. /**
  24140. * An event triggered when particles rendering is done
  24141. * Note: This event can be trigger more than once per frame (because particles can be rendered by render target textures as well)
  24142. */
  24143. this.onAfterParticlesRenderingObservable = new BABYLON.Observable();
  24144. /**
  24145. * An event triggered when sprites rendering is about to start
  24146. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24147. */
  24148. this.onBeforeSpritesRenderingObservable = new BABYLON.Observable();
  24149. /**
  24150. * An event triggered when sprites rendering is done
  24151. * Note: This event can be trigger more than once per frame (because sprites can be rendered by render target textures as well)
  24152. */
  24153. this.onAfterSpritesRenderingObservable = new BABYLON.Observable();
  24154. /**
  24155. * An event triggered when SceneLoader.Append or SceneLoader.Load or SceneLoader.ImportMesh were successfully executed
  24156. */
  24157. this.onDataLoadedObservable = new BABYLON.Observable();
  24158. /**
  24159. * An event triggered when a camera is created
  24160. */
  24161. this.onNewCameraAddedObservable = new BABYLON.Observable();
  24162. /**
  24163. * An event triggered when a camera is removed
  24164. */
  24165. this.onCameraRemovedObservable = new BABYLON.Observable();
  24166. /**
  24167. * An event triggered when a light is created
  24168. */
  24169. this.onNewLightAddedObservable = new BABYLON.Observable();
  24170. /**
  24171. * An event triggered when a light is removed
  24172. */
  24173. this.onLightRemovedObservable = new BABYLON.Observable();
  24174. /**
  24175. * An event triggered when a geometry is created
  24176. */
  24177. this.onNewGeometryAddedObservable = new BABYLON.Observable();
  24178. /**
  24179. * An event triggered when a geometry is removed
  24180. */
  24181. this.onGeometryRemovedObservable = new BABYLON.Observable();
  24182. /**
  24183. * An event triggered when a transform node is created
  24184. */
  24185. this.onNewTransformNodeAddedObservable = new BABYLON.Observable();
  24186. /**
  24187. * An event triggered when a transform node is removed
  24188. */
  24189. this.onTransformNodeRemovedObservable = new BABYLON.Observable();
  24190. /**
  24191. * An event triggered when a mesh is created
  24192. */
  24193. this.onNewMeshAddedObservable = new BABYLON.Observable();
  24194. /**
  24195. * An event triggered when a mesh is removed
  24196. */
  24197. this.onMeshRemovedObservable = new BABYLON.Observable();
  24198. /**
  24199. * An event triggered when render targets are about to be rendered
  24200. * Can happen multiple times per frame.
  24201. */
  24202. this.onBeforeRenderTargetsRenderObservable = new BABYLON.Observable();
  24203. /**
  24204. * An event triggered when render targets were rendered.
  24205. * Can happen multiple times per frame.
  24206. */
  24207. this.onAfterRenderTargetsRenderObservable = new BABYLON.Observable();
  24208. /**
  24209. * An event triggered before calculating deterministic simulation step
  24210. */
  24211. this.onBeforeStepObservable = new BABYLON.Observable();
  24212. /**
  24213. * An event triggered after calculating deterministic simulation step
  24214. */
  24215. this.onAfterStepObservable = new BABYLON.Observable();
  24216. /**
  24217. * This Observable will be triggered for each stage of each renderingGroup of each rendered camera.
  24218. * The RenderinGroupInfo class contains all the information about the context in which the observable is called
  24219. * 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)
  24220. */
  24221. this.onRenderingGroupObservable = new BABYLON.Observable();
  24222. // Animations
  24223. /**
  24224. * Gets a list of Animations associated with the scene
  24225. */
  24226. this.animations = [];
  24227. this._registeredForLateAnimationBindings = new BABYLON.SmartArrayNoDuplicate(256);
  24228. /**
  24229. * 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).
  24230. * You have the possibility to skip the process and the call to onPointerObservable by setting PointerInfoPre.skipOnPointerObservable to true
  24231. */
  24232. this.onPrePointerObservable = new BABYLON.Observable();
  24233. /**
  24234. * Observable event triggered each time an input event is received from the rendering canvas
  24235. */
  24236. this.onPointerObservable = new BABYLON.Observable();
  24237. this._meshPickProceed = false;
  24238. this._currentPickResult = null;
  24239. this._previousPickResult = null;
  24240. this._totalPointersPressed = 0;
  24241. this._doubleClickOccured = false;
  24242. /** Define this parameter if you are using multiple cameras and you want to specify which one should be used for pointer position */
  24243. this.cameraToUseForPointers = null;
  24244. this._pointerX = 0;
  24245. this._pointerY = 0;
  24246. this._startingPointerPosition = new BABYLON.Vector2(0, 0);
  24247. this._previousStartingPointerPosition = new BABYLON.Vector2(0, 0);
  24248. this._startingPointerTime = 0;
  24249. this._previousStartingPointerTime = 0;
  24250. this._pointerCaptures = {};
  24251. // Deterministic lockstep
  24252. this._timeAccumulator = 0;
  24253. this._currentStepId = 0;
  24254. this._currentInternalStep = 0;
  24255. // Keyboard
  24256. /**
  24257. * This observable event is triggered when any keyboard event si raised and registered during Scene.attachControl()
  24258. * You have the possibility to skip the process and the call to onKeyboardObservable by setting KeyboardInfoPre.skipOnPointerObservable to true
  24259. */
  24260. this.onPreKeyboardObservable = new BABYLON.Observable();
  24261. /**
  24262. * Observable event triggered each time an keyboard event is received from the hosting window
  24263. */
  24264. this.onKeyboardObservable = new BABYLON.Observable();
  24265. // Coordinates system
  24266. this._useRightHandedSystem = false;
  24267. // Fog
  24268. this._fogEnabled = true;
  24269. this._fogMode = Scene.FOGMODE_NONE;
  24270. /**
  24271. * Gets or sets the fog color to use
  24272. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24273. */
  24274. this.fogColor = new BABYLON.Color3(0.2, 0.2, 0.3);
  24275. /**
  24276. * Gets or sets the fog density to use
  24277. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24278. */
  24279. this.fogDensity = 0.1;
  24280. /**
  24281. * Gets or sets the fog start distance to use
  24282. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24283. */
  24284. this.fogStart = 0;
  24285. /**
  24286. * Gets or sets the fog end distance to use
  24287. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24288. */
  24289. this.fogEnd = 1000.0;
  24290. // Lights
  24291. this._shadowsEnabled = true;
  24292. this._lightsEnabled = true;
  24293. /**
  24294. * All of the lights added to this scene
  24295. * @see http://doc.babylonjs.com/babylon101/lights
  24296. */
  24297. this.lights = new Array();
  24298. // Cameras
  24299. /** All of the cameras added to this scene.
  24300. * @see http://doc.babylonjs.com/babylon101/cameras
  24301. */
  24302. this.cameras = new Array();
  24303. /** All of the active cameras added to this scene. */
  24304. this.activeCameras = new Array();
  24305. // Meshes
  24306. /**
  24307. * All of the tranform nodes added to this scene
  24308. * @see http://doc.babylonjs.com/how_to/transformnode
  24309. */
  24310. this.transformNodes = new Array();
  24311. /**
  24312. * All of the (abstract) meshes added to this scene
  24313. */
  24314. this.meshes = new Array();
  24315. /**
  24316. * All of the animation groups added to this scene
  24317. * @see http://doc.babylonjs.com/how_to/group
  24318. */
  24319. this.animationGroups = new Array();
  24320. // Geometries
  24321. this._geometries = new Array();
  24322. /**
  24323. * All of the materials added to this scene
  24324. * @see http://doc.babylonjs.com/babylon101/materials
  24325. */
  24326. this.materials = new Array();
  24327. /**
  24328. * All of the multi-materials added to this scene
  24329. * @see http://doc.babylonjs.com/how_to/multi_materials
  24330. */
  24331. this.multiMaterials = new Array();
  24332. // Textures
  24333. this._texturesEnabled = true;
  24334. /**
  24335. * All of the textures added to this scene
  24336. */
  24337. this.textures = new Array();
  24338. // Particles
  24339. /**
  24340. * Gets or sets a boolean indicating if particles are enabled on this scene
  24341. */
  24342. this.particlesEnabled = true;
  24343. /**
  24344. * All of the particle systems added to this scene
  24345. * @see http://doc.babylonjs.com/babylon101/particles
  24346. */
  24347. this.particleSystems = new Array();
  24348. // Sprites
  24349. /**
  24350. * Gets or sets a boolean indicating if sprites are enabled on this scene
  24351. */
  24352. this.spritesEnabled = true;
  24353. /**
  24354. * All of the sprite managers added to this scene
  24355. * @see http://doc.babylonjs.com/babylon101/sprites
  24356. */
  24357. this.spriteManagers = new Array();
  24358. /**
  24359. * The list of layers (background and foreground) of the scene
  24360. */
  24361. this.layers = new Array();
  24362. /**
  24363. * The list of effect layers (highlights/glow) added to the scene
  24364. * @see http://doc.babylonjs.com/how_to/highlight_layer
  24365. * @see http://doc.babylonjs.com/how_to/glow_layer
  24366. */
  24367. this.effectLayers = new Array();
  24368. // Skeletons
  24369. this._skeletonsEnabled = true;
  24370. /**
  24371. * The list of skeletons added to the scene
  24372. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  24373. */
  24374. this.skeletons = new Array();
  24375. // Morph targets
  24376. /**
  24377. * The list of morph target managers added to the scene
  24378. * @see http://doc.babylonjs.com/how_to/how_to_dynamically_morph_a_mesh
  24379. */
  24380. this.morphTargetManagers = new Array();
  24381. // Lens flares
  24382. /**
  24383. * Gets or sets a boolean indicating if lens flares are enabled on this scene
  24384. */
  24385. this.lensFlaresEnabled = true;
  24386. /**
  24387. * The list of lens flare system added to the scene
  24388. * @see http://doc.babylonjs.com/how_to/how_to_use_lens_flares
  24389. */
  24390. this.lensFlareSystems = new Array();
  24391. // Collisions
  24392. /**
  24393. * Gets or sets a boolean indicating if collisions are enabled on this scene
  24394. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24395. */
  24396. this.collisionsEnabled = true;
  24397. /**
  24398. * Defines the gravity applied to this scene (used only for collisions)
  24399. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity
  24400. */
  24401. this.gravity = new BABYLON.Vector3(0, -9.807, 0);
  24402. // Postprocesses
  24403. /**
  24404. * Gets or sets a boolean indicating if postprocesses are enabled on this scene
  24405. */
  24406. this.postProcessesEnabled = true;
  24407. /**
  24408. * The list of postprocesses added to the scene
  24409. */
  24410. this.postProcesses = new Array();
  24411. // Customs render targets
  24412. /**
  24413. * Gets or sets a boolean indicating if render targets are enabled on this scene
  24414. */
  24415. this.renderTargetsEnabled = true;
  24416. /**
  24417. * Gets or sets a boolean indicating if next render targets must be dumped as image for debugging purposes
  24418. * We recommend not using it and instead rely on Spector.js: http://spector.babylonjs.com
  24419. */
  24420. this.dumpNextRenderTargets = false;
  24421. /**
  24422. * The list of user defined render targets added to the scene
  24423. */
  24424. this.customRenderTargets = new Array();
  24425. /**
  24426. * Gets the list of meshes imported to the scene through SceneLoader
  24427. */
  24428. this.importedMeshesFiles = new Array();
  24429. // Probes
  24430. /**
  24431. * Gets or sets a boolean indicating if probes are enabled on this scene
  24432. */
  24433. this.probesEnabled = true;
  24434. /**
  24435. * The list of reflection probes added to the scene
  24436. * @see http://doc.babylonjs.com/how_to/how_to_use_reflection_probes
  24437. */
  24438. this.reflectionProbes = new Array();
  24439. /** @hidden */
  24440. this._actionManagers = new Array();
  24441. this._meshesForIntersections = new BABYLON.SmartArrayNoDuplicate(256);
  24442. // Procedural textures
  24443. /**
  24444. * Gets or sets a boolean indicating if procedural textures are enabled on this scene
  24445. */
  24446. this.proceduralTexturesEnabled = true;
  24447. /**
  24448. * The list of procedural textures added to the scene
  24449. * @see http://doc.babylonjs.com/how_to/how_to_use_procedural_textures
  24450. */
  24451. this.proceduralTextures = new Array();
  24452. /**
  24453. * The list of sound tracks added to the scene
  24454. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  24455. */
  24456. this.soundTracks = new Array();
  24457. this._audioEnabled = true;
  24458. this._headphone = false;
  24459. // Performance counters
  24460. this._totalVertices = new BABYLON.PerfCounter();
  24461. /** @hidden */
  24462. this._activeIndices = new BABYLON.PerfCounter();
  24463. /** @hidden */
  24464. this._activeParticles = new BABYLON.PerfCounter();
  24465. /** @hidden */
  24466. this._activeBones = new BABYLON.PerfCounter();
  24467. this._animationTime = 0;
  24468. /**
  24469. * Gets or sets a general scale for animation speed
  24470. * @see https://www.babylonjs-playground.com/#IBU2W7#3
  24471. */
  24472. this.animationTimeScale = 1;
  24473. this._renderId = 0;
  24474. this._executeWhenReadyTimeoutId = -1;
  24475. this._intermediateRendering = false;
  24476. this._viewUpdateFlag = -1;
  24477. this._projectionUpdateFlag = -1;
  24478. this._alternateViewUpdateFlag = -1;
  24479. this._alternateProjectionUpdateFlag = -1;
  24480. /** @hidden */
  24481. this._toBeDisposed = new BABYLON.SmartArray(256);
  24482. this._activeRequests = new Array();
  24483. this._pendingData = new Array();
  24484. this._isDisposed = false;
  24485. /**
  24486. * Gets or sets a boolean indicating that all submeshes of active meshes must be rendered
  24487. * Use this boolean to avoid computing frustum clipping on submeshes (This could help when you are CPU bound)
  24488. */
  24489. this.dispatchAllSubMeshesOfActiveMeshes = false;
  24490. this._activeMeshes = new BABYLON.SmartArray(256);
  24491. this._processedMaterials = new BABYLON.SmartArray(256);
  24492. this._renderTargets = new BABYLON.SmartArrayNoDuplicate(256);
  24493. /** @hidden */
  24494. this._activeParticleSystems = new BABYLON.SmartArray(256);
  24495. this._activeSkeletons = new BABYLON.SmartArrayNoDuplicate(32);
  24496. this._softwareSkinnedMeshes = new BABYLON.SmartArrayNoDuplicate(32);
  24497. /** @hidden */
  24498. this._activeAnimatables = new Array();
  24499. this._transformMatrix = BABYLON.Matrix.Zero();
  24500. this._useAlternateCameraConfiguration = false;
  24501. this._alternateRendering = false;
  24502. /**
  24503. * Gets or sets a boolean indicating if lights must be sorted by priority (off by default)
  24504. * This is useful if there are more lights that the maximum simulteanous authorized
  24505. */
  24506. this.requireLightSorting = false;
  24507. this._depthRenderer = {};
  24508. this._activeMeshesFrozen = false;
  24509. this._tempPickingRay = BABYLON.Ray ? BABYLON.Ray.Zero() : null;
  24510. this._engine = engine || BABYLON.Engine.LastCreatedEngine;
  24511. this._engine.scenes.push(this);
  24512. this._uid = null;
  24513. this._renderingManager = new BABYLON.RenderingManager(this);
  24514. if (BABYLON.PostProcessManager) {
  24515. this.postProcessManager = new BABYLON.PostProcessManager(this);
  24516. }
  24517. if (BABYLON.OutlineRenderer) {
  24518. this._outlineRenderer = new BABYLON.OutlineRenderer(this);
  24519. }
  24520. if (BABYLON.Tools.IsWindowObjectExist()) {
  24521. this.attachControl();
  24522. }
  24523. //simplification queue
  24524. if (BABYLON.SimplificationQueue) {
  24525. this.simplificationQueue = new BABYLON.SimplificationQueue();
  24526. }
  24527. //collision coordinator initialization. For now legacy per default.
  24528. this.workerCollisions = false; //(!!Worker && (!!BABYLON.CollisionWorker || BABYLON.WorkerIncluded));
  24529. // Uniform Buffer
  24530. this._createUbo();
  24531. // Default Image processing definition
  24532. if (BABYLON.ImageProcessingConfiguration) {
  24533. this._imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  24534. }
  24535. }
  24536. Object.defineProperty(Scene, "FOGMODE_NONE", {
  24537. /** The fog is deactivated */
  24538. get: function () {
  24539. return Scene._FOGMODE_NONE;
  24540. },
  24541. enumerable: true,
  24542. configurable: true
  24543. });
  24544. Object.defineProperty(Scene, "FOGMODE_EXP", {
  24545. /** The fog density is following an exponential function */
  24546. get: function () {
  24547. return Scene._FOGMODE_EXP;
  24548. },
  24549. enumerable: true,
  24550. configurable: true
  24551. });
  24552. Object.defineProperty(Scene, "FOGMODE_EXP2", {
  24553. /** The fog density is following an exponential function faster than FOGMODE_EXP */
  24554. get: function () {
  24555. return Scene._FOGMODE_EXP2;
  24556. },
  24557. enumerable: true,
  24558. configurable: true
  24559. });
  24560. Object.defineProperty(Scene, "FOGMODE_LINEAR", {
  24561. /** The fog density is following a linear function. */
  24562. get: function () {
  24563. return Scene._FOGMODE_LINEAR;
  24564. },
  24565. enumerable: true,
  24566. configurable: true
  24567. });
  24568. Object.defineProperty(Scene.prototype, "environmentTexture", {
  24569. /**
  24570. * Texture used in all pbr material as the reflection texture.
  24571. * As in the majority of the scene they are the same (exception for multi room and so on),
  24572. * this is easier to reference from here than from all the materials.
  24573. */
  24574. get: function () {
  24575. return this._environmentTexture;
  24576. },
  24577. /**
  24578. * Texture used in all pbr material as the reflection texture.
  24579. * As in the majority of the scene they are the same (exception for multi room and so on),
  24580. * this is easier to set here than in all the materials.
  24581. */
  24582. set: function (value) {
  24583. if (this._environmentTexture === value) {
  24584. return;
  24585. }
  24586. this._environmentTexture = value;
  24587. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24588. },
  24589. enumerable: true,
  24590. configurable: true
  24591. });
  24592. Object.defineProperty(Scene.prototype, "imageProcessingConfiguration", {
  24593. /**
  24594. * Default image processing configuration used either in the rendering
  24595. * Forward main pass or through the imageProcessingPostProcess if present.
  24596. * As in the majority of the scene they are the same (exception for multi camera),
  24597. * this is easier to reference from here than from all the materials and post process.
  24598. *
  24599. * No setter as we it is a shared configuration, you can set the values instead.
  24600. */
  24601. get: function () {
  24602. return this._imageProcessingConfiguration;
  24603. },
  24604. enumerable: true,
  24605. configurable: true
  24606. });
  24607. Object.defineProperty(Scene.prototype, "forceWireframe", {
  24608. get: function () {
  24609. return this._forceWireframe;
  24610. },
  24611. /**
  24612. * Gets or sets a boolean indicating if all rendering must be done in wireframe
  24613. */
  24614. set: function (value) {
  24615. if (this._forceWireframe === value) {
  24616. return;
  24617. }
  24618. this._forceWireframe = value;
  24619. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24620. },
  24621. enumerable: true,
  24622. configurable: true
  24623. });
  24624. Object.defineProperty(Scene.prototype, "forcePointsCloud", {
  24625. get: function () {
  24626. return this._forcePointsCloud;
  24627. },
  24628. /**
  24629. * Gets or sets a boolean indicating if all rendering must be done in point cloud
  24630. */
  24631. set: function (value) {
  24632. if (this._forcePointsCloud === value) {
  24633. return;
  24634. }
  24635. this._forcePointsCloud = value;
  24636. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24637. },
  24638. enumerable: true,
  24639. configurable: true
  24640. });
  24641. Object.defineProperty(Scene.prototype, "animationPropertiesOverride", {
  24642. /**
  24643. * Gets or sets the animation properties override
  24644. */
  24645. get: function () {
  24646. return this._animationPropertiesOverride;
  24647. },
  24648. set: function (value) {
  24649. this._animationPropertiesOverride = value;
  24650. },
  24651. enumerable: true,
  24652. configurable: true
  24653. });
  24654. Object.defineProperty(Scene.prototype, "onDispose", {
  24655. /** Sets a function to be executed when this scene is disposed. */
  24656. set: function (callback) {
  24657. if (this._onDisposeObserver) {
  24658. this.onDisposeObservable.remove(this._onDisposeObserver);
  24659. }
  24660. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  24661. },
  24662. enumerable: true,
  24663. configurable: true
  24664. });
  24665. Object.defineProperty(Scene.prototype, "beforeRender", {
  24666. /** Sets a function to be executed before rendering this scene */
  24667. set: function (callback) {
  24668. if (this._onBeforeRenderObserver) {
  24669. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  24670. }
  24671. if (callback) {
  24672. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  24673. }
  24674. },
  24675. enumerable: true,
  24676. configurable: true
  24677. });
  24678. Object.defineProperty(Scene.prototype, "afterRender", {
  24679. /** Sets a function to be executed after rendering this scene */
  24680. set: function (callback) {
  24681. if (this._onAfterRenderObserver) {
  24682. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  24683. }
  24684. if (callback) {
  24685. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  24686. }
  24687. },
  24688. enumerable: true,
  24689. configurable: true
  24690. });
  24691. Object.defineProperty(Scene.prototype, "beforeCameraRender", {
  24692. /** Sets a function to be executed before rendering a camera*/
  24693. set: function (callback) {
  24694. if (this._onBeforeCameraRenderObserver) {
  24695. this.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  24696. }
  24697. this._onBeforeCameraRenderObserver = this.onBeforeCameraRenderObservable.add(callback);
  24698. },
  24699. enumerable: true,
  24700. configurable: true
  24701. });
  24702. Object.defineProperty(Scene.prototype, "afterCameraRender", {
  24703. /** Sets a function to be executed after rendering a camera*/
  24704. set: function (callback) {
  24705. if (this._onAfterCameraRenderObserver) {
  24706. this.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  24707. }
  24708. this._onAfterCameraRenderObserver = this.onAfterCameraRenderObservable.add(callback);
  24709. },
  24710. enumerable: true,
  24711. configurable: true
  24712. });
  24713. Object.defineProperty(Scene.prototype, "gamepadManager", {
  24714. /**
  24715. * Gets the gamepad manager associated with the scene
  24716. * @see http://doc.babylonjs.com/how_to/how_to_use_gamepads
  24717. */
  24718. get: function () {
  24719. if (!this._gamepadManager) {
  24720. this._gamepadManager = new BABYLON.GamepadManager(this);
  24721. }
  24722. return this._gamepadManager;
  24723. },
  24724. enumerable: true,
  24725. configurable: true
  24726. });
  24727. Object.defineProperty(Scene.prototype, "unTranslatedPointer", {
  24728. /**
  24729. * Gets the pointer coordinates without any translation (ie. straight out of the pointer event)
  24730. */
  24731. get: function () {
  24732. return new BABYLON.Vector2(this._unTranslatedPointerX, this._unTranslatedPointerY);
  24733. },
  24734. enumerable: true,
  24735. configurable: true
  24736. });
  24737. Object.defineProperty(Scene.prototype, "useRightHandedSystem", {
  24738. get: function () {
  24739. return this._useRightHandedSystem;
  24740. },
  24741. /**
  24742. * Gets or sets a boolean indicating if the scene must use right-handed coordinates system
  24743. */
  24744. set: function (value) {
  24745. if (this._useRightHandedSystem === value) {
  24746. return;
  24747. }
  24748. this._useRightHandedSystem = value;
  24749. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24750. },
  24751. enumerable: true,
  24752. configurable: true
  24753. });
  24754. /**
  24755. * Sets the step Id used by deterministic lock step
  24756. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24757. * @param newStepId defines the step Id
  24758. */
  24759. Scene.prototype.setStepId = function (newStepId) {
  24760. this._currentStepId = newStepId;
  24761. };
  24762. ;
  24763. /**
  24764. * Gets the step Id used by deterministic lock step
  24765. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24766. * @returns the step Id
  24767. */
  24768. Scene.prototype.getStepId = function () {
  24769. return this._currentStepId;
  24770. };
  24771. ;
  24772. /**
  24773. * Gets the internal step used by deterministic lock step
  24774. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  24775. * @returns the internal step
  24776. */
  24777. Scene.prototype.getInternalStep = function () {
  24778. return this._currentInternalStep;
  24779. };
  24780. ;
  24781. Object.defineProperty(Scene.prototype, "fogEnabled", {
  24782. get: function () {
  24783. return this._fogEnabled;
  24784. },
  24785. /**
  24786. * Gets or sets a boolean indicating if fog is enabled on this scene
  24787. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24788. */
  24789. set: function (value) {
  24790. if (this._fogEnabled === value) {
  24791. return;
  24792. }
  24793. this._fogEnabled = value;
  24794. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24795. },
  24796. enumerable: true,
  24797. configurable: true
  24798. });
  24799. Object.defineProperty(Scene.prototype, "fogMode", {
  24800. get: function () {
  24801. return this._fogMode;
  24802. },
  24803. /**
  24804. * Gets or sets the fog mode to use
  24805. * @see http://doc.babylonjs.com/babylon101/environment#fog
  24806. */
  24807. set: function (value) {
  24808. if (this._fogMode === value) {
  24809. return;
  24810. }
  24811. this._fogMode = value;
  24812. this.markAllMaterialsAsDirty(BABYLON.Material.MiscDirtyFlag);
  24813. },
  24814. enumerable: true,
  24815. configurable: true
  24816. });
  24817. Object.defineProperty(Scene.prototype, "shadowsEnabled", {
  24818. get: function () {
  24819. return this._shadowsEnabled;
  24820. },
  24821. /**
  24822. * Gets or sets a boolean indicating if shadows are enabled on this scene
  24823. */
  24824. set: function (value) {
  24825. if (this._shadowsEnabled === value) {
  24826. return;
  24827. }
  24828. this._shadowsEnabled = value;
  24829. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24830. },
  24831. enumerable: true,
  24832. configurable: true
  24833. });
  24834. Object.defineProperty(Scene.prototype, "lightsEnabled", {
  24835. get: function () {
  24836. return this._lightsEnabled;
  24837. },
  24838. /**
  24839. * Gets or sets a boolean indicating if lights are enabled on this scene
  24840. */
  24841. set: function (value) {
  24842. if (this._lightsEnabled === value) {
  24843. return;
  24844. }
  24845. this._lightsEnabled = value;
  24846. this.markAllMaterialsAsDirty(BABYLON.Material.LightDirtyFlag);
  24847. },
  24848. enumerable: true,
  24849. configurable: true
  24850. });
  24851. Object.defineProperty(Scene.prototype, "defaultMaterial", {
  24852. /** The default material used on meshes when no material is affected */
  24853. get: function () {
  24854. if (!this._defaultMaterial) {
  24855. this._defaultMaterial = new BABYLON.StandardMaterial("default material", this);
  24856. }
  24857. return this._defaultMaterial;
  24858. },
  24859. /** The default material used on meshes when no material is affected */
  24860. set: function (value) {
  24861. this._defaultMaterial = value;
  24862. },
  24863. enumerable: true,
  24864. configurable: true
  24865. });
  24866. Object.defineProperty(Scene.prototype, "texturesEnabled", {
  24867. get: function () {
  24868. return this._texturesEnabled;
  24869. },
  24870. /**
  24871. * Gets or sets a boolean indicating if textures are enabled on this scene
  24872. */
  24873. set: function (value) {
  24874. if (this._texturesEnabled === value) {
  24875. return;
  24876. }
  24877. this._texturesEnabled = value;
  24878. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  24879. },
  24880. enumerable: true,
  24881. configurable: true
  24882. });
  24883. Object.defineProperty(Scene.prototype, "skeletonsEnabled", {
  24884. get: function () {
  24885. return this._skeletonsEnabled;
  24886. },
  24887. /**
  24888. * Gets or sets a boolean indicating if skeletons are enabled on this scene
  24889. */
  24890. set: function (value) {
  24891. if (this._skeletonsEnabled === value) {
  24892. return;
  24893. }
  24894. this._skeletonsEnabled = value;
  24895. this.markAllMaterialsAsDirty(BABYLON.Material.AttributesDirtyFlag);
  24896. },
  24897. enumerable: true,
  24898. configurable: true
  24899. });
  24900. Object.defineProperty(Scene.prototype, "postProcessRenderPipelineManager", {
  24901. /**
  24902. * Gets the postprocess render pipeline manager
  24903. * @see http://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  24904. * @see http://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  24905. */
  24906. get: function () {
  24907. if (!this._postProcessRenderPipelineManager) {
  24908. this._postProcessRenderPipelineManager = new BABYLON.PostProcessRenderPipelineManager();
  24909. }
  24910. return this._postProcessRenderPipelineManager;
  24911. },
  24912. enumerable: true,
  24913. configurable: true
  24914. });
  24915. Object.defineProperty(Scene.prototype, "mainSoundTrack", {
  24916. /**
  24917. * Gets the main soundtrack associated with the scene
  24918. */
  24919. get: function () {
  24920. if (!this._mainSoundTrack) {
  24921. this._mainSoundTrack = new BABYLON.SoundTrack(this, { mainTrack: true });
  24922. }
  24923. return this._mainSoundTrack;
  24924. },
  24925. enumerable: true,
  24926. configurable: true
  24927. });
  24928. Object.defineProperty(Scene.prototype, "_isAlternateRenderingEnabled", {
  24929. /** @hidden */
  24930. get: function () {
  24931. return this._alternateRendering;
  24932. },
  24933. enumerable: true,
  24934. configurable: true
  24935. });
  24936. Object.defineProperty(Scene.prototype, "frustumPlanes", {
  24937. /**
  24938. * Gets the list of frustum planes (built from the active camera)
  24939. */
  24940. get: function () {
  24941. return this._frustumPlanes;
  24942. },
  24943. enumerable: true,
  24944. configurable: true
  24945. });
  24946. Object.defineProperty(Scene.prototype, "geometryBufferRenderer", {
  24947. /**
  24948. * Gets the current geometry buffer associated to the scene.
  24949. */
  24950. get: function () {
  24951. return this._geometryBufferRenderer;
  24952. },
  24953. /**
  24954. * Sets the current geometry buffer for the scene.
  24955. */
  24956. set: function (geometryBufferRenderer) {
  24957. if (geometryBufferRenderer && geometryBufferRenderer.isSupported) {
  24958. this._geometryBufferRenderer = geometryBufferRenderer;
  24959. }
  24960. },
  24961. enumerable: true,
  24962. configurable: true
  24963. });
  24964. Object.defineProperty(Scene.prototype, "debugLayer", {
  24965. /**
  24966. * Gets the debug layer (aka Inspector) associated with the scene
  24967. * @see http://doc.babylonjs.com/features/playground_debuglayer
  24968. */
  24969. get: function () {
  24970. if (!this._debugLayer) {
  24971. this._debugLayer = new BABYLON.DebugLayer(this);
  24972. }
  24973. return this._debugLayer;
  24974. },
  24975. enumerable: true,
  24976. configurable: true
  24977. });
  24978. Object.defineProperty(Scene.prototype, "workerCollisions", {
  24979. /**
  24980. * Gets a boolean indicating if collisions are processed on a web worker
  24981. * @see http://doc.babylonjs.com/babylon101/cameras,_mesh_collisions_and_gravity#web-worker-based-collision-system-since-21
  24982. */
  24983. get: function () {
  24984. return this._workerCollisions;
  24985. },
  24986. set: function (enabled) {
  24987. if (!BABYLON.CollisionCoordinatorLegacy) {
  24988. return;
  24989. }
  24990. enabled = (enabled && !!Worker && !!BABYLON.CollisionWorker);
  24991. this._workerCollisions = enabled;
  24992. if (this.collisionCoordinator) {
  24993. this.collisionCoordinator.destroy();
  24994. }
  24995. this.collisionCoordinator = enabled ? new BABYLON.CollisionCoordinatorWorker() : new BABYLON.CollisionCoordinatorLegacy();
  24996. this.collisionCoordinator.init(this);
  24997. },
  24998. enumerable: true,
  24999. configurable: true
  25000. });
  25001. Object.defineProperty(Scene.prototype, "selectionOctree", {
  25002. /**
  25003. * Gets the octree used to boost mesh selection (picking)
  25004. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  25005. */
  25006. get: function () {
  25007. return this._selectionOctree;
  25008. },
  25009. enumerable: true,
  25010. configurable: true
  25011. });
  25012. Object.defineProperty(Scene.prototype, "meshUnderPointer", {
  25013. /**
  25014. * Gets the mesh that is currently under the pointer
  25015. */
  25016. get: function () {
  25017. return this._pointerOverMesh;
  25018. },
  25019. enumerable: true,
  25020. configurable: true
  25021. });
  25022. Object.defineProperty(Scene.prototype, "pointerX", {
  25023. /**
  25024. * Gets the current on-screen X position of the pointer
  25025. */
  25026. get: function () {
  25027. return this._pointerX;
  25028. },
  25029. enumerable: true,
  25030. configurable: true
  25031. });
  25032. Object.defineProperty(Scene.prototype, "pointerY", {
  25033. /**
  25034. * Gets the current on-screen Y position of the pointer
  25035. */
  25036. get: function () {
  25037. return this._pointerY;
  25038. },
  25039. enumerable: true,
  25040. configurable: true
  25041. });
  25042. /**
  25043. * Gets the cached material (ie. the latest rendered one)
  25044. * @returns the cached material
  25045. */
  25046. Scene.prototype.getCachedMaterial = function () {
  25047. return this._cachedMaterial;
  25048. };
  25049. /**
  25050. * Gets the cached effect (ie. the latest rendered one)
  25051. * @returns the cached effect
  25052. */
  25053. Scene.prototype.getCachedEffect = function () {
  25054. return this._cachedEffect;
  25055. };
  25056. /**
  25057. * Gets the cached visibility state (ie. the latest rendered one)
  25058. * @returns the cached visibility state
  25059. */
  25060. Scene.prototype.getCachedVisibility = function () {
  25061. return this._cachedVisibility;
  25062. };
  25063. /**
  25064. * Gets a boolean indicating if the current material / effect / visibility must be bind again
  25065. * @param material defines the current material
  25066. * @param effect defines the current effect
  25067. * @param visibility defines the current visibility state
  25068. * @returns true if one parameter is not cached
  25069. */
  25070. Scene.prototype.isCachedMaterialInvalid = function (material, effect, visibility) {
  25071. if (visibility === void 0) { visibility = 1; }
  25072. return this._cachedEffect !== effect || this._cachedMaterial !== material || this._cachedVisibility !== visibility;
  25073. };
  25074. /**
  25075. * Gets the bounding box renderer associated with the scene
  25076. * @returns a BoundingBoxRenderer
  25077. */
  25078. Scene.prototype.getBoundingBoxRenderer = function () {
  25079. if (!this._boundingBoxRenderer) {
  25080. this._boundingBoxRenderer = new BABYLON.BoundingBoxRenderer(this);
  25081. }
  25082. return this._boundingBoxRenderer;
  25083. };
  25084. /**
  25085. * Gets the outline renderer associated with the scene
  25086. * @returns a OutlineRenderer
  25087. */
  25088. Scene.prototype.getOutlineRenderer = function () {
  25089. return this._outlineRenderer;
  25090. };
  25091. /**
  25092. * Gets the engine associated with the scene
  25093. * @returns an Engine
  25094. */
  25095. Scene.prototype.getEngine = function () {
  25096. return this._engine;
  25097. };
  25098. /**
  25099. * Gets the total number of vertices rendered per frame
  25100. * @returns the total number of vertices rendered per frame
  25101. */
  25102. Scene.prototype.getTotalVertices = function () {
  25103. return this._totalVertices.current;
  25104. };
  25105. Object.defineProperty(Scene.prototype, "totalVerticesPerfCounter", {
  25106. /**
  25107. * Gets the performance counter for total vertices
  25108. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25109. */
  25110. get: function () {
  25111. return this._totalVertices;
  25112. },
  25113. enumerable: true,
  25114. configurable: true
  25115. });
  25116. /**
  25117. * Gets the total number of active indices rendered per frame (You can deduce the number of rendered triangles by dividing this number by 3)
  25118. * @returns the total number of active indices rendered per frame
  25119. */
  25120. Scene.prototype.getActiveIndices = function () {
  25121. return this._activeIndices.current;
  25122. };
  25123. Object.defineProperty(Scene.prototype, "totalActiveIndicesPerfCounter", {
  25124. /**
  25125. * Gets the performance counter for active indices
  25126. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25127. */
  25128. get: function () {
  25129. return this._activeIndices;
  25130. },
  25131. enumerable: true,
  25132. configurable: true
  25133. });
  25134. /**
  25135. * Gets the total number of active particles rendered per frame
  25136. * @returns the total number of active particles rendered per frame
  25137. */
  25138. Scene.prototype.getActiveParticles = function () {
  25139. return this._activeParticles.current;
  25140. };
  25141. Object.defineProperty(Scene.prototype, "activeParticlesPerfCounter", {
  25142. /**
  25143. * Gets the performance counter for active particles
  25144. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25145. */
  25146. get: function () {
  25147. return this._activeParticles;
  25148. },
  25149. enumerable: true,
  25150. configurable: true
  25151. });
  25152. /**
  25153. * Gets the total number of active bones rendered per frame
  25154. * @returns the total number of active bones rendered per frame
  25155. */
  25156. Scene.prototype.getActiveBones = function () {
  25157. return this._activeBones.current;
  25158. };
  25159. Object.defineProperty(Scene.prototype, "activeBonesPerfCounter", {
  25160. /**
  25161. * Gets the performance counter for active bones
  25162. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene#instrumentation
  25163. */
  25164. get: function () {
  25165. return this._activeBones;
  25166. },
  25167. enumerable: true,
  25168. configurable: true
  25169. });
  25170. /** @hidden */
  25171. Scene.prototype.getInterFramePerfCounter = function () {
  25172. BABYLON.Tools.Warn("getInterFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25173. return 0;
  25174. };
  25175. Object.defineProperty(Scene.prototype, "interFramePerfCounter", {
  25176. /** @hidden */
  25177. get: function () {
  25178. BABYLON.Tools.Warn("interFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25179. return null;
  25180. },
  25181. enumerable: true,
  25182. configurable: true
  25183. });
  25184. /** @hidden */
  25185. Scene.prototype.getLastFrameDuration = function () {
  25186. BABYLON.Tools.Warn("getLastFrameDuration is deprecated. Please use SceneInstrumentation class");
  25187. return 0;
  25188. };
  25189. Object.defineProperty(Scene.prototype, "lastFramePerfCounter", {
  25190. /** @hidden */
  25191. get: function () {
  25192. BABYLON.Tools.Warn("lastFramePerfCounter is deprecated. Please use SceneInstrumentation class");
  25193. return null;
  25194. },
  25195. enumerable: true,
  25196. configurable: true
  25197. });
  25198. /** @hidden */
  25199. Scene.prototype.getEvaluateActiveMeshesDuration = function () {
  25200. BABYLON.Tools.Warn("getEvaluateActiveMeshesDuration is deprecated. Please use SceneInstrumentation class");
  25201. return 0;
  25202. };
  25203. Object.defineProperty(Scene.prototype, "evaluateActiveMeshesDurationPerfCounter", {
  25204. /** @hidden */
  25205. get: function () {
  25206. BABYLON.Tools.Warn("evaluateActiveMeshesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25207. return null;
  25208. },
  25209. enumerable: true,
  25210. configurable: true
  25211. });
  25212. /**
  25213. * Gets the array of active meshes
  25214. * @returns an array of AbstractMesh
  25215. */
  25216. Scene.prototype.getActiveMeshes = function () {
  25217. return this._activeMeshes;
  25218. };
  25219. /** @hidden */
  25220. Scene.prototype.getRenderTargetsDuration = function () {
  25221. BABYLON.Tools.Warn("getRenderTargetsDuration is deprecated. Please use SceneInstrumentation class");
  25222. return 0;
  25223. };
  25224. /** @hidden */
  25225. Scene.prototype.getRenderDuration = function () {
  25226. BABYLON.Tools.Warn("getRenderDuration is deprecated. Please use SceneInstrumentation class");
  25227. return 0;
  25228. };
  25229. Object.defineProperty(Scene.prototype, "renderDurationPerfCounter", {
  25230. /** @hidden */
  25231. get: function () {
  25232. BABYLON.Tools.Warn("renderDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25233. return null;
  25234. },
  25235. enumerable: true,
  25236. configurable: true
  25237. });
  25238. /** @hidden */
  25239. Scene.prototype.getParticlesDuration = function () {
  25240. BABYLON.Tools.Warn("getParticlesDuration is deprecated. Please use SceneInstrumentation class");
  25241. return 0;
  25242. };
  25243. Object.defineProperty(Scene.prototype, "particlesDurationPerfCounter", {
  25244. /** @hidden */
  25245. get: function () {
  25246. BABYLON.Tools.Warn("particlesDurationPerfCounter is deprecated. Please use SceneInstrumentation class");
  25247. return null;
  25248. },
  25249. enumerable: true,
  25250. configurable: true
  25251. });
  25252. /** @hidden */
  25253. Scene.prototype.getSpritesDuration = function () {
  25254. BABYLON.Tools.Warn("getSpritesDuration is deprecated. Please use SceneInstrumentation class");
  25255. return 0;
  25256. };
  25257. Object.defineProperty(Scene.prototype, "spriteDuractionPerfCounter", {
  25258. /** @hidden */
  25259. get: function () {
  25260. BABYLON.Tools.Warn("spriteDuractionPerfCounter is deprecated. Please use SceneInstrumentation class");
  25261. return null;
  25262. },
  25263. enumerable: true,
  25264. configurable: true
  25265. });
  25266. /**
  25267. * Gets the animation ratio (which is 1.0 is the scene renders at 60fps and 2 if the scene renders at 30fps, etc.)
  25268. * @returns a number
  25269. */
  25270. Scene.prototype.getAnimationRatio = function () {
  25271. return this._animationRatio;
  25272. };
  25273. /**
  25274. * Gets an unique Id for the current frame
  25275. * @returns a number
  25276. */
  25277. Scene.prototype.getRenderId = function () {
  25278. return this._renderId;
  25279. };
  25280. /** Call this function if you want to manually increment the render Id*/
  25281. Scene.prototype.incrementRenderId = function () {
  25282. this._renderId++;
  25283. };
  25284. Scene.prototype._updatePointerPosition = function (evt) {
  25285. var canvasRect = this._engine.getRenderingCanvasClientRect();
  25286. if (!canvasRect) {
  25287. return;
  25288. }
  25289. this._pointerX = evt.clientX - canvasRect.left;
  25290. this._pointerY = evt.clientY - canvasRect.top;
  25291. this._unTranslatedPointerX = this._pointerX;
  25292. this._unTranslatedPointerY = this._pointerY;
  25293. };
  25294. Scene.prototype._createUbo = function () {
  25295. this._sceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25296. this._sceneUbo.addUniform("viewProjection", 16);
  25297. this._sceneUbo.addUniform("view", 16);
  25298. };
  25299. Scene.prototype._createAlternateUbo = function () {
  25300. this._alternateSceneUbo = new BABYLON.UniformBuffer(this._engine, undefined, true);
  25301. this._alternateSceneUbo.addUniform("viewProjection", 16);
  25302. this._alternateSceneUbo.addUniform("view", 16);
  25303. };
  25304. // Pointers handling
  25305. Scene.prototype._pickSpriteButKeepRay = function (originalPointerInfo, x, y, predicate, fastCheck, camera) {
  25306. var result = this.pickSprite(x, y, predicate, fastCheck, camera);
  25307. if (result) {
  25308. result.ray = originalPointerInfo ? originalPointerInfo.ray : null;
  25309. }
  25310. return result;
  25311. };
  25312. Scene.prototype._setRayOnPointerInfo = function (pointerInfo) {
  25313. if (pointerInfo.pickInfo) {
  25314. if (!pointerInfo.pickInfo.ray) {
  25315. pointerInfo.pickInfo.ray = this.createPickingRay(pointerInfo.event.offsetX, pointerInfo.event.offsetY, BABYLON.Matrix.Identity(), this.activeCamera);
  25316. }
  25317. }
  25318. };
  25319. /**
  25320. * Use this method to simulate a pointer move on a mesh
  25321. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25322. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25323. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25324. * @returns the current scene
  25325. */
  25326. Scene.prototype.simulatePointerMove = function (pickResult, pointerEventInit) {
  25327. var evt = new PointerEvent("pointermove", pointerEventInit);
  25328. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERMOVE)) {
  25329. return this;
  25330. }
  25331. return this._processPointerMove(pickResult, evt);
  25332. };
  25333. Scene.prototype._processPointerMove = function (pickResult, evt) {
  25334. var canvas = this._engine.getRenderingCanvas();
  25335. if (!canvas) {
  25336. return this;
  25337. }
  25338. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25339. this.setPointerOverSprite(null);
  25340. this.setPointerOverMesh(pickResult.pickedMesh);
  25341. if (this._pointerOverMesh && this._pointerOverMesh.actionManager && this._pointerOverMesh.actionManager.hasPointerTriggers) {
  25342. if (this._pointerOverMesh.actionManager.hoverCursor) {
  25343. canvas.style.cursor = this._pointerOverMesh.actionManager.hoverCursor;
  25344. }
  25345. else {
  25346. canvas.style.cursor = this.hoverCursor;
  25347. }
  25348. }
  25349. else {
  25350. canvas.style.cursor = this.defaultCursor;
  25351. }
  25352. }
  25353. else {
  25354. this.setPointerOverMesh(null);
  25355. // Sprites
  25356. pickResult = this._pickSpriteButKeepRay(pickResult, this._unTranslatedPointerX, this._unTranslatedPointerY, this._spritePredicate, false, this.cameraToUseForPointers || undefined);
  25357. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25358. this.setPointerOverSprite(pickResult.pickedSprite);
  25359. if (this._pointerOverSprite && this._pointerOverSprite.actionManager && this._pointerOverSprite.actionManager.hoverCursor) {
  25360. canvas.style.cursor = this._pointerOverSprite.actionManager.hoverCursor;
  25361. }
  25362. else {
  25363. canvas.style.cursor = this.hoverCursor;
  25364. }
  25365. }
  25366. else {
  25367. this.setPointerOverSprite(null);
  25368. // Restore pointer
  25369. canvas.style.cursor = this.defaultCursor;
  25370. }
  25371. }
  25372. if (pickResult) {
  25373. var type = evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE;
  25374. if (this.onPointerMove) {
  25375. this.onPointerMove(evt, pickResult, type);
  25376. }
  25377. if (this.onPointerObservable.hasObservers()) {
  25378. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25379. this._setRayOnPointerInfo(pi);
  25380. this.onPointerObservable.notifyObservers(pi, type);
  25381. }
  25382. }
  25383. return this;
  25384. };
  25385. Scene.prototype._checkPrePointerObservable = function (pickResult, evt, type) {
  25386. var pi = new BABYLON.PointerInfoPre(type, evt, this._unTranslatedPointerX, this._unTranslatedPointerY);
  25387. if (pickResult) {
  25388. pi.ray = pickResult.ray;
  25389. }
  25390. this.onPrePointerObservable.notifyObservers(pi, type);
  25391. if (pi.skipOnPointerObservable) {
  25392. return true;
  25393. }
  25394. else {
  25395. return false;
  25396. }
  25397. };
  25398. /**
  25399. * Use this method to simulate a pointer down on a mesh
  25400. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25401. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25402. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25403. * @returns the current scene
  25404. */
  25405. Scene.prototype.simulatePointerDown = function (pickResult, pointerEventInit) {
  25406. var evt = new PointerEvent("pointerdown", pointerEventInit);
  25407. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25408. return this;
  25409. }
  25410. return this._processPointerDown(pickResult, evt);
  25411. };
  25412. Scene.prototype._processPointerDown = function (pickResult, evt) {
  25413. var _this = this;
  25414. if (pickResult && pickResult.hit && pickResult.pickedMesh) {
  25415. this._pickedDownMesh = pickResult.pickedMesh;
  25416. var actionManager = pickResult.pickedMesh.actionManager;
  25417. if (actionManager) {
  25418. if (actionManager.hasPickTriggers) {
  25419. actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25420. switch (evt.button) {
  25421. case 0:
  25422. actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25423. break;
  25424. case 1:
  25425. actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25426. break;
  25427. case 2:
  25428. actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25429. break;
  25430. }
  25431. }
  25432. if (actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnLongPressTrigger)) {
  25433. window.setTimeout(function () {
  25434. 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);
  25435. if (pickResult && pickResult.hit && pickResult.pickedMesh && actionManager) {
  25436. if (_this._totalPointersPressed !== 0 &&
  25437. ((Date.now() - _this._startingPointerTime) > Scene.LongPressDelay) &&
  25438. (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold &&
  25439. Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold)) {
  25440. _this._startingPointerTime = 0;
  25441. actionManager.processTrigger(BABYLON.ActionManager.OnLongPressTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25442. }
  25443. }
  25444. }, Scene.LongPressDelay);
  25445. }
  25446. }
  25447. }
  25448. if (pickResult) {
  25449. var type = BABYLON.PointerEventTypes.POINTERDOWN;
  25450. if (this.onPointerDown) {
  25451. this.onPointerDown(evt, pickResult, type);
  25452. }
  25453. if (this.onPointerObservable.hasObservers()) {
  25454. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25455. this._setRayOnPointerInfo(pi);
  25456. this.onPointerObservable.notifyObservers(pi, type);
  25457. }
  25458. }
  25459. return this;
  25460. };
  25461. /**
  25462. * Use this method to simulate a pointer up on a mesh
  25463. * The pickResult parameter can be obtained from a scene.pick or scene.pickWithRay
  25464. * @param pickResult pickingInfo of the object wished to simulate pointer event on
  25465. * @param pointerEventInit pointer event state to be used when simulating the pointer event (eg. pointer id for multitouch)
  25466. * @returns the current scene
  25467. */
  25468. Scene.prototype.simulatePointerUp = function (pickResult, pointerEventInit) {
  25469. var evt = new PointerEvent("pointerup", pointerEventInit);
  25470. var clickInfo = new ClickInfo();
  25471. clickInfo.singleClick = true;
  25472. clickInfo.ignore = true;
  25473. if (this._checkPrePointerObservable(pickResult, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25474. return this;
  25475. }
  25476. return this._processPointerUp(pickResult, evt, clickInfo);
  25477. };
  25478. Scene.prototype._processPointerUp = function (pickResult, evt, clickInfo) {
  25479. if (pickResult && pickResult && pickResult.pickedMesh) {
  25480. this._pickedUpMesh = pickResult.pickedMesh;
  25481. if (this._pickedDownMesh === this._pickedUpMesh) {
  25482. if (this.onPointerPick) {
  25483. this.onPointerPick(evt, pickResult);
  25484. }
  25485. if (clickInfo.singleClick && !clickInfo.ignore && this.onPointerObservable.hasObservers()) {
  25486. var type_1 = BABYLON.PointerEventTypes.POINTERPICK;
  25487. var pi = new BABYLON.PointerInfo(type_1, evt, pickResult);
  25488. this._setRayOnPointerInfo(pi);
  25489. this.onPointerObservable.notifyObservers(pi, type_1);
  25490. }
  25491. }
  25492. if (pickResult.pickedMesh.actionManager) {
  25493. if (clickInfo.ignore) {
  25494. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25495. }
  25496. if (!clickInfo.hasSwiped && !clickInfo.ignore && clickInfo.singleClick) {
  25497. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25498. }
  25499. if (clickInfo.doubleClick && !clickInfo.ignore && pickResult.pickedMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25500. pickResult.pickedMesh.actionManager.processTrigger(BABYLON.ActionManager.OnDoublePickTrigger, BABYLON.ActionEvent.CreateNew(pickResult.pickedMesh, evt));
  25501. }
  25502. }
  25503. }
  25504. if (this._pickedDownMesh &&
  25505. this._pickedDownMesh.actionManager &&
  25506. this._pickedDownMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnPickOutTrigger) &&
  25507. this._pickedDownMesh !== this._pickedUpMesh) {
  25508. this._pickedDownMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNew(this._pickedDownMesh, evt));
  25509. }
  25510. var type = BABYLON.PointerEventTypes.POINTERUP;
  25511. if (this.onPointerObservable.hasObservers()) {
  25512. if (!clickInfo.ignore) {
  25513. if (!clickInfo.hasSwiped) {
  25514. if (clickInfo.singleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25515. var type_2 = BABYLON.PointerEventTypes.POINTERTAP;
  25516. var pi = new BABYLON.PointerInfo(type_2, evt, pickResult);
  25517. this._setRayOnPointerInfo(pi);
  25518. this.onPointerObservable.notifyObservers(pi, type_2);
  25519. }
  25520. if (clickInfo.doubleClick && this.onPointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25521. var type_3 = BABYLON.PointerEventTypes.POINTERDOUBLETAP;
  25522. var pi = new BABYLON.PointerInfo(type_3, evt, pickResult);
  25523. this._setRayOnPointerInfo(pi);
  25524. this.onPointerObservable.notifyObservers(pi, type_3);
  25525. }
  25526. }
  25527. }
  25528. else {
  25529. var pi = new BABYLON.PointerInfo(type, evt, pickResult);
  25530. this._setRayOnPointerInfo(pi);
  25531. this.onPointerObservable.notifyObservers(pi, type);
  25532. }
  25533. }
  25534. if (this.onPointerUp) {
  25535. this.onPointerUp(evt, pickResult, type);
  25536. }
  25537. return this;
  25538. };
  25539. /**
  25540. * Gets a boolean indicating if the current pointer event is captured (meaning that the scene has already handled the pointer down)
  25541. * @param pointerId defines the pointer id to use in a multi-touch scenario (0 by default)
  25542. * @returns true if the pointer was captured
  25543. */
  25544. Scene.prototype.isPointerCaptured = function (pointerId) {
  25545. if (pointerId === void 0) { pointerId = 0; }
  25546. return this._pointerCaptures[pointerId];
  25547. };
  25548. /**
  25549. * Attach events to the canvas (To handle actionManagers triggers and raise onPointerMove, onPointerDown and onPointerUp
  25550. * @param attachUp defines if you want to attach events to pointerup
  25551. * @param attachDown defines if you want to attach events to pointerdown
  25552. * @param attachMove defines if you want to attach events to pointermove
  25553. */
  25554. Scene.prototype.attachControl = function (attachUp, attachDown, attachMove) {
  25555. var _this = this;
  25556. if (attachUp === void 0) { attachUp = true; }
  25557. if (attachDown === void 0) { attachDown = true; }
  25558. if (attachMove === void 0) { attachMove = true; }
  25559. this._initActionManager = function (act, clickInfo) {
  25560. if (!_this._meshPickProceed) {
  25561. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25562. _this._currentPickResult = pickResult;
  25563. if (pickResult) {
  25564. act = (pickResult.hit && pickResult.pickedMesh) ? pickResult.pickedMesh.actionManager : null;
  25565. }
  25566. _this._meshPickProceed = true;
  25567. }
  25568. return act;
  25569. };
  25570. this._delayedSimpleClick = function (btn, clickInfo, cb) {
  25571. // double click delay is over and that no double click has been raised since, or the 2 consecutive keys pressed are different
  25572. if ((Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay && !_this._doubleClickOccured) ||
  25573. btn !== _this._previousButtonPressed) {
  25574. _this._doubleClickOccured = false;
  25575. clickInfo.singleClick = true;
  25576. clickInfo.ignore = false;
  25577. cb(clickInfo, _this._currentPickResult);
  25578. }
  25579. };
  25580. this._initClickEvent = function (obs1, obs2, evt, cb) {
  25581. var clickInfo = new ClickInfo();
  25582. _this._currentPickResult = null;
  25583. var act = null;
  25584. var checkPicking = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERPICK)
  25585. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)
  25586. || obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) || obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25587. if (!checkPicking && BABYLON.ActionManager && BABYLON.ActionManager.HasPickTriggers) {
  25588. act = _this._initActionManager(act, clickInfo);
  25589. if (act)
  25590. checkPicking = act.hasPickTriggers;
  25591. }
  25592. if (checkPicking) {
  25593. var btn = evt.button;
  25594. clickInfo.hasSwiped = Math.abs(_this._startingPointerPosition.x - _this._pointerX) > Scene.DragMovementThreshold ||
  25595. Math.abs(_this._startingPointerPosition.y - _this._pointerY) > Scene.DragMovementThreshold;
  25596. if (!clickInfo.hasSwiped) {
  25597. var checkSingleClickImmediately = !Scene.ExclusiveDoubleClickMode;
  25598. if (!checkSingleClickImmediately) {
  25599. checkSingleClickImmediately = !obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) &&
  25600. !obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25601. if (checkSingleClickImmediately && !BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25602. act = _this._initActionManager(act, clickInfo);
  25603. if (act)
  25604. checkSingleClickImmediately = !act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25605. }
  25606. }
  25607. if (checkSingleClickImmediately) {
  25608. // single click detected if double click delay is over or two different successive keys pressed without exclusive double click or no double click required
  25609. if (Date.now() - _this._previousStartingPointerTime > Scene.DoubleClickDelay ||
  25610. btn !== _this._previousButtonPressed) {
  25611. clickInfo.singleClick = true;
  25612. cb(clickInfo, _this._currentPickResult);
  25613. }
  25614. }
  25615. // at least one double click is required to be check and exclusive double click is enabled
  25616. else {
  25617. // wait that no double click has been raised during the double click delay
  25618. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25619. _this._delayedSimpleClickTimeout = window.setTimeout(_this._delayedSimpleClick.bind(_this, btn, clickInfo, cb), Scene.DoubleClickDelay);
  25620. }
  25621. var checkDoubleClick = obs1.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP) ||
  25622. obs2.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP);
  25623. if (!checkDoubleClick && BABYLON.ActionManager.HasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger)) {
  25624. act = _this._initActionManager(act, clickInfo);
  25625. if (act)
  25626. checkDoubleClick = act.hasSpecificTrigger(BABYLON.ActionManager.OnDoublePickTrigger);
  25627. }
  25628. if (checkDoubleClick) {
  25629. // two successive keys pressed are equal, double click delay is not over and double click has not just occurred
  25630. if (btn === _this._previousButtonPressed &&
  25631. Date.now() - _this._previousStartingPointerTime < Scene.DoubleClickDelay &&
  25632. !_this._doubleClickOccured) {
  25633. // pointer has not moved for 2 clicks, it's a double click
  25634. if (!clickInfo.hasSwiped &&
  25635. Math.abs(_this._previousStartingPointerPosition.x - _this._startingPointerPosition.x) < Scene.DragMovementThreshold &&
  25636. Math.abs(_this._previousStartingPointerPosition.y - _this._startingPointerPosition.y) < Scene.DragMovementThreshold) {
  25637. _this._previousStartingPointerTime = 0;
  25638. _this._doubleClickOccured = true;
  25639. clickInfo.doubleClick = true;
  25640. clickInfo.ignore = false;
  25641. if (Scene.ExclusiveDoubleClickMode && _this._previousDelayedSimpleClickTimeout) {
  25642. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25643. }
  25644. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25645. cb(clickInfo, _this._currentPickResult);
  25646. }
  25647. // if the two successive clicks are too far, it's just two simple clicks
  25648. else {
  25649. _this._doubleClickOccured = false;
  25650. _this._previousStartingPointerTime = _this._startingPointerTime;
  25651. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25652. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25653. _this._previousButtonPressed = btn;
  25654. if (Scene.ExclusiveDoubleClickMode) {
  25655. if (_this._previousDelayedSimpleClickTimeout) {
  25656. clearTimeout(_this._previousDelayedSimpleClickTimeout);
  25657. }
  25658. _this._previousDelayedSimpleClickTimeout = _this._delayedSimpleClickTimeout;
  25659. cb(clickInfo, _this._previousPickResult);
  25660. }
  25661. else {
  25662. cb(clickInfo, _this._currentPickResult);
  25663. }
  25664. }
  25665. }
  25666. // just the first click of the double has been raised
  25667. else {
  25668. _this._doubleClickOccured = false;
  25669. _this._previousStartingPointerTime = _this._startingPointerTime;
  25670. _this._previousStartingPointerPosition.x = _this._startingPointerPosition.x;
  25671. _this._previousStartingPointerPosition.y = _this._startingPointerPosition.y;
  25672. _this._previousButtonPressed = btn;
  25673. }
  25674. }
  25675. }
  25676. }
  25677. clickInfo.ignore = true;
  25678. cb(clickInfo, _this._currentPickResult);
  25679. };
  25680. this._spritePredicate = function (sprite) {
  25681. return sprite.isPickable && sprite.actionManager && sprite.actionManager.hasPointerTriggers;
  25682. };
  25683. this._onPointerMove = function (evt) {
  25684. _this._updatePointerPosition(evt);
  25685. // PreObservable support
  25686. if (_this._checkPrePointerObservable(null, evt, evt.type === "mousewheel" || evt.type === "DOMMouseScroll" ? BABYLON.PointerEventTypes.POINTERWHEEL : BABYLON.PointerEventTypes.POINTERMOVE)) {
  25687. return;
  25688. }
  25689. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25690. return;
  25691. }
  25692. if (!_this.pointerMovePredicate) {
  25693. _this.pointerMovePredicate = function (mesh) { return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled() && (mesh.enablePointerMoveEvents || _this.constantlyUpdateMeshUnderPointer || (mesh.actionManager !== null && mesh.actionManager !== undefined)); };
  25694. }
  25695. // Meshes
  25696. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerMovePredicate, false, _this.cameraToUseForPointers);
  25697. _this._processPointerMove(pickResult, evt);
  25698. };
  25699. this._onPointerDown = function (evt) {
  25700. _this._totalPointersPressed++;
  25701. _this._pickedDownMesh = null;
  25702. _this._meshPickProceed = false;
  25703. _this._updatePointerPosition(evt);
  25704. if (_this.preventDefaultOnPointerDown && canvas) {
  25705. evt.preventDefault();
  25706. canvas.focus();
  25707. }
  25708. // PreObservable support
  25709. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOWN)) {
  25710. return;
  25711. }
  25712. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25713. return;
  25714. }
  25715. _this._pointerCaptures[evt.pointerId] = true;
  25716. _this._startingPointerPosition.x = _this._pointerX;
  25717. _this._startingPointerPosition.y = _this._pointerY;
  25718. _this._startingPointerTime = Date.now();
  25719. if (!_this.pointerDownPredicate) {
  25720. _this.pointerDownPredicate = function (mesh) {
  25721. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25722. };
  25723. }
  25724. // Meshes
  25725. _this._pickedDownMesh = null;
  25726. var pickResult = _this.pick(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this.pointerDownPredicate, false, _this.cameraToUseForPointers);
  25727. _this._processPointerDown(pickResult, evt);
  25728. // Sprites
  25729. _this._pickedDownSprite = null;
  25730. if (_this.spriteManagers.length > 0) {
  25731. pickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25732. if (pickResult && pickResult.hit && pickResult.pickedSprite) {
  25733. if (pickResult.pickedSprite.actionManager) {
  25734. _this._pickedDownSprite = pickResult.pickedSprite;
  25735. switch (evt.button) {
  25736. case 0:
  25737. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnLeftPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25738. break;
  25739. case 1:
  25740. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnCenterPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25741. break;
  25742. case 2:
  25743. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnRightPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25744. break;
  25745. }
  25746. if (pickResult.pickedSprite.actionManager) {
  25747. pickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickDownTrigger, BABYLON.ActionEvent.CreateNewFromSprite(pickResult.pickedSprite, _this, evt));
  25748. }
  25749. }
  25750. }
  25751. }
  25752. };
  25753. this._onPointerUp = function (evt) {
  25754. if (_this._totalPointersPressed === 0) { // We are attaching the pointer up to windows because of a bug in FF
  25755. return; // So we need to test it the pointer down was pressed before.
  25756. }
  25757. _this._totalPointersPressed--;
  25758. _this._pickedUpMesh = null;
  25759. _this._meshPickProceed = false;
  25760. _this._updatePointerPosition(evt);
  25761. _this._initClickEvent(_this.onPrePointerObservable, _this.onPointerObservable, evt, function (clickInfo, pickResult) {
  25762. // PreObservable support
  25763. if (_this.onPrePointerObservable.hasObservers()) {
  25764. if (!clickInfo.ignore) {
  25765. if (!clickInfo.hasSwiped) {
  25766. if (clickInfo.singleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERTAP)) {
  25767. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERTAP)) {
  25768. return;
  25769. }
  25770. }
  25771. if (clickInfo.doubleClick && _this.onPrePointerObservable.hasSpecificMask(BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25772. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERDOUBLETAP)) {
  25773. return;
  25774. }
  25775. }
  25776. }
  25777. }
  25778. else {
  25779. if (_this._checkPrePointerObservable(null, evt, BABYLON.PointerEventTypes.POINTERUP)) {
  25780. return;
  25781. }
  25782. }
  25783. }
  25784. if (!_this.cameraToUseForPointers && !_this.activeCamera) {
  25785. return;
  25786. }
  25787. _this._pointerCaptures[evt.pointerId] = false;
  25788. if (!_this.pointerUpPredicate) {
  25789. _this.pointerUpPredicate = function (mesh) {
  25790. return mesh.isPickable && mesh.isVisible && mesh.isReady() && mesh.isEnabled();
  25791. };
  25792. }
  25793. // Meshes
  25794. if (!_this._meshPickProceed && (BABYLON.ActionManager && BABYLON.ActionManager.HasTriggers || _this.onPointerObservable.hasObservers())) {
  25795. _this._initActionManager(null, clickInfo);
  25796. }
  25797. if (!pickResult) {
  25798. pickResult = _this._currentPickResult;
  25799. }
  25800. _this._processPointerUp(pickResult, evt, clickInfo);
  25801. // Sprites
  25802. if (!clickInfo.ignore) {
  25803. if (_this.spriteManagers.length > 0) {
  25804. var spritePickResult = _this.pickSprite(_this._unTranslatedPointerX, _this._unTranslatedPointerY, _this._spritePredicate, false, _this.cameraToUseForPointers || undefined);
  25805. if (spritePickResult) {
  25806. if (spritePickResult.hit && spritePickResult.pickedSprite) {
  25807. if (spritePickResult.pickedSprite.actionManager) {
  25808. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickUpTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25809. if (spritePickResult.pickedSprite.actionManager) {
  25810. if (Math.abs(_this._startingPointerPosition.x - _this._pointerX) < Scene.DragMovementThreshold && Math.abs(_this._startingPointerPosition.y - _this._pointerY) < Scene.DragMovementThreshold) {
  25811. spritePickResult.pickedSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickTrigger, BABYLON.ActionEvent.CreateNewFromSprite(spritePickResult.pickedSprite, _this, evt));
  25812. }
  25813. }
  25814. }
  25815. }
  25816. if (_this._pickedDownSprite && _this._pickedDownSprite.actionManager && _this._pickedDownSprite !== spritePickResult.pickedSprite) {
  25817. _this._pickedDownSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPickOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(_this._pickedDownSprite, _this, evt));
  25818. }
  25819. }
  25820. }
  25821. }
  25822. _this._previousPickResult = _this._currentPickResult;
  25823. });
  25824. };
  25825. this._onKeyDown = function (evt) {
  25826. var type = BABYLON.KeyboardEventTypes.KEYDOWN;
  25827. if (_this.onPreKeyboardObservable.hasObservers()) {
  25828. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25829. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25830. if (pi.skipOnPointerObservable) {
  25831. return;
  25832. }
  25833. }
  25834. if (_this.onKeyboardObservable.hasObservers()) {
  25835. var pi = new BABYLON.KeyboardInfo(type, evt);
  25836. _this.onKeyboardObservable.notifyObservers(pi, type);
  25837. }
  25838. if (_this.actionManager) {
  25839. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyDownTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25840. }
  25841. };
  25842. this._onKeyUp = function (evt) {
  25843. var type = BABYLON.KeyboardEventTypes.KEYUP;
  25844. if (_this.onPreKeyboardObservable.hasObservers()) {
  25845. var pi = new BABYLON.KeyboardInfoPre(type, evt);
  25846. _this.onPreKeyboardObservable.notifyObservers(pi, type);
  25847. if (pi.skipOnPointerObservable) {
  25848. return;
  25849. }
  25850. }
  25851. if (_this.onKeyboardObservable.hasObservers()) {
  25852. var pi = new BABYLON.KeyboardInfo(type, evt);
  25853. _this.onKeyboardObservable.notifyObservers(pi, type);
  25854. }
  25855. if (_this.actionManager) {
  25856. _this.actionManager.processTrigger(BABYLON.ActionManager.OnKeyUpTrigger, BABYLON.ActionEvent.CreateNewFromScene(_this, evt));
  25857. }
  25858. };
  25859. var engine = this.getEngine();
  25860. this._onCanvasFocusObserver = engine.onCanvasFocusObservable.add(function () {
  25861. if (!canvas) {
  25862. return;
  25863. }
  25864. canvas.addEventListener("keydown", _this._onKeyDown, false);
  25865. canvas.addEventListener("keyup", _this._onKeyUp, false);
  25866. });
  25867. this._onCanvasBlurObserver = engine.onCanvasBlurObservable.add(function () {
  25868. if (!canvas) {
  25869. return;
  25870. }
  25871. canvas.removeEventListener("keydown", _this._onKeyDown);
  25872. canvas.removeEventListener("keyup", _this._onKeyUp);
  25873. });
  25874. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25875. var canvas = this._engine.getRenderingCanvas();
  25876. if (!canvas) {
  25877. return;
  25878. }
  25879. if (attachMove) {
  25880. canvas.addEventListener(eventPrefix + "move", this._onPointerMove, false);
  25881. // Wheel
  25882. canvas.addEventListener('mousewheel', this._onPointerMove, false);
  25883. canvas.addEventListener('DOMMouseScroll', this._onPointerMove, false);
  25884. }
  25885. if (attachDown) {
  25886. canvas.addEventListener(eventPrefix + "down", this._onPointerDown, false);
  25887. }
  25888. if (attachUp) {
  25889. window.addEventListener(eventPrefix + "up", this._onPointerUp, false);
  25890. }
  25891. canvas.tabIndex = 1;
  25892. };
  25893. /** Detaches all event handlers*/
  25894. Scene.prototype.detachControl = function () {
  25895. var engine = this.getEngine();
  25896. var eventPrefix = BABYLON.Tools.GetPointerPrefix();
  25897. var canvas = engine.getRenderingCanvas();
  25898. if (!canvas) {
  25899. return;
  25900. }
  25901. canvas.removeEventListener(eventPrefix + "move", this._onPointerMove);
  25902. canvas.removeEventListener(eventPrefix + "down", this._onPointerDown);
  25903. window.removeEventListener(eventPrefix + "up", this._onPointerUp);
  25904. if (this._onCanvasBlurObserver) {
  25905. engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  25906. }
  25907. if (this._onCanvasFocusObserver) {
  25908. engine.onCanvasFocusObservable.remove(this._onCanvasFocusObserver);
  25909. }
  25910. // Wheel
  25911. canvas.removeEventListener('mousewheel', this._onPointerMove);
  25912. canvas.removeEventListener('DOMMouseScroll', this._onPointerMove);
  25913. // Keyboard
  25914. canvas.removeEventListener("keydown", this._onKeyDown);
  25915. canvas.removeEventListener("keyup", this._onKeyUp);
  25916. // Observables
  25917. this.onKeyboardObservable.clear();
  25918. this.onPreKeyboardObservable.clear();
  25919. this.onPointerObservable.clear();
  25920. this.onPrePointerObservable.clear();
  25921. };
  25922. /**
  25923. * This function will check if the scene can be rendered (textures are loaded, shaders are compiled)
  25924. * Delay loaded resources are not taking in account
  25925. * @return true if all required resources are ready
  25926. */
  25927. Scene.prototype.isReady = function () {
  25928. if (this._isDisposed) {
  25929. return false;
  25930. }
  25931. if (this._pendingData.length > 0) {
  25932. return false;
  25933. }
  25934. var index;
  25935. var engine = this.getEngine();
  25936. // Geometries
  25937. for (index = 0; index < this._geometries.length; index++) {
  25938. var geometry = this._geometries[index];
  25939. if (geometry.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  25940. return false;
  25941. }
  25942. }
  25943. // Meshes
  25944. for (index = 0; index < this.meshes.length; index++) {
  25945. var mesh = this.meshes[index];
  25946. if (!mesh.isEnabled()) {
  25947. continue;
  25948. }
  25949. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  25950. continue;
  25951. }
  25952. if (!mesh.isReady(true)) {
  25953. return false;
  25954. }
  25955. // Effect layers
  25956. var hardwareInstancedRendering = mesh.getClassName() === "InstancedMesh" || engine.getCaps().instancedArrays && mesh.instances.length > 0;
  25957. for (var _i = 0, _a = this.effectLayers; _i < _a.length; _i++) {
  25958. var layer = _a[_i];
  25959. if (!layer.hasMesh(mesh)) {
  25960. continue;
  25961. }
  25962. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  25963. var subMesh = _c[_b];
  25964. if (!layer.isReady(subMesh, hardwareInstancedRendering)) {
  25965. return false;
  25966. }
  25967. }
  25968. }
  25969. }
  25970. // Post-processes
  25971. if (this.activeCameras && this.activeCameras.length > 0) {
  25972. for (var _d = 0, _e = this.activeCameras; _d < _e.length; _d++) {
  25973. var camera = _e[_d];
  25974. if (!camera.isReady(true)) {
  25975. return false;
  25976. }
  25977. }
  25978. }
  25979. else if (this.activeCamera) {
  25980. if (!this.activeCamera.isReady(true)) {
  25981. return false;
  25982. }
  25983. }
  25984. // Particles
  25985. for (var _f = 0, _g = this.particleSystems; _f < _g.length; _f++) {
  25986. var particleSystem = _g[_f];
  25987. if (!particleSystem.isReady()) {
  25988. return false;
  25989. }
  25990. }
  25991. return true;
  25992. };
  25993. /** Resets all cached information relative to material (including effect and visibility) */
  25994. Scene.prototype.resetCachedMaterial = function () {
  25995. this._cachedMaterial = null;
  25996. this._cachedEffect = null;
  25997. this._cachedVisibility = null;
  25998. };
  25999. /**
  26000. * Registers a function to be called before every frame render
  26001. * @param func defines the function to register
  26002. */
  26003. Scene.prototype.registerBeforeRender = function (func) {
  26004. this.onBeforeRenderObservable.add(func);
  26005. };
  26006. /**
  26007. * Unregisters a function called before every frame render
  26008. * @param func defines the function to unregister
  26009. */
  26010. Scene.prototype.unregisterBeforeRender = function (func) {
  26011. this.onBeforeRenderObservable.removeCallback(func);
  26012. };
  26013. /**
  26014. * Registers a function to be called after every frame render
  26015. * @param func defines the function to register
  26016. */
  26017. Scene.prototype.registerAfterRender = function (func) {
  26018. this.onAfterRenderObservable.add(func);
  26019. };
  26020. /**
  26021. * Unregisters a function called after every frame render
  26022. * @param func defines the function to unregister
  26023. */
  26024. Scene.prototype.unregisterAfterRender = function (func) {
  26025. this.onAfterRenderObservable.removeCallback(func);
  26026. };
  26027. Scene.prototype._executeOnceBeforeRender = function (func) {
  26028. var _this = this;
  26029. var execFunc = function () {
  26030. func();
  26031. setTimeout(function () {
  26032. _this.unregisterBeforeRender(execFunc);
  26033. });
  26034. };
  26035. this.registerBeforeRender(execFunc);
  26036. };
  26037. /**
  26038. * The provided function will run before render once and will be disposed afterwards.
  26039. * A timeout delay can be provided so that the function will be executed in N ms.
  26040. * The timeout is using the browser's native setTimeout so time percision cannot be guaranteed.
  26041. * @param func The function to be executed.
  26042. * @param timeout optional delay in ms
  26043. */
  26044. Scene.prototype.executeOnceBeforeRender = function (func, timeout) {
  26045. var _this = this;
  26046. if (timeout !== undefined) {
  26047. setTimeout(function () {
  26048. _this._executeOnceBeforeRender(func);
  26049. }, timeout);
  26050. }
  26051. else {
  26052. this._executeOnceBeforeRender(func);
  26053. }
  26054. };
  26055. /** @hidden */
  26056. Scene.prototype._addPendingData = function (data) {
  26057. this._pendingData.push(data);
  26058. };
  26059. /** @hidden */
  26060. Scene.prototype._removePendingData = function (data) {
  26061. var wasLoading = this.isLoading;
  26062. var index = this._pendingData.indexOf(data);
  26063. if (index !== -1) {
  26064. this._pendingData.splice(index, 1);
  26065. }
  26066. if (wasLoading && !this.isLoading) {
  26067. this.onDataLoadedObservable.notifyObservers(this);
  26068. }
  26069. };
  26070. /**
  26071. * Returns the number of items waiting to be loaded
  26072. * @returns the number of items waiting to be loaded
  26073. */
  26074. Scene.prototype.getWaitingItemsCount = function () {
  26075. return this._pendingData.length;
  26076. };
  26077. Object.defineProperty(Scene.prototype, "isLoading", {
  26078. /**
  26079. * Returns a boolean indicating if the scene is still loading data
  26080. */
  26081. get: function () {
  26082. return this._pendingData.length > 0;
  26083. },
  26084. enumerable: true,
  26085. configurable: true
  26086. });
  26087. /**
  26088. * Registers a function to be executed when the scene is ready
  26089. * @param {Function} func - the function to be executed
  26090. */
  26091. Scene.prototype.executeWhenReady = function (func) {
  26092. var _this = this;
  26093. this.onReadyObservable.add(func);
  26094. if (this._executeWhenReadyTimeoutId !== -1) {
  26095. return;
  26096. }
  26097. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26098. _this._checkIsReady();
  26099. }, 150);
  26100. };
  26101. /**
  26102. * Returns a promise that resolves when the scene is ready
  26103. * @returns A promise that resolves when the scene is ready
  26104. */
  26105. Scene.prototype.whenReadyAsync = function () {
  26106. var _this = this;
  26107. return new Promise(function (resolve) {
  26108. _this.executeWhenReady(function () {
  26109. resolve();
  26110. });
  26111. });
  26112. };
  26113. /** @hidden */
  26114. Scene.prototype._checkIsReady = function () {
  26115. var _this = this;
  26116. if (this.isReady()) {
  26117. this.onReadyObservable.notifyObservers(this);
  26118. this.onReadyObservable.clear();
  26119. this._executeWhenReadyTimeoutId = -1;
  26120. return;
  26121. }
  26122. this._executeWhenReadyTimeoutId = setTimeout(function () {
  26123. _this._checkIsReady();
  26124. }, 150);
  26125. };
  26126. // Animations
  26127. /**
  26128. * Will start the animation sequence of a given target
  26129. * @param target defines the target
  26130. * @param from defines from which frame should animation start
  26131. * @param to defines until which frame should animation run.
  26132. * @param weight defines the weight to apply to the animation (1.0 by default)
  26133. * @param loop defines if the animation loops
  26134. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26135. * @param onAnimationEnd defines the function to be executed when the animation ends
  26136. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26137. * @returns the animatable object created for this animation
  26138. */
  26139. Scene.prototype.beginWeightedAnimation = function (target, from, to, weight, loop, speedRatio, onAnimationEnd, animatable) {
  26140. if (weight === void 0) { weight = 1.0; }
  26141. if (speedRatio === void 0) { speedRatio = 1.0; }
  26142. var returnedAnimatable = this.beginAnimation(target, from, to, loop, speedRatio, onAnimationEnd, animatable, false);
  26143. returnedAnimatable.weight = weight;
  26144. return returnedAnimatable;
  26145. };
  26146. /**
  26147. * Will start the animation sequence of a given target
  26148. * @param target defines the target
  26149. * @param from defines from which frame should animation start
  26150. * @param to defines until which frame should animation run.
  26151. * @param loop defines if the animation loops
  26152. * @param speedRatio defines the speed in which to run the animation (1.0 by default)
  26153. * @param onAnimationEnd defines the function to be executed when the animation ends
  26154. * @param animatable defines an animatable object. If not provided a new one will be created from the given params
  26155. * @param stopCurrent defines if the current animations must be stopped first (true by default)
  26156. * @returns the animatable object created for this animation
  26157. */
  26158. Scene.prototype.beginAnimation = function (target, from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent) {
  26159. if (speedRatio === void 0) { speedRatio = 1.0; }
  26160. if (stopCurrent === void 0) { stopCurrent = true; }
  26161. if (from > to && speedRatio > 0) {
  26162. speedRatio *= -1;
  26163. }
  26164. if (stopCurrent) {
  26165. this.stopAnimation(target);
  26166. }
  26167. if (!animatable) {
  26168. animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd);
  26169. }
  26170. // Local animations
  26171. if (target.animations) {
  26172. animatable.appendAnimations(target, target.animations);
  26173. }
  26174. // Children animations
  26175. if (target.getAnimatables) {
  26176. var animatables = target.getAnimatables();
  26177. for (var index = 0; index < animatables.length; index++) {
  26178. this.beginAnimation(animatables[index], from, to, loop, speedRatio, onAnimationEnd, animatable, stopCurrent);
  26179. }
  26180. }
  26181. animatable.reset();
  26182. return animatable;
  26183. };
  26184. /**
  26185. * Begin a new animation on a given node
  26186. * @param target defines the target where the animation will take place
  26187. * @param animations defines the list of animations to start
  26188. * @param from defines the initial value
  26189. * @param to defines the final value
  26190. * @param loop defines if you want animation to loop (off by default)
  26191. * @param speedRatio defines the speed ratio to apply to all animations
  26192. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26193. * @returns the list of created animatables
  26194. */
  26195. Scene.prototype.beginDirectAnimation = function (target, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26196. if (speedRatio === undefined) {
  26197. speedRatio = 1.0;
  26198. }
  26199. var animatable = new BABYLON.Animatable(this, target, from, to, loop, speedRatio, onAnimationEnd, animations);
  26200. return animatable;
  26201. };
  26202. /**
  26203. * Begin a new animation on a given node and its hierarchy
  26204. * @param target defines the root node where the animation will take place
  26205. * @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.
  26206. * @param animations defines the list of animations to start
  26207. * @param from defines the initial value
  26208. * @param to defines the final value
  26209. * @param loop defines if you want animation to loop (off by default)
  26210. * @param speedRatio defines the speed ratio to apply to all animations
  26211. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  26212. * @returns the list of animatables created for all nodes
  26213. */
  26214. Scene.prototype.beginDirectHierarchyAnimation = function (target, directDescendantsOnly, animations, from, to, loop, speedRatio, onAnimationEnd) {
  26215. var children = target.getDescendants(directDescendantsOnly);
  26216. var result = [];
  26217. result.push(this.beginDirectAnimation(target, animations, from, to, loop, speedRatio, onAnimationEnd));
  26218. for (var _i = 0, children_1 = children; _i < children_1.length; _i++) {
  26219. var child = children_1[_i];
  26220. result.push(this.beginDirectAnimation(child, animations, from, to, loop, speedRatio, onAnimationEnd));
  26221. }
  26222. return result;
  26223. };
  26224. /**
  26225. * Gets the animatable associated with a specific target
  26226. * @param target defines the target of the animatable
  26227. * @returns the required animatable if found
  26228. */
  26229. Scene.prototype.getAnimatableByTarget = function (target) {
  26230. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26231. if (this._activeAnimatables[index].target === target) {
  26232. return this._activeAnimatables[index];
  26233. }
  26234. }
  26235. return null;
  26236. };
  26237. /**
  26238. * Gets all animatables associated with a given target
  26239. * @param target defines the target to look animatables for
  26240. * @returns an array of Animatables
  26241. */
  26242. Scene.prototype.getAllAnimatablesByTarget = function (target) {
  26243. var result = [];
  26244. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26245. if (this._activeAnimatables[index].target === target) {
  26246. result.push(this._activeAnimatables[index]);
  26247. }
  26248. }
  26249. return result;
  26250. };
  26251. Object.defineProperty(Scene.prototype, "animatables", {
  26252. /**
  26253. * Gets all animatable attached to the scene
  26254. */
  26255. get: function () {
  26256. return this._activeAnimatables;
  26257. },
  26258. enumerable: true,
  26259. configurable: true
  26260. });
  26261. /**
  26262. * Will stop the animation of the given target
  26263. * @param target - the target
  26264. * @param animationName - the name of the animation to stop (all animations will be stopped if empty)
  26265. */
  26266. Scene.prototype.stopAnimation = function (target, animationName) {
  26267. var animatables = this.getAllAnimatablesByTarget(target);
  26268. for (var _i = 0, animatables_1 = animatables; _i < animatables_1.length; _i++) {
  26269. var animatable = animatables_1[_i];
  26270. animatable.stop(animationName);
  26271. }
  26272. };
  26273. /**
  26274. * Stops and removes all animations that have been applied to the scene
  26275. */
  26276. Scene.prototype.stopAllAnimations = function () {
  26277. if (this._activeAnimatables) {
  26278. for (var i = 0; i < this._activeAnimatables.length; i++) {
  26279. this._activeAnimatables[i].stop();
  26280. }
  26281. this._activeAnimatables = [];
  26282. }
  26283. for (var _i = 0, _a = this.animationGroups; _i < _a.length; _i++) {
  26284. var group = _a[_i];
  26285. group.stop();
  26286. }
  26287. };
  26288. Scene.prototype._animate = function () {
  26289. if (!this.animationsEnabled || this._activeAnimatables.length === 0) {
  26290. return;
  26291. }
  26292. // Getting time
  26293. var now = BABYLON.Tools.Now;
  26294. if (!this._animationTimeLast) {
  26295. if (this._pendingData.length > 0) {
  26296. return;
  26297. }
  26298. this._animationTimeLast = now;
  26299. }
  26300. var deltaTime = this.useConstantAnimationDeltaTime ? 16.0 : (now - this._animationTimeLast) * this.animationTimeScale;
  26301. this._animationTime += deltaTime;
  26302. this._animationTimeLast = now;
  26303. for (var index = 0; index < this._activeAnimatables.length; index++) {
  26304. this._activeAnimatables[index]._animate(this._animationTime);
  26305. }
  26306. // Late animation bindings
  26307. this._processLateAnimationBindings();
  26308. };
  26309. /** @hidden */
  26310. Scene.prototype._registerTargetForLateAnimationBinding = function (runtimeAnimation, originalValue) {
  26311. var target = runtimeAnimation.target;
  26312. this._registeredForLateAnimationBindings.pushNoDuplicate(target);
  26313. if (!target._lateAnimationHolders) {
  26314. target._lateAnimationHolders = {};
  26315. }
  26316. if (!target._lateAnimationHolders[runtimeAnimation.targetPath]) {
  26317. target._lateAnimationHolders[runtimeAnimation.targetPath] = {
  26318. totalWeight: 0,
  26319. animations: [],
  26320. originalValue: originalValue
  26321. };
  26322. }
  26323. target._lateAnimationHolders[runtimeAnimation.targetPath].animations.push(runtimeAnimation);
  26324. target._lateAnimationHolders[runtimeAnimation.targetPath].totalWeight += runtimeAnimation.weight;
  26325. };
  26326. Scene.prototype._processLateAnimationBindingsForMatrices = function (holder) {
  26327. var normalizer = 1.0;
  26328. var finalPosition = BABYLON.Tmp.Vector3[0];
  26329. var finalScaling = BABYLON.Tmp.Vector3[1];
  26330. var finalQuaternion = BABYLON.Tmp.Quaternion[0];
  26331. var startIndex = 0;
  26332. var originalAnimation = holder.animations[0];
  26333. var originalValue = holder.originalValue;
  26334. var scale = 1;
  26335. if (holder.totalWeight < 1.0) {
  26336. // We need to mix the original value in
  26337. originalValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26338. scale = 1.0 - holder.totalWeight;
  26339. }
  26340. else {
  26341. startIndex = 1;
  26342. // We need to normalize the weights
  26343. normalizer = holder.totalWeight;
  26344. originalAnimation.currentValue.decompose(finalScaling, finalQuaternion, finalPosition);
  26345. scale = originalAnimation.weight / normalizer;
  26346. if (scale == 1) {
  26347. return originalAnimation.currentValue;
  26348. }
  26349. }
  26350. finalScaling.scaleInPlace(scale);
  26351. finalPosition.scaleInPlace(scale);
  26352. finalQuaternion.scaleInPlace(scale);
  26353. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26354. var runtimeAnimation = holder.animations[animIndex];
  26355. var scale = runtimeAnimation.weight / normalizer;
  26356. var currentPosition = BABYLON.Tmp.Vector3[2];
  26357. var currentScaling = BABYLON.Tmp.Vector3[3];
  26358. var currentQuaternion = BABYLON.Tmp.Quaternion[1];
  26359. runtimeAnimation.currentValue.decompose(currentScaling, currentQuaternion, currentPosition);
  26360. currentScaling.scaleAndAddToRef(scale, finalScaling);
  26361. currentQuaternion.scaleAndAddToRef(scale, finalQuaternion);
  26362. currentPosition.scaleAndAddToRef(scale, finalPosition);
  26363. }
  26364. BABYLON.Matrix.ComposeToRef(finalScaling, finalQuaternion, finalPosition, originalAnimation._workValue);
  26365. return originalAnimation._workValue;
  26366. };
  26367. Scene.prototype._processLateAnimationBindingsForQuaternions = function (holder) {
  26368. var originalAnimation = holder.animations[0];
  26369. var originalValue = holder.originalValue;
  26370. if (holder.animations.length === 1) {
  26371. return BABYLON.Quaternion.Slerp(originalValue, originalAnimation.currentValue, Math.min(1.0, holder.totalWeight));
  26372. }
  26373. var normalizer = 1.0;
  26374. var quaternions;
  26375. var weights;
  26376. if (holder.totalWeight < 1.0) {
  26377. var scale = 1.0 - holder.totalWeight;
  26378. quaternions = [];
  26379. weights = [];
  26380. quaternions.push(originalValue);
  26381. weights.push(scale);
  26382. }
  26383. else {
  26384. if (holder.animations.length === 2) { // Slerp as soon as we can
  26385. return BABYLON.Quaternion.Slerp(holder.animations[0].currentValue, holder.animations[1].currentValue, holder.animations[1].weight / holder.totalWeight);
  26386. }
  26387. quaternions = [];
  26388. weights = [];
  26389. normalizer = holder.totalWeight;
  26390. }
  26391. for (var animIndex = 0; animIndex < holder.animations.length; animIndex++) {
  26392. var runtimeAnimation = holder.animations[animIndex];
  26393. quaternions.push(runtimeAnimation.currentValue);
  26394. weights.push(runtimeAnimation.weight / normalizer);
  26395. }
  26396. // https://gamedev.stackexchange.com/questions/62354/method-for-interpolation-between-3-quaternions
  26397. var cumulativeAmount = 0;
  26398. var cumulativeQuaternion = null;
  26399. for (var index = 0; index < quaternions.length;) {
  26400. if (!cumulativeQuaternion) {
  26401. cumulativeQuaternion = BABYLON.Quaternion.Slerp(quaternions[index], quaternions[index + 1], weights[index + 1] / (weights[index] + weights[index + 1]));
  26402. cumulativeAmount = weights[index] + weights[index + 1];
  26403. index += 2;
  26404. continue;
  26405. }
  26406. cumulativeAmount += weights[index];
  26407. BABYLON.Quaternion.SlerpToRef(cumulativeQuaternion, quaternions[index], weights[index] / cumulativeAmount, cumulativeQuaternion);
  26408. index++;
  26409. }
  26410. return cumulativeQuaternion;
  26411. };
  26412. Scene.prototype._processLateAnimationBindings = function () {
  26413. if (!this._registeredForLateAnimationBindings.length) {
  26414. return;
  26415. }
  26416. for (var index = 0; index < this._registeredForLateAnimationBindings.length; index++) {
  26417. var target = this._registeredForLateAnimationBindings.data[index];
  26418. for (var path in target._lateAnimationHolders) {
  26419. var holder = target._lateAnimationHolders[path];
  26420. var originalAnimation = holder.animations[0];
  26421. var originalValue = holder.originalValue;
  26422. var matrixDecomposeMode = BABYLON.Animation.AllowMatrixDecomposeForInterpolation && originalValue.m; // ie. data is matrix
  26423. var finalValue = void 0;
  26424. if (matrixDecomposeMode) {
  26425. finalValue = this._processLateAnimationBindingsForMatrices(holder);
  26426. }
  26427. else {
  26428. var quaternionMode = originalValue.w !== undefined;
  26429. if (quaternionMode) {
  26430. finalValue = this._processLateAnimationBindingsForQuaternions(holder);
  26431. }
  26432. else {
  26433. var startIndex = 0;
  26434. var normalizer = 1.0;
  26435. if (holder.totalWeight < 1.0) {
  26436. // We need to mix the original value in
  26437. if (originalValue.scale) {
  26438. finalValue = originalValue.scale(1.0 - holder.totalWeight);
  26439. }
  26440. else {
  26441. finalValue = originalValue * (1.0 - holder.totalWeight);
  26442. }
  26443. }
  26444. else {
  26445. // We need to normalize the weights
  26446. normalizer = holder.totalWeight;
  26447. var scale_1 = originalAnimation.weight / normalizer;
  26448. if (scale_1 !== 1) {
  26449. if (originalAnimation.currentValue.scale) {
  26450. finalValue = originalAnimation.currentValue.scale(scale_1);
  26451. }
  26452. else {
  26453. finalValue = originalAnimation.currentValue * scale_1;
  26454. }
  26455. }
  26456. else {
  26457. finalValue = originalAnimation.currentValue;
  26458. }
  26459. startIndex = 1;
  26460. }
  26461. for (var animIndex = startIndex; animIndex < holder.animations.length; animIndex++) {
  26462. var runtimeAnimation = holder.animations[animIndex];
  26463. var scale = runtimeAnimation.weight / normalizer;
  26464. if (runtimeAnimation.currentValue.scaleAndAddToRef) {
  26465. runtimeAnimation.currentValue.scaleAndAddToRef(scale, finalValue);
  26466. }
  26467. else {
  26468. finalValue += runtimeAnimation.currentValue * scale;
  26469. }
  26470. }
  26471. }
  26472. }
  26473. target[path] = finalValue;
  26474. }
  26475. target._lateAnimationHolders = {};
  26476. }
  26477. this._registeredForLateAnimationBindings.reset();
  26478. };
  26479. // Matrix
  26480. /** @hidden */
  26481. Scene.prototype._switchToAlternateCameraConfiguration = function (active) {
  26482. this._useAlternateCameraConfiguration = active;
  26483. };
  26484. /**
  26485. * Gets the current view matrix
  26486. * @returns a Matrix
  26487. */
  26488. Scene.prototype.getViewMatrix = function () {
  26489. return this._useAlternateCameraConfiguration ? this._alternateViewMatrix : this._viewMatrix;
  26490. };
  26491. /**
  26492. * Gets the current projection matrix
  26493. * @returns a Matrix
  26494. */
  26495. Scene.prototype.getProjectionMatrix = function () {
  26496. return this._useAlternateCameraConfiguration ? this._alternateProjectionMatrix : this._projectionMatrix;
  26497. };
  26498. /**
  26499. * Gets the current transform matrix
  26500. * @returns a Matrix made of View * Projection
  26501. */
  26502. Scene.prototype.getTransformMatrix = function () {
  26503. return this._useAlternateCameraConfiguration ? this._alternateTransformMatrix : this._transformMatrix;
  26504. };
  26505. /**
  26506. * Sets the current transform matrix
  26507. * @param view defines the View matrix to use
  26508. * @param projection defines the Projection matrix to use
  26509. */
  26510. Scene.prototype.setTransformMatrix = function (view, projection) {
  26511. if (this._viewUpdateFlag === view.updateFlag && this._projectionUpdateFlag === projection.updateFlag) {
  26512. return;
  26513. }
  26514. this._viewUpdateFlag = view.updateFlag;
  26515. this._projectionUpdateFlag = projection.updateFlag;
  26516. this._viewMatrix = view;
  26517. this._projectionMatrix = projection;
  26518. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  26519. // Update frustum
  26520. if (!this._frustumPlanes) {
  26521. this._frustumPlanes = BABYLON.Frustum.GetPlanes(this._transformMatrix);
  26522. }
  26523. else {
  26524. BABYLON.Frustum.GetPlanesToRef(this._transformMatrix, this._frustumPlanes);
  26525. }
  26526. if (this.activeCamera && this.activeCamera._alternateCamera) {
  26527. var otherCamera = this.activeCamera._alternateCamera;
  26528. otherCamera.getViewMatrix().multiplyToRef(otherCamera.getProjectionMatrix(), BABYLON.Tmp.Matrix[0]);
  26529. BABYLON.Frustum.GetRightPlaneToRef(BABYLON.Tmp.Matrix[0], this._frustumPlanes[3]); // Replace right plane by second camera right plane
  26530. }
  26531. if (this._sceneUbo.useUbo) {
  26532. this._sceneUbo.updateMatrix("viewProjection", this._transformMatrix);
  26533. this._sceneUbo.updateMatrix("view", this._viewMatrix);
  26534. this._sceneUbo.update();
  26535. }
  26536. };
  26537. /** @hidden */
  26538. Scene.prototype._setAlternateTransformMatrix = function (view, projection) {
  26539. if (this._alternateViewUpdateFlag === view.updateFlag && this._alternateProjectionUpdateFlag === projection.updateFlag) {
  26540. return;
  26541. }
  26542. this._alternateViewUpdateFlag = view.updateFlag;
  26543. this._alternateProjectionUpdateFlag = projection.updateFlag;
  26544. this._alternateViewMatrix = view;
  26545. this._alternateProjectionMatrix = projection;
  26546. if (!this._alternateTransformMatrix) {
  26547. this._alternateTransformMatrix = BABYLON.Matrix.Zero();
  26548. }
  26549. this._alternateViewMatrix.multiplyToRef(this._alternateProjectionMatrix, this._alternateTransformMatrix);
  26550. if (!this._alternateSceneUbo) {
  26551. this._createAlternateUbo();
  26552. }
  26553. if (this._alternateSceneUbo.useUbo) {
  26554. this._alternateSceneUbo.updateMatrix("viewProjection", this._alternateTransformMatrix);
  26555. this._alternateSceneUbo.updateMatrix("view", this._alternateViewMatrix);
  26556. this._alternateSceneUbo.update();
  26557. }
  26558. };
  26559. /**
  26560. * Gets the uniform buffer used to store scene data
  26561. * @returns a UniformBuffer
  26562. */
  26563. Scene.prototype.getSceneUniformBuffer = function () {
  26564. return this._useAlternateCameraConfiguration ? this._alternateSceneUbo : this._sceneUbo;
  26565. };
  26566. /**
  26567. * Gets an unique (relatively to the current scene) Id
  26568. * @returns an unique number for the scene
  26569. */
  26570. Scene.prototype.getUniqueId = function () {
  26571. var result = Scene._uniqueIdCounter;
  26572. Scene._uniqueIdCounter++;
  26573. return result;
  26574. };
  26575. /**
  26576. * Add a mesh to the list of scene's meshes
  26577. * @param newMesh defines the mesh to add
  26578. * @param recursive if all child meshes should also be added to the scene
  26579. */
  26580. Scene.prototype.addMesh = function (newMesh, recursive) {
  26581. var _this = this;
  26582. if (recursive === void 0) { recursive = false; }
  26583. this.meshes.push(newMesh);
  26584. //notify the collision coordinator
  26585. if (this.collisionCoordinator) {
  26586. this.collisionCoordinator.onMeshAdded(newMesh);
  26587. }
  26588. newMesh._resyncLightSources();
  26589. this.onNewMeshAddedObservable.notifyObservers(newMesh);
  26590. if (recursive) {
  26591. newMesh.getChildMeshes().forEach(function (m) {
  26592. _this.addMesh(m);
  26593. });
  26594. }
  26595. };
  26596. /**
  26597. * Remove a mesh for the list of scene's meshes
  26598. * @param toRemove defines the mesh to remove
  26599. * @param recursive if all child meshes should also be removed from the scene
  26600. * @returns the index where the mesh was in the mesh list
  26601. */
  26602. Scene.prototype.removeMesh = function (toRemove, recursive) {
  26603. var _this = this;
  26604. if (recursive === void 0) { recursive = false; }
  26605. var index = this.meshes.indexOf(toRemove);
  26606. if (index !== -1) {
  26607. // Remove from the scene if mesh found
  26608. this.meshes.splice(index, 1);
  26609. }
  26610. this.onMeshRemovedObservable.notifyObservers(toRemove);
  26611. if (recursive) {
  26612. toRemove.getChildMeshes().forEach(function (m) {
  26613. _this.removeMesh(m);
  26614. });
  26615. }
  26616. return index;
  26617. };
  26618. /**
  26619. * Add a transform node to the list of scene's transform nodes
  26620. * @param newTransformNode defines the transform node to add
  26621. */
  26622. Scene.prototype.addTransformNode = function (newTransformNode) {
  26623. this.transformNodes.push(newTransformNode);
  26624. this.onNewTransformNodeAddedObservable.notifyObservers(newTransformNode);
  26625. };
  26626. /**
  26627. * Remove a transform node for the list of scene's transform nodes
  26628. * @param toRemove defines the transform node to remove
  26629. * @returns the index where the transform node was in the transform node list
  26630. */
  26631. Scene.prototype.removeTransformNode = function (toRemove) {
  26632. var index = this.transformNodes.indexOf(toRemove);
  26633. if (index !== -1) {
  26634. // Remove from the scene if found
  26635. this.transformNodes.splice(index, 1);
  26636. }
  26637. this.onTransformNodeRemovedObservable.notifyObservers(toRemove);
  26638. return index;
  26639. };
  26640. /**
  26641. * Remove a skeleton for the list of scene's skeletons
  26642. * @param toRemove defines the skeleton to remove
  26643. * @returns the index where the skeleton was in the skeleton list
  26644. */
  26645. Scene.prototype.removeSkeleton = function (toRemove) {
  26646. var index = this.skeletons.indexOf(toRemove);
  26647. if (index !== -1) {
  26648. // Remove from the scene if found
  26649. this.skeletons.splice(index, 1);
  26650. }
  26651. return index;
  26652. };
  26653. /**
  26654. * Remove a morph target for the list of scene's morph targets
  26655. * @param toRemove defines the morph target to remove
  26656. * @returns the index where the morph target was in the morph target list
  26657. */
  26658. Scene.prototype.removeMorphTargetManager = function (toRemove) {
  26659. var index = this.morphTargetManagers.indexOf(toRemove);
  26660. if (index !== -1) {
  26661. // Remove from the scene if found
  26662. this.morphTargetManagers.splice(index, 1);
  26663. }
  26664. return index;
  26665. };
  26666. /**
  26667. * Remove a light for the list of scene's lights
  26668. * @param toRemove defines the light to remove
  26669. * @returns the index where the light was in the light list
  26670. */
  26671. Scene.prototype.removeLight = function (toRemove) {
  26672. var index = this.lights.indexOf(toRemove);
  26673. if (index !== -1) {
  26674. // Remove from meshes
  26675. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26676. var mesh = _a[_i];
  26677. mesh._removeLightSource(toRemove);
  26678. }
  26679. // Remove from the scene if mesh found
  26680. this.lights.splice(index, 1);
  26681. this.sortLightsByPriority();
  26682. }
  26683. this.onLightRemovedObservable.notifyObservers(toRemove);
  26684. return index;
  26685. };
  26686. /**
  26687. * Remove a camera for the list of scene's cameras
  26688. * @param toRemove defines the camera to remove
  26689. * @returns the index where the camera was in the camera list
  26690. */
  26691. Scene.prototype.removeCamera = function (toRemove) {
  26692. var index = this.cameras.indexOf(toRemove);
  26693. if (index !== -1) {
  26694. // Remove from the scene if mesh found
  26695. this.cameras.splice(index, 1);
  26696. }
  26697. // Remove from activeCameras
  26698. var index2 = this.activeCameras.indexOf(toRemove);
  26699. if (index2 !== -1) {
  26700. // Remove from the scene if mesh found
  26701. this.activeCameras.splice(index2, 1);
  26702. }
  26703. // Reset the activeCamera
  26704. if (this.activeCamera === toRemove) {
  26705. if (this.cameras.length > 0) {
  26706. this.activeCamera = this.cameras[0];
  26707. }
  26708. else {
  26709. this.activeCamera = null;
  26710. }
  26711. }
  26712. this.onCameraRemovedObservable.notifyObservers(toRemove);
  26713. return index;
  26714. };
  26715. /**
  26716. * Remove a particle system for the list of scene's particle systems
  26717. * @param toRemove defines the particle system to remove
  26718. * @returns the index where the particle system was in the particle system list
  26719. */
  26720. Scene.prototype.removeParticleSystem = function (toRemove) {
  26721. var index = this.particleSystems.indexOf(toRemove);
  26722. if (index !== -1) {
  26723. this.particleSystems.splice(index, 1);
  26724. }
  26725. return index;
  26726. };
  26727. /**
  26728. * Remove a animation for the list of scene's animations
  26729. * @param toRemove defines the animation to remove
  26730. * @returns the index where the animation was in the animation list
  26731. */
  26732. Scene.prototype.removeAnimation = function (toRemove) {
  26733. var index = this.animations.indexOf(toRemove);
  26734. if (index !== -1) {
  26735. this.animations.splice(index, 1);
  26736. }
  26737. return index;
  26738. };
  26739. /**
  26740. * Removes the given animation group from this scene.
  26741. * @param toRemove The animation group to remove
  26742. * @returns The index of the removed animation group
  26743. */
  26744. Scene.prototype.removeAnimationGroup = function (toRemove) {
  26745. var index = this.animationGroups.indexOf(toRemove);
  26746. if (index !== -1) {
  26747. this.animationGroups.splice(index, 1);
  26748. }
  26749. return index;
  26750. };
  26751. /**
  26752. * Removes the given multi-material from this scene.
  26753. * @param toRemove The multi-material to remove
  26754. * @returns The index of the removed multi-material
  26755. */
  26756. Scene.prototype.removeMultiMaterial = function (toRemove) {
  26757. var index = this.multiMaterials.indexOf(toRemove);
  26758. if (index !== -1) {
  26759. this.multiMaterials.splice(index, 1);
  26760. }
  26761. return index;
  26762. };
  26763. /**
  26764. * Removes the given material from this scene.
  26765. * @param toRemove The material to remove
  26766. * @returns The index of the removed material
  26767. */
  26768. Scene.prototype.removeMaterial = function (toRemove) {
  26769. var index = this.materials.indexOf(toRemove);
  26770. if (index !== -1) {
  26771. this.materials.splice(index, 1);
  26772. }
  26773. return index;
  26774. };
  26775. /**
  26776. * Removes the given lens flare system from this scene.
  26777. * @param toRemove The lens flare system to remove
  26778. * @returns The index of the removed lens flare system
  26779. */
  26780. Scene.prototype.removeLensFlareSystem = function (toRemove) {
  26781. var index = this.lensFlareSystems.indexOf(toRemove);
  26782. if (index !== -1) {
  26783. this.lensFlareSystems.splice(index, 1);
  26784. }
  26785. return index;
  26786. };
  26787. /**
  26788. * Removes the given action manager from this scene.
  26789. * @param toRemove The action manager to remove
  26790. * @returns The index of the removed action manager
  26791. */
  26792. Scene.prototype.removeActionManager = function (toRemove) {
  26793. var index = this._actionManagers.indexOf(toRemove);
  26794. if (index !== -1) {
  26795. this._actionManagers.splice(index, 1);
  26796. }
  26797. return index;
  26798. };
  26799. /**
  26800. * Removes the given effect layer from this scene.
  26801. * @param toRemove defines the effect layer to remove
  26802. * @returns the index of the removed effect layer
  26803. */
  26804. Scene.prototype.removeEffectLayer = function (toRemove) {
  26805. var index = this.effectLayers.indexOf(toRemove);
  26806. if (index !== -1) {
  26807. this.effectLayers.splice(index, 1);
  26808. }
  26809. return index;
  26810. };
  26811. /**
  26812. * Removes the given texture from this scene.
  26813. * @param toRemove The texture to remove
  26814. * @returns The index of the removed texture
  26815. */
  26816. Scene.prototype.removeTexture = function (toRemove) {
  26817. var index = this.textures.indexOf(toRemove);
  26818. if (index !== -1) {
  26819. this.textures.splice(index, 1);
  26820. }
  26821. return index;
  26822. };
  26823. /**
  26824. * Adds the given light to this scene
  26825. * @param newLight The light to add
  26826. */
  26827. Scene.prototype.addLight = function (newLight) {
  26828. this.lights.push(newLight);
  26829. this.sortLightsByPriority();
  26830. // Add light to all meshes (To support if the light is removed and then readded)
  26831. for (var _i = 0, _a = this.meshes; _i < _a.length; _i++) {
  26832. var mesh = _a[_i];
  26833. if (mesh._lightSources.indexOf(newLight) === -1) {
  26834. mesh._lightSources.push(newLight);
  26835. mesh._resyncLightSources();
  26836. }
  26837. }
  26838. this.onNewLightAddedObservable.notifyObservers(newLight);
  26839. };
  26840. /**
  26841. * Sorts the list list based on light priorities
  26842. */
  26843. Scene.prototype.sortLightsByPriority = function () {
  26844. if (this.requireLightSorting) {
  26845. this.lights.sort(BABYLON.Light.CompareLightsPriority);
  26846. }
  26847. };
  26848. /**
  26849. * Adds the given camera to this scene
  26850. * @param newCamera The camera to add
  26851. */
  26852. Scene.prototype.addCamera = function (newCamera) {
  26853. this.cameras.push(newCamera);
  26854. this.onNewCameraAddedObservable.notifyObservers(newCamera);
  26855. };
  26856. /**
  26857. * Adds the given skeleton to this scene
  26858. * @param newSkeleton The skeleton to add
  26859. */
  26860. Scene.prototype.addSkeleton = function (newSkeleton) {
  26861. this.skeletons.push(newSkeleton);
  26862. };
  26863. /**
  26864. * Adds the given particle system to this scene
  26865. * @param newParticleSystem The particle system to add
  26866. */
  26867. Scene.prototype.addParticleSystem = function (newParticleSystem) {
  26868. this.particleSystems.push(newParticleSystem);
  26869. };
  26870. /**
  26871. * Adds the given animation to this scene
  26872. * @param newAnimation The animation to add
  26873. */
  26874. Scene.prototype.addAnimation = function (newAnimation) {
  26875. this.animations.push(newAnimation);
  26876. };
  26877. /**
  26878. * Adds the given animation group to this scene.
  26879. * @param newAnimationGroup The animation group to add
  26880. */
  26881. Scene.prototype.addAnimationGroup = function (newAnimationGroup) {
  26882. this.animationGroups.push(newAnimationGroup);
  26883. };
  26884. /**
  26885. * Adds the given multi-material to this scene
  26886. * @param newMultiMaterial The multi-material to add
  26887. */
  26888. Scene.prototype.addMultiMaterial = function (newMultiMaterial) {
  26889. this.multiMaterials.push(newMultiMaterial);
  26890. };
  26891. /**
  26892. * Adds the given material to this scene
  26893. * @param newMaterial The material to add
  26894. */
  26895. Scene.prototype.addMaterial = function (newMaterial) {
  26896. this.materials.push(newMaterial);
  26897. };
  26898. /**
  26899. * Adds the given morph target to this scene
  26900. * @param newMorphTargetManager The morph target to add
  26901. */
  26902. Scene.prototype.addMorphTargetManager = function (newMorphTargetManager) {
  26903. this.morphTargetManagers.push(newMorphTargetManager);
  26904. };
  26905. /**
  26906. * Adds the given geometry to this scene
  26907. * @param newGeometry The geometry to add
  26908. */
  26909. Scene.prototype.addGeometry = function (newGeometry) {
  26910. this._geometries.push(newGeometry);
  26911. };
  26912. /**
  26913. * Adds the given lens flare system to this scene
  26914. * @param newLensFlareSystem The lens flare system to add
  26915. */
  26916. Scene.prototype.addLensFlareSystem = function (newLensFlareSystem) {
  26917. this.lensFlareSystems.push(newLensFlareSystem);
  26918. };
  26919. /**
  26920. * Adds the given effect layer to this scene
  26921. * @param newEffectLayer defines the effect layer to add
  26922. */
  26923. Scene.prototype.addEffectLayer = function (newEffectLayer) {
  26924. this.effectLayers.push(newEffectLayer);
  26925. };
  26926. /**
  26927. * Adds the given action manager to this scene
  26928. * @param newActionManager The action manager to add
  26929. */
  26930. Scene.prototype.addActionManager = function (newActionManager) {
  26931. this._actionManagers.push(newActionManager);
  26932. };
  26933. /**
  26934. * Adds the given texture to this scene.
  26935. * @param newTexture The texture to add
  26936. */
  26937. Scene.prototype.addTexture = function (newTexture) {
  26938. this.textures.push(newTexture);
  26939. };
  26940. /**
  26941. * Switch active camera
  26942. * @param newCamera defines the new active camera
  26943. * @param attachControl defines if attachControl must be called for the new active camera (default: true)
  26944. */
  26945. Scene.prototype.switchActiveCamera = function (newCamera, attachControl) {
  26946. if (attachControl === void 0) { attachControl = true; }
  26947. var canvas = this._engine.getRenderingCanvas();
  26948. if (!canvas) {
  26949. return;
  26950. }
  26951. if (this.activeCamera) {
  26952. this.activeCamera.detachControl(canvas);
  26953. }
  26954. this.activeCamera = newCamera;
  26955. if (attachControl) {
  26956. newCamera.attachControl(canvas);
  26957. }
  26958. };
  26959. /**
  26960. * sets the active camera of the scene using its ID
  26961. * @param id defines the camera's ID
  26962. * @return the new active camera or null if none found.
  26963. */
  26964. Scene.prototype.setActiveCameraByID = function (id) {
  26965. var camera = this.getCameraByID(id);
  26966. if (camera) {
  26967. this.activeCamera = camera;
  26968. return camera;
  26969. }
  26970. return null;
  26971. };
  26972. /**
  26973. * sets the active camera of the scene using its name
  26974. * @param name defines the camera's name
  26975. * @returns the new active camera or null if none found.
  26976. */
  26977. Scene.prototype.setActiveCameraByName = function (name) {
  26978. var camera = this.getCameraByName(name);
  26979. if (camera) {
  26980. this.activeCamera = camera;
  26981. return camera;
  26982. }
  26983. return null;
  26984. };
  26985. /**
  26986. * get an animation group using its name
  26987. * @param name defines the material's name
  26988. * @return the animation group or null if none found.
  26989. */
  26990. Scene.prototype.getAnimationGroupByName = function (name) {
  26991. for (var index = 0; index < this.animationGroups.length; index++) {
  26992. if (this.animationGroups[index].name === name) {
  26993. return this.animationGroups[index];
  26994. }
  26995. }
  26996. return null;
  26997. };
  26998. /**
  26999. * get a material using its id
  27000. * @param id defines the material's ID
  27001. * @return the material or null if none found.
  27002. */
  27003. Scene.prototype.getMaterialByID = function (id) {
  27004. for (var index = 0; index < this.materials.length; index++) {
  27005. if (this.materials[index].id === id) {
  27006. return this.materials[index];
  27007. }
  27008. }
  27009. return null;
  27010. };
  27011. /**
  27012. * Gets a material using its name
  27013. * @param name defines the material's name
  27014. * @return the material or null if none found.
  27015. */
  27016. Scene.prototype.getMaterialByName = function (name) {
  27017. for (var index = 0; index < this.materials.length; index++) {
  27018. if (this.materials[index].name === name) {
  27019. return this.materials[index];
  27020. }
  27021. }
  27022. return null;
  27023. };
  27024. /**
  27025. * Gets a lens flare system using its name
  27026. * @param name defines the name to look for
  27027. * @returns the lens flare system or null if not found
  27028. */
  27029. Scene.prototype.getLensFlareSystemByName = function (name) {
  27030. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  27031. if (this.lensFlareSystems[index].name === name) {
  27032. return this.lensFlareSystems[index];
  27033. }
  27034. }
  27035. return null;
  27036. };
  27037. /**
  27038. * Gets a lens flare system using its id
  27039. * @param id defines the id to look for
  27040. * @returns the lens flare system or null if not found
  27041. */
  27042. Scene.prototype.getLensFlareSystemByID = function (id) {
  27043. for (var index = 0; index < this.lensFlareSystems.length; index++) {
  27044. if (this.lensFlareSystems[index].id === id) {
  27045. return this.lensFlareSystems[index];
  27046. }
  27047. }
  27048. return null;
  27049. };
  27050. /**
  27051. * Gets a camera using its id
  27052. * @param id defines the id to look for
  27053. * @returns the camera or null if not found
  27054. */
  27055. Scene.prototype.getCameraByID = function (id) {
  27056. for (var index = 0; index < this.cameras.length; index++) {
  27057. if (this.cameras[index].id === id) {
  27058. return this.cameras[index];
  27059. }
  27060. }
  27061. return null;
  27062. };
  27063. /**
  27064. * Gets a camera using its unique id
  27065. * @param uniqueId defines the unique id to look for
  27066. * @returns the camera or null if not found
  27067. */
  27068. Scene.prototype.getCameraByUniqueID = function (uniqueId) {
  27069. for (var index = 0; index < this.cameras.length; index++) {
  27070. if (this.cameras[index].uniqueId === uniqueId) {
  27071. return this.cameras[index];
  27072. }
  27073. }
  27074. return null;
  27075. };
  27076. /**
  27077. * Gets a camera using its name
  27078. * @param name defines the camera's name
  27079. * @return the camera or null if none found.
  27080. */
  27081. Scene.prototype.getCameraByName = function (name) {
  27082. for (var index = 0; index < this.cameras.length; index++) {
  27083. if (this.cameras[index].name === name) {
  27084. return this.cameras[index];
  27085. }
  27086. }
  27087. return null;
  27088. };
  27089. /**
  27090. * Gets a bone using its id
  27091. * @param id defines the bone's id
  27092. * @return the bone or null if not found
  27093. */
  27094. Scene.prototype.getBoneByID = function (id) {
  27095. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27096. var skeleton = this.skeletons[skeletonIndex];
  27097. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27098. if (skeleton.bones[boneIndex].id === id) {
  27099. return skeleton.bones[boneIndex];
  27100. }
  27101. }
  27102. }
  27103. return null;
  27104. };
  27105. /**
  27106. * Gets a bone using its id
  27107. * @param name defines the bone's name
  27108. * @return the bone or null if not found
  27109. */
  27110. Scene.prototype.getBoneByName = function (name) {
  27111. for (var skeletonIndex = 0; skeletonIndex < this.skeletons.length; skeletonIndex++) {
  27112. var skeleton = this.skeletons[skeletonIndex];
  27113. for (var boneIndex = 0; boneIndex < skeleton.bones.length; boneIndex++) {
  27114. if (skeleton.bones[boneIndex].name === name) {
  27115. return skeleton.bones[boneIndex];
  27116. }
  27117. }
  27118. }
  27119. return null;
  27120. };
  27121. /**
  27122. * Gets a light node using its name
  27123. * @param name defines the the light's name
  27124. * @return the light or null if none found.
  27125. */
  27126. Scene.prototype.getLightByName = function (name) {
  27127. for (var index = 0; index < this.lights.length; index++) {
  27128. if (this.lights[index].name === name) {
  27129. return this.lights[index];
  27130. }
  27131. }
  27132. return null;
  27133. };
  27134. /**
  27135. * Gets a light node using its id
  27136. * @param id defines the light's id
  27137. * @return the light or null if none found.
  27138. */
  27139. Scene.prototype.getLightByID = function (id) {
  27140. for (var index = 0; index < this.lights.length; index++) {
  27141. if (this.lights[index].id === id) {
  27142. return this.lights[index];
  27143. }
  27144. }
  27145. return null;
  27146. };
  27147. /**
  27148. * Gets a light node using its scene-generated unique ID
  27149. * @param uniqueId defines the light's unique id
  27150. * @return the light or null if none found.
  27151. */
  27152. Scene.prototype.getLightByUniqueID = function (uniqueId) {
  27153. for (var index = 0; index < this.lights.length; index++) {
  27154. if (this.lights[index].uniqueId === uniqueId) {
  27155. return this.lights[index];
  27156. }
  27157. }
  27158. return null;
  27159. };
  27160. /**
  27161. * Gets a particle system by id
  27162. * @param id defines the particle system id
  27163. * @return the corresponding system or null if none found
  27164. */
  27165. Scene.prototype.getParticleSystemByID = function (id) {
  27166. for (var index = 0; index < this.particleSystems.length; index++) {
  27167. if (this.particleSystems[index].id === id) {
  27168. return this.particleSystems[index];
  27169. }
  27170. }
  27171. return null;
  27172. };
  27173. /**
  27174. * Gets a geometry using its ID
  27175. * @param id defines the geometry's id
  27176. * @return the geometry or null if none found.
  27177. */
  27178. Scene.prototype.getGeometryByID = function (id) {
  27179. for (var index = 0; index < this._geometries.length; index++) {
  27180. if (this._geometries[index].id === id) {
  27181. return this._geometries[index];
  27182. }
  27183. }
  27184. return null;
  27185. };
  27186. /**
  27187. * Add a new geometry to this scene
  27188. * @param geometry defines the geometry to be added to the scene.
  27189. * @param force defines if the geometry must be pushed even if a geometry with this id already exists
  27190. * @return a boolean defining if the geometry was added or not
  27191. */
  27192. Scene.prototype.pushGeometry = function (geometry, force) {
  27193. if (!force && this.getGeometryByID(geometry.id)) {
  27194. return false;
  27195. }
  27196. this._geometries.push(geometry);
  27197. //notify the collision coordinator
  27198. if (this.collisionCoordinator) {
  27199. this.collisionCoordinator.onGeometryAdded(geometry);
  27200. }
  27201. this.onNewGeometryAddedObservable.notifyObservers(geometry);
  27202. return true;
  27203. };
  27204. /**
  27205. * Removes an existing geometry
  27206. * @param geometry defines the geometry to be removed from the scene
  27207. * @return a boolean defining if the geometry was removed or not
  27208. */
  27209. Scene.prototype.removeGeometry = function (geometry) {
  27210. var index = this._geometries.indexOf(geometry);
  27211. if (index > -1) {
  27212. this._geometries.splice(index, 1);
  27213. //notify the collision coordinator
  27214. if (this.collisionCoordinator) {
  27215. this.collisionCoordinator.onGeometryDeleted(geometry);
  27216. }
  27217. this.onGeometryRemovedObservable.notifyObservers(geometry);
  27218. return true;
  27219. }
  27220. return false;
  27221. };
  27222. /**
  27223. * Gets the list of geometries attached to the scene
  27224. * @returns an array of Geometry
  27225. */
  27226. Scene.prototype.getGeometries = function () {
  27227. return this._geometries;
  27228. };
  27229. /**
  27230. * Gets the first added mesh found of a given ID
  27231. * @param id defines the id to search for
  27232. * @return the mesh found or null if not found at all
  27233. */
  27234. Scene.prototype.getMeshByID = function (id) {
  27235. for (var index = 0; index < this.meshes.length; index++) {
  27236. if (this.meshes[index].id === id) {
  27237. return this.meshes[index];
  27238. }
  27239. }
  27240. return null;
  27241. };
  27242. /**
  27243. * Gets a list of meshes using their id
  27244. * @param id defines the id to search for
  27245. * @returns a list of meshes
  27246. */
  27247. Scene.prototype.getMeshesByID = function (id) {
  27248. return this.meshes.filter(function (m) {
  27249. return m.id === id;
  27250. });
  27251. };
  27252. /**
  27253. * Gets the first added transform node found of a given ID
  27254. * @param id defines the id to search for
  27255. * @return the found transform node or null if not found at all.
  27256. */
  27257. Scene.prototype.getTransformNodeByID = function (id) {
  27258. for (var index = 0; index < this.transformNodes.length; index++) {
  27259. if (this.transformNodes[index].id === id) {
  27260. return this.transformNodes[index];
  27261. }
  27262. }
  27263. return null;
  27264. };
  27265. /**
  27266. * Gets a list of transform nodes using their id
  27267. * @param id defines the id to search for
  27268. * @returns a list of transform nodes
  27269. */
  27270. Scene.prototype.getTransformNodesByID = function (id) {
  27271. return this.transformNodes.filter(function (m) {
  27272. return m.id === id;
  27273. });
  27274. };
  27275. /**
  27276. * Gets a mesh with its auto-generated unique id
  27277. * @param uniqueId defines the unique id to search for
  27278. * @return the found mesh or null if not found at all.
  27279. */
  27280. Scene.prototype.getMeshByUniqueID = function (uniqueId) {
  27281. for (var index = 0; index < this.meshes.length; index++) {
  27282. if (this.meshes[index].uniqueId === uniqueId) {
  27283. return this.meshes[index];
  27284. }
  27285. }
  27286. return null;
  27287. };
  27288. /**
  27289. * Gets a the last added mesh using a given id
  27290. * @param id defines the id to search for
  27291. * @return the found mesh or null if not found at all.
  27292. */
  27293. Scene.prototype.getLastMeshByID = function (id) {
  27294. for (var index = this.meshes.length - 1; index >= 0; index--) {
  27295. if (this.meshes[index].id === id) {
  27296. return this.meshes[index];
  27297. }
  27298. }
  27299. return null;
  27300. };
  27301. /**
  27302. * Gets a the last added node (Mesh, Camera, Light) using a given id
  27303. * @param id defines the id to search for
  27304. * @return the found node or null if not found at all
  27305. */
  27306. Scene.prototype.getLastEntryByID = function (id) {
  27307. var index;
  27308. for (index = this.meshes.length - 1; index >= 0; index--) {
  27309. if (this.meshes[index].id === id) {
  27310. return this.meshes[index];
  27311. }
  27312. }
  27313. for (index = this.transformNodes.length - 1; index >= 0; index--) {
  27314. if (this.transformNodes[index].id === id) {
  27315. return this.transformNodes[index];
  27316. }
  27317. }
  27318. for (index = this.cameras.length - 1; index >= 0; index--) {
  27319. if (this.cameras[index].id === id) {
  27320. return this.cameras[index];
  27321. }
  27322. }
  27323. for (index = this.lights.length - 1; index >= 0; index--) {
  27324. if (this.lights[index].id === id) {
  27325. return this.lights[index];
  27326. }
  27327. }
  27328. return null;
  27329. };
  27330. /**
  27331. * Gets a node (Mesh, Camera, Light) using a given id
  27332. * @param id defines the id to search for
  27333. * @return the found node or null if not found at all
  27334. */
  27335. Scene.prototype.getNodeByID = function (id) {
  27336. var mesh = this.getMeshByID(id);
  27337. if (mesh) {
  27338. return mesh;
  27339. }
  27340. var light = this.getLightByID(id);
  27341. if (light) {
  27342. return light;
  27343. }
  27344. var camera = this.getCameraByID(id);
  27345. if (camera) {
  27346. return camera;
  27347. }
  27348. var bone = this.getBoneByID(id);
  27349. return bone;
  27350. };
  27351. /**
  27352. * Gets a node (Mesh, Camera, Light) using a given name
  27353. * @param name defines the name to search for
  27354. * @return the found node or null if not found at all.
  27355. */
  27356. Scene.prototype.getNodeByName = function (name) {
  27357. var mesh = this.getMeshByName(name);
  27358. if (mesh) {
  27359. return mesh;
  27360. }
  27361. var light = this.getLightByName(name);
  27362. if (light) {
  27363. return light;
  27364. }
  27365. var camera = this.getCameraByName(name);
  27366. if (camera) {
  27367. return camera;
  27368. }
  27369. var bone = this.getBoneByName(name);
  27370. return bone;
  27371. };
  27372. /**
  27373. * Gets a mesh using a given name
  27374. * @param name defines the name to search for
  27375. * @return the found mesh or null if not found at all.
  27376. */
  27377. Scene.prototype.getMeshByName = function (name) {
  27378. for (var index = 0; index < this.meshes.length; index++) {
  27379. if (this.meshes[index].name === name) {
  27380. return this.meshes[index];
  27381. }
  27382. }
  27383. return null;
  27384. };
  27385. /**
  27386. * Gets a transform node using a given name
  27387. * @param name defines the name to search for
  27388. * @return the found transform node or null if not found at all.
  27389. */
  27390. Scene.prototype.getTransformNodeByName = function (name) {
  27391. for (var index = 0; index < this.transformNodes.length; index++) {
  27392. if (this.transformNodes[index].name === name) {
  27393. return this.transformNodes[index];
  27394. }
  27395. }
  27396. return null;
  27397. };
  27398. /**
  27399. * Gets a sound using a given name
  27400. * @param name defines the name to search for
  27401. * @return the found sound or null if not found at all.
  27402. */
  27403. Scene.prototype.getSoundByName = function (name) {
  27404. var index;
  27405. if (BABYLON.AudioEngine) {
  27406. for (index = 0; index < this.mainSoundTrack.soundCollection.length; index++) {
  27407. if (this.mainSoundTrack.soundCollection[index].name === name) {
  27408. return this.mainSoundTrack.soundCollection[index];
  27409. }
  27410. }
  27411. for (var sdIndex = 0; sdIndex < this.soundTracks.length; sdIndex++) {
  27412. for (index = 0; index < this.soundTracks[sdIndex].soundCollection.length; index++) {
  27413. if (this.soundTracks[sdIndex].soundCollection[index].name === name) {
  27414. return this.soundTracks[sdIndex].soundCollection[index];
  27415. }
  27416. }
  27417. }
  27418. }
  27419. return null;
  27420. };
  27421. /**
  27422. * Gets a skeleton using a given id (if many are found, this function will pick the last one)
  27423. * @param id defines the id to search for
  27424. * @return the found skeleton or null if not found at all.
  27425. */
  27426. Scene.prototype.getLastSkeletonByID = function (id) {
  27427. for (var index = this.skeletons.length - 1; index >= 0; index--) {
  27428. if (this.skeletons[index].id === id) {
  27429. return this.skeletons[index];
  27430. }
  27431. }
  27432. return null;
  27433. };
  27434. /**
  27435. * Gets a skeleton using a given id (if many are found, this function will pick the first one)
  27436. * @param id defines the id to search for
  27437. * @return the found skeleton or null if not found at all.
  27438. */
  27439. Scene.prototype.getSkeletonById = function (id) {
  27440. for (var index = 0; index < this.skeletons.length; index++) {
  27441. if (this.skeletons[index].id === id) {
  27442. return this.skeletons[index];
  27443. }
  27444. }
  27445. return null;
  27446. };
  27447. /**
  27448. * Gets a skeleton using a given name
  27449. * @param name defines the name to search for
  27450. * @return the found skeleton or null if not found at all.
  27451. */
  27452. Scene.prototype.getSkeletonByName = function (name) {
  27453. for (var index = 0; index < this.skeletons.length; index++) {
  27454. if (this.skeletons[index].name === name) {
  27455. return this.skeletons[index];
  27456. }
  27457. }
  27458. return null;
  27459. };
  27460. /**
  27461. * Gets a morph target manager using a given id (if many are found, this function will pick the last one)
  27462. * @param id defines the id to search for
  27463. * @return the found morph target manager or null if not found at all.
  27464. */
  27465. Scene.prototype.getMorphTargetManagerById = function (id) {
  27466. for (var index = 0; index < this.morphTargetManagers.length; index++) {
  27467. if (this.morphTargetManagers[index].uniqueId === id) {
  27468. return this.morphTargetManagers[index];
  27469. }
  27470. }
  27471. return null;
  27472. };
  27473. /**
  27474. * Gets a boolean indicating if the given mesh is active
  27475. * @param mesh defines the mesh to look for
  27476. * @returns true if the mesh is in the active list
  27477. */
  27478. Scene.prototype.isActiveMesh = function (mesh) {
  27479. return (this._activeMeshes.indexOf(mesh) !== -1);
  27480. };
  27481. /**
  27482. * Return a the first highlight layer of the scene with a given name.
  27483. * @param name The name of the highlight layer to look for.
  27484. * @return The highlight layer if found otherwise null.
  27485. */
  27486. Scene.prototype.getHighlightLayerByName = function (name) {
  27487. for (var index = 0; index < this.effectLayers.length; index++) {
  27488. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.HighlightLayer.EffectName) {
  27489. return this.effectLayers[index];
  27490. }
  27491. }
  27492. return null;
  27493. };
  27494. /**
  27495. * Return a the first highlight layer of the scene with a given name.
  27496. * @param name The name of the highlight layer to look for.
  27497. * @return The highlight layer if found otherwise null.
  27498. */
  27499. Scene.prototype.getGlowLayerByName = function (name) {
  27500. for (var index = 0; index < this.effectLayers.length; index++) {
  27501. if (this.effectLayers[index].name === name && this.effectLayers[index].getEffectName() === BABYLON.GlowLayer.EffectName) {
  27502. return this.effectLayers[index];
  27503. }
  27504. }
  27505. return null;
  27506. };
  27507. Object.defineProperty(Scene.prototype, "uid", {
  27508. /**
  27509. * Return a unique id as a string which can serve as an identifier for the scene
  27510. */
  27511. get: function () {
  27512. if (!this._uid) {
  27513. this._uid = BABYLON.Tools.RandomId();
  27514. }
  27515. return this._uid;
  27516. },
  27517. enumerable: true,
  27518. configurable: true
  27519. });
  27520. /**
  27521. * Add an externaly attached data from its key.
  27522. * This method call will fail and return false, if such key already exists.
  27523. * If you don't care and just want to get the data no matter what, use the more convenient getOrAddExternalDataWithFactory() method.
  27524. * @param key the unique key that identifies the data
  27525. * @param data the data object to associate to the key for this Engine instance
  27526. * @return true if no such key were already present and the data was added successfully, false otherwise
  27527. */
  27528. Scene.prototype.addExternalData = function (key, data) {
  27529. if (!this._externalData) {
  27530. this._externalData = new BABYLON.StringDictionary();
  27531. }
  27532. return this._externalData.add(key, data);
  27533. };
  27534. /**
  27535. * Get an externaly attached data from its key
  27536. * @param key the unique key that identifies the data
  27537. * @return the associated data, if present (can be null), or undefined if not present
  27538. */
  27539. Scene.prototype.getExternalData = function (key) {
  27540. if (!this._externalData) {
  27541. return null;
  27542. }
  27543. return this._externalData.get(key);
  27544. };
  27545. /**
  27546. * Get an externaly attached data from its key, create it using a factory if it's not already present
  27547. * @param key the unique key that identifies the data
  27548. * @param factory the factory that will be called to create the instance if and only if it doesn't exists
  27549. * @return the associated data, can be null if the factory returned null.
  27550. */
  27551. Scene.prototype.getOrAddExternalDataWithFactory = function (key, factory) {
  27552. if (!this._externalData) {
  27553. this._externalData = new BABYLON.StringDictionary();
  27554. }
  27555. return this._externalData.getOrAddWithFactory(key, factory);
  27556. };
  27557. /**
  27558. * Remove an externaly attached data from the Engine instance
  27559. * @param key the unique key that identifies the data
  27560. * @return true if the data was successfully removed, false if it doesn't exist
  27561. */
  27562. Scene.prototype.removeExternalData = function (key) {
  27563. return this._externalData.remove(key);
  27564. };
  27565. Scene.prototype._evaluateSubMesh = function (subMesh, mesh) {
  27566. if (this.dispatchAllSubMeshesOfActiveMeshes || mesh.alwaysSelectAsActiveMesh || mesh.subMeshes.length === 1 || subMesh.isInFrustum(this._frustumPlanes)) {
  27567. if (mesh.showSubMeshesBoundingBox) {
  27568. var boundingInfo = subMesh.getBoundingInfo();
  27569. if (boundingInfo !== null && boundingInfo !== undefined) {
  27570. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27571. }
  27572. }
  27573. var material = subMesh.getMaterial();
  27574. if (material !== null && material !== undefined) {
  27575. // Render targets
  27576. if (material.getRenderTargetTextures !== undefined) {
  27577. if (this._processedMaterials.indexOf(material) === -1) {
  27578. this._processedMaterials.push(material);
  27579. this._renderTargets.concatWithNoDuplicate(material.getRenderTargetTextures());
  27580. }
  27581. }
  27582. // Dispatch
  27583. this._activeIndices.addCount(subMesh.indexCount, false);
  27584. this._renderingManager.dispatch(subMesh, mesh, material);
  27585. }
  27586. }
  27587. };
  27588. /**
  27589. * Clear the processed materials smart array preventing retention point in material dispose.
  27590. */
  27591. Scene.prototype.freeProcessedMaterials = function () {
  27592. this._processedMaterials.dispose();
  27593. };
  27594. /**
  27595. * Clear the active meshes smart array preventing retention point in mesh dispose.
  27596. */
  27597. Scene.prototype.freeActiveMeshes = function () {
  27598. this._activeMeshes.dispose();
  27599. if (this.activeCamera && this.activeCamera._activeMeshes) {
  27600. this.activeCamera._activeMeshes.dispose();
  27601. }
  27602. if (this.activeCameras) {
  27603. for (var i = 0; i < this.activeCameras.length; i++) {
  27604. var activeCamera = this.activeCameras[i];
  27605. if (activeCamera && activeCamera._activeMeshes) {
  27606. activeCamera._activeMeshes.dispose();
  27607. }
  27608. }
  27609. }
  27610. };
  27611. /**
  27612. * Clear the info related to rendering groups preventing retention points during dispose.
  27613. */
  27614. Scene.prototype.freeRenderingGroups = function () {
  27615. if (this._renderingManager) {
  27616. this._renderingManager.freeRenderingGroups();
  27617. }
  27618. if (this.textures) {
  27619. for (var i = 0; i < this.textures.length; i++) {
  27620. var texture = this.textures[i];
  27621. if (texture && texture.renderList) {
  27622. texture.freeRenderingGroups();
  27623. }
  27624. }
  27625. }
  27626. };
  27627. /** @hidden */
  27628. Scene.prototype._isInIntermediateRendering = function () {
  27629. return this._intermediateRendering;
  27630. };
  27631. /**
  27632. * Defines the current active mesh candidate provider
  27633. * @param provider defines the provider to use
  27634. */
  27635. Scene.prototype.setActiveMeshCandidateProvider = function (provider) {
  27636. this._activeMeshCandidateProvider = provider;
  27637. };
  27638. /**
  27639. * Gets the current active mesh candidate provider
  27640. * @returns the current active mesh candidate provider
  27641. */
  27642. Scene.prototype.getActiveMeshCandidateProvider = function () {
  27643. return this._activeMeshCandidateProvider;
  27644. };
  27645. /**
  27646. * Use this function to stop evaluating active meshes. The current list will be keep alive between frames
  27647. * @returns the current scene
  27648. */
  27649. Scene.prototype.freezeActiveMeshes = function () {
  27650. if (!this.activeCamera) {
  27651. return this;
  27652. }
  27653. if (!this._frustumPlanes) {
  27654. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27655. }
  27656. this._evaluateActiveMeshes();
  27657. this._activeMeshesFrozen = true;
  27658. return this;
  27659. };
  27660. /**
  27661. * Use this function to restart evaluating active meshes on every frame
  27662. * @returns the current scene
  27663. */
  27664. Scene.prototype.unfreezeActiveMeshes = function () {
  27665. this._activeMeshesFrozen = false;
  27666. return this;
  27667. };
  27668. Scene.prototype._evaluateActiveMeshes = function () {
  27669. if (this._activeMeshesFrozen && this._activeMeshes.length) {
  27670. return;
  27671. }
  27672. if (!this.activeCamera) {
  27673. return;
  27674. }
  27675. this.onBeforeActiveMeshesEvaluationObservable.notifyObservers(this);
  27676. this.activeCamera._activeMeshes.reset();
  27677. this._activeMeshes.reset();
  27678. this._renderingManager.reset();
  27679. this._processedMaterials.reset();
  27680. this._activeParticleSystems.reset();
  27681. this._activeSkeletons.reset();
  27682. this._softwareSkinnedMeshes.reset();
  27683. if (this._boundingBoxRenderer) {
  27684. this._boundingBoxRenderer.reset();
  27685. }
  27686. // Meshes
  27687. var meshes;
  27688. var len;
  27689. var checkIsEnabled = true;
  27690. // Determine mesh candidates
  27691. if (this._activeMeshCandidateProvider !== undefined) {
  27692. // Use _activeMeshCandidateProvider
  27693. meshes = this._activeMeshCandidateProvider.getMeshes(this);
  27694. checkIsEnabled = this._activeMeshCandidateProvider.checksIsEnabled === false;
  27695. if (meshes !== undefined) {
  27696. len = meshes.length;
  27697. }
  27698. else {
  27699. len = 0;
  27700. }
  27701. }
  27702. else if (this._selectionOctree !== undefined) {
  27703. // Octree
  27704. var selection = this._selectionOctree.select(this._frustumPlanes);
  27705. meshes = selection.data;
  27706. len = selection.length;
  27707. }
  27708. else {
  27709. // Full scene traversal
  27710. len = this.meshes.length;
  27711. meshes = this.meshes;
  27712. }
  27713. // Check each mesh
  27714. for (var meshIndex = 0, mesh, meshLOD; meshIndex < len; meshIndex++) {
  27715. mesh = meshes[meshIndex];
  27716. if (mesh.isBlocked) {
  27717. continue;
  27718. }
  27719. this._totalVertices.addCount(mesh.getTotalVertices(), false);
  27720. if (!mesh.isReady() || (checkIsEnabled && !mesh.isEnabled())) {
  27721. continue;
  27722. }
  27723. mesh.computeWorldMatrix();
  27724. // Intersections
  27725. if (mesh.actionManager && mesh.actionManager.hasSpecificTriggers([BABYLON.ActionManager.OnIntersectionEnterTrigger, BABYLON.ActionManager.OnIntersectionExitTrigger])) {
  27726. this._meshesForIntersections.pushNoDuplicate(mesh);
  27727. }
  27728. // Switch to current LOD
  27729. meshLOD = mesh.getLOD(this.activeCamera);
  27730. if (meshLOD === undefined || meshLOD === null) {
  27731. continue;
  27732. }
  27733. mesh._preActivate();
  27734. if (mesh.alwaysSelectAsActiveMesh || mesh.isVisible && mesh.visibility > 0 && ((mesh.layerMask & this.activeCamera.layerMask) !== 0) && mesh.isInFrustum(this._frustumPlanes)) {
  27735. this._activeMeshes.push(mesh);
  27736. this.activeCamera._activeMeshes.push(mesh);
  27737. mesh._activate(this._renderId);
  27738. if (meshLOD !== mesh) {
  27739. meshLOD._activate(this._renderId);
  27740. }
  27741. this._activeMesh(mesh, meshLOD);
  27742. }
  27743. }
  27744. this.onAfterActiveMeshesEvaluationObservable.notifyObservers(this);
  27745. // Particle systems
  27746. if (this.particlesEnabled) {
  27747. this.onBeforeParticlesRenderingObservable.notifyObservers(this);
  27748. for (var particleIndex = 0; particleIndex < this.particleSystems.length; particleIndex++) {
  27749. var particleSystem = this.particleSystems[particleIndex];
  27750. if (!particleSystem.isStarted() || !particleSystem.emitter) {
  27751. continue;
  27752. }
  27753. var emitter = particleSystem.emitter;
  27754. if (!emitter.position || emitter.isEnabled()) {
  27755. this._activeParticleSystems.push(particleSystem);
  27756. particleSystem.animate();
  27757. this._renderingManager.dispatchParticles(particleSystem);
  27758. }
  27759. }
  27760. this.onAfterParticlesRenderingObservable.notifyObservers(this);
  27761. }
  27762. };
  27763. Scene.prototype._activeMesh = function (sourceMesh, mesh) {
  27764. if (this.skeletonsEnabled && mesh.skeleton !== null && mesh.skeleton !== undefined) {
  27765. if (this._activeSkeletons.pushNoDuplicate(mesh.skeleton)) {
  27766. mesh.skeleton.prepare();
  27767. }
  27768. if (!mesh.computeBonesUsingShaders) {
  27769. this._softwareSkinnedMeshes.pushNoDuplicate(mesh);
  27770. }
  27771. }
  27772. if (sourceMesh.showBoundingBox || this.forceShowBoundingBoxes) {
  27773. var boundingInfo = sourceMesh.getBoundingInfo();
  27774. this.getBoundingBoxRenderer().renderList.push(boundingInfo.boundingBox);
  27775. }
  27776. if (mesh !== undefined && mesh !== null
  27777. && mesh.subMeshes !== undefined && mesh.subMeshes !== null && mesh.subMeshes.length > 0) {
  27778. // Submeshes Octrees
  27779. var len;
  27780. var subMeshes;
  27781. if (mesh.useOctreeForRenderingSelection && mesh._submeshesOctree !== undefined && mesh._submeshesOctree !== null) {
  27782. var intersections = mesh._submeshesOctree.select(this._frustumPlanes);
  27783. len = intersections.length;
  27784. subMeshes = intersections.data;
  27785. }
  27786. else {
  27787. subMeshes = mesh.subMeshes;
  27788. len = subMeshes.length;
  27789. }
  27790. for (var subIndex = 0, subMesh; subIndex < len; subIndex++) {
  27791. subMesh = subMeshes[subIndex];
  27792. this._evaluateSubMesh(subMesh, mesh);
  27793. }
  27794. }
  27795. };
  27796. /**
  27797. * Update the transform matrix to update from the current active camera
  27798. * @param force defines a boolean used to force the update even if cache is up to date
  27799. */
  27800. Scene.prototype.updateTransformMatrix = function (force) {
  27801. if (!this.activeCamera) {
  27802. return;
  27803. }
  27804. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(force));
  27805. };
  27806. /**
  27807. * 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)
  27808. * @param alternateCamera defines the camera to use
  27809. */
  27810. Scene.prototype.updateAlternateTransformMatrix = function (alternateCamera) {
  27811. this._setAlternateTransformMatrix(alternateCamera.getViewMatrix(), alternateCamera.getProjectionMatrix());
  27812. };
  27813. Scene.prototype._renderForCamera = function (camera, rigParent) {
  27814. if (camera && camera._skipRendering) {
  27815. return;
  27816. }
  27817. var engine = this._engine;
  27818. this.activeCamera = camera;
  27819. if (!this.activeCamera)
  27820. throw new Error("Active camera not set");
  27821. // Viewport
  27822. engine.setViewport(this.activeCamera.viewport);
  27823. // Camera
  27824. this.resetCachedMaterial();
  27825. this._renderId++;
  27826. this.updateTransformMatrix();
  27827. if (camera._alternateCamera) {
  27828. this.updateAlternateTransformMatrix(camera._alternateCamera);
  27829. this._alternateRendering = true;
  27830. }
  27831. this.onBeforeCameraRenderObservable.notifyObservers(this.activeCamera);
  27832. // Meshes
  27833. this._evaluateActiveMeshes();
  27834. // Software skinning
  27835. for (var softwareSkinnedMeshIndex = 0; softwareSkinnedMeshIndex < this._softwareSkinnedMeshes.length; softwareSkinnedMeshIndex++) {
  27836. var mesh = this._softwareSkinnedMeshes.data[softwareSkinnedMeshIndex];
  27837. mesh.applySkeleton(mesh.skeleton);
  27838. }
  27839. // Render targets
  27840. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  27841. var needsRestoreFrameBuffer = false;
  27842. if (camera.customRenderTargets && camera.customRenderTargets.length > 0) {
  27843. this._renderTargets.concatWithNoDuplicate(camera.customRenderTargets);
  27844. }
  27845. if (rigParent && rigParent.customRenderTargets && rigParent.customRenderTargets.length > 0) {
  27846. this._renderTargets.concatWithNoDuplicate(rigParent.customRenderTargets);
  27847. }
  27848. if (this.renderTargetsEnabled && this._renderTargets.length > 0) {
  27849. this._intermediateRendering = true;
  27850. BABYLON.Tools.StartPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27851. for (var renderIndex = 0; renderIndex < this._renderTargets.length; renderIndex++) {
  27852. var renderTarget = this._renderTargets.data[renderIndex];
  27853. if (renderTarget._shouldRender()) {
  27854. this._renderId++;
  27855. var hasSpecialRenderTargetCamera = renderTarget.activeCamera && renderTarget.activeCamera !== this.activeCamera;
  27856. renderTarget.render(hasSpecialRenderTargetCamera, this.dumpNextRenderTargets);
  27857. }
  27858. }
  27859. BABYLON.Tools.EndPerformanceCounter("Render targets", this._renderTargets.length > 0);
  27860. this._intermediateRendering = false;
  27861. this._renderId++;
  27862. needsRestoreFrameBuffer = true; // Restore back buffer
  27863. }
  27864. // Render EffectLayer Texture
  27865. var stencilState = this._engine.getStencilBuffer();
  27866. var renderEffects = false;
  27867. var needStencil = false;
  27868. if (this.renderTargetsEnabled && this.effectLayers && this.effectLayers.length > 0) {
  27869. this._intermediateRendering = true;
  27870. for (var i = 0; i < this.effectLayers.length; i++) {
  27871. var effectLayer = this.effectLayers[i];
  27872. if (effectLayer.shouldRender() &&
  27873. (!effectLayer.camera ||
  27874. (effectLayer.camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE && camera === effectLayer.camera) ||
  27875. (effectLayer.camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE && effectLayer.camera._rigCameras.indexOf(camera) > -1))) {
  27876. renderEffects = true;
  27877. needStencil = needStencil || effectLayer.needStencil();
  27878. var renderTarget = effectLayer._mainTexture;
  27879. if (renderTarget._shouldRender()) {
  27880. this._renderId++;
  27881. renderTarget.render(false, false);
  27882. needsRestoreFrameBuffer = true;
  27883. }
  27884. }
  27885. }
  27886. this._intermediateRendering = false;
  27887. this._renderId++;
  27888. }
  27889. if (needsRestoreFrameBuffer) {
  27890. engine.restoreDefaultFramebuffer(); // Restore back buffer
  27891. }
  27892. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  27893. // Prepare Frame
  27894. if (this.postProcessManager) {
  27895. this.postProcessManager._prepareFrame();
  27896. }
  27897. // Backgrounds
  27898. var layerIndex;
  27899. var layer;
  27900. if (this.layers.length) {
  27901. engine.setDepthBuffer(false);
  27902. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27903. layer = this.layers[layerIndex];
  27904. if (layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27905. layer.render();
  27906. }
  27907. }
  27908. engine.setDepthBuffer(true);
  27909. }
  27910. // Activate effect Layer stencil
  27911. if (needStencil) {
  27912. this._engine.setStencilBuffer(true);
  27913. }
  27914. // Render
  27915. this.onBeforeDrawPhaseObservable.notifyObservers(this);
  27916. this._renderingManager.render(null, null, true, true);
  27917. this.onAfterDrawPhaseObservable.notifyObservers(this);
  27918. // Restore effect Layer stencil
  27919. if (needStencil) {
  27920. this._engine.setStencilBuffer(stencilState);
  27921. }
  27922. // Bounding boxes
  27923. if (this._boundingBoxRenderer) {
  27924. this._boundingBoxRenderer.render();
  27925. }
  27926. // Lens flares
  27927. if (this.lensFlaresEnabled) {
  27928. BABYLON.Tools.StartPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27929. for (var lensFlareSystemIndex = 0; lensFlareSystemIndex < this.lensFlareSystems.length; lensFlareSystemIndex++) {
  27930. var lensFlareSystem = this.lensFlareSystems[lensFlareSystemIndex];
  27931. if ((camera.layerMask & lensFlareSystem.layerMask) !== 0) {
  27932. lensFlareSystem.render();
  27933. }
  27934. }
  27935. BABYLON.Tools.EndPerformanceCounter("Lens flares", this.lensFlareSystems.length > 0);
  27936. }
  27937. // Effect Layer
  27938. if (renderEffects) {
  27939. engine.setDepthBuffer(false);
  27940. for (var i = 0; i < this.effectLayers.length; i++) {
  27941. if (this.effectLayers[i].shouldRender()) {
  27942. this.effectLayers[i].render();
  27943. }
  27944. }
  27945. engine.setDepthBuffer(true);
  27946. }
  27947. // Foregrounds
  27948. if (this.layers.length) {
  27949. engine.setDepthBuffer(false);
  27950. for (layerIndex = 0; layerIndex < this.layers.length; layerIndex++) {
  27951. layer = this.layers[layerIndex];
  27952. if (!layer.isBackground && ((layer.layerMask & this.activeCamera.layerMask) !== 0)) {
  27953. layer.render();
  27954. }
  27955. }
  27956. engine.setDepthBuffer(true);
  27957. }
  27958. // Finalize frame
  27959. if (this.postProcessManager) {
  27960. this.postProcessManager._finalizeFrame(camera.isIntermediate);
  27961. }
  27962. // Reset some special arrays
  27963. this._renderTargets.reset();
  27964. this._alternateRendering = false;
  27965. this.onAfterCameraRenderObservable.notifyObservers(this.activeCamera);
  27966. };
  27967. Scene.prototype._processSubCameras = function (camera) {
  27968. if (camera.cameraRigMode === BABYLON.Camera.RIG_MODE_NONE) {
  27969. this._renderForCamera(camera);
  27970. return;
  27971. }
  27972. // rig cameras
  27973. for (var index = 0; index < camera._rigCameras.length; index++) {
  27974. this._renderForCamera(camera._rigCameras[index], camera);
  27975. }
  27976. this.activeCamera = camera;
  27977. this.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix());
  27978. };
  27979. Scene.prototype._checkIntersections = function () {
  27980. for (var index = 0; index < this._meshesForIntersections.length; index++) {
  27981. var sourceMesh = this._meshesForIntersections.data[index];
  27982. if (!sourceMesh.actionManager) {
  27983. continue;
  27984. }
  27985. for (var actionIndex = 0; actionIndex < sourceMesh.actionManager.actions.length; actionIndex++) {
  27986. var action = sourceMesh.actionManager.actions[actionIndex];
  27987. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27988. var parameters = action.getTriggerParameter();
  27989. var otherMesh = parameters instanceof BABYLON.AbstractMesh ? parameters : parameters.mesh;
  27990. var areIntersecting = otherMesh.intersectsMesh(sourceMesh, parameters.usePreciseIntersection);
  27991. var currentIntersectionInProgress = sourceMesh._intersectionsInProgress.indexOf(otherMesh);
  27992. if (areIntersecting && currentIntersectionInProgress === -1) {
  27993. if (action.trigger === BABYLON.ActionManager.OnIntersectionEnterTrigger) {
  27994. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  27995. sourceMesh._intersectionsInProgress.push(otherMesh);
  27996. }
  27997. else if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  27998. sourceMesh._intersectionsInProgress.push(otherMesh);
  27999. }
  28000. }
  28001. else if (!areIntersecting && currentIntersectionInProgress > -1) {
  28002. //They intersected, and now they don't.
  28003. //is this trigger an exit trigger? execute an event.
  28004. if (action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28005. action._executeCurrent(BABYLON.ActionEvent.CreateNew(sourceMesh, undefined, otherMesh));
  28006. }
  28007. //if this is an exit trigger, or no exit trigger exists, remove the id from the intersection in progress array.
  28008. if (!sourceMesh.actionManager.hasSpecificTrigger(BABYLON.ActionManager.OnIntersectionExitTrigger, function (parameter) {
  28009. var parameterMesh = parameter instanceof BABYLON.AbstractMesh ? parameter : parameter.mesh;
  28010. return otherMesh === parameterMesh;
  28011. }) || action.trigger === BABYLON.ActionManager.OnIntersectionExitTrigger) {
  28012. sourceMesh._intersectionsInProgress.splice(currentIntersectionInProgress, 1);
  28013. }
  28014. }
  28015. }
  28016. }
  28017. }
  28018. };
  28019. /**
  28020. * Render the scene
  28021. * @param updateCameras defines a boolean indicating if cameras must update according to their inputs (true by default)
  28022. */
  28023. Scene.prototype.render = function (updateCameras) {
  28024. if (updateCameras === void 0) { updateCameras = true; }
  28025. if (this.isDisposed) {
  28026. return;
  28027. }
  28028. this._activeParticles.fetchNewFrame();
  28029. this._totalVertices.fetchNewFrame();
  28030. this._activeIndices.fetchNewFrame();
  28031. this._activeBones.fetchNewFrame();
  28032. this._meshesForIntersections.reset();
  28033. this.resetCachedMaterial();
  28034. this.onBeforeAnimationsObservable.notifyObservers(this);
  28035. // Actions
  28036. if (this.actionManager) {
  28037. this.actionManager.processTrigger(BABYLON.ActionManager.OnEveryFrameTrigger);
  28038. }
  28039. //Simplification Queue
  28040. if (this.simplificationQueue && !this.simplificationQueue.running) {
  28041. this.simplificationQueue.executeNext();
  28042. }
  28043. if (this._engine.isDeterministicLockStep()) {
  28044. var deltaTime = Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime)) + this._timeAccumulator;
  28045. var defaultFPS = (60.0 / 1000.0);
  28046. var defaultFrameTime = 1000 / 60; // frame time in MS
  28047. if (this._physicsEngine) {
  28048. defaultFrameTime = this._physicsEngine.getTimeStep() * 1000;
  28049. }
  28050. var stepsTaken = 0;
  28051. var maxSubSteps = this._engine.getLockstepMaxSteps();
  28052. var internalSteps = Math.floor(deltaTime / (1000 * defaultFPS));
  28053. internalSteps = Math.min(internalSteps, maxSubSteps);
  28054. do {
  28055. this.onBeforeStepObservable.notifyObservers(this);
  28056. // Animations
  28057. this._animationRatio = defaultFrameTime * defaultFPS;
  28058. this._animate();
  28059. this.onAfterAnimationsObservable.notifyObservers(this);
  28060. // Physics
  28061. if (this._physicsEngine) {
  28062. this.onBeforePhysicsObservable.notifyObservers(this);
  28063. this._physicsEngine._step(defaultFrameTime / 1000);
  28064. this.onAfterPhysicsObservable.notifyObservers(this);
  28065. }
  28066. this.onAfterStepObservable.notifyObservers(this);
  28067. this._currentStepId++;
  28068. stepsTaken++;
  28069. deltaTime -= defaultFrameTime;
  28070. } while (deltaTime > 0 && stepsTaken < internalSteps);
  28071. this._timeAccumulator = deltaTime < 0 ? 0 : deltaTime;
  28072. }
  28073. else {
  28074. // Animations
  28075. var deltaTime = this.useConstantAnimationDeltaTime ? 16 : Math.max(Scene.MinDeltaTime, Math.min(this._engine.getDeltaTime(), Scene.MaxDeltaTime));
  28076. this._animationRatio = deltaTime * (60.0 / 1000.0);
  28077. this._animate();
  28078. this.onAfterAnimationsObservable.notifyObservers(this);
  28079. // Physics
  28080. if (this._physicsEngine) {
  28081. this.onBeforePhysicsObservable.notifyObservers(this);
  28082. this._physicsEngine._step(deltaTime / 1000.0);
  28083. this.onAfterPhysicsObservable.notifyObservers(this);
  28084. }
  28085. }
  28086. // update gamepad manager
  28087. if (this._gamepadManager && this._gamepadManager._isMonitoring) {
  28088. this._gamepadManager._checkGamepadsStatus();
  28089. }
  28090. // Update Cameras
  28091. if (updateCameras) {
  28092. if (this.activeCameras.length > 0) {
  28093. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28094. var camera = this.activeCameras[cameraIndex];
  28095. camera.update();
  28096. if (camera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28097. // rig cameras
  28098. for (var index = 0; index < camera._rigCameras.length; index++) {
  28099. camera._rigCameras[index].update();
  28100. }
  28101. }
  28102. }
  28103. }
  28104. else if (this.activeCamera) {
  28105. this.activeCamera.update();
  28106. if (this.activeCamera.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  28107. // rig cameras
  28108. for (var index = 0; index < this.activeCamera._rigCameras.length; index++) {
  28109. this.activeCamera._rigCameras[index].update();
  28110. }
  28111. }
  28112. }
  28113. }
  28114. // Before render
  28115. this.onBeforeRenderObservable.notifyObservers(this);
  28116. // Customs render targets
  28117. this.onBeforeRenderTargetsRenderObservable.notifyObservers(this);
  28118. var engine = this.getEngine();
  28119. var currentActiveCamera = this.activeCamera;
  28120. if (this.renderTargetsEnabled) {
  28121. BABYLON.Tools.StartPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28122. this._intermediateRendering = true;
  28123. for (var customIndex = 0; customIndex < this.customRenderTargets.length; customIndex++) {
  28124. var renderTarget = this.customRenderTargets[customIndex];
  28125. if (renderTarget._shouldRender()) {
  28126. this._renderId++;
  28127. this.activeCamera = renderTarget.activeCamera || this.activeCamera;
  28128. if (!this.activeCamera)
  28129. throw new Error("Active camera not set");
  28130. // Viewport
  28131. engine.setViewport(this.activeCamera.viewport);
  28132. // Camera
  28133. this.updateTransformMatrix();
  28134. renderTarget.render(currentActiveCamera !== this.activeCamera, this.dumpNextRenderTargets);
  28135. }
  28136. }
  28137. BABYLON.Tools.EndPerformanceCounter("Custom render targets", this.customRenderTargets.length > 0);
  28138. this._intermediateRendering = false;
  28139. this._renderId++;
  28140. }
  28141. // Restore back buffer
  28142. if (this.customRenderTargets.length > 0) {
  28143. engine.restoreDefaultFramebuffer();
  28144. }
  28145. this.onAfterRenderTargetsRenderObservable.notifyObservers(this);
  28146. this.activeCamera = currentActiveCamera;
  28147. // Procedural textures
  28148. if (this.proceduralTexturesEnabled) {
  28149. BABYLON.Tools.StartPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28150. for (var proceduralIndex = 0; proceduralIndex < this.proceduralTextures.length; proceduralIndex++) {
  28151. var proceduralTexture = this.proceduralTextures[proceduralIndex];
  28152. if (proceduralTexture._shouldRender()) {
  28153. proceduralTexture.render();
  28154. }
  28155. }
  28156. BABYLON.Tools.EndPerformanceCounter("Procedural textures", this.proceduralTextures.length > 0);
  28157. }
  28158. // Clear
  28159. if (this.autoClearDepthAndStencil || this.autoClear) {
  28160. this._engine.clear(this.clearColor, this.autoClear || this.forceWireframe || this.forcePointsCloud, this.autoClearDepthAndStencil, this.autoClearDepthAndStencil);
  28161. }
  28162. // Shadows
  28163. if (this.shadowsEnabled) {
  28164. for (var lightIndex = 0; lightIndex < this.lights.length; lightIndex++) {
  28165. var light = this.lights[lightIndex];
  28166. var shadowGenerator = light.getShadowGenerator();
  28167. if (light.isEnabled() && light.shadowEnabled && shadowGenerator) {
  28168. var shadowMap = (shadowGenerator.getShadowMap());
  28169. if (this.textures.indexOf(shadowMap) !== -1) {
  28170. this._renderTargets.push(shadowMap);
  28171. }
  28172. }
  28173. }
  28174. }
  28175. // Depth renderer
  28176. for (var key in this._depthRenderer) {
  28177. this._renderTargets.push(this._depthRenderer[key].getDepthMap());
  28178. }
  28179. // Geometry renderer
  28180. if (this._geometryBufferRenderer) {
  28181. this._renderTargets.push(this._geometryBufferRenderer.getGBuffer());
  28182. }
  28183. // RenderPipeline
  28184. if (this._postProcessRenderPipelineManager) {
  28185. this._postProcessRenderPipelineManager.update();
  28186. }
  28187. // Multi-cameras?
  28188. if (this.activeCameras.length > 0) {
  28189. for (var cameraIndex = 0; cameraIndex < this.activeCameras.length; cameraIndex++) {
  28190. if (cameraIndex > 0) {
  28191. this._engine.clear(null, false, true, true);
  28192. }
  28193. this._processSubCameras(this.activeCameras[cameraIndex]);
  28194. }
  28195. }
  28196. else {
  28197. if (!this.activeCamera) {
  28198. throw new Error("No camera defined");
  28199. }
  28200. this._processSubCameras(this.activeCamera);
  28201. }
  28202. // Intersection checks
  28203. this._checkIntersections();
  28204. // Update the audio listener attached to the camera
  28205. if (BABYLON.AudioEngine) {
  28206. this._updateAudioParameters();
  28207. }
  28208. // After render
  28209. if (this.afterRender) {
  28210. this.afterRender();
  28211. }
  28212. this.onAfterRenderObservable.notifyObservers(this);
  28213. // Cleaning
  28214. for (var index = 0; index < this._toBeDisposed.length; index++) {
  28215. var data = this._toBeDisposed.data[index];
  28216. if (data) {
  28217. data.dispose();
  28218. }
  28219. this._toBeDisposed[index] = null;
  28220. }
  28221. this._toBeDisposed.reset();
  28222. if (this.dumpNextRenderTargets) {
  28223. this.dumpNextRenderTargets = false;
  28224. }
  28225. this._activeBones.addCount(0, true);
  28226. this._activeIndices.addCount(0, true);
  28227. this._activeParticles.addCount(0, true);
  28228. };
  28229. Scene.prototype._updateAudioParameters = function () {
  28230. if (!this.audioEnabled || !this._mainSoundTrack || (this._mainSoundTrack.soundCollection.length === 0 && this.soundTracks.length === 1)) {
  28231. return;
  28232. }
  28233. var listeningCamera;
  28234. var audioEngine = BABYLON.Engine.audioEngine;
  28235. if (this.activeCameras.length > 0) {
  28236. listeningCamera = this.activeCameras[0];
  28237. }
  28238. else {
  28239. listeningCamera = this.activeCamera;
  28240. }
  28241. if (listeningCamera && audioEngine.canUseWebAudio && audioEngine.audioContext) {
  28242. audioEngine.audioContext.listener.setPosition(listeningCamera.position.x, listeningCamera.position.y, listeningCamera.position.z);
  28243. // for VR cameras
  28244. if (listeningCamera.rigCameras && listeningCamera.rigCameras.length > 0) {
  28245. listeningCamera = listeningCamera.rigCameras[0];
  28246. }
  28247. var mat = BABYLON.Matrix.Invert(listeningCamera.getViewMatrix());
  28248. var cameraDirection = BABYLON.Vector3.TransformNormal(new BABYLON.Vector3(0, 0, -1), mat);
  28249. cameraDirection.normalize();
  28250. // To avoid some errors on GearVR
  28251. if (!isNaN(cameraDirection.x) && !isNaN(cameraDirection.y) && !isNaN(cameraDirection.z)) {
  28252. audioEngine.audioContext.listener.setOrientation(cameraDirection.x, cameraDirection.y, cameraDirection.z, 0, 1, 0);
  28253. }
  28254. var i;
  28255. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28256. var sound = this.mainSoundTrack.soundCollection[i];
  28257. if (sound.useCustomAttenuation) {
  28258. sound.updateDistanceFromListener();
  28259. }
  28260. }
  28261. for (i = 0; i < this.soundTracks.length; i++) {
  28262. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28263. sound = this.soundTracks[i].soundCollection[j];
  28264. if (sound.useCustomAttenuation) {
  28265. sound.updateDistanceFromListener();
  28266. }
  28267. }
  28268. }
  28269. }
  28270. };
  28271. Object.defineProperty(Scene.prototype, "audioEnabled", {
  28272. // Audio
  28273. /**
  28274. * Gets or sets if audio support is enabled
  28275. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28276. */
  28277. get: function () {
  28278. return this._audioEnabled;
  28279. },
  28280. set: function (value) {
  28281. this._audioEnabled = value;
  28282. if (BABYLON.AudioEngine) {
  28283. if (this._audioEnabled) {
  28284. this._enableAudio();
  28285. }
  28286. else {
  28287. this._disableAudio();
  28288. }
  28289. }
  28290. },
  28291. enumerable: true,
  28292. configurable: true
  28293. });
  28294. Scene.prototype._disableAudio = function () {
  28295. var i;
  28296. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28297. this.mainSoundTrack.soundCollection[i].pause();
  28298. }
  28299. for (i = 0; i < this.soundTracks.length; i++) {
  28300. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28301. this.soundTracks[i].soundCollection[j].pause();
  28302. }
  28303. }
  28304. };
  28305. Scene.prototype._enableAudio = function () {
  28306. var i;
  28307. for (i = 0; i < this.mainSoundTrack.soundCollection.length; i++) {
  28308. if (this.mainSoundTrack.soundCollection[i].isPaused) {
  28309. this.mainSoundTrack.soundCollection[i].play();
  28310. }
  28311. }
  28312. for (i = 0; i < this.soundTracks.length; i++) {
  28313. for (var j = 0; j < this.soundTracks[i].soundCollection.length; j++) {
  28314. if (this.soundTracks[i].soundCollection[j].isPaused) {
  28315. this.soundTracks[i].soundCollection[j].play();
  28316. }
  28317. }
  28318. }
  28319. };
  28320. Object.defineProperty(Scene.prototype, "headphone", {
  28321. /**
  28322. * Gets or sets if audio will be output to headphones
  28323. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  28324. */
  28325. get: function () {
  28326. return this._headphone;
  28327. },
  28328. set: function (value) {
  28329. this._headphone = value;
  28330. if (BABYLON.AudioEngine) {
  28331. if (this._headphone) {
  28332. this._switchAudioModeForHeadphones();
  28333. }
  28334. else {
  28335. this._switchAudioModeForNormalSpeakers();
  28336. }
  28337. }
  28338. },
  28339. enumerable: true,
  28340. configurable: true
  28341. });
  28342. Scene.prototype._switchAudioModeForHeadphones = function () {
  28343. this.mainSoundTrack.switchPanningModelToHRTF();
  28344. for (var i = 0; i < this.soundTracks.length; i++) {
  28345. this.soundTracks[i].switchPanningModelToHRTF();
  28346. }
  28347. };
  28348. Scene.prototype._switchAudioModeForNormalSpeakers = function () {
  28349. this.mainSoundTrack.switchPanningModelToEqualPower();
  28350. for (var i = 0; i < this.soundTracks.length; i++) {
  28351. this.soundTracks[i].switchPanningModelToEqualPower();
  28352. }
  28353. };
  28354. /**
  28355. * Creates a depth renderer a given camera which contains a depth map which can be used for post processing.
  28356. * @param camera The camera to create the depth renderer on (default: scene's active camera)
  28357. * @returns the created depth renderer
  28358. */
  28359. Scene.prototype.enableDepthRenderer = function (camera) {
  28360. camera = camera || this.activeCamera;
  28361. if (!camera) {
  28362. throw "No camera available to enable depth renderer";
  28363. }
  28364. if (!this._depthRenderer[camera.id]) {
  28365. var textureType = 0;
  28366. if (this._engine.getCaps().textureHalfFloatRender) {
  28367. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  28368. }
  28369. else if (this._engine.getCaps().textureFloatRender) {
  28370. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  28371. }
  28372. else {
  28373. throw "Depth renderer does not support int texture type";
  28374. }
  28375. this._depthRenderer[camera.id] = new BABYLON.DepthRenderer(this, textureType, camera);
  28376. }
  28377. return this._depthRenderer[camera.id];
  28378. };
  28379. /**
  28380. * Disables a depth renderer for a given camera
  28381. * @param camera The camera to disable the depth renderer on (default: scene's active camera)
  28382. */
  28383. Scene.prototype.disableDepthRenderer = function (camera) {
  28384. camera = camera || this.activeCamera;
  28385. if (!camera || !this._depthRenderer[camera.id]) {
  28386. return;
  28387. }
  28388. this._depthRenderer[camera.id].dispose();
  28389. delete this._depthRenderer[camera.id];
  28390. };
  28391. /**
  28392. * Enables a GeometryBufferRender and associates it with the scene
  28393. * @param ratio defines the scaling ratio to apply to the renderer (1 by default which means same resolution)
  28394. * @returns the GeometryBufferRenderer
  28395. */
  28396. Scene.prototype.enableGeometryBufferRenderer = function (ratio) {
  28397. if (ratio === void 0) { ratio = 1; }
  28398. if (this._geometryBufferRenderer) {
  28399. return this._geometryBufferRenderer;
  28400. }
  28401. this._geometryBufferRenderer = new BABYLON.GeometryBufferRenderer(this, ratio);
  28402. if (!this._geometryBufferRenderer.isSupported) {
  28403. this._geometryBufferRenderer = null;
  28404. }
  28405. return this._geometryBufferRenderer;
  28406. };
  28407. /**
  28408. * Disables the GeometryBufferRender associated with the scene
  28409. */
  28410. Scene.prototype.disableGeometryBufferRenderer = function () {
  28411. if (!this._geometryBufferRenderer) {
  28412. return;
  28413. }
  28414. this._geometryBufferRenderer.dispose();
  28415. this._geometryBufferRenderer = null;
  28416. };
  28417. /**
  28418. * Freeze all materials
  28419. * A frozen material will not be updatable but should be faster to render
  28420. */
  28421. Scene.prototype.freezeMaterials = function () {
  28422. for (var i = 0; i < this.materials.length; i++) {
  28423. this.materials[i].freeze();
  28424. }
  28425. };
  28426. /**
  28427. * Unfreeze all materials
  28428. * A frozen material will not be updatable but should be faster to render
  28429. */
  28430. Scene.prototype.unfreezeMaterials = function () {
  28431. for (var i = 0; i < this.materials.length; i++) {
  28432. this.materials[i].unfreeze();
  28433. }
  28434. };
  28435. /**
  28436. * Releases all held ressources
  28437. */
  28438. Scene.prototype.dispose = function () {
  28439. this.beforeRender = null;
  28440. this.afterRender = null;
  28441. this.skeletons = [];
  28442. this.morphTargetManagers = [];
  28443. this.importedMeshesFiles = new Array();
  28444. this.stopAllAnimations();
  28445. this.resetCachedMaterial();
  28446. for (var key in this._depthRenderer) {
  28447. this._depthRenderer[key].dispose();
  28448. }
  28449. if (this._gamepadManager) {
  28450. this._gamepadManager.dispose();
  28451. this._gamepadManager = null;
  28452. }
  28453. // Smart arrays
  28454. if (this.activeCamera) {
  28455. this.activeCamera._activeMeshes.dispose();
  28456. this.activeCamera = null;
  28457. }
  28458. this._activeMeshes.dispose();
  28459. this._renderingManager.dispose();
  28460. this._processedMaterials.dispose();
  28461. this._activeParticleSystems.dispose();
  28462. this._activeSkeletons.dispose();
  28463. this._softwareSkinnedMeshes.dispose();
  28464. this._renderTargets.dispose();
  28465. this._registeredForLateAnimationBindings.dispose();
  28466. if (this._boundingBoxRenderer) {
  28467. this._boundingBoxRenderer.dispose();
  28468. }
  28469. this._meshesForIntersections.dispose();
  28470. this._toBeDisposed.dispose();
  28471. // Abort active requests
  28472. for (var _i = 0, _a = this._activeRequests; _i < _a.length; _i++) {
  28473. var request = _a[_i];
  28474. request.abort();
  28475. }
  28476. // Debug layer
  28477. if (this._debugLayer) {
  28478. this._debugLayer.hide();
  28479. }
  28480. // Events
  28481. this.onDisposeObservable.notifyObservers(this);
  28482. this.onDisposeObservable.clear();
  28483. this.onBeforeRenderObservable.clear();
  28484. this.onAfterRenderObservable.clear();
  28485. this.onBeforeRenderTargetsRenderObservable.clear();
  28486. this.onAfterRenderTargetsRenderObservable.clear();
  28487. this.onAfterStepObservable.clear();
  28488. this.onBeforeStepObservable.clear();
  28489. this.onBeforeActiveMeshesEvaluationObservable.clear();
  28490. this.onAfterActiveMeshesEvaluationObservable.clear();
  28491. this.onBeforeParticlesRenderingObservable.clear();
  28492. this.onAfterParticlesRenderingObservable.clear();
  28493. this.onBeforeSpritesRenderingObservable.clear();
  28494. this.onAfterSpritesRenderingObservable.clear();
  28495. this.onBeforeDrawPhaseObservable.clear();
  28496. this.onAfterDrawPhaseObservable.clear();
  28497. this.onBeforePhysicsObservable.clear();
  28498. this.onAfterPhysicsObservable.clear();
  28499. this.onBeforeAnimationsObservable.clear();
  28500. this.onAfterAnimationsObservable.clear();
  28501. this.onDataLoadedObservable.clear();
  28502. this.detachControl();
  28503. // Release sounds & sounds tracks
  28504. if (BABYLON.AudioEngine) {
  28505. this.disposeSounds();
  28506. }
  28507. // VR Helper
  28508. if (this.VRHelper) {
  28509. this.VRHelper.dispose();
  28510. }
  28511. // Detach cameras
  28512. var canvas = this._engine.getRenderingCanvas();
  28513. if (canvas) {
  28514. var index;
  28515. for (index = 0; index < this.cameras.length; index++) {
  28516. this.cameras[index].detachControl(canvas);
  28517. }
  28518. }
  28519. // Release animation groups
  28520. while (this.animationGroups.length) {
  28521. this.animationGroups[0].dispose();
  28522. }
  28523. // Release lights
  28524. while (this.lights.length) {
  28525. this.lights[0].dispose();
  28526. }
  28527. // Release meshes
  28528. while (this.meshes.length) {
  28529. this.meshes[0].dispose(true);
  28530. }
  28531. while (this.transformNodes.length) {
  28532. this.removeTransformNode(this.transformNodes[0]);
  28533. }
  28534. // Release cameras
  28535. while (this.cameras.length) {
  28536. this.cameras[0].dispose();
  28537. }
  28538. // Release materials
  28539. if (this.defaultMaterial) {
  28540. this.defaultMaterial.dispose();
  28541. }
  28542. while (this.multiMaterials.length) {
  28543. this.multiMaterials[0].dispose();
  28544. }
  28545. while (this.materials.length) {
  28546. this.materials[0].dispose();
  28547. }
  28548. // Release particles
  28549. while (this.particleSystems.length) {
  28550. this.particleSystems[0].dispose();
  28551. }
  28552. // Release sprites
  28553. while (this.spriteManagers.length) {
  28554. this.spriteManagers[0].dispose();
  28555. }
  28556. // Release postProcesses
  28557. while (this.postProcesses.length) {
  28558. this.postProcesses[0].dispose();
  28559. }
  28560. // Release layers
  28561. while (this.layers.length) {
  28562. this.layers[0].dispose();
  28563. }
  28564. while (this.effectLayers.length) {
  28565. this.effectLayers[0].dispose();
  28566. }
  28567. // Release textures
  28568. while (this.textures.length) {
  28569. this.textures[0].dispose();
  28570. }
  28571. // Release UBO
  28572. this._sceneUbo.dispose();
  28573. if (this._alternateSceneUbo) {
  28574. this._alternateSceneUbo.dispose();
  28575. }
  28576. // Post-processes
  28577. this.postProcessManager.dispose();
  28578. if (this._postProcessRenderPipelineManager) {
  28579. this._postProcessRenderPipelineManager.dispose();
  28580. }
  28581. // Physics
  28582. if (this._physicsEngine) {
  28583. this.disablePhysicsEngine();
  28584. }
  28585. // Remove from engine
  28586. index = this._engine.scenes.indexOf(this);
  28587. if (index > -1) {
  28588. this._engine.scenes.splice(index, 1);
  28589. }
  28590. this._engine.wipeCaches(true);
  28591. this._isDisposed = true;
  28592. };
  28593. Object.defineProperty(Scene.prototype, "isDisposed", {
  28594. /**
  28595. * Gets if the scene is already disposed
  28596. */
  28597. get: function () {
  28598. return this._isDisposed;
  28599. },
  28600. enumerable: true,
  28601. configurable: true
  28602. });
  28603. /**
  28604. * Releases sounds & soundtracks
  28605. */
  28606. Scene.prototype.disposeSounds = function () {
  28607. if (!this._mainSoundTrack) {
  28608. return;
  28609. }
  28610. this.mainSoundTrack.dispose();
  28611. for (var scIndex = 0; scIndex < this.soundTracks.length; scIndex++) {
  28612. this.soundTracks[scIndex].dispose();
  28613. }
  28614. };
  28615. /**
  28616. * Call this function to reduce memory footprint of the scene.
  28617. * Vertex buffers will not store CPU data anymore (this will prevent picking, collisions or physics to work correctly)
  28618. */
  28619. Scene.prototype.clearCachedVertexData = function () {
  28620. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28621. var mesh = this.meshes[meshIndex];
  28622. var geometry = mesh.geometry;
  28623. if (geometry) {
  28624. geometry._indices = [];
  28625. for (var vbName in geometry._vertexBuffers) {
  28626. if (!geometry._vertexBuffers.hasOwnProperty(vbName)) {
  28627. continue;
  28628. }
  28629. geometry._vertexBuffers[vbName]._buffer._data = null;
  28630. }
  28631. }
  28632. }
  28633. };
  28634. /**
  28635. * This function will remove the local cached buffer data from texture.
  28636. * It will save memory but will prevent the texture from being rebuilt
  28637. */
  28638. Scene.prototype.cleanCachedTextureBuffer = function () {
  28639. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  28640. var baseTexture = _a[_i];
  28641. var buffer = baseTexture._buffer;
  28642. if (buffer) {
  28643. baseTexture._buffer = null;
  28644. }
  28645. }
  28646. };
  28647. // Octrees
  28648. /**
  28649. * Get the world extend vectors with an optional filter
  28650. *
  28651. * @param filterPredicate the predicate - which meshes should be included when calculating the world size
  28652. * @returns {{ min: Vector3; max: Vector3 }} min and max vectors
  28653. */
  28654. Scene.prototype.getWorldExtends = function (filterPredicate) {
  28655. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  28656. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  28657. filterPredicate = filterPredicate || (function () { return true; });
  28658. this.meshes.filter(filterPredicate).forEach(function (mesh) {
  28659. mesh.computeWorldMatrix(true);
  28660. if (!mesh.subMeshes || mesh.subMeshes.length === 0 || mesh.infiniteDistance) {
  28661. return;
  28662. }
  28663. var boundingInfo = mesh.getBoundingInfo();
  28664. var minBox = boundingInfo.boundingBox.minimumWorld;
  28665. var maxBox = boundingInfo.boundingBox.maximumWorld;
  28666. BABYLON.Tools.CheckExtends(minBox, min, max);
  28667. BABYLON.Tools.CheckExtends(maxBox, min, max);
  28668. });
  28669. return {
  28670. min: min,
  28671. max: max
  28672. };
  28673. };
  28674. /**
  28675. * Creates or updates the octree used to boost selection (picking)
  28676. * @see http://doc.babylonjs.com/how_to/optimizing_your_scene_with_octrees
  28677. * @param maxCapacity defines the maximum capacity per leaf
  28678. * @param maxDepth defines the maximum depth of the octree
  28679. * @returns an octree of AbstractMesh
  28680. */
  28681. Scene.prototype.createOrUpdateSelectionOctree = function (maxCapacity, maxDepth) {
  28682. if (maxCapacity === void 0) { maxCapacity = 64; }
  28683. if (maxDepth === void 0) { maxDepth = 2; }
  28684. if (!this._selectionOctree) {
  28685. this._selectionOctree = new BABYLON.Octree(BABYLON.Octree.CreationFuncForMeshes, maxCapacity, maxDepth);
  28686. }
  28687. var worldExtends = this.getWorldExtends();
  28688. // Update octree
  28689. this._selectionOctree.update(worldExtends.min, worldExtends.max, this.meshes);
  28690. return this._selectionOctree;
  28691. };
  28692. // Picking
  28693. /**
  28694. * Creates a ray that can be used to pick in the scene
  28695. * @param x defines the x coordinate of the origin (on-screen)
  28696. * @param y defines the y coordinate of the origin (on-screen)
  28697. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28698. * @param camera defines the camera to use for the picking
  28699. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28700. * @returns a Ray
  28701. */
  28702. Scene.prototype.createPickingRay = function (x, y, world, camera, cameraViewSpace) {
  28703. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28704. var result = BABYLON.Ray.Zero();
  28705. this.createPickingRayToRef(x, y, world, result, camera, cameraViewSpace);
  28706. return result;
  28707. };
  28708. /**
  28709. * Creates a ray that can be used to pick in the scene
  28710. * @param x defines the x coordinate of the origin (on-screen)
  28711. * @param y defines the y coordinate of the origin (on-screen)
  28712. * @param world defines the world matrix to use if you want to pick in object space (instead of world space)
  28713. * @param result defines the ray where to store the picking ray
  28714. * @param camera defines the camera to use for the picking
  28715. * @param cameraViewSpace defines if picking will be done in view space (false by default)
  28716. * @returns the current scene
  28717. */
  28718. Scene.prototype.createPickingRayToRef = function (x, y, world, result, camera, cameraViewSpace) {
  28719. if (cameraViewSpace === void 0) { cameraViewSpace = false; }
  28720. var engine = this._engine;
  28721. if (!camera) {
  28722. if (!this.activeCamera)
  28723. throw new Error("Active camera not set");
  28724. camera = this.activeCamera;
  28725. }
  28726. var cameraViewport = camera.viewport;
  28727. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28728. // Moving coordinates to local viewport world
  28729. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28730. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28731. result.update(x, y, viewport.width, viewport.height, world ? world : BABYLON.Matrix.Identity(), cameraViewSpace ? BABYLON.Matrix.Identity() : camera.getViewMatrix(), camera.getProjectionMatrix());
  28732. return this;
  28733. };
  28734. /**
  28735. * Creates a ray that can be used to pick in the scene
  28736. * @param x defines the x coordinate of the origin (on-screen)
  28737. * @param y defines the y coordinate of the origin (on-screen)
  28738. * @param camera defines the camera to use for the picking
  28739. * @returns a Ray
  28740. */
  28741. Scene.prototype.createPickingRayInCameraSpace = function (x, y, camera) {
  28742. var result = BABYLON.Ray.Zero();
  28743. this.createPickingRayInCameraSpaceToRef(x, y, result, camera);
  28744. return result;
  28745. };
  28746. /**
  28747. * Creates a ray that can be used to pick in the scene
  28748. * @param x defines the x coordinate of the origin (on-screen)
  28749. * @param y defines the y coordinate of the origin (on-screen)
  28750. * @param result defines the ray where to store the picking ray
  28751. * @param camera defines the camera to use for the picking
  28752. * @returns the current scene
  28753. */
  28754. Scene.prototype.createPickingRayInCameraSpaceToRef = function (x, y, result, camera) {
  28755. if (!BABYLON.PickingInfo) {
  28756. return this;
  28757. }
  28758. var engine = this._engine;
  28759. if (!camera) {
  28760. if (!this.activeCamera)
  28761. throw new Error("Active camera not set");
  28762. camera = this.activeCamera;
  28763. }
  28764. var cameraViewport = camera.viewport;
  28765. var viewport = cameraViewport.toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  28766. var identity = BABYLON.Matrix.Identity();
  28767. // Moving coordinates to local viewport world
  28768. x = x / this._engine.getHardwareScalingLevel() - viewport.x;
  28769. y = y / this._engine.getHardwareScalingLevel() - (this._engine.getRenderHeight() - viewport.y - viewport.height);
  28770. result.update(x, y, viewport.width, viewport.height, identity, identity, camera.getProjectionMatrix());
  28771. return this;
  28772. };
  28773. Scene.prototype._internalPick = function (rayFunction, predicate, fastCheck) {
  28774. if (!BABYLON.PickingInfo) {
  28775. return null;
  28776. }
  28777. var pickingInfo = null;
  28778. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28779. var mesh = this.meshes[meshIndex];
  28780. if (predicate) {
  28781. if (!predicate(mesh)) {
  28782. continue;
  28783. }
  28784. }
  28785. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28786. continue;
  28787. }
  28788. var world = mesh.getWorldMatrix();
  28789. var ray = rayFunction(world);
  28790. var result = mesh.intersects(ray, fastCheck);
  28791. if (!result || !result.hit)
  28792. continue;
  28793. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28794. continue;
  28795. pickingInfo = result;
  28796. if (fastCheck) {
  28797. break;
  28798. }
  28799. }
  28800. return pickingInfo || new BABYLON.PickingInfo();
  28801. };
  28802. Scene.prototype._internalMultiPick = function (rayFunction, predicate) {
  28803. if (!BABYLON.PickingInfo) {
  28804. return null;
  28805. }
  28806. var pickingInfos = new Array();
  28807. for (var meshIndex = 0; meshIndex < this.meshes.length; meshIndex++) {
  28808. var mesh = this.meshes[meshIndex];
  28809. if (predicate) {
  28810. if (!predicate(mesh)) {
  28811. continue;
  28812. }
  28813. }
  28814. else if (!mesh.isEnabled() || !mesh.isVisible || !mesh.isPickable) {
  28815. continue;
  28816. }
  28817. var world = mesh.getWorldMatrix();
  28818. var ray = rayFunction(world);
  28819. var result = mesh.intersects(ray, false);
  28820. if (!result || !result.hit)
  28821. continue;
  28822. pickingInfos.push(result);
  28823. }
  28824. return pickingInfos;
  28825. };
  28826. Scene.prototype._internalPickSprites = function (ray, predicate, fastCheck, camera) {
  28827. if (!BABYLON.PickingInfo) {
  28828. return null;
  28829. }
  28830. var pickingInfo = null;
  28831. if (!camera) {
  28832. if (!this.activeCamera) {
  28833. return null;
  28834. }
  28835. camera = this.activeCamera;
  28836. }
  28837. if (this.spriteManagers.length > 0) {
  28838. for (var spriteIndex = 0; spriteIndex < this.spriteManagers.length; spriteIndex++) {
  28839. var spriteManager = this.spriteManagers[spriteIndex];
  28840. if (!spriteManager.isPickable) {
  28841. continue;
  28842. }
  28843. var result = spriteManager.intersects(ray, camera, predicate, fastCheck);
  28844. if (!result || !result.hit)
  28845. continue;
  28846. if (!fastCheck && pickingInfo != null && result.distance >= pickingInfo.distance)
  28847. continue;
  28848. pickingInfo = result;
  28849. if (fastCheck) {
  28850. break;
  28851. }
  28852. }
  28853. }
  28854. return pickingInfo || new BABYLON.PickingInfo();
  28855. };
  28856. /** Launch a ray to try to pick a mesh in the scene
  28857. * @param x position on screen
  28858. * @param y position on screen
  28859. * @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
  28860. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28861. * @param camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28862. * @returns a PickingInfo
  28863. */
  28864. Scene.prototype.pick = function (x, y, predicate, fastCheck, camera) {
  28865. var _this = this;
  28866. if (!BABYLON.PickingInfo) {
  28867. return null;
  28868. }
  28869. var result = this._internalPick(function (world) {
  28870. _this.createPickingRayToRef(x, y, world, _this._tempPickingRay, camera || null);
  28871. return _this._tempPickingRay;
  28872. }, predicate, fastCheck);
  28873. if (result) {
  28874. result.ray = this.createPickingRay(x, y, BABYLON.Matrix.Identity(), camera || null);
  28875. }
  28876. return result;
  28877. };
  28878. /** Launch a ray to try to pick a sprite in the scene
  28879. * @param x position on screen
  28880. * @param y position on screen
  28881. * @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
  28882. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null.
  28883. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28884. * @returns a PickingInfo
  28885. */
  28886. Scene.prototype.pickSprite = function (x, y, predicate, fastCheck, camera) {
  28887. this.createPickingRayInCameraSpaceToRef(x, y, this._tempPickingRay, camera);
  28888. return this._internalPickSprites(this._tempPickingRay, predicate, fastCheck, camera);
  28889. };
  28890. /** Use the given ray to pick a mesh in the scene
  28891. * @param ray The ray to use to pick meshes
  28892. * @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
  28893. * @param fastCheck Launch a fast check only using the bounding boxes. Can be set to null
  28894. * @returns a PickingInfo
  28895. */
  28896. Scene.prototype.pickWithRay = function (ray, predicate, fastCheck) {
  28897. var _this = this;
  28898. var result = this._internalPick(function (world) {
  28899. if (!_this._pickWithRayInverseMatrix) {
  28900. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28901. }
  28902. world.invertToRef(_this._pickWithRayInverseMatrix);
  28903. if (!_this._cachedRayForTransform) {
  28904. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28905. }
  28906. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28907. return _this._cachedRayForTransform;
  28908. }, predicate, fastCheck);
  28909. if (result) {
  28910. result.ray = ray;
  28911. }
  28912. return result;
  28913. };
  28914. /**
  28915. * Launch a ray to try to pick a mesh in the scene
  28916. * @param x X position on screen
  28917. * @param y Y position on screen
  28918. * @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
  28919. * @param camera camera to use for computing the picking ray. Can be set to null. In this case, the scene.activeCamera will be used
  28920. * @returns an array of PickingInfo
  28921. */
  28922. Scene.prototype.multiPick = function (x, y, predicate, camera) {
  28923. var _this = this;
  28924. return this._internalMultiPick(function (world) { return _this.createPickingRay(x, y, world, camera || null); }, predicate);
  28925. };
  28926. /**
  28927. * Launch a ray to try to pick a mesh in the scene
  28928. * @param ray Ray to use
  28929. * @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
  28930. * @returns an array of PickingInfo
  28931. */
  28932. Scene.prototype.multiPickWithRay = function (ray, predicate) {
  28933. var _this = this;
  28934. return this._internalMultiPick(function (world) {
  28935. if (!_this._pickWithRayInverseMatrix) {
  28936. _this._pickWithRayInverseMatrix = BABYLON.Matrix.Identity();
  28937. }
  28938. world.invertToRef(_this._pickWithRayInverseMatrix);
  28939. if (!_this._cachedRayForTransform) {
  28940. _this._cachedRayForTransform = BABYLON.Ray.Zero();
  28941. }
  28942. BABYLON.Ray.TransformToRef(ray, _this._pickWithRayInverseMatrix, _this._cachedRayForTransform);
  28943. return _this._cachedRayForTransform;
  28944. }, predicate);
  28945. };
  28946. /**
  28947. * Force the value of meshUnderPointer
  28948. * @param mesh defines the mesh to use
  28949. */
  28950. Scene.prototype.setPointerOverMesh = function (mesh) {
  28951. if (this._pointerOverMesh === mesh) {
  28952. return;
  28953. }
  28954. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28955. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28956. }
  28957. this._pointerOverMesh = mesh;
  28958. if (this._pointerOverMesh && this._pointerOverMesh.actionManager) {
  28959. this._pointerOverMesh.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNew(this._pointerOverMesh));
  28960. }
  28961. };
  28962. /**
  28963. * Gets the mesh under the pointer
  28964. * @returns a Mesh or null if no mesh is under the pointer
  28965. */
  28966. Scene.prototype.getPointerOverMesh = function () {
  28967. return this._pointerOverMesh;
  28968. };
  28969. /**
  28970. * Force the sprite under the pointer
  28971. * @param sprite defines the sprite to use
  28972. */
  28973. Scene.prototype.setPointerOverSprite = function (sprite) {
  28974. if (this._pointerOverSprite === sprite) {
  28975. return;
  28976. }
  28977. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28978. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOutTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28979. }
  28980. this._pointerOverSprite = sprite;
  28981. if (this._pointerOverSprite && this._pointerOverSprite.actionManager) {
  28982. this._pointerOverSprite.actionManager.processTrigger(BABYLON.ActionManager.OnPointerOverTrigger, BABYLON.ActionEvent.CreateNewFromSprite(this._pointerOverSprite, this));
  28983. }
  28984. };
  28985. /**
  28986. * Gets the sprite under the pointer
  28987. * @returns a Sprite or null if no sprite is under the pointer
  28988. */
  28989. Scene.prototype.getPointerOverSprite = function () {
  28990. return this._pointerOverSprite;
  28991. };
  28992. // Physics
  28993. /**
  28994. * Gets the current physics engine
  28995. * @returns a PhysicsEngine or null if none attached
  28996. */
  28997. Scene.prototype.getPhysicsEngine = function () {
  28998. return this._physicsEngine;
  28999. };
  29000. /**
  29001. * Enables physics to the current scene
  29002. * @param gravity defines the scene's gravity for the physics engine
  29003. * @param plugin defines the physics engine to be used. defaults to OimoJS.
  29004. * @return a boolean indicating if the physics engine was initialized
  29005. */
  29006. Scene.prototype.enablePhysics = function (gravity, plugin) {
  29007. if (gravity === void 0) { gravity = null; }
  29008. if (this._physicsEngine) {
  29009. return true;
  29010. }
  29011. try {
  29012. this._physicsEngine = new BABYLON.PhysicsEngine(gravity, plugin);
  29013. return true;
  29014. }
  29015. catch (e) {
  29016. BABYLON.Tools.Error(e.message);
  29017. return false;
  29018. }
  29019. };
  29020. /**
  29021. * Disables and disposes the physics engine associated with the scene
  29022. */
  29023. Scene.prototype.disablePhysicsEngine = function () {
  29024. if (!this._physicsEngine) {
  29025. return;
  29026. }
  29027. this._physicsEngine.dispose();
  29028. this._physicsEngine = null;
  29029. };
  29030. /**
  29031. * Gets a boolean indicating if there is an active physics engine
  29032. * @returns a boolean indicating if there is an active physics engine
  29033. */
  29034. Scene.prototype.isPhysicsEnabled = function () {
  29035. return this._physicsEngine !== undefined;
  29036. };
  29037. /**
  29038. * Deletes a physics compound impostor
  29039. * @param compound defines the compound to delete
  29040. */
  29041. Scene.prototype.deleteCompoundImpostor = function (compound) {
  29042. var mesh = compound.parts[0].mesh;
  29043. if (mesh.physicsImpostor) {
  29044. mesh.physicsImpostor.dispose( /*true*/);
  29045. mesh.physicsImpostor = null;
  29046. }
  29047. };
  29048. // Misc.
  29049. /** @hidden */
  29050. Scene.prototype._rebuildGeometries = function () {
  29051. for (var _i = 0, _a = this._geometries; _i < _a.length; _i++) {
  29052. var geometry = _a[_i];
  29053. geometry._rebuild();
  29054. }
  29055. for (var _b = 0, _c = this.meshes; _b < _c.length; _b++) {
  29056. var mesh = _c[_b];
  29057. mesh._rebuild();
  29058. }
  29059. if (this.postProcessManager) {
  29060. this.postProcessManager._rebuild();
  29061. }
  29062. for (var _d = 0, _e = this.layers; _d < _e.length; _d++) {
  29063. var layer = _e[_d];
  29064. layer._rebuild();
  29065. }
  29066. for (var _f = 0, _g = this.effectLayers; _f < _g.length; _f++) {
  29067. var effectLayer = _g[_f];
  29068. effectLayer._rebuild();
  29069. }
  29070. if (this._boundingBoxRenderer) {
  29071. this._boundingBoxRenderer._rebuild();
  29072. }
  29073. for (var _h = 0, _j = this.particleSystems; _h < _j.length; _h++) {
  29074. var system = _j[_h];
  29075. system.rebuild();
  29076. }
  29077. if (this._postProcessRenderPipelineManager) {
  29078. this._postProcessRenderPipelineManager._rebuild();
  29079. }
  29080. };
  29081. /** @hidden */
  29082. Scene.prototype._rebuildTextures = function () {
  29083. for (var _i = 0, _a = this.textures; _i < _a.length; _i++) {
  29084. var texture = _a[_i];
  29085. texture._rebuild();
  29086. }
  29087. this.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  29088. };
  29089. /**
  29090. * Creates a default light for the scene.
  29091. * @param replace Whether to replace the existing lights in the scene.
  29092. */
  29093. Scene.prototype.createDefaultLight = function (replace) {
  29094. if (replace === void 0) { replace = false; }
  29095. // Dispose existing light in replace mode.
  29096. if (replace) {
  29097. if (this.lights) {
  29098. for (var i = 0; i < this.lights.length; i++) {
  29099. this.lights[i].dispose();
  29100. }
  29101. }
  29102. }
  29103. // Light
  29104. if (this.lights.length === 0) {
  29105. new BABYLON.HemisphericLight("default light", BABYLON.Vector3.Up(), this);
  29106. }
  29107. };
  29108. /**
  29109. * Creates a default camera for the scene.
  29110. * @param createArcRotateCamera Whether to create an arc rotate or a free camera.
  29111. * @param replace Whether to replace the existing active camera in the scene.
  29112. * @param attachCameraControls Whether to attach camera controls to the canvas.
  29113. */
  29114. Scene.prototype.createDefaultCamera = function (createArcRotateCamera, replace, attachCameraControls) {
  29115. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29116. if (replace === void 0) { replace = false; }
  29117. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29118. // Dispose existing camera in replace mode.
  29119. if (replace) {
  29120. if (this.activeCamera) {
  29121. this.activeCamera.dispose();
  29122. this.activeCamera = null;
  29123. }
  29124. }
  29125. // Camera
  29126. if (!this.activeCamera) {
  29127. var worldExtends = this.getWorldExtends();
  29128. var worldSize = worldExtends.max.subtract(worldExtends.min);
  29129. var worldCenter = worldExtends.min.add(worldSize.scale(0.5));
  29130. var camera;
  29131. var radius = worldSize.length() * 1.5;
  29132. // empty scene scenario!
  29133. if (!isFinite(radius)) {
  29134. radius = 1;
  29135. worldCenter.copyFromFloats(0, 0, 0);
  29136. }
  29137. if (createArcRotateCamera) {
  29138. var arcRotateCamera = new BABYLON.ArcRotateCamera("default camera", -(Math.PI / 2), Math.PI / 2, radius, worldCenter, this);
  29139. arcRotateCamera.lowerRadiusLimit = radius * 0.01;
  29140. arcRotateCamera.wheelPrecision = 100 / radius;
  29141. camera = arcRotateCamera;
  29142. }
  29143. else {
  29144. var freeCamera = new BABYLON.FreeCamera("default camera", new BABYLON.Vector3(worldCenter.x, worldCenter.y, -radius), this);
  29145. freeCamera.setTarget(worldCenter);
  29146. camera = freeCamera;
  29147. }
  29148. camera.minZ = radius * 0.01;
  29149. camera.maxZ = radius * 1000;
  29150. camera.speed = radius * 0.2;
  29151. this.activeCamera = camera;
  29152. var canvas = this.getEngine().getRenderingCanvas();
  29153. if (attachCameraControls && canvas) {
  29154. camera.attachControl(canvas);
  29155. }
  29156. }
  29157. };
  29158. /**
  29159. * Creates a default camera and a default light
  29160. * @param createArcRotateCamera defines that the camera will be an ArcRotateCamera
  29161. * @param replace defines if the camera and/or light will replace the existing ones
  29162. * @param attachCameraControls defines if attachControl will be called on the new camera
  29163. */
  29164. Scene.prototype.createDefaultCameraOrLight = function (createArcRotateCamera, replace, attachCameraControls) {
  29165. if (createArcRotateCamera === void 0) { createArcRotateCamera = false; }
  29166. if (replace === void 0) { replace = false; }
  29167. if (attachCameraControls === void 0) { attachCameraControls = false; }
  29168. this.createDefaultLight(replace);
  29169. this.createDefaultCamera(createArcRotateCamera, replace, attachCameraControls);
  29170. };
  29171. /**
  29172. * Creates a new sky box
  29173. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29174. * @param environmentTexture defines the texture to use as environment texture
  29175. * @param pbr defines if PBRMaterial must be used instead of StandardMaterial
  29176. * @param scale defines the overall scale of the skybox
  29177. * @param blur defines if blurring must be applied to the environment texture (works only with pbr === true)
  29178. * @param setGlobalEnvTexture defines a boolean indicating that scene.environmentTexture must match the current skybox texture (true by default)
  29179. * @returns a new mesh holding the sky box
  29180. */
  29181. Scene.prototype.createDefaultSkybox = function (environmentTexture, pbr, scale, blur, setGlobalEnvTexture) {
  29182. if (pbr === void 0) { pbr = false; }
  29183. if (scale === void 0) { scale = 1000; }
  29184. if (blur === void 0) { blur = 0; }
  29185. if (setGlobalEnvTexture === void 0) { setGlobalEnvTexture = true; }
  29186. if (!environmentTexture) {
  29187. BABYLON.Tools.Warn("Can not create default skybox without environment texture.");
  29188. return null;
  29189. }
  29190. if (setGlobalEnvTexture) {
  29191. if (environmentTexture) {
  29192. this.environmentTexture = environmentTexture;
  29193. }
  29194. }
  29195. // Skybox
  29196. var hdrSkybox = BABYLON.Mesh.CreateBox("hdrSkyBox", scale, this);
  29197. if (pbr) {
  29198. var hdrSkyboxMaterial = new BABYLON.PBRMaterial("skyBox", this);
  29199. hdrSkyboxMaterial.backFaceCulling = false;
  29200. hdrSkyboxMaterial.reflectionTexture = environmentTexture.clone();
  29201. if (hdrSkyboxMaterial.reflectionTexture) {
  29202. hdrSkyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29203. }
  29204. hdrSkyboxMaterial.microSurface = 1.0 - blur;
  29205. hdrSkyboxMaterial.disableLighting = true;
  29206. hdrSkyboxMaterial.twoSidedLighting = true;
  29207. hdrSkybox.infiniteDistance = true;
  29208. hdrSkybox.material = hdrSkyboxMaterial;
  29209. }
  29210. else {
  29211. var skyboxMaterial = new BABYLON.StandardMaterial("skyBox", this);
  29212. skyboxMaterial.backFaceCulling = false;
  29213. skyboxMaterial.reflectionTexture = environmentTexture.clone();
  29214. if (skyboxMaterial.reflectionTexture) {
  29215. skyboxMaterial.reflectionTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  29216. }
  29217. skyboxMaterial.disableLighting = true;
  29218. hdrSkybox.infiniteDistance = true;
  29219. hdrSkybox.material = skyboxMaterial;
  29220. }
  29221. return hdrSkybox;
  29222. };
  29223. /**
  29224. * Creates a new environment
  29225. * @see http://doc.babylonjs.com/babylon101/environment#skybox
  29226. * @param options defines the options you can use to configure the environment
  29227. * @returns the new EnvironmentHelper
  29228. */
  29229. Scene.prototype.createDefaultEnvironment = function (options) {
  29230. if (BABYLON.EnvironmentHelper) {
  29231. return new BABYLON.EnvironmentHelper(options, this);
  29232. }
  29233. return null;
  29234. };
  29235. /**
  29236. * Creates a new VREXperienceHelper
  29237. * @see http://doc.babylonjs.com/how_to/webvr_helper
  29238. * @param webVROptions defines the options used to create the new VREXperienceHelper
  29239. * @returns a new VREXperienceHelper
  29240. */
  29241. Scene.prototype.createDefaultVRExperience = function (webVROptions) {
  29242. if (webVROptions === void 0) { webVROptions = {}; }
  29243. return new BABYLON.VRExperienceHelper(this, webVROptions);
  29244. };
  29245. // Tags
  29246. Scene.prototype._getByTags = function (list, tagsQuery, forEach) {
  29247. if (tagsQuery === undefined) {
  29248. // returns the complete list (could be done with BABYLON.Tags.MatchesQuery but no need to have a for-loop here)
  29249. return list;
  29250. }
  29251. var listByTags = [];
  29252. forEach = forEach || (function (item) { return; });
  29253. for (var i in list) {
  29254. var item = list[i];
  29255. if (BABYLON.Tags && BABYLON.Tags.MatchesQuery(item, tagsQuery)) {
  29256. listByTags.push(item);
  29257. forEach(item);
  29258. }
  29259. }
  29260. return listByTags;
  29261. };
  29262. /**
  29263. * Get a list of meshes by tags
  29264. * @param tagsQuery defines the tags query to use
  29265. * @param forEach defines a predicate used to filter results
  29266. * @returns an array of Mesh
  29267. */
  29268. Scene.prototype.getMeshesByTags = function (tagsQuery, forEach) {
  29269. return this._getByTags(this.meshes, tagsQuery, forEach);
  29270. };
  29271. /**
  29272. * Get a list of cameras by tags
  29273. * @param tagsQuery defines the tags query to use
  29274. * @param forEach defines a predicate used to filter results
  29275. * @returns an array of Camera
  29276. */
  29277. Scene.prototype.getCamerasByTags = function (tagsQuery, forEach) {
  29278. return this._getByTags(this.cameras, tagsQuery, forEach);
  29279. };
  29280. /**
  29281. * Get a list of lights by tags
  29282. * @param tagsQuery defines the tags query to use
  29283. * @param forEach defines a predicate used to filter results
  29284. * @returns an array of Light
  29285. */
  29286. Scene.prototype.getLightsByTags = function (tagsQuery, forEach) {
  29287. return this._getByTags(this.lights, tagsQuery, forEach);
  29288. };
  29289. /**
  29290. * Get a list of materials by tags
  29291. * @param tagsQuery defines the tags query to use
  29292. * @param forEach defines a predicate used to filter results
  29293. * @returns an array of Material
  29294. */
  29295. Scene.prototype.getMaterialByTags = function (tagsQuery, forEach) {
  29296. return this._getByTags(this.materials, tagsQuery, forEach).concat(this._getByTags(this.multiMaterials, tagsQuery, forEach));
  29297. };
  29298. /**
  29299. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  29300. * This allowed control for front to back rendering or reversly depending of the special needs.
  29301. *
  29302. * @param renderingGroupId The rendering group id corresponding to its index
  29303. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  29304. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  29305. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  29306. */
  29307. Scene.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  29308. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  29309. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  29310. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  29311. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  29312. };
  29313. /**
  29314. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  29315. *
  29316. * @param renderingGroupId The rendering group id corresponding to its index
  29317. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  29318. * @param depth Automatically clears depth between groups if true and autoClear is true.
  29319. * @param stencil Automatically clears stencil between groups if true and autoClear is true.
  29320. */
  29321. Scene.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil, depth, stencil) {
  29322. if (depth === void 0) { depth = true; }
  29323. if (stencil === void 0) { stencil = true; }
  29324. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil, depth, stencil);
  29325. };
  29326. /**
  29327. * Will flag all materials as dirty to trigger new shader compilation
  29328. * @param flag defines the flag used to specify which material part must be marked as dirty
  29329. * @param predicate If not null, it will be used to specifiy if a material has to be marked as dirty
  29330. */
  29331. Scene.prototype.markAllMaterialsAsDirty = function (flag, predicate) {
  29332. for (var _i = 0, _a = this.materials; _i < _a.length; _i++) {
  29333. var material = _a[_i];
  29334. if (predicate && !predicate(material)) {
  29335. continue;
  29336. }
  29337. material.markAsDirty(flag);
  29338. }
  29339. };
  29340. /** @hidden */
  29341. Scene.prototype._loadFile = function (url, onSuccess, onProgress, useDatabase, useArrayBuffer, onError) {
  29342. var _this = this;
  29343. var request = BABYLON.Tools.LoadFile(url, onSuccess, onProgress, useDatabase ? this.database : undefined, useArrayBuffer, onError);
  29344. this._activeRequests.push(request);
  29345. request.onCompleteObservable.add(function (request) {
  29346. _this._activeRequests.splice(_this._activeRequests.indexOf(request), 1);
  29347. });
  29348. return request;
  29349. };
  29350. /** @hidden */
  29351. Scene.prototype._loadFileAsync = function (url, useDatabase, useArrayBuffer) {
  29352. var _this = this;
  29353. return new Promise(function (resolve, reject) {
  29354. _this._loadFile(url, function (data) {
  29355. resolve(data);
  29356. }, undefined, useDatabase, useArrayBuffer, function (request, exception) {
  29357. reject(exception);
  29358. });
  29359. });
  29360. };
  29361. // Statics
  29362. Scene._FOGMODE_NONE = 0;
  29363. Scene._FOGMODE_EXP = 1;
  29364. Scene._FOGMODE_EXP2 = 2;
  29365. Scene._FOGMODE_LINEAR = 3;
  29366. Scene._uniqueIdCounter = 0;
  29367. /**
  29368. * Gets or sets the minimum deltatime when deterministic lock step is enabled
  29369. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29370. */
  29371. Scene.MinDeltaTime = 1.0;
  29372. /**
  29373. * Gets or sets the maximum deltatime when deterministic lock step is enabled
  29374. * @see http://doc.babylonjs.com/babylon101/animations#deterministic-lockstep
  29375. */
  29376. Scene.MaxDeltaTime = 1000.0;
  29377. /** The distance in pixel that you have to move to prevent some events */
  29378. Scene.DragMovementThreshold = 10; // in pixels
  29379. /** Time in milliseconds to wait to raise long press events if button is still pressed */
  29380. Scene.LongPressDelay = 500; // in milliseconds
  29381. /** Time in milliseconds with two consecutive clicks will be considered as a double click */
  29382. Scene.DoubleClickDelay = 300; // in milliseconds
  29383. /** If you need to check double click without raising a single click at first click, enable this flag */
  29384. Scene.ExclusiveDoubleClickMode = false;
  29385. return Scene;
  29386. }());
  29387. BABYLON.Scene = Scene;
  29388. })(BABYLON || (BABYLON = {}));
  29389. //# sourceMappingURL=babylon.scene.js.map
  29390. var BABYLON;
  29391. (function (BABYLON) {
  29392. /**
  29393. * Set of assets to keep when moving a scene into an asset container.
  29394. */
  29395. var KeepAssets = /** @class */ (function () {
  29396. function KeepAssets() {
  29397. /**
  29398. * Cameras to keep.
  29399. */
  29400. this.cameras = new Array();
  29401. /**
  29402. * Lights to keep.
  29403. */
  29404. this.lights = new Array();
  29405. /**
  29406. * Meshes to keep.
  29407. */
  29408. this.meshes = new Array();
  29409. /**
  29410. * Skeletons to keep.
  29411. */
  29412. this.skeletons = new Array();
  29413. /**
  29414. * ParticleSystems to keep.
  29415. */
  29416. this.particleSystems = new Array();
  29417. /**
  29418. * Animations to keep.
  29419. */
  29420. this.animations = new Array();
  29421. /**
  29422. * AnimationGroups to keep.
  29423. */
  29424. this.animationGroups = new Array();
  29425. /**
  29426. * MultiMaterials to keep.
  29427. */
  29428. this.multiMaterials = new Array();
  29429. /**
  29430. * Materials to keep.
  29431. */
  29432. this.materials = new Array();
  29433. /**
  29434. * MorphTargetManagers to keep.
  29435. */
  29436. this.morphTargetManagers = new Array();
  29437. /**
  29438. * Geometries to keep.
  29439. */
  29440. this.geometries = new Array();
  29441. /**
  29442. * TransformNodes to keep.
  29443. */
  29444. this.transformNodes = new Array();
  29445. /**
  29446. * LensFlareSystems to keep.
  29447. */
  29448. this.lensFlareSystems = new Array();
  29449. /**
  29450. * ShadowGenerators to keep.
  29451. */
  29452. this.shadowGenerators = new Array();
  29453. /**
  29454. * ActionManagers to keep.
  29455. */
  29456. this.actionManagers = new Array();
  29457. /**
  29458. * Sounds to keep.
  29459. */
  29460. this.sounds = new Array();
  29461. /**
  29462. * Textures to keep.
  29463. */
  29464. this.textures = new Array();
  29465. /**
  29466. * Effect layers to keep.
  29467. */
  29468. this.effectLayers = new Array();
  29469. }
  29470. return KeepAssets;
  29471. }());
  29472. BABYLON.KeepAssets = KeepAssets;
  29473. /**
  29474. * Container with a set of assets that can be added or removed from a scene.
  29475. */
  29476. var AssetContainer = /** @class */ (function () {
  29477. /**
  29478. * Instantiates an AssetContainer.
  29479. * @param scene The scene the AssetContainer belongs to.
  29480. */
  29481. function AssetContainer(scene) {
  29482. // Objects
  29483. /**
  29484. * Cameras populated in the container.
  29485. */
  29486. this.cameras = new Array();
  29487. /**
  29488. * Lights populated in the container.
  29489. */
  29490. this.lights = new Array();
  29491. /**
  29492. * Meshes populated in the container.
  29493. */
  29494. this.meshes = new Array();
  29495. /**
  29496. * Skeletons populated in the container.
  29497. */
  29498. this.skeletons = new Array();
  29499. /**
  29500. * ParticleSystems populated in the container.
  29501. */
  29502. this.particleSystems = new Array();
  29503. /**
  29504. * Animations populated in the container.
  29505. */
  29506. this.animations = new Array();
  29507. /**
  29508. * AnimationGroups populated in the container.
  29509. */
  29510. this.animationGroups = new Array();
  29511. /**
  29512. * MultiMaterials populated in the container.
  29513. */
  29514. this.multiMaterials = new Array();
  29515. /**
  29516. * Materials populated in the container.
  29517. */
  29518. this.materials = new Array();
  29519. /**
  29520. * MorphTargetManagers populated in the container.
  29521. */
  29522. this.morphTargetManagers = new Array();
  29523. /**
  29524. * Geometries populated in the container.
  29525. */
  29526. this.geometries = new Array();
  29527. /**
  29528. * TransformNodes populated in the container.
  29529. */
  29530. this.transformNodes = new Array();
  29531. /**
  29532. * LensFlareSystems populated in the container.
  29533. */
  29534. this.lensFlareSystems = new Array();
  29535. /**
  29536. * ShadowGenerators populated in the container.
  29537. */
  29538. this.shadowGenerators = new Array();
  29539. /**
  29540. * ActionManagers populated in the container.
  29541. */
  29542. this.actionManagers = new Array();
  29543. /**
  29544. * Sounds populated in the container.
  29545. */
  29546. this.sounds = new Array();
  29547. /**
  29548. * Textures populated in the container.
  29549. */
  29550. this.textures = new Array();
  29551. /**
  29552. * Effect layers populated in the container.
  29553. */
  29554. this.effectLayers = new Array();
  29555. this.scene = scene;
  29556. }
  29557. /**
  29558. * Adds all the assets from the container to the scene.
  29559. */
  29560. AssetContainer.prototype.addAllToScene = function () {
  29561. var _this = this;
  29562. this.cameras.forEach(function (o) {
  29563. _this.scene.addCamera(o);
  29564. });
  29565. this.lights.forEach(function (o) {
  29566. _this.scene.addLight(o);
  29567. });
  29568. this.meshes.forEach(function (o) {
  29569. _this.scene.addMesh(o);
  29570. });
  29571. this.skeletons.forEach(function (o) {
  29572. _this.scene.addSkeleton(o);
  29573. });
  29574. this.particleSystems.forEach(function (o) {
  29575. _this.scene.addParticleSystem(o);
  29576. });
  29577. this.animations.forEach(function (o) {
  29578. _this.scene.addAnimation(o);
  29579. });
  29580. this.animationGroups.forEach(function (o) {
  29581. _this.scene.addAnimationGroup(o);
  29582. });
  29583. this.multiMaterials.forEach(function (o) {
  29584. _this.scene.addMultiMaterial(o);
  29585. });
  29586. this.materials.forEach(function (o) {
  29587. _this.scene.addMaterial(o);
  29588. });
  29589. this.morphTargetManagers.forEach(function (o) {
  29590. _this.scene.addMorphTargetManager(o);
  29591. });
  29592. this.geometries.forEach(function (o) {
  29593. _this.scene.addGeometry(o);
  29594. });
  29595. this.transformNodes.forEach(function (o) {
  29596. _this.scene.addTransformNode(o);
  29597. });
  29598. this.lensFlareSystems.forEach(function (o) {
  29599. _this.scene.addLensFlareSystem(o);
  29600. });
  29601. this.actionManagers.forEach(function (o) {
  29602. _this.scene.addActionManager(o);
  29603. });
  29604. this.sounds.forEach(function (o) {
  29605. o.play();
  29606. o.autoplay = true;
  29607. _this.scene.mainSoundTrack.AddSound(o);
  29608. });
  29609. this.textures.forEach(function (o) {
  29610. _this.scene.addTexture(o);
  29611. });
  29612. this.effectLayers.forEach(function (o) {
  29613. _this.scene.addEffectLayer(o);
  29614. });
  29615. };
  29616. /**
  29617. * Removes all the assets in the container from the scene
  29618. */
  29619. AssetContainer.prototype.removeAllFromScene = function () {
  29620. var _this = this;
  29621. this.cameras.forEach(function (o) {
  29622. _this.scene.removeCamera(o);
  29623. });
  29624. this.lights.forEach(function (o) {
  29625. _this.scene.removeLight(o);
  29626. });
  29627. this.meshes.forEach(function (o) {
  29628. _this.scene.removeMesh(o);
  29629. });
  29630. this.skeletons.forEach(function (o) {
  29631. _this.scene.removeSkeleton(o);
  29632. });
  29633. this.particleSystems.forEach(function (o) {
  29634. _this.scene.removeParticleSystem(o);
  29635. });
  29636. this.animations.forEach(function (o) {
  29637. _this.scene.removeAnimation(o);
  29638. });
  29639. this.animationGroups.forEach(function (o) {
  29640. _this.scene.removeAnimationGroup(o);
  29641. });
  29642. this.multiMaterials.forEach(function (o) {
  29643. _this.scene.removeMultiMaterial(o);
  29644. });
  29645. this.materials.forEach(function (o) {
  29646. _this.scene.removeMaterial(o);
  29647. });
  29648. this.morphTargetManagers.forEach(function (o) {
  29649. _this.scene.removeMorphTargetManager(o);
  29650. });
  29651. this.geometries.forEach(function (o) {
  29652. _this.scene.removeGeometry(o);
  29653. });
  29654. this.transformNodes.forEach(function (o) {
  29655. _this.scene.removeTransformNode(o);
  29656. });
  29657. this.lensFlareSystems.forEach(function (o) {
  29658. _this.scene.removeLensFlareSystem(o);
  29659. });
  29660. this.actionManagers.forEach(function (o) {
  29661. _this.scene.removeActionManager(o);
  29662. });
  29663. this.sounds.forEach(function (o) {
  29664. o.stop();
  29665. o.autoplay = false;
  29666. _this.scene.mainSoundTrack.RemoveSound(o);
  29667. });
  29668. this.textures.forEach(function (o) {
  29669. _this.scene.removeTexture(o);
  29670. });
  29671. this.effectLayers.forEach(function (o) {
  29672. _this.scene.removeEffectLayer(o);
  29673. });
  29674. };
  29675. AssetContainer.prototype._moveAssets = function (sourceAssets, targetAssets, keepAssets) {
  29676. for (var _i = 0, sourceAssets_1 = sourceAssets; _i < sourceAssets_1.length; _i++) {
  29677. var asset = sourceAssets_1[_i];
  29678. var move = true;
  29679. for (var _a = 0, keepAssets_1 = keepAssets; _a < keepAssets_1.length; _a++) {
  29680. var keepAsset = keepAssets_1[_a];
  29681. if (asset === keepAsset) {
  29682. move = false;
  29683. break;
  29684. }
  29685. }
  29686. if (move) {
  29687. targetAssets.push(asset);
  29688. }
  29689. }
  29690. };
  29691. /**
  29692. * Removes all the assets contained in the scene and adds them to the container.
  29693. * @param keepAssets Set of assets to keep in the scene. (default: empty)
  29694. */
  29695. AssetContainer.prototype.moveAllFromScene = function (keepAssets) {
  29696. if (keepAssets === undefined) {
  29697. keepAssets = new KeepAssets();
  29698. }
  29699. this._moveAssets(this.scene.cameras, this.cameras, keepAssets.cameras);
  29700. this._moveAssets(this.scene.meshes, this.meshes, keepAssets.meshes);
  29701. this._moveAssets(this.scene.getGeometries(), this.geometries, keepAssets.geometries);
  29702. this._moveAssets(this.scene.materials, this.materials, keepAssets.materials);
  29703. this._moveAssets(this.scene._actionManagers, this.actionManagers, keepAssets.actionManagers);
  29704. this._moveAssets(this.scene.animations, this.animations, keepAssets.animations);
  29705. this._moveAssets(this.scene.animationGroups, this.animationGroups, keepAssets.animationGroups);
  29706. this._moveAssets(this.scene.lensFlareSystems, this.lensFlareSystems, keepAssets.lensFlareSystems);
  29707. this._moveAssets(this.scene.lights, this.lights, keepAssets.lights);
  29708. this._moveAssets(this.scene.morphTargetManagers, this.morphTargetManagers, keepAssets.morphTargetManagers);
  29709. this._moveAssets(this.scene.multiMaterials, this.multiMaterials, keepAssets.multiMaterials);
  29710. this._moveAssets(this.scene.skeletons, this.skeletons, keepAssets.skeletons);
  29711. this._moveAssets(this.scene.particleSystems, this.particleSystems, keepAssets.particleSystems);
  29712. this._moveAssets(this.scene.mainSoundTrack.soundCollection, this.sounds, keepAssets.sounds);
  29713. this._moveAssets(this.scene.transformNodes, this.transformNodes, keepAssets.transformNodes);
  29714. this._moveAssets(this.scene.textures, this.textures, keepAssets.textures);
  29715. this._moveAssets(this.scene.effectLayers, this.effectLayers, keepAssets.effectLayers);
  29716. this.removeAllFromScene();
  29717. };
  29718. /**
  29719. * Adds all meshes in the asset container to a root mesh that can be used to position all the contained meshes. The root mesh is then added to the front of the meshes in the assetContainer.
  29720. * @returns the root mesh
  29721. */
  29722. AssetContainer.prototype.createRootMesh = function () {
  29723. var rootMesh = new BABYLON.Mesh("assetContainerRootMesh", this.scene);
  29724. this.meshes.forEach(function (m) {
  29725. if (!m.parent) {
  29726. rootMesh.addChild(m);
  29727. }
  29728. });
  29729. this.meshes.unshift(rootMesh);
  29730. return rootMesh;
  29731. };
  29732. return AssetContainer;
  29733. }());
  29734. BABYLON.AssetContainer = AssetContainer;
  29735. })(BABYLON || (BABYLON = {}));
  29736. //# sourceMappingURL=babylon.assetContainer.js.map
  29737. var BABYLON;
  29738. (function (BABYLON) {
  29739. var Buffer = /** @class */ (function () {
  29740. /**
  29741. * Constructor
  29742. * @param engine the engine
  29743. * @param data the data to use for this buffer
  29744. * @param updatable whether the data is updatable
  29745. * @param stride the stride (optional)
  29746. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29747. * @param instanced whether the buffer is instanced (optional)
  29748. * @param useBytes set to true if the stride in in bytes (optional)
  29749. */
  29750. function Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes) {
  29751. if (stride === void 0) { stride = 0; }
  29752. if (postponeInternalCreation === void 0) { postponeInternalCreation = false; }
  29753. if (instanced === void 0) { instanced = false; }
  29754. if (useBytes === void 0) { useBytes = false; }
  29755. if (engine instanceof BABYLON.Mesh) { // old versions of BABYLON.VertexBuffer accepted 'mesh' instead of 'engine'
  29756. this._engine = engine.getScene().getEngine();
  29757. }
  29758. else {
  29759. this._engine = engine;
  29760. }
  29761. this._updatable = updatable;
  29762. this._instanced = instanced;
  29763. this._data = data;
  29764. this.byteStride = useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT;
  29765. if (!postponeInternalCreation) { // by default
  29766. this.create();
  29767. }
  29768. }
  29769. /**
  29770. * Create a new {BABYLON.VertexBuffer} based on the current buffer
  29771. * @param kind defines the vertex buffer kind (position, normal, etc.)
  29772. * @param offset defines offset in the buffer (0 by default)
  29773. * @param size defines the size in floats of attributes (position is 3 for instance)
  29774. * @param stride defines the stride size in floats in the buffer (the offset to apply to reach next value when data is interleaved)
  29775. * @param instanced defines if the vertex buffer contains indexed data
  29776. * @param useBytes defines if the offset and stride are in bytes
  29777. * @returns the new vertex buffer
  29778. */
  29779. Buffer.prototype.createVertexBuffer = function (kind, offset, size, stride, instanced, useBytes) {
  29780. if (useBytes === void 0) { useBytes = false; }
  29781. var byteOffset = useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT;
  29782. var byteStride = stride ? (useBytes ? stride : stride * Float32Array.BYTES_PER_ELEMENT) : this.byteStride;
  29783. // a lot of these parameters are ignored as they are overriden by the buffer
  29784. return new BABYLON.VertexBuffer(this._engine, this, kind, this._updatable, true, byteStride, instanced === undefined ? this._instanced : instanced, byteOffset, size, undefined, undefined, true);
  29785. };
  29786. // Properties
  29787. Buffer.prototype.isUpdatable = function () {
  29788. return this._updatable;
  29789. };
  29790. Buffer.prototype.getData = function () {
  29791. return this._data;
  29792. };
  29793. Buffer.prototype.getBuffer = function () {
  29794. return this._buffer;
  29795. };
  29796. /**
  29797. * Gets the stride in float32 units (i.e. byte stride / 4).
  29798. * May not be an integer if the byte stride is not divisible by 4.
  29799. * DEPRECATED. Use byteStride instead.
  29800. * @returns the stride in float32 units
  29801. */
  29802. Buffer.prototype.getStrideSize = function () {
  29803. return this.byteStride / Float32Array.BYTES_PER_ELEMENT;
  29804. };
  29805. // Methods
  29806. Buffer.prototype.create = function (data) {
  29807. if (data === void 0) { data = null; }
  29808. if (!data && this._buffer) {
  29809. return; // nothing to do
  29810. }
  29811. data = data || this._data;
  29812. if (!data) {
  29813. return;
  29814. }
  29815. if (!this._buffer) { // create buffer
  29816. if (this._updatable) {
  29817. this._buffer = this._engine.createDynamicVertexBuffer(data);
  29818. this._data = data;
  29819. }
  29820. else {
  29821. this._buffer = this._engine.createVertexBuffer(data);
  29822. }
  29823. }
  29824. else if (this._updatable) { // update buffer
  29825. this._engine.updateDynamicVertexBuffer(this._buffer, data);
  29826. this._data = data;
  29827. }
  29828. };
  29829. Buffer.prototype._rebuild = function () {
  29830. this._buffer = null;
  29831. this.create(this._data);
  29832. };
  29833. Buffer.prototype.update = function (data) {
  29834. this.create(data);
  29835. };
  29836. /**
  29837. * Updates the data directly.
  29838. * @param data the new data
  29839. * @param offset the new offset
  29840. * @param vertexCount the vertex count (optional)
  29841. * @param useBytes set to true if the offset is in bytes
  29842. */
  29843. Buffer.prototype.updateDirectly = function (data, offset, vertexCount, useBytes) {
  29844. if (useBytes === void 0) { useBytes = false; }
  29845. if (!this._buffer) {
  29846. return;
  29847. }
  29848. if (this._updatable) { // update buffer
  29849. this._engine.updateDynamicVertexBuffer(this._buffer, data, useBytes ? offset : offset * Float32Array.BYTES_PER_ELEMENT, (vertexCount ? vertexCount * this.byteStride : undefined));
  29850. this._data = null;
  29851. }
  29852. };
  29853. Buffer.prototype.dispose = function () {
  29854. if (!this._buffer) {
  29855. return;
  29856. }
  29857. if (this._engine._releaseBuffer(this._buffer)) {
  29858. this._buffer = null;
  29859. }
  29860. };
  29861. return Buffer;
  29862. }());
  29863. BABYLON.Buffer = Buffer;
  29864. })(BABYLON || (BABYLON = {}));
  29865. //# sourceMappingURL=babylon.buffer.js.map
  29866. var BABYLON;
  29867. (function (BABYLON) {
  29868. var VertexBuffer = /** @class */ (function () {
  29869. /**
  29870. * Constructor
  29871. * @param engine the engine
  29872. * @param data the data to use for this vertex buffer
  29873. * @param kind the vertex buffer kind
  29874. * @param updatable whether the data is updatable
  29875. * @param postponeInternalCreation whether to postpone creating the internal WebGL buffer (optional)
  29876. * @param stride the stride (optional)
  29877. * @param instanced whether the buffer is instanced (optional)
  29878. * @param offset the offset of the data (optional)
  29879. * @param size the number of components (optional)
  29880. * @param type the type of the component (optional)
  29881. * @param normalized whether the data contains normalized data (optional)
  29882. * @param useBytes set to true if stride and offset are in bytes (optional)
  29883. */
  29884. function VertexBuffer(engine, data, kind, updatable, postponeInternalCreation, stride, instanced, offset, size, type, normalized, useBytes) {
  29885. if (normalized === void 0) { normalized = false; }
  29886. if (useBytes === void 0) { useBytes = false; }
  29887. if (data instanceof BABYLON.Buffer) {
  29888. this._buffer = data;
  29889. this._ownsBuffer = false;
  29890. }
  29891. else {
  29892. this._buffer = new BABYLON.Buffer(engine, data, updatable, stride, postponeInternalCreation, instanced, useBytes);
  29893. this._ownsBuffer = true;
  29894. }
  29895. this._kind = kind;
  29896. if (type == undefined) {
  29897. var data_1 = this.getData();
  29898. this.type = VertexBuffer.FLOAT;
  29899. if (data_1 instanceof Int8Array)
  29900. this.type = VertexBuffer.BYTE;
  29901. else if (data_1 instanceof Uint8Array)
  29902. this.type = VertexBuffer.UNSIGNED_BYTE;
  29903. else if (data_1 instanceof Int16Array)
  29904. this.type = VertexBuffer.SHORT;
  29905. else if (data_1 instanceof Uint16Array)
  29906. this.type = VertexBuffer.UNSIGNED_SHORT;
  29907. else if (data_1 instanceof Int32Array)
  29908. this.type = VertexBuffer.INT;
  29909. else if (data_1 instanceof Uint32Array)
  29910. this.type = VertexBuffer.UNSIGNED_INT;
  29911. }
  29912. else {
  29913. this.type = type;
  29914. }
  29915. var typeByteLength = VertexBuffer.GetTypeByteLength(this.type);
  29916. if (useBytes) {
  29917. this._size = size || (stride ? (stride / typeByteLength) : VertexBuffer.DeduceStride(kind));
  29918. this.byteStride = stride || this._buffer.byteStride || (this._size * typeByteLength);
  29919. this.byteOffset = offset || 0;
  29920. }
  29921. else {
  29922. this._size = size || stride || VertexBuffer.DeduceStride(kind);
  29923. this.byteStride = stride ? (stride * typeByteLength) : (this._buffer.byteStride || (this._size * typeByteLength));
  29924. this.byteOffset = (offset || 0) * typeByteLength;
  29925. }
  29926. this.normalized = normalized;
  29927. this._instanced = instanced !== undefined ? instanced : false;
  29928. this._instanceDivisor = instanced ? 1 : 0;
  29929. }
  29930. Object.defineProperty(VertexBuffer.prototype, "instanceDivisor", {
  29931. /**
  29932. * Gets or sets the instance divisor when in instanced mode
  29933. */
  29934. get: function () {
  29935. return this._instanceDivisor;
  29936. },
  29937. set: function (value) {
  29938. this._instanceDivisor = value;
  29939. if (value == 0) {
  29940. this._instanced = false;
  29941. }
  29942. else {
  29943. this._instanced = true;
  29944. }
  29945. },
  29946. enumerable: true,
  29947. configurable: true
  29948. });
  29949. VertexBuffer.prototype._rebuild = function () {
  29950. if (!this._buffer) {
  29951. return;
  29952. }
  29953. this._buffer._rebuild();
  29954. };
  29955. /**
  29956. * Returns the kind of the VertexBuffer (string).
  29957. */
  29958. VertexBuffer.prototype.getKind = function () {
  29959. return this._kind;
  29960. };
  29961. // Properties
  29962. /**
  29963. * Boolean : is the VertexBuffer updatable ?
  29964. */
  29965. VertexBuffer.prototype.isUpdatable = function () {
  29966. return this._buffer.isUpdatable();
  29967. };
  29968. /**
  29969. * Returns an array of numbers or a typed array containing the VertexBuffer data.
  29970. */
  29971. VertexBuffer.prototype.getData = function () {
  29972. return this._buffer.getData();
  29973. };
  29974. /**
  29975. * Returns the WebGLBuffer associated to the VertexBuffer.
  29976. */
  29977. VertexBuffer.prototype.getBuffer = function () {
  29978. return this._buffer.getBuffer();
  29979. };
  29980. /**
  29981. * Returns the stride as a multiple of the type byte length.
  29982. * DEPRECATED. Use byteStride instead.
  29983. */
  29984. VertexBuffer.prototype.getStrideSize = function () {
  29985. return this.byteStride / VertexBuffer.GetTypeByteLength(this.type);
  29986. };
  29987. /**
  29988. * Returns the offset as a multiple of the type byte length.
  29989. * DEPRECATED. Use byteOffset instead.
  29990. */
  29991. VertexBuffer.prototype.getOffset = function () {
  29992. return this.byteOffset / VertexBuffer.GetTypeByteLength(this.type);
  29993. };
  29994. /**
  29995. * Returns the number of components per vertex attribute (integer).
  29996. */
  29997. VertexBuffer.prototype.getSize = function () {
  29998. return this._size;
  29999. };
  30000. /**
  30001. * Boolean : is the WebGLBuffer of the VertexBuffer instanced now ?
  30002. */
  30003. VertexBuffer.prototype.getIsInstanced = function () {
  30004. return this._instanced;
  30005. };
  30006. /**
  30007. * Returns the instancing divisor, zero for non-instanced (integer).
  30008. */
  30009. VertexBuffer.prototype.getInstanceDivisor = function () {
  30010. return this._instanceDivisor;
  30011. };
  30012. // Methods
  30013. /**
  30014. * Creates the underlying WebGLBuffer from the passed numeric array or Float32Array.
  30015. * Returns the created WebGLBuffer.
  30016. */
  30017. VertexBuffer.prototype.create = function (data) {
  30018. return this._buffer.create(data);
  30019. };
  30020. /**
  30021. * Updates the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30022. * This function will create a new buffer if the current one is not updatable
  30023. * Returns the updated WebGLBuffer.
  30024. */
  30025. VertexBuffer.prototype.update = function (data) {
  30026. return this._buffer.update(data);
  30027. };
  30028. /**
  30029. * Updates directly the underlying WebGLBuffer according to the passed numeric array or Float32Array.
  30030. * Returns the directly updated WebGLBuffer.
  30031. * @param data the new data
  30032. * @param offset the new offset
  30033. * @param useBytes set to true if the offset is in bytes
  30034. */
  30035. VertexBuffer.prototype.updateDirectly = function (data, offset, useBytes) {
  30036. if (useBytes === void 0) { useBytes = false; }
  30037. this._buffer.updateDirectly(data, offset, undefined, useBytes);
  30038. };
  30039. /**
  30040. * Disposes the VertexBuffer and the underlying WebGLBuffer.
  30041. */
  30042. VertexBuffer.prototype.dispose = function () {
  30043. if (this._ownsBuffer) {
  30044. this._buffer.dispose();
  30045. }
  30046. };
  30047. /**
  30048. * Enumerates each value of this vertex buffer as numbers.
  30049. * @param count the number of values to enumerate
  30050. * @param callback the callback function called for each value
  30051. */
  30052. VertexBuffer.prototype.forEach = function (count, callback) {
  30053. VertexBuffer.ForEach(this._buffer.getData(), this.byteOffset, this.byteStride, this._size, this.type, count, this.normalized, callback);
  30054. };
  30055. Object.defineProperty(VertexBuffer, "PositionKind", {
  30056. get: function () {
  30057. return VertexBuffer._PositionKind;
  30058. },
  30059. enumerable: true,
  30060. configurable: true
  30061. });
  30062. Object.defineProperty(VertexBuffer, "NormalKind", {
  30063. get: function () {
  30064. return VertexBuffer._NormalKind;
  30065. },
  30066. enumerable: true,
  30067. configurable: true
  30068. });
  30069. Object.defineProperty(VertexBuffer, "TangentKind", {
  30070. get: function () {
  30071. return VertexBuffer._TangentKind;
  30072. },
  30073. enumerable: true,
  30074. configurable: true
  30075. });
  30076. Object.defineProperty(VertexBuffer, "UVKind", {
  30077. get: function () {
  30078. return VertexBuffer._UVKind;
  30079. },
  30080. enumerable: true,
  30081. configurable: true
  30082. });
  30083. Object.defineProperty(VertexBuffer, "UV2Kind", {
  30084. get: function () {
  30085. return VertexBuffer._UV2Kind;
  30086. },
  30087. enumerable: true,
  30088. configurable: true
  30089. });
  30090. Object.defineProperty(VertexBuffer, "UV3Kind", {
  30091. get: function () {
  30092. return VertexBuffer._UV3Kind;
  30093. },
  30094. enumerable: true,
  30095. configurable: true
  30096. });
  30097. Object.defineProperty(VertexBuffer, "UV4Kind", {
  30098. get: function () {
  30099. return VertexBuffer._UV4Kind;
  30100. },
  30101. enumerable: true,
  30102. configurable: true
  30103. });
  30104. Object.defineProperty(VertexBuffer, "UV5Kind", {
  30105. get: function () {
  30106. return VertexBuffer._UV5Kind;
  30107. },
  30108. enumerable: true,
  30109. configurable: true
  30110. });
  30111. Object.defineProperty(VertexBuffer, "UV6Kind", {
  30112. get: function () {
  30113. return VertexBuffer._UV6Kind;
  30114. },
  30115. enumerable: true,
  30116. configurable: true
  30117. });
  30118. Object.defineProperty(VertexBuffer, "ColorKind", {
  30119. get: function () {
  30120. return VertexBuffer._ColorKind;
  30121. },
  30122. enumerable: true,
  30123. configurable: true
  30124. });
  30125. Object.defineProperty(VertexBuffer, "MatricesIndicesKind", {
  30126. get: function () {
  30127. return VertexBuffer._MatricesIndicesKind;
  30128. },
  30129. enumerable: true,
  30130. configurable: true
  30131. });
  30132. Object.defineProperty(VertexBuffer, "MatricesWeightsKind", {
  30133. get: function () {
  30134. return VertexBuffer._MatricesWeightsKind;
  30135. },
  30136. enumerable: true,
  30137. configurable: true
  30138. });
  30139. Object.defineProperty(VertexBuffer, "MatricesIndicesExtraKind", {
  30140. get: function () {
  30141. return VertexBuffer._MatricesIndicesExtraKind;
  30142. },
  30143. enumerable: true,
  30144. configurable: true
  30145. });
  30146. Object.defineProperty(VertexBuffer, "MatricesWeightsExtraKind", {
  30147. get: function () {
  30148. return VertexBuffer._MatricesWeightsExtraKind;
  30149. },
  30150. enumerable: true,
  30151. configurable: true
  30152. });
  30153. /**
  30154. * Deduces the stride given a kind.
  30155. * @param kind The kind string to deduce
  30156. * @returns The deduced stride
  30157. */
  30158. VertexBuffer.DeduceStride = function (kind) {
  30159. switch (kind) {
  30160. case VertexBuffer.UVKind:
  30161. case VertexBuffer.UV2Kind:
  30162. case VertexBuffer.UV3Kind:
  30163. case VertexBuffer.UV4Kind:
  30164. case VertexBuffer.UV5Kind:
  30165. case VertexBuffer.UV6Kind:
  30166. return 2;
  30167. case VertexBuffer.NormalKind:
  30168. case VertexBuffer.PositionKind:
  30169. return 3;
  30170. case VertexBuffer.ColorKind:
  30171. case VertexBuffer.MatricesIndicesKind:
  30172. case VertexBuffer.MatricesIndicesExtraKind:
  30173. case VertexBuffer.MatricesWeightsKind:
  30174. case VertexBuffer.MatricesWeightsExtraKind:
  30175. case VertexBuffer.TangentKind:
  30176. return 4;
  30177. default:
  30178. throw new Error("Invalid kind '" + kind + "'");
  30179. }
  30180. };
  30181. /**
  30182. * Gets the byte length of the given type.
  30183. * @param type the type
  30184. * @returns the number of bytes
  30185. */
  30186. VertexBuffer.GetTypeByteLength = function (type) {
  30187. switch (type) {
  30188. case VertexBuffer.BYTE:
  30189. case VertexBuffer.UNSIGNED_BYTE:
  30190. return 1;
  30191. case VertexBuffer.SHORT:
  30192. case VertexBuffer.UNSIGNED_SHORT:
  30193. return 2;
  30194. case VertexBuffer.INT:
  30195. case VertexBuffer.FLOAT:
  30196. return 4;
  30197. default:
  30198. throw new Error("Invalid type '" + type + "'");
  30199. }
  30200. };
  30201. /**
  30202. * Enumerates each value of the given parameters as numbers.
  30203. * @param data the data to enumerate
  30204. * @param byteOffset the byte offset of the data
  30205. * @param byteStride the byte stride of the data
  30206. * @param componentCount the number of components per element
  30207. * @param componentType the type of the component
  30208. * @param count the total number of components
  30209. * @param normalized whether the data is normalized
  30210. * @param callback the callback function called for each value
  30211. */
  30212. VertexBuffer.ForEach = function (data, byteOffset, byteStride, componentCount, componentType, count, normalized, callback) {
  30213. if (data instanceof Array) {
  30214. var offset = byteOffset / 4;
  30215. var stride = byteStride / 4;
  30216. for (var index = 0; index < count; index += componentCount) {
  30217. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30218. callback(data[offset + componentIndex], index + componentIndex);
  30219. }
  30220. offset += stride;
  30221. }
  30222. }
  30223. else {
  30224. var dataView = data instanceof ArrayBuffer ? new DataView(data) : new DataView(data.buffer, data.byteOffset, data.byteLength);
  30225. var componentByteLength = VertexBuffer.GetTypeByteLength(componentType);
  30226. for (var index = 0; index < count; index += componentCount) {
  30227. var componentByteOffset = byteOffset;
  30228. for (var componentIndex = 0; componentIndex < componentCount; componentIndex++) {
  30229. var value = VertexBuffer._GetFloatValue(dataView, componentType, componentByteOffset, normalized);
  30230. callback(value, index + componentIndex);
  30231. componentByteOffset += componentByteLength;
  30232. }
  30233. byteOffset += byteStride;
  30234. }
  30235. }
  30236. };
  30237. VertexBuffer._GetFloatValue = function (dataView, type, byteOffset, normalized) {
  30238. switch (type) {
  30239. case VertexBuffer.BYTE: {
  30240. var value = dataView.getInt8(byteOffset);
  30241. if (normalized) {
  30242. value = Math.max(value / 127, -1);
  30243. }
  30244. return value;
  30245. }
  30246. case VertexBuffer.UNSIGNED_BYTE: {
  30247. var value = dataView.getUint8(byteOffset);
  30248. if (normalized) {
  30249. value = value / 255;
  30250. }
  30251. return value;
  30252. }
  30253. case VertexBuffer.SHORT: {
  30254. var value = dataView.getInt16(byteOffset, true);
  30255. if (normalized) {
  30256. value = Math.max(value / 16383, -1);
  30257. }
  30258. return value;
  30259. }
  30260. case VertexBuffer.UNSIGNED_SHORT: {
  30261. var value = dataView.getUint16(byteOffset, true);
  30262. if (normalized) {
  30263. value = value / 65535;
  30264. }
  30265. return value;
  30266. }
  30267. case VertexBuffer.FLOAT: {
  30268. return dataView.getFloat32(byteOffset, true);
  30269. }
  30270. default: {
  30271. throw new Error("Invalid component type " + type);
  30272. }
  30273. }
  30274. };
  30275. /**
  30276. * The byte type.
  30277. */
  30278. VertexBuffer.BYTE = 5120;
  30279. /**
  30280. * The unsigned byte type.
  30281. */
  30282. VertexBuffer.UNSIGNED_BYTE = 5121;
  30283. /**
  30284. * The short type.
  30285. */
  30286. VertexBuffer.SHORT = 5122;
  30287. /**
  30288. * The unsigned short type.
  30289. */
  30290. VertexBuffer.UNSIGNED_SHORT = 5123;
  30291. /**
  30292. * The integer type.
  30293. */
  30294. VertexBuffer.INT = 5124;
  30295. /**
  30296. * The unsigned integer type.
  30297. */
  30298. VertexBuffer.UNSIGNED_INT = 5125;
  30299. /**
  30300. * The float type.
  30301. */
  30302. VertexBuffer.FLOAT = 5126;
  30303. // Enums
  30304. VertexBuffer._PositionKind = "position";
  30305. VertexBuffer._NormalKind = "normal";
  30306. VertexBuffer._TangentKind = "tangent";
  30307. VertexBuffer._UVKind = "uv";
  30308. VertexBuffer._UV2Kind = "uv2";
  30309. VertexBuffer._UV3Kind = "uv3";
  30310. VertexBuffer._UV4Kind = "uv4";
  30311. VertexBuffer._UV5Kind = "uv5";
  30312. VertexBuffer._UV6Kind = "uv6";
  30313. VertexBuffer._ColorKind = "color";
  30314. VertexBuffer._MatricesIndicesKind = "matricesIndices";
  30315. VertexBuffer._MatricesWeightsKind = "matricesWeights";
  30316. VertexBuffer._MatricesIndicesExtraKind = "matricesIndicesExtra";
  30317. VertexBuffer._MatricesWeightsExtraKind = "matricesWeightsExtra";
  30318. return VertexBuffer;
  30319. }());
  30320. BABYLON.VertexBuffer = VertexBuffer;
  30321. })(BABYLON || (BABYLON = {}));
  30322. //# sourceMappingURL=babylon.vertexBuffer.js.map
  30323. var BABYLON;
  30324. (function (BABYLON) {
  30325. /**
  30326. * Internal class used by the engine to get list of {BABYLON.InternalTexture} already bound to the GL context
  30327. */
  30328. var DummyInternalTextureTracker = /** @class */ (function () {
  30329. function DummyInternalTextureTracker() {
  30330. /**
  30331. * Gets or set the previous tracker in the list
  30332. */
  30333. this.previous = null;
  30334. /**
  30335. * Gets or set the next tracker in the list
  30336. */
  30337. this.next = null;
  30338. }
  30339. return DummyInternalTextureTracker;
  30340. }());
  30341. BABYLON.DummyInternalTextureTracker = DummyInternalTextureTracker;
  30342. })(BABYLON || (BABYLON = {}));
  30343. //# sourceMappingURL=babylon.internalTextureTracker.js.map
  30344. var BABYLON;
  30345. (function (BABYLON) {
  30346. /**
  30347. * Class used to store data associated with WebGL texture data for the engine
  30348. * This class should not be used directly
  30349. */
  30350. var InternalTexture = /** @class */ (function () {
  30351. /**
  30352. * Creates a new InternalTexture
  30353. * @param engine defines the engine to use
  30354. * @param dataSource defines the type of data that will be used
  30355. */
  30356. function InternalTexture(engine, dataSource) {
  30357. /**
  30358. * Observable called when the texture is loaded
  30359. */
  30360. this.onLoadedObservable = new BABYLON.Observable();
  30361. /**
  30362. * Gets or set the previous tracker in the list
  30363. */
  30364. this.previous = null;
  30365. /**
  30366. * Gets or set the next tracker in the list
  30367. */
  30368. this.next = null;
  30369. // Private
  30370. /** @hidden */
  30371. this._initialSlot = -1;
  30372. /** @hidden */
  30373. this._designatedSlot = -1;
  30374. /** @hidden */
  30375. this._dataSource = InternalTexture.DATASOURCE_UNKNOWN;
  30376. /** @hidden */
  30377. this._comparisonFunction = 0;
  30378. /** @hidden */
  30379. this._lodGenerationScale = 0;
  30380. /** @hidden */
  30381. this._lodGenerationOffset = 0;
  30382. /** @hidden */
  30383. this._isRGBD = false;
  30384. /** @hidden */
  30385. this._references = 1;
  30386. this._engine = engine;
  30387. this._dataSource = dataSource;
  30388. this._webGLTexture = engine._createTexture();
  30389. }
  30390. /**
  30391. * Gets the Engine the texture belongs to.
  30392. * @returns The babylon engine
  30393. */
  30394. InternalTexture.prototype.getEngine = function () {
  30395. return this._engine;
  30396. };
  30397. Object.defineProperty(InternalTexture.prototype, "dataSource", {
  30398. /**
  30399. * Gets the data source type of the texture (can be one of the BABYLON.InternalTexture.DATASOURCE_XXXX)
  30400. */
  30401. get: function () {
  30402. return this._dataSource;
  30403. },
  30404. enumerable: true,
  30405. configurable: true
  30406. });
  30407. /**
  30408. * Increments the number of references (ie. the number of {BABYLON.Texture} that point to it)
  30409. */
  30410. InternalTexture.prototype.incrementReferences = function () {
  30411. this._references++;
  30412. };
  30413. /**
  30414. * Change the size of the texture (not the size of the content)
  30415. * @param width defines the new width
  30416. * @param height defines the new height
  30417. * @param depth defines the new depth (1 by default)
  30418. */
  30419. InternalTexture.prototype.updateSize = function (width, height, depth) {
  30420. if (depth === void 0) { depth = 1; }
  30421. this.width = width;
  30422. this.height = height;
  30423. this.depth = depth;
  30424. this.baseWidth = width;
  30425. this.baseHeight = height;
  30426. this.baseDepth = depth;
  30427. this._size = width * height * depth;
  30428. };
  30429. /** @hidden */
  30430. InternalTexture.prototype._rebuild = function () {
  30431. var _this = this;
  30432. var proxy;
  30433. this.isReady = false;
  30434. this._cachedCoordinatesMode = null;
  30435. this._cachedWrapU = null;
  30436. this._cachedWrapV = null;
  30437. this._cachedAnisotropicFilteringLevel = null;
  30438. switch (this._dataSource) {
  30439. case InternalTexture.DATASOURCE_TEMP:
  30440. return;
  30441. case InternalTexture.DATASOURCE_URL:
  30442. proxy = this._engine.createTexture(this.url, !this.generateMipMaps, this.invertY, null, this.samplingMode, function () {
  30443. _this.isReady = true;
  30444. }, null, this._buffer, undefined, this.format);
  30445. proxy._swapAndDie(this);
  30446. return;
  30447. case InternalTexture.DATASOURCE_RAW:
  30448. proxy = this._engine.createRawTexture(this._bufferView, this.baseWidth, this.baseHeight, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30449. proxy._swapAndDie(this);
  30450. this.isReady = true;
  30451. return;
  30452. case InternalTexture.DATASOURCE_RAW3D:
  30453. proxy = this._engine.createRawTexture3D(this._bufferView, this.baseWidth, this.baseHeight, this.baseDepth, this.format, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30454. proxy._swapAndDie(this);
  30455. this.isReady = true;
  30456. return;
  30457. case InternalTexture.DATASOURCE_DYNAMIC:
  30458. proxy = this._engine.createDynamicTexture(this.baseWidth, this.baseHeight, this.generateMipMaps, this.samplingMode);
  30459. proxy._swapAndDie(this);
  30460. // The engine will make sure to update content so no need to flag it as isReady = true
  30461. return;
  30462. case InternalTexture.DATASOURCE_RENDERTARGET:
  30463. var options = new BABYLON.RenderTargetCreationOptions();
  30464. options.generateDepthBuffer = this._generateDepthBuffer;
  30465. options.generateMipMaps = this.generateMipMaps;
  30466. options.generateStencilBuffer = this._generateStencilBuffer;
  30467. options.samplingMode = this.samplingMode;
  30468. options.type = this.type;
  30469. if (this.isCube) {
  30470. proxy = this._engine.createRenderTargetCubeTexture(this.width, options);
  30471. }
  30472. else {
  30473. var size = {
  30474. width: this.width,
  30475. height: this.height
  30476. };
  30477. proxy = this._engine.createRenderTargetTexture(size, options);
  30478. }
  30479. proxy._swapAndDie(this);
  30480. this.isReady = true;
  30481. return;
  30482. case InternalTexture.DATASOURCE_DEPTHTEXTURE:
  30483. var depthTextureOptions = {
  30484. bilinearFiltering: this.samplingMode !== BABYLON.Texture.BILINEAR_SAMPLINGMODE,
  30485. comparisonFunction: this._comparisonFunction,
  30486. generateStencil: this._generateStencilBuffer,
  30487. isCube: this.isCube
  30488. };
  30489. proxy = this._engine.createDepthStencilTexture({ width: this.width, height: this.height }, depthTextureOptions);
  30490. proxy._swapAndDie(this);
  30491. this.isReady = true;
  30492. return;
  30493. case InternalTexture.DATASOURCE_CUBE:
  30494. proxy = this._engine.createCubeTexture(this.url, null, this._files, !this.generateMipMaps, function () {
  30495. _this.isReady = true;
  30496. }, null, this.format, this._extension);
  30497. proxy._swapAndDie(this);
  30498. return;
  30499. case InternalTexture.DATASOURCE_CUBERAW:
  30500. proxy = this._engine.createRawCubeTexture(this._bufferViewArray, this.width, this.format, this.type, this.generateMipMaps, this.invertY, this.samplingMode, this._compression);
  30501. proxy._swapAndDie(this);
  30502. this.isReady = true;
  30503. return;
  30504. case InternalTexture.DATASOURCE_CUBEPREFILTERED:
  30505. proxy = this._engine.createPrefilteredCubeTexture(this.url, null, this._lodGenerationScale, this._lodGenerationOffset, function (proxy) {
  30506. if (proxy) {
  30507. proxy._swapAndDie(_this);
  30508. }
  30509. _this.isReady = true;
  30510. }, null, this.format, this._extension);
  30511. proxy._sphericalPolynomial = this._sphericalPolynomial;
  30512. return;
  30513. }
  30514. };
  30515. InternalTexture.prototype._swapAndDie = function (target) {
  30516. target._webGLTexture = this._webGLTexture;
  30517. if (this._framebuffer) {
  30518. target._framebuffer = this._framebuffer;
  30519. }
  30520. if (this._depthStencilBuffer) {
  30521. target._depthStencilBuffer = this._depthStencilBuffer;
  30522. }
  30523. if (this._lodTextureHigh) {
  30524. if (target._lodTextureHigh) {
  30525. target._lodTextureHigh.dispose();
  30526. }
  30527. target._lodTextureHigh = this._lodTextureHigh;
  30528. }
  30529. if (this._lodTextureMid) {
  30530. if (target._lodTextureMid) {
  30531. target._lodTextureMid.dispose();
  30532. }
  30533. target._lodTextureMid = this._lodTextureMid;
  30534. }
  30535. if (this._lodTextureLow) {
  30536. if (target._lodTextureLow) {
  30537. target._lodTextureLow.dispose();
  30538. }
  30539. target._lodTextureLow = this._lodTextureLow;
  30540. }
  30541. var cache = this._engine.getLoadedTexturesCache();
  30542. var index = cache.indexOf(this);
  30543. if (index !== -1) {
  30544. cache.splice(index, 1);
  30545. }
  30546. };
  30547. /**
  30548. * Dispose the current allocated resources
  30549. */
  30550. InternalTexture.prototype.dispose = function () {
  30551. if (!this._webGLTexture) {
  30552. return;
  30553. }
  30554. this._references--;
  30555. if (this._references === 0) {
  30556. this._engine._releaseTexture(this);
  30557. this._webGLTexture = null;
  30558. this.previous = null;
  30559. this.next = null;
  30560. }
  30561. };
  30562. /**
  30563. * The source of the texture data is unknown
  30564. */
  30565. InternalTexture.DATASOURCE_UNKNOWN = 0;
  30566. /**
  30567. * Texture data comes from an URL
  30568. */
  30569. InternalTexture.DATASOURCE_URL = 1;
  30570. /**
  30571. * Texture data is only used for temporary storage
  30572. */
  30573. InternalTexture.DATASOURCE_TEMP = 2;
  30574. /**
  30575. * Texture data comes from raw data (ArrayBuffer)
  30576. */
  30577. InternalTexture.DATASOURCE_RAW = 3;
  30578. /**
  30579. * Texture content is dynamic (video or dynamic texture)
  30580. */
  30581. InternalTexture.DATASOURCE_DYNAMIC = 4;
  30582. /**
  30583. * Texture content is generated by rendering to it
  30584. */
  30585. InternalTexture.DATASOURCE_RENDERTARGET = 5;
  30586. /**
  30587. * Texture content is part of a multi render target process
  30588. */
  30589. InternalTexture.DATASOURCE_MULTIRENDERTARGET = 6;
  30590. /**
  30591. * Texture data comes from a cube data file
  30592. */
  30593. InternalTexture.DATASOURCE_CUBE = 7;
  30594. /**
  30595. * Texture data comes from a raw cube data
  30596. */
  30597. InternalTexture.DATASOURCE_CUBERAW = 8;
  30598. /**
  30599. * Texture data come from a prefiltered cube data file
  30600. */
  30601. InternalTexture.DATASOURCE_CUBEPREFILTERED = 9;
  30602. /**
  30603. * Texture content is raw 3D data
  30604. */
  30605. InternalTexture.DATASOURCE_RAW3D = 10;
  30606. /**
  30607. * Texture content is a depth texture
  30608. */
  30609. InternalTexture.DATASOURCE_DEPTHTEXTURE = 11;
  30610. return InternalTexture;
  30611. }());
  30612. BABYLON.InternalTexture = InternalTexture;
  30613. })(BABYLON || (BABYLON = {}));
  30614. //# sourceMappingURL=babylon.internalTexture.js.map
  30615. var BABYLON;
  30616. (function (BABYLON) {
  30617. var BaseTexture = /** @class */ (function () {
  30618. function BaseTexture(scene) {
  30619. this._hasAlpha = false;
  30620. this.getAlphaFromRGB = false;
  30621. this.level = 1;
  30622. this.coordinatesIndex = 0;
  30623. this._coordinatesMode = BABYLON.Texture.EXPLICIT_MODE;
  30624. /**
  30625. * | Value | Type | Description |
  30626. * | ----- | ------------------ | ----------- |
  30627. * | 0 | CLAMP_ADDRESSMODE | |
  30628. * | 1 | WRAP_ADDRESSMODE | |
  30629. * | 2 | MIRROR_ADDRESSMODE | |
  30630. */
  30631. this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  30632. /**
  30633. * | Value | Type | Description |
  30634. * | ----- | ------------------ | ----------- |
  30635. * | 0 | CLAMP_ADDRESSMODE | |
  30636. * | 1 | WRAP_ADDRESSMODE | |
  30637. * | 2 | MIRROR_ADDRESSMODE | |
  30638. */
  30639. this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  30640. /**
  30641. * | Value | Type | Description |
  30642. * | ----- | ------------------ | ----------- |
  30643. * | 0 | CLAMP_ADDRESSMODE | |
  30644. * | 1 | WRAP_ADDRESSMODE | |
  30645. * | 2 | MIRROR_ADDRESSMODE | |
  30646. */
  30647. this.wrapR = BABYLON.Texture.WRAP_ADDRESSMODE;
  30648. this.anisotropicFilteringLevel = BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL;
  30649. this.isCube = false;
  30650. this.is3D = false;
  30651. this.gammaSpace = true;
  30652. this.invertZ = false;
  30653. this.lodLevelInAlpha = false;
  30654. this.isRenderTarget = false;
  30655. this.animations = new Array();
  30656. /**
  30657. * An event triggered when the texture is disposed.
  30658. */
  30659. this.onDisposeObservable = new BABYLON.Observable();
  30660. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  30661. this._cachedSize = BABYLON.Size.Zero();
  30662. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  30663. if (this._scene) {
  30664. this._scene.textures.push(this);
  30665. }
  30666. this._uid = null;
  30667. }
  30668. Object.defineProperty(BaseTexture.prototype, "hasAlpha", {
  30669. get: function () {
  30670. return this._hasAlpha;
  30671. },
  30672. set: function (value) {
  30673. if (this._hasAlpha === value) {
  30674. return;
  30675. }
  30676. this._hasAlpha = value;
  30677. if (this._scene) {
  30678. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  30679. }
  30680. },
  30681. enumerable: true,
  30682. configurable: true
  30683. });
  30684. Object.defineProperty(BaseTexture.prototype, "coordinatesMode", {
  30685. get: function () {
  30686. return this._coordinatesMode;
  30687. },
  30688. /**
  30689. * How a texture is mapped.
  30690. *
  30691. * | Value | Type | Description |
  30692. * | ----- | ----------------------------------- | ----------- |
  30693. * | 0 | EXPLICIT_MODE | |
  30694. * | 1 | SPHERICAL_MODE | |
  30695. * | 2 | PLANAR_MODE | |
  30696. * | 3 | CUBIC_MODE | |
  30697. * | 4 | PROJECTION_MODE | |
  30698. * | 5 | SKYBOX_MODE | |
  30699. * | 6 | INVCUBIC_MODE | |
  30700. * | 7 | EQUIRECTANGULAR_MODE | |
  30701. * | 8 | FIXED_EQUIRECTANGULAR_MODE | |
  30702. * | 9 | FIXED_EQUIRECTANGULAR_MIRRORED_MODE | |
  30703. */
  30704. set: function (value) {
  30705. if (this._coordinatesMode === value) {
  30706. return;
  30707. }
  30708. this._coordinatesMode = value;
  30709. if (this._scene) {
  30710. this._scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  30711. }
  30712. },
  30713. enumerable: true,
  30714. configurable: true
  30715. });
  30716. Object.defineProperty(BaseTexture.prototype, "isRGBD", {
  30717. /**
  30718. * Gets whether or not the texture contains RGBD data.
  30719. */
  30720. get: function () {
  30721. return this._texture != null && this._texture._isRGBD;
  30722. },
  30723. enumerable: true,
  30724. configurable: true
  30725. });
  30726. Object.defineProperty(BaseTexture.prototype, "lodGenerationOffset", {
  30727. get: function () {
  30728. if (this._texture)
  30729. return this._texture._lodGenerationOffset;
  30730. return 0.0;
  30731. },
  30732. set: function (value) {
  30733. if (this._texture)
  30734. this._texture._lodGenerationOffset = value;
  30735. },
  30736. enumerable: true,
  30737. configurable: true
  30738. });
  30739. Object.defineProperty(BaseTexture.prototype, "lodGenerationScale", {
  30740. get: function () {
  30741. if (this._texture)
  30742. return this._texture._lodGenerationScale;
  30743. return 0.0;
  30744. },
  30745. set: function (value) {
  30746. if (this._texture)
  30747. this._texture._lodGenerationScale = value;
  30748. },
  30749. enumerable: true,
  30750. configurable: true
  30751. });
  30752. Object.defineProperty(BaseTexture.prototype, "uid", {
  30753. get: function () {
  30754. if (!this._uid) {
  30755. this._uid = BABYLON.Tools.RandomId();
  30756. }
  30757. return this._uid;
  30758. },
  30759. enumerable: true,
  30760. configurable: true
  30761. });
  30762. BaseTexture.prototype.toString = function () {
  30763. return this.name;
  30764. };
  30765. BaseTexture.prototype.getClassName = function () {
  30766. return "BaseTexture";
  30767. };
  30768. Object.defineProperty(BaseTexture.prototype, "onDispose", {
  30769. set: function (callback) {
  30770. if (this._onDisposeObserver) {
  30771. this.onDisposeObservable.remove(this._onDisposeObserver);
  30772. }
  30773. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  30774. },
  30775. enumerable: true,
  30776. configurable: true
  30777. });
  30778. Object.defineProperty(BaseTexture.prototype, "isBlocking", {
  30779. get: function () {
  30780. return true;
  30781. },
  30782. enumerable: true,
  30783. configurable: true
  30784. });
  30785. BaseTexture.prototype.getScene = function () {
  30786. return this._scene;
  30787. };
  30788. BaseTexture.prototype.getTextureMatrix = function () {
  30789. return BABYLON.Matrix.IdentityReadOnly;
  30790. };
  30791. BaseTexture.prototype.getReflectionTextureMatrix = function () {
  30792. return BABYLON.Matrix.IdentityReadOnly;
  30793. };
  30794. BaseTexture.prototype.getInternalTexture = function () {
  30795. return this._texture;
  30796. };
  30797. BaseTexture.prototype.isReadyOrNotBlocking = function () {
  30798. return !this.isBlocking || this.isReady();
  30799. };
  30800. BaseTexture.prototype.isReady = function () {
  30801. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  30802. this.delayLoad();
  30803. return false;
  30804. }
  30805. if (this._texture) {
  30806. return this._texture.isReady;
  30807. }
  30808. return false;
  30809. };
  30810. BaseTexture.prototype.getSize = function () {
  30811. if (this._texture) {
  30812. if (this._texture.width) {
  30813. this._cachedSize.width = this._texture.width;
  30814. this._cachedSize.height = this._texture.height;
  30815. return this._cachedSize;
  30816. }
  30817. if (this._texture._size) {
  30818. this._cachedSize.width = this._texture._size;
  30819. this._cachedSize.height = this._texture._size;
  30820. return this._cachedSize;
  30821. }
  30822. }
  30823. return this._cachedSize;
  30824. };
  30825. BaseTexture.prototype.getBaseSize = function () {
  30826. if (!this.isReady() || !this._texture)
  30827. return BABYLON.Size.Zero();
  30828. if (this._texture._size) {
  30829. return new BABYLON.Size(this._texture._size, this._texture._size);
  30830. }
  30831. return new BABYLON.Size(this._texture.baseWidth, this._texture.baseHeight);
  30832. };
  30833. BaseTexture.prototype.scale = function (ratio) {
  30834. };
  30835. Object.defineProperty(BaseTexture.prototype, "canRescale", {
  30836. get: function () {
  30837. return false;
  30838. },
  30839. enumerable: true,
  30840. configurable: true
  30841. });
  30842. BaseTexture.prototype._getFromCache = function (url, noMipmap, sampling) {
  30843. if (!this._scene) {
  30844. return null;
  30845. }
  30846. var texturesCache = this._scene.getEngine().getLoadedTexturesCache();
  30847. for (var index = 0; index < texturesCache.length; index++) {
  30848. var texturesCacheEntry = texturesCache[index];
  30849. if (texturesCacheEntry.url === url && texturesCacheEntry.generateMipMaps === !noMipmap) {
  30850. if (!sampling || sampling === texturesCacheEntry.samplingMode) {
  30851. texturesCacheEntry.incrementReferences();
  30852. return texturesCacheEntry;
  30853. }
  30854. }
  30855. }
  30856. return null;
  30857. };
  30858. BaseTexture.prototype._rebuild = function () {
  30859. };
  30860. BaseTexture.prototype.delayLoad = function () {
  30861. };
  30862. BaseTexture.prototype.clone = function () {
  30863. return null;
  30864. };
  30865. Object.defineProperty(BaseTexture.prototype, "textureType", {
  30866. get: function () {
  30867. if (!this._texture) {
  30868. return BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30869. }
  30870. return (this._texture.type !== undefined) ? this._texture.type : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  30871. },
  30872. enumerable: true,
  30873. configurable: true
  30874. });
  30875. Object.defineProperty(BaseTexture.prototype, "textureFormat", {
  30876. get: function () {
  30877. if (!this._texture) {
  30878. return BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30879. }
  30880. return (this._texture.format !== undefined) ? this._texture.format : BABYLON.Engine.TEXTUREFORMAT_RGBA;
  30881. },
  30882. enumerable: true,
  30883. configurable: true
  30884. });
  30885. /**
  30886. * Reads the pixels stored in the webgl texture and returns them as an ArrayBuffer.
  30887. * This will returns an RGBA array buffer containing either in values (0-255) or
  30888. * float values (0-1) depending of the underlying buffer type.
  30889. * @param faceIndex The face of the texture to read (in case of cube texture)
  30890. * @param level The LOD level of the texture to read (in case of Mip Maps)
  30891. * @returns The Array buffer containing the pixels data.
  30892. */
  30893. BaseTexture.prototype.readPixels = function (faceIndex, level) {
  30894. if (faceIndex === void 0) { faceIndex = 0; }
  30895. if (level === void 0) { level = 0; }
  30896. if (!this._texture) {
  30897. return null;
  30898. }
  30899. var size = this.getSize();
  30900. var width = size.width;
  30901. var height = size.height;
  30902. var scene = this.getScene();
  30903. if (!scene) {
  30904. return null;
  30905. }
  30906. var engine = scene.getEngine();
  30907. if (level != 0) {
  30908. width = width / Math.pow(2, level);
  30909. height = height / Math.pow(2, level);
  30910. width = Math.round(width);
  30911. height = Math.round(height);
  30912. }
  30913. if (this._texture.isCube) {
  30914. return engine._readTexturePixels(this._texture, width, height, faceIndex, level);
  30915. }
  30916. return engine._readTexturePixels(this._texture, width, height, -1, level);
  30917. };
  30918. BaseTexture.prototype.releaseInternalTexture = function () {
  30919. if (this._texture) {
  30920. this._texture.dispose();
  30921. this._texture = null;
  30922. }
  30923. };
  30924. Object.defineProperty(BaseTexture.prototype, "sphericalPolynomial", {
  30925. get: function () {
  30926. if (!this._texture || !BABYLON.CubeMapToSphericalPolynomialTools || !this.isReady()) {
  30927. return null;
  30928. }
  30929. if (!this._texture._sphericalPolynomial) {
  30930. this._texture._sphericalPolynomial =
  30931. BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial(this);
  30932. }
  30933. return this._texture._sphericalPolynomial;
  30934. },
  30935. set: function (value) {
  30936. if (this._texture) {
  30937. this._texture._sphericalPolynomial = value;
  30938. }
  30939. },
  30940. enumerable: true,
  30941. configurable: true
  30942. });
  30943. Object.defineProperty(BaseTexture.prototype, "_lodTextureHigh", {
  30944. get: function () {
  30945. if (this._texture) {
  30946. return this._texture._lodTextureHigh;
  30947. }
  30948. return null;
  30949. },
  30950. enumerable: true,
  30951. configurable: true
  30952. });
  30953. Object.defineProperty(BaseTexture.prototype, "_lodTextureMid", {
  30954. get: function () {
  30955. if (this._texture) {
  30956. return this._texture._lodTextureMid;
  30957. }
  30958. return null;
  30959. },
  30960. enumerable: true,
  30961. configurable: true
  30962. });
  30963. Object.defineProperty(BaseTexture.prototype, "_lodTextureLow", {
  30964. get: function () {
  30965. if (this._texture) {
  30966. return this._texture._lodTextureLow;
  30967. }
  30968. return null;
  30969. },
  30970. enumerable: true,
  30971. configurable: true
  30972. });
  30973. BaseTexture.prototype.dispose = function () {
  30974. if (!this._scene) {
  30975. return;
  30976. }
  30977. // Animations
  30978. this._scene.stopAnimation(this);
  30979. // Remove from scene
  30980. this._scene._removePendingData(this);
  30981. var index = this._scene.textures.indexOf(this);
  30982. if (index >= 0) {
  30983. this._scene.textures.splice(index, 1);
  30984. }
  30985. if (this._texture === undefined) {
  30986. return;
  30987. }
  30988. // Release
  30989. this.releaseInternalTexture();
  30990. // Callback
  30991. this.onDisposeObservable.notifyObservers(this);
  30992. this.onDisposeObservable.clear();
  30993. };
  30994. BaseTexture.prototype.serialize = function () {
  30995. if (!this.name) {
  30996. return null;
  30997. }
  30998. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  30999. // Animations
  31000. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  31001. return serializationObject;
  31002. };
  31003. BaseTexture.WhenAllReady = function (textures, callback) {
  31004. var numRemaining = textures.length;
  31005. if (numRemaining === 0) {
  31006. callback();
  31007. return;
  31008. }
  31009. var _loop_1 = function () {
  31010. texture = textures[i];
  31011. if (texture.isReady()) {
  31012. if (--numRemaining === 0) {
  31013. callback();
  31014. }
  31015. }
  31016. else {
  31017. onLoadObservable = texture.onLoadObservable;
  31018. var onLoadCallback_1 = function () {
  31019. onLoadObservable.removeCallback(onLoadCallback_1);
  31020. if (--numRemaining === 0) {
  31021. callback();
  31022. }
  31023. };
  31024. onLoadObservable.add(onLoadCallback_1);
  31025. }
  31026. };
  31027. var texture, onLoadObservable;
  31028. for (var i = 0; i < textures.length; i++) {
  31029. _loop_1();
  31030. }
  31031. };
  31032. BaseTexture.DEFAULT_ANISOTROPIC_FILTERING_LEVEL = 4;
  31033. __decorate([
  31034. BABYLON.serialize()
  31035. ], BaseTexture.prototype, "name", void 0);
  31036. __decorate([
  31037. BABYLON.serialize("hasAlpha")
  31038. ], BaseTexture.prototype, "_hasAlpha", void 0);
  31039. __decorate([
  31040. BABYLON.serialize()
  31041. ], BaseTexture.prototype, "getAlphaFromRGB", void 0);
  31042. __decorate([
  31043. BABYLON.serialize()
  31044. ], BaseTexture.prototype, "level", void 0);
  31045. __decorate([
  31046. BABYLON.serialize()
  31047. ], BaseTexture.prototype, "coordinatesIndex", void 0);
  31048. __decorate([
  31049. BABYLON.serialize("coordinatesMode")
  31050. ], BaseTexture.prototype, "_coordinatesMode", void 0);
  31051. __decorate([
  31052. BABYLON.serialize()
  31053. ], BaseTexture.prototype, "wrapU", void 0);
  31054. __decorate([
  31055. BABYLON.serialize()
  31056. ], BaseTexture.prototype, "wrapV", void 0);
  31057. __decorate([
  31058. BABYLON.serialize()
  31059. ], BaseTexture.prototype, "wrapR", void 0);
  31060. __decorate([
  31061. BABYLON.serialize()
  31062. ], BaseTexture.prototype, "anisotropicFilteringLevel", void 0);
  31063. __decorate([
  31064. BABYLON.serialize()
  31065. ], BaseTexture.prototype, "isCube", void 0);
  31066. __decorate([
  31067. BABYLON.serialize()
  31068. ], BaseTexture.prototype, "is3D", void 0);
  31069. __decorate([
  31070. BABYLON.serialize()
  31071. ], BaseTexture.prototype, "gammaSpace", void 0);
  31072. __decorate([
  31073. BABYLON.serialize()
  31074. ], BaseTexture.prototype, "invertZ", void 0);
  31075. __decorate([
  31076. BABYLON.serialize()
  31077. ], BaseTexture.prototype, "lodLevelInAlpha", void 0);
  31078. __decorate([
  31079. BABYLON.serialize()
  31080. ], BaseTexture.prototype, "lodGenerationOffset", null);
  31081. __decorate([
  31082. BABYLON.serialize()
  31083. ], BaseTexture.prototype, "lodGenerationScale", null);
  31084. __decorate([
  31085. BABYLON.serialize()
  31086. ], BaseTexture.prototype, "isRenderTarget", void 0);
  31087. return BaseTexture;
  31088. }());
  31089. BABYLON.BaseTexture = BaseTexture;
  31090. })(BABYLON || (BABYLON = {}));
  31091. //# sourceMappingURL=babylon.baseTexture.js.map
  31092. var BABYLON;
  31093. (function (BABYLON) {
  31094. var Texture = /** @class */ (function (_super) {
  31095. __extends(Texture, _super);
  31096. function Texture(url, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format) {
  31097. if (noMipmap === void 0) { noMipmap = false; }
  31098. if (invertY === void 0) { invertY = true; }
  31099. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31100. if (onLoad === void 0) { onLoad = null; }
  31101. if (onError === void 0) { onError = null; }
  31102. if (buffer === void 0) { buffer = null; }
  31103. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31104. var _this = _super.call(this, scene) || this;
  31105. _this.uOffset = 0;
  31106. _this.vOffset = 0;
  31107. _this.uScale = 1.0;
  31108. _this.vScale = 1.0;
  31109. _this.uAng = 0;
  31110. _this.vAng = 0;
  31111. _this.wAng = 0;
  31112. /**
  31113. * Defines the center of rotation (U)
  31114. */
  31115. _this.uRotationCenter = 0.5;
  31116. /**
  31117. * Defines the center of rotation (V)
  31118. */
  31119. _this.vRotationCenter = 0.5;
  31120. /**
  31121. * Defines the center of rotation (W)
  31122. */
  31123. _this.wRotationCenter = 0.5;
  31124. _this._isBlocking = true;
  31125. _this.name = url || "";
  31126. _this.url = url;
  31127. _this._noMipmap = noMipmap;
  31128. _this._invertY = invertY;
  31129. _this._samplingMode = samplingMode;
  31130. _this._buffer = buffer;
  31131. _this._deleteBuffer = deleteBuffer;
  31132. if (format) {
  31133. _this._format = format;
  31134. }
  31135. scene = _this.getScene();
  31136. if (!scene) {
  31137. return _this;
  31138. }
  31139. scene.getEngine().onBeforeTextureInitObservable.notifyObservers(_this);
  31140. var load = function () {
  31141. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  31142. _this.onLoadObservable.notifyObservers(_this);
  31143. }
  31144. if (onLoad) {
  31145. onLoad();
  31146. }
  31147. if (!_this.isBlocking && scene) {
  31148. scene.resetCachedMaterial();
  31149. }
  31150. };
  31151. if (!_this.url) {
  31152. _this._delayedOnLoad = load;
  31153. _this._delayedOnError = onError;
  31154. return _this;
  31155. }
  31156. _this._texture = _this._getFromCache(_this.url, noMipmap, samplingMode);
  31157. if (!_this._texture) {
  31158. if (!scene.useDelayedTextureLoading) {
  31159. _this._texture = scene.getEngine().createTexture(_this.url, noMipmap, invertY, scene, _this._samplingMode, load, onError, _this._buffer, undefined, _this._format);
  31160. if (deleteBuffer) {
  31161. delete _this._buffer;
  31162. }
  31163. }
  31164. else {
  31165. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31166. _this._delayedOnLoad = load;
  31167. _this._delayedOnError = onError;
  31168. }
  31169. }
  31170. else {
  31171. if (_this._texture.isReady) {
  31172. BABYLON.Tools.SetImmediate(function () { return load(); });
  31173. }
  31174. else {
  31175. _this._texture.onLoadedObservable.add(load);
  31176. }
  31177. }
  31178. return _this;
  31179. }
  31180. Object.defineProperty(Texture.prototype, "noMipmap", {
  31181. get: function () {
  31182. return this._noMipmap;
  31183. },
  31184. enumerable: true,
  31185. configurable: true
  31186. });
  31187. Object.defineProperty(Texture.prototype, "isBlocking", {
  31188. get: function () {
  31189. return this._isBlocking;
  31190. },
  31191. set: function (value) {
  31192. this._isBlocking = value;
  31193. },
  31194. enumerable: true,
  31195. configurable: true
  31196. });
  31197. Object.defineProperty(Texture.prototype, "samplingMode", {
  31198. get: function () {
  31199. return this._samplingMode;
  31200. },
  31201. enumerable: true,
  31202. configurable: true
  31203. });
  31204. /**
  31205. * Update the url (and optional buffer) of this texture if url was null during construction.
  31206. * @param url the url of the texture
  31207. * @param buffer the buffer of the texture (defaults to null)
  31208. */
  31209. Texture.prototype.updateURL = function (url, buffer) {
  31210. if (buffer === void 0) { buffer = null; }
  31211. if (this.url) {
  31212. throw new Error("URL is already set");
  31213. }
  31214. this.url = url;
  31215. this._buffer = buffer;
  31216. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  31217. this.delayLoad();
  31218. };
  31219. Texture.prototype.delayLoad = function () {
  31220. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  31221. return;
  31222. }
  31223. var scene = this.getScene();
  31224. if (!scene) {
  31225. return;
  31226. }
  31227. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  31228. this._texture = this._getFromCache(this.url, this._noMipmap, this._samplingMode);
  31229. if (!this._texture) {
  31230. this._texture = scene.getEngine().createTexture(this.url, this._noMipmap, this._invertY, scene, this._samplingMode, this._delayedOnLoad, this._delayedOnError, this._buffer, null, this._format);
  31231. if (this._deleteBuffer) {
  31232. delete this._buffer;
  31233. }
  31234. }
  31235. else {
  31236. if (this._delayedOnLoad) {
  31237. if (this._texture.isReady) {
  31238. BABYLON.Tools.SetImmediate(this._delayedOnLoad);
  31239. }
  31240. else {
  31241. this._texture.onLoadedObservable.add(this._delayedOnLoad);
  31242. }
  31243. }
  31244. }
  31245. this._delayedOnLoad = null;
  31246. this._delayedOnError = null;
  31247. };
  31248. Texture.prototype.updateSamplingMode = function (samplingMode) {
  31249. if (!this._texture) {
  31250. return;
  31251. }
  31252. var scene = this.getScene();
  31253. if (!scene) {
  31254. return;
  31255. }
  31256. this._samplingMode = samplingMode;
  31257. scene.getEngine().updateTextureSamplingMode(samplingMode, this._texture);
  31258. };
  31259. Texture.prototype._prepareRowForTextureGeneration = function (x, y, z, t) {
  31260. x *= this.uScale;
  31261. y *= this.vScale;
  31262. x -= this.uRotationCenter * this.uScale;
  31263. y -= this.vRotationCenter * this.vScale;
  31264. z -= this.wRotationCenter;
  31265. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, y, z, this._rowGenerationMatrix, t);
  31266. t.x += this.uRotationCenter * this.uScale + this.uOffset;
  31267. t.y += this.vRotationCenter * this.vScale + this.vOffset;
  31268. t.z += this.wRotationCenter;
  31269. };
  31270. Texture.prototype.getTextureMatrix = function () {
  31271. var _this = this;
  31272. if (this.uOffset === this._cachedUOffset &&
  31273. this.vOffset === this._cachedVOffset &&
  31274. this.uScale === this._cachedUScale &&
  31275. this.vScale === this._cachedVScale &&
  31276. this.uAng === this._cachedUAng &&
  31277. this.vAng === this._cachedVAng &&
  31278. this.wAng === this._cachedWAng) {
  31279. return this._cachedTextureMatrix;
  31280. }
  31281. this._cachedUOffset = this.uOffset;
  31282. this._cachedVOffset = this.vOffset;
  31283. this._cachedUScale = this.uScale;
  31284. this._cachedVScale = this.vScale;
  31285. this._cachedUAng = this.uAng;
  31286. this._cachedVAng = this.vAng;
  31287. this._cachedWAng = this.wAng;
  31288. if (!this._cachedTextureMatrix) {
  31289. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31290. this._rowGenerationMatrix = new BABYLON.Matrix();
  31291. this._t0 = BABYLON.Vector3.Zero();
  31292. this._t1 = BABYLON.Vector3.Zero();
  31293. this._t2 = BABYLON.Vector3.Zero();
  31294. }
  31295. BABYLON.Matrix.RotationYawPitchRollToRef(this.vAng, this.uAng, this.wAng, this._rowGenerationMatrix);
  31296. this._prepareRowForTextureGeneration(0, 0, 0, this._t0);
  31297. this._prepareRowForTextureGeneration(1.0, 0, 0, this._t1);
  31298. this._prepareRowForTextureGeneration(0, 1.0, 0, this._t2);
  31299. this._t1.subtractInPlace(this._t0);
  31300. this._t2.subtractInPlace(this._t0);
  31301. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31302. this._cachedTextureMatrix.m[0] = this._t1.x;
  31303. this._cachedTextureMatrix.m[1] = this._t1.y;
  31304. this._cachedTextureMatrix.m[2] = this._t1.z;
  31305. this._cachedTextureMatrix.m[4] = this._t2.x;
  31306. this._cachedTextureMatrix.m[5] = this._t2.y;
  31307. this._cachedTextureMatrix.m[6] = this._t2.z;
  31308. this._cachedTextureMatrix.m[8] = this._t0.x;
  31309. this._cachedTextureMatrix.m[9] = this._t0.y;
  31310. this._cachedTextureMatrix.m[10] = this._t0.z;
  31311. var scene = this.getScene();
  31312. if (!scene) {
  31313. return this._cachedTextureMatrix;
  31314. }
  31315. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31316. return mat.hasTexture(_this);
  31317. });
  31318. return this._cachedTextureMatrix;
  31319. };
  31320. Texture.prototype.getReflectionTextureMatrix = function () {
  31321. var _this = this;
  31322. var scene = this.getScene();
  31323. if (!scene) {
  31324. return this._cachedTextureMatrix;
  31325. }
  31326. if (this.uOffset === this._cachedUOffset &&
  31327. this.vOffset === this._cachedVOffset &&
  31328. this.uScale === this._cachedUScale &&
  31329. this.vScale === this._cachedVScale &&
  31330. this.coordinatesMode === this._cachedCoordinatesMode) {
  31331. if (this.coordinatesMode === Texture.PROJECTION_MODE) {
  31332. if (this._cachedProjectionMatrixId === scene.getProjectionMatrix().updateFlag) {
  31333. return this._cachedTextureMatrix;
  31334. }
  31335. }
  31336. else {
  31337. return this._cachedTextureMatrix;
  31338. }
  31339. }
  31340. if (!this._cachedTextureMatrix) {
  31341. this._cachedTextureMatrix = BABYLON.Matrix.Zero();
  31342. }
  31343. if (!this._projectionModeMatrix) {
  31344. this._projectionModeMatrix = BABYLON.Matrix.Zero();
  31345. }
  31346. this._cachedUOffset = this.uOffset;
  31347. this._cachedVOffset = this.vOffset;
  31348. this._cachedUScale = this.uScale;
  31349. this._cachedVScale = this.vScale;
  31350. this._cachedCoordinatesMode = this.coordinatesMode;
  31351. switch (this.coordinatesMode) {
  31352. case Texture.PLANAR_MODE:
  31353. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31354. this._cachedTextureMatrix[0] = this.uScale;
  31355. this._cachedTextureMatrix[5] = this.vScale;
  31356. this._cachedTextureMatrix[12] = this.uOffset;
  31357. this._cachedTextureMatrix[13] = this.vOffset;
  31358. break;
  31359. case Texture.PROJECTION_MODE:
  31360. BABYLON.Matrix.IdentityToRef(this._projectionModeMatrix);
  31361. this._projectionModeMatrix.m[0] = 0.5;
  31362. this._projectionModeMatrix.m[5] = -0.5;
  31363. this._projectionModeMatrix.m[10] = 0.0;
  31364. this._projectionModeMatrix.m[12] = 0.5;
  31365. this._projectionModeMatrix.m[13] = 0.5;
  31366. this._projectionModeMatrix.m[14] = 1.0;
  31367. this._projectionModeMatrix.m[15] = 1.0;
  31368. var projectionMatrix = scene.getProjectionMatrix();
  31369. this._cachedProjectionMatrixId = projectionMatrix.updateFlag;
  31370. projectionMatrix.multiplyToRef(this._projectionModeMatrix, this._cachedTextureMatrix);
  31371. break;
  31372. default:
  31373. BABYLON.Matrix.IdentityToRef(this._cachedTextureMatrix);
  31374. break;
  31375. }
  31376. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag, function (mat) {
  31377. return (mat.getActiveTextures().indexOf(_this) !== -1);
  31378. });
  31379. return this._cachedTextureMatrix;
  31380. };
  31381. Texture.prototype.clone = function () {
  31382. var _this = this;
  31383. return BABYLON.SerializationHelper.Clone(function () {
  31384. return new Texture(_this._texture ? _this._texture.url : null, _this.getScene(), _this._noMipmap, _this._invertY, _this._samplingMode);
  31385. }, this);
  31386. };
  31387. Object.defineProperty(Texture.prototype, "onLoadObservable", {
  31388. get: function () {
  31389. if (!this._onLoadObservable) {
  31390. this._onLoadObservable = new BABYLON.Observable();
  31391. }
  31392. return this._onLoadObservable;
  31393. },
  31394. enumerable: true,
  31395. configurable: true
  31396. });
  31397. Texture.prototype.serialize = function () {
  31398. var serializationObject = _super.prototype.serialize.call(this);
  31399. if (typeof this._buffer === "string" && this._buffer.substr(0, 5) === "data:") {
  31400. serializationObject.base64String = this._buffer;
  31401. serializationObject.name = serializationObject.name.replace("data:", "");
  31402. }
  31403. serializationObject.invertY = this._invertY;
  31404. serializationObject.samplingMode = this.samplingMode;
  31405. return serializationObject;
  31406. };
  31407. Texture.prototype.getClassName = function () {
  31408. return "Texture";
  31409. };
  31410. Texture.prototype.dispose = function () {
  31411. _super.prototype.dispose.call(this);
  31412. if (this._onLoadObservable) {
  31413. this._onLoadObservable.clear();
  31414. this._onLoadObservable = null;
  31415. }
  31416. this._delayedOnLoad = null;
  31417. this._delayedOnError = null;
  31418. };
  31419. // Statics
  31420. Texture.CreateFromBase64String = function (data, name, scene, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31421. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31422. if (onLoad === void 0) { onLoad = null; }
  31423. if (onError === void 0) { onError = null; }
  31424. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31425. return new Texture("data:" + name, scene, noMipmap, invertY, samplingMode, onLoad, onError, data, false, format);
  31426. };
  31427. Texture.Parse = function (parsedTexture, scene, rootUrl) {
  31428. if (parsedTexture.customType) {
  31429. var customTexture = BABYLON.Tools.Instantiate(parsedTexture.customType);
  31430. // Update Sampling Mode
  31431. var parsedCustomTexture = customTexture.Parse(parsedTexture, scene, rootUrl);
  31432. if (parsedTexture.samplingMode && parsedCustomTexture.updateSamplingMode && parsedCustomTexture._samplingMode) {
  31433. if (parsedCustomTexture._samplingMode !== parsedTexture.samplingMode) {
  31434. parsedCustomTexture.updateSamplingMode(parsedTexture.samplingMode);
  31435. }
  31436. }
  31437. return parsedCustomTexture;
  31438. }
  31439. if (parsedTexture.isCube) {
  31440. return BABYLON.CubeTexture.Parse(parsedTexture, scene, rootUrl);
  31441. }
  31442. if (!parsedTexture.name && !parsedTexture.isRenderTarget) {
  31443. return null;
  31444. }
  31445. var texture = BABYLON.SerializationHelper.Parse(function () {
  31446. var generateMipMaps = true;
  31447. if (parsedTexture.noMipmap) {
  31448. generateMipMaps = false;
  31449. }
  31450. if (parsedTexture.mirrorPlane) {
  31451. var mirrorTexture = new BABYLON.MirrorTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31452. mirrorTexture._waitingRenderList = parsedTexture.renderList;
  31453. mirrorTexture.mirrorPlane = BABYLON.Plane.FromArray(parsedTexture.mirrorPlane);
  31454. return mirrorTexture;
  31455. }
  31456. else if (parsedTexture.isRenderTarget) {
  31457. var renderTargetTexture = new BABYLON.RenderTargetTexture(parsedTexture.name, parsedTexture.renderTargetSize, scene, generateMipMaps);
  31458. renderTargetTexture._waitingRenderList = parsedTexture.renderList;
  31459. return renderTargetTexture;
  31460. }
  31461. else {
  31462. var texture;
  31463. if (parsedTexture.base64String) {
  31464. texture = Texture.CreateFromBase64String(parsedTexture.base64String, parsedTexture.name, scene, !generateMipMaps);
  31465. }
  31466. else {
  31467. var url = rootUrl + parsedTexture.name;
  31468. if (Texture.UseSerializedUrlIfAny && parsedTexture.url) {
  31469. url = parsedTexture.url;
  31470. }
  31471. texture = new Texture(url, scene, !generateMipMaps, parsedTexture.invertY);
  31472. }
  31473. return texture;
  31474. }
  31475. }, parsedTexture, scene);
  31476. // Update Sampling Mode
  31477. if (parsedTexture.samplingMode) {
  31478. var sampling = parsedTexture.samplingMode;
  31479. if (texture._samplingMode !== sampling) {
  31480. texture.updateSamplingMode(sampling);
  31481. }
  31482. }
  31483. // Animations
  31484. if (parsedTexture.animations) {
  31485. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  31486. var parsedAnimation = parsedTexture.animations[animationIndex];
  31487. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  31488. }
  31489. }
  31490. return texture;
  31491. };
  31492. Texture.LoadFromDataString = function (name, buffer, scene, deleteBuffer, noMipmap, invertY, samplingMode, onLoad, onError, format) {
  31493. if (deleteBuffer === void 0) { deleteBuffer = false; }
  31494. if (noMipmap === void 0) { noMipmap = false; }
  31495. if (invertY === void 0) { invertY = true; }
  31496. if (samplingMode === void 0) { samplingMode = Texture.TRILINEAR_SAMPLINGMODE; }
  31497. if (onLoad === void 0) { onLoad = null; }
  31498. if (onError === void 0) { onError = null; }
  31499. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  31500. if (name.substr(0, 5) !== "data:") {
  31501. name = "data:" + name;
  31502. }
  31503. return new Texture(name, scene, noMipmap, invertY, samplingMode, onLoad, onError, buffer, deleteBuffer, format);
  31504. };
  31505. // Constants
  31506. Texture.NEAREST_SAMPLINGMODE = 1;
  31507. Texture.NEAREST_NEAREST_MIPLINEAR = 1; // nearest is mag = nearest and min = nearest and mip = linear
  31508. Texture.BILINEAR_SAMPLINGMODE = 2;
  31509. Texture.LINEAR_LINEAR_MIPNEAREST = 2; // Bilinear is mag = linear and min = linear and mip = nearest
  31510. Texture.TRILINEAR_SAMPLINGMODE = 3;
  31511. Texture.LINEAR_LINEAR_MIPLINEAR = 3; // Trilinear is mag = linear and min = linear and mip = linear
  31512. Texture.NEAREST_NEAREST_MIPNEAREST = 4;
  31513. Texture.NEAREST_LINEAR_MIPNEAREST = 5;
  31514. Texture.NEAREST_LINEAR_MIPLINEAR = 6;
  31515. Texture.NEAREST_LINEAR = 7;
  31516. Texture.NEAREST_NEAREST = 8;
  31517. Texture.LINEAR_NEAREST_MIPNEAREST = 9;
  31518. Texture.LINEAR_NEAREST_MIPLINEAR = 10;
  31519. Texture.LINEAR_LINEAR = 11;
  31520. Texture.LINEAR_NEAREST = 12;
  31521. Texture.EXPLICIT_MODE = 0;
  31522. Texture.SPHERICAL_MODE = 1;
  31523. Texture.PLANAR_MODE = 2;
  31524. Texture.CUBIC_MODE = 3;
  31525. Texture.PROJECTION_MODE = 4;
  31526. Texture.SKYBOX_MODE = 5;
  31527. Texture.INVCUBIC_MODE = 6;
  31528. Texture.EQUIRECTANGULAR_MODE = 7;
  31529. Texture.FIXED_EQUIRECTANGULAR_MODE = 8;
  31530. Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE = 9;
  31531. Texture.CLAMP_ADDRESSMODE = 0;
  31532. Texture.WRAP_ADDRESSMODE = 1;
  31533. Texture.MIRROR_ADDRESSMODE = 2;
  31534. /**
  31535. * 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
  31536. */
  31537. Texture.UseSerializedUrlIfAny = false;
  31538. __decorate([
  31539. BABYLON.serialize()
  31540. ], Texture.prototype, "url", void 0);
  31541. __decorate([
  31542. BABYLON.serialize()
  31543. ], Texture.prototype, "uOffset", void 0);
  31544. __decorate([
  31545. BABYLON.serialize()
  31546. ], Texture.prototype, "vOffset", void 0);
  31547. __decorate([
  31548. BABYLON.serialize()
  31549. ], Texture.prototype, "uScale", void 0);
  31550. __decorate([
  31551. BABYLON.serialize()
  31552. ], Texture.prototype, "vScale", void 0);
  31553. __decorate([
  31554. BABYLON.serialize()
  31555. ], Texture.prototype, "uAng", void 0);
  31556. __decorate([
  31557. BABYLON.serialize()
  31558. ], Texture.prototype, "vAng", void 0);
  31559. __decorate([
  31560. BABYLON.serialize()
  31561. ], Texture.prototype, "wAng", void 0);
  31562. __decorate([
  31563. BABYLON.serialize()
  31564. ], Texture.prototype, "uRotationCenter", void 0);
  31565. __decorate([
  31566. BABYLON.serialize()
  31567. ], Texture.prototype, "vRotationCenter", void 0);
  31568. __decorate([
  31569. BABYLON.serialize()
  31570. ], Texture.prototype, "wRotationCenter", void 0);
  31571. __decorate([
  31572. BABYLON.serialize()
  31573. ], Texture.prototype, "isBlocking", null);
  31574. return Texture;
  31575. }(BABYLON.BaseTexture));
  31576. BABYLON.Texture = Texture;
  31577. })(BABYLON || (BABYLON = {}));
  31578. //# sourceMappingURL=babylon.texture.js.map
  31579. var BABYLON;
  31580. (function (BABYLON) {
  31581. /**
  31582. * @hidden
  31583. **/
  31584. var _InstancesBatch = /** @class */ (function () {
  31585. function _InstancesBatch() {
  31586. this.mustReturn = false;
  31587. this.visibleInstances = new Array();
  31588. this.renderSelf = new Array();
  31589. }
  31590. return _InstancesBatch;
  31591. }());
  31592. BABYLON._InstancesBatch = _InstancesBatch;
  31593. var Mesh = /** @class */ (function (_super) {
  31594. __extends(Mesh, _super);
  31595. /**
  31596. * @constructor
  31597. * @param {string} name The value used by scene.getMeshByName() to do a lookup.
  31598. * @param {Scene} scene The scene to add this mesh to.
  31599. * @param {Node} parent The parent of this mesh, if it has one
  31600. * @param {Mesh} source An optional Mesh from which geometry is shared, cloned.
  31601. * @param {boolean} doNotCloneChildren When cloning, skip cloning child meshes of source, default False.
  31602. * When false, achieved by calling a clone(), also passing False.
  31603. * This will make creation of children, recursive.
  31604. * @param {boolean} clonePhysicsImpostor When cloning, include cloning mesh physics impostor, default True.
  31605. */
  31606. function Mesh(name, scene, parent, source, doNotCloneChildren, clonePhysicsImpostor) {
  31607. if (scene === void 0) { scene = null; }
  31608. if (parent === void 0) { parent = null; }
  31609. if (source === void 0) { source = null; }
  31610. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  31611. var _this = _super.call(this, name, scene) || this;
  31612. // Events
  31613. /**
  31614. * An event triggered before rendering the mesh
  31615. */
  31616. _this.onBeforeRenderObservable = new BABYLON.Observable();
  31617. /**
  31618. * An event triggered after rendering the mesh
  31619. */
  31620. _this.onAfterRenderObservable = new BABYLON.Observable();
  31621. /**
  31622. * An event triggered before drawing the mesh
  31623. */
  31624. _this.onBeforeDrawObservable = new BABYLON.Observable();
  31625. // Members
  31626. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  31627. _this.instances = new Array();
  31628. _this._LODLevels = new Array();
  31629. _this._visibleInstances = {};
  31630. _this._renderIdForInstances = new Array();
  31631. _this._batchCache = new _InstancesBatch();
  31632. _this._instancesBufferSize = 32 * 16 * 4; // let's start with a maximum of 32 instances
  31633. // Use by builder only to know what orientation were the mesh build in.
  31634. _this._originalBuilderSideOrientation = Mesh._DEFAULTSIDE;
  31635. _this.overrideMaterialSideOrientation = null;
  31636. _this._areNormalsFrozen = false; // Will be used by ribbons mainly
  31637. // Will be used to save a source mesh reference, If any
  31638. _this._source = null;
  31639. scene = _this.getScene();
  31640. if (source) {
  31641. // Geometry
  31642. if (source._geometry) {
  31643. source._geometry.applyToMesh(_this);
  31644. }
  31645. // Deep copy
  31646. BABYLON.Tools.DeepCopy(source, _this, ["name", "material", "skeleton", "instances", "parent", "uniqueId",
  31647. "source", "metadata", "hasLODLevels", "geometry", "isBlocked", "areNormalsFrozen"], ["_poseMatrix"]);
  31648. // Source mesh
  31649. _this._source = source;
  31650. // Metadata
  31651. if (source.metadata && source.metadata.clone) {
  31652. _this.metadata = source.metadata.clone();
  31653. }
  31654. else {
  31655. _this.metadata = source.metadata;
  31656. }
  31657. // Tags
  31658. if (BABYLON.Tags && BABYLON.Tags.HasTags(source)) {
  31659. BABYLON.Tags.AddTagsTo(_this, BABYLON.Tags.GetTags(source, true));
  31660. }
  31661. // Parent
  31662. _this.parent = source.parent;
  31663. // Pivot
  31664. _this.setPivotMatrix(source.getPivotMatrix());
  31665. _this.id = name + "." + source.id;
  31666. // Material
  31667. _this.material = source.material;
  31668. var index;
  31669. if (!doNotCloneChildren) {
  31670. // Children
  31671. var directDescendants = source.getDescendants(true);
  31672. for (var index_1 = 0; index_1 < directDescendants.length; index_1++) {
  31673. var child = directDescendants[index_1];
  31674. if (child.clone) {
  31675. child.clone(name + "." + child.name, _this);
  31676. }
  31677. }
  31678. }
  31679. // Physics clone
  31680. var physicsEngine = _this.getScene().getPhysicsEngine();
  31681. if (clonePhysicsImpostor && physicsEngine) {
  31682. var impostor = physicsEngine.getImpostorForPhysicsObject(source);
  31683. if (impostor) {
  31684. _this.physicsImpostor = impostor.clone(_this);
  31685. }
  31686. }
  31687. // Particles
  31688. for (index = 0; index < scene.particleSystems.length; index++) {
  31689. var system = scene.particleSystems[index];
  31690. if (system.emitter === source) {
  31691. system.clone(system.name, _this);
  31692. }
  31693. }
  31694. _this.refreshBoundingInfo();
  31695. _this.computeWorldMatrix(true);
  31696. }
  31697. // Parent
  31698. if (parent !== null) {
  31699. _this.parent = parent;
  31700. }
  31701. return _this;
  31702. }
  31703. Object.defineProperty(Mesh, "FRONTSIDE", {
  31704. /**
  31705. * Mesh side orientation : usually the external or front surface
  31706. */
  31707. get: function () {
  31708. return Mesh._FRONTSIDE;
  31709. },
  31710. enumerable: true,
  31711. configurable: true
  31712. });
  31713. Object.defineProperty(Mesh, "BACKSIDE", {
  31714. /**
  31715. * Mesh side orientation : usually the internal or back surface
  31716. */
  31717. get: function () {
  31718. return Mesh._BACKSIDE;
  31719. },
  31720. enumerable: true,
  31721. configurable: true
  31722. });
  31723. Object.defineProperty(Mesh, "DOUBLESIDE", {
  31724. /**
  31725. * Mesh side orientation : both internal and external or front and back surfaces
  31726. */
  31727. get: function () {
  31728. return Mesh._DOUBLESIDE;
  31729. },
  31730. enumerable: true,
  31731. configurable: true
  31732. });
  31733. Object.defineProperty(Mesh, "DEFAULTSIDE", {
  31734. /**
  31735. * Mesh side orientation : by default, `FRONTSIDE`
  31736. */
  31737. get: function () {
  31738. return Mesh._DEFAULTSIDE;
  31739. },
  31740. enumerable: true,
  31741. configurable: true
  31742. });
  31743. Object.defineProperty(Mesh, "NO_CAP", {
  31744. /**
  31745. * Mesh cap setting : no cap
  31746. */
  31747. get: function () {
  31748. return Mesh._NO_CAP;
  31749. },
  31750. enumerable: true,
  31751. configurable: true
  31752. });
  31753. Object.defineProperty(Mesh, "CAP_START", {
  31754. /**
  31755. * Mesh cap setting : one cap at the beginning of the mesh
  31756. */
  31757. get: function () {
  31758. return Mesh._CAP_START;
  31759. },
  31760. enumerable: true,
  31761. configurable: true
  31762. });
  31763. Object.defineProperty(Mesh, "CAP_END", {
  31764. /**
  31765. * Mesh cap setting : one cap at the end of the mesh
  31766. */
  31767. get: function () {
  31768. return Mesh._CAP_END;
  31769. },
  31770. enumerable: true,
  31771. configurable: true
  31772. });
  31773. Object.defineProperty(Mesh, "CAP_ALL", {
  31774. /**
  31775. * Mesh cap setting : two caps, one at the beginning and one at the end of the mesh
  31776. */
  31777. get: function () {
  31778. return Mesh._CAP_ALL;
  31779. },
  31780. enumerable: true,
  31781. configurable: true
  31782. });
  31783. Object.defineProperty(Mesh.prototype, "onBeforeDraw", {
  31784. set: function (callback) {
  31785. if (this._onBeforeDrawObserver) {
  31786. this.onBeforeDrawObservable.remove(this._onBeforeDrawObserver);
  31787. }
  31788. this._onBeforeDrawObserver = this.onBeforeDrawObservable.add(callback);
  31789. },
  31790. enumerable: true,
  31791. configurable: true
  31792. });
  31793. Object.defineProperty(Mesh.prototype, "morphTargetManager", {
  31794. get: function () {
  31795. return this._morphTargetManager;
  31796. },
  31797. set: function (value) {
  31798. if (this._morphTargetManager === value) {
  31799. return;
  31800. }
  31801. this._morphTargetManager = value;
  31802. this._syncGeometryWithMorphTargetManager();
  31803. },
  31804. enumerable: true,
  31805. configurable: true
  31806. });
  31807. Object.defineProperty(Mesh.prototype, "source", {
  31808. get: function () {
  31809. return this._source;
  31810. },
  31811. enumerable: true,
  31812. configurable: true
  31813. });
  31814. Object.defineProperty(Mesh.prototype, "isUnIndexed", {
  31815. get: function () {
  31816. return this._unIndexed;
  31817. },
  31818. set: function (value) {
  31819. if (this._unIndexed !== value) {
  31820. this._unIndexed = value;
  31821. this._markSubMeshesAsAttributesDirty();
  31822. }
  31823. },
  31824. enumerable: true,
  31825. configurable: true
  31826. });
  31827. // Methods
  31828. /**
  31829. * Returns the string "Mesh".
  31830. */
  31831. Mesh.prototype.getClassName = function () {
  31832. return "Mesh";
  31833. };
  31834. /**
  31835. * Returns a string.
  31836. * @param {boolean} fullDetails - support for multiple levels of logging within scene loading
  31837. */
  31838. Mesh.prototype.toString = function (fullDetails) {
  31839. var ret = _super.prototype.toString.call(this, fullDetails);
  31840. ret += ", n vertices: " + this.getTotalVertices();
  31841. ret += ", parent: " + (this._waitingParentId ? this._waitingParentId : (this.parent ? this.parent.name : "NONE"));
  31842. if (this.animations) {
  31843. for (var i = 0; i < this.animations.length; i++) {
  31844. ret += ", animation[0]: " + this.animations[i].toString(fullDetails);
  31845. }
  31846. }
  31847. if (fullDetails) {
  31848. if (this._geometry) {
  31849. var ib = this.getIndices();
  31850. var vb = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  31851. if (vb && ib) {
  31852. ret += ", flat shading: " + (vb.length / 3 === ib.length ? "YES" : "NO");
  31853. }
  31854. }
  31855. else {
  31856. ret += ", flat shading: UNKNOWN";
  31857. }
  31858. }
  31859. return ret;
  31860. };
  31861. Mesh.prototype._unBindEffect = function () {
  31862. _super.prototype._unBindEffect.call(this);
  31863. for (var _i = 0, _a = this.instances; _i < _a.length; _i++) {
  31864. var instance = _a[_i];
  31865. instance._unBindEffect();
  31866. }
  31867. };
  31868. Object.defineProperty(Mesh.prototype, "hasLODLevels", {
  31869. /**
  31870. * True if the mesh has some Levels Of Details (LOD).
  31871. * Returns a boolean.
  31872. */
  31873. get: function () {
  31874. return this._LODLevels.length > 0;
  31875. },
  31876. enumerable: true,
  31877. configurable: true
  31878. });
  31879. /**
  31880. * Gets the list of {BABYLON.MeshLODLevel} associated with the current mesh
  31881. * @returns an array of {BABYLON.MeshLODLevel}
  31882. */
  31883. Mesh.prototype.getLODLevels = function () {
  31884. return this._LODLevels;
  31885. };
  31886. Mesh.prototype._sortLODLevels = function () {
  31887. this._LODLevels.sort(function (a, b) {
  31888. if (a.distance < b.distance) {
  31889. return 1;
  31890. }
  31891. if (a.distance > b.distance) {
  31892. return -1;
  31893. }
  31894. return 0;
  31895. });
  31896. };
  31897. /**
  31898. * Add a mesh as LOD level triggered at the given distance.
  31899. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31900. * @param distance The distance from the center of the object to show this level
  31901. * @param mesh The mesh to be added as LOD level (can be null)
  31902. * @return This mesh (for chaining)
  31903. */
  31904. Mesh.prototype.addLODLevel = function (distance, mesh) {
  31905. if (mesh && mesh._masterMesh) {
  31906. BABYLON.Tools.Warn("You cannot use a mesh as LOD level twice");
  31907. return this;
  31908. }
  31909. var level = new BABYLON.MeshLODLevel(distance, mesh);
  31910. this._LODLevels.push(level);
  31911. if (mesh) {
  31912. mesh._masterMesh = this;
  31913. }
  31914. this._sortLODLevels();
  31915. return this;
  31916. };
  31917. /**
  31918. * Returns the LOD level mesh at the passed distance or null if not found.
  31919. * It is related to the method `addLODLevel(distance, mesh)`.
  31920. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31921. * Returns an object Mesh or `null`.
  31922. */
  31923. Mesh.prototype.getLODLevelAtDistance = function (distance) {
  31924. for (var index = 0; index < this._LODLevels.length; index++) {
  31925. var level = this._LODLevels[index];
  31926. if (level.distance === distance) {
  31927. return level.mesh;
  31928. }
  31929. }
  31930. return null;
  31931. };
  31932. /**
  31933. * Remove a mesh from the LOD array
  31934. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_LOD
  31935. * @param {Mesh} mesh The mesh to be removed.
  31936. * @return {Mesh} This mesh (for chaining)
  31937. */
  31938. Mesh.prototype.removeLODLevel = function (mesh) {
  31939. for (var index = 0; index < this._LODLevels.length; index++) {
  31940. if (this._LODLevels[index].mesh === mesh) {
  31941. this._LODLevels.splice(index, 1);
  31942. if (mesh) {
  31943. mesh._masterMesh = null;
  31944. }
  31945. }
  31946. }
  31947. this._sortLODLevels();
  31948. return this;
  31949. };
  31950. /**
  31951. * Returns the registered LOD mesh distant from the parameter `camera` position if any, else returns the current mesh.
  31952. * tuto : http://doc.babylonjs.com/how_to/how_to_use_lod
  31953. */
  31954. Mesh.prototype.getLOD = function (camera, boundingSphere) {
  31955. if (!this._LODLevels || this._LODLevels.length === 0) {
  31956. return this;
  31957. }
  31958. var bSphere;
  31959. if (boundingSphere) {
  31960. bSphere = boundingSphere;
  31961. }
  31962. else {
  31963. var boundingInfo = this.getBoundingInfo();
  31964. bSphere = boundingInfo.boundingSphere;
  31965. }
  31966. var distanceToCamera = bSphere.centerWorld.subtract(camera.globalPosition).length();
  31967. if (this._LODLevels[this._LODLevels.length - 1].distance > distanceToCamera) {
  31968. if (this.onLODLevelSelection) {
  31969. this.onLODLevelSelection(distanceToCamera, this, this._LODLevels[this._LODLevels.length - 1].mesh);
  31970. }
  31971. return this;
  31972. }
  31973. for (var index = 0; index < this._LODLevels.length; index++) {
  31974. var level = this._LODLevels[index];
  31975. if (level.distance < distanceToCamera) {
  31976. if (level.mesh) {
  31977. level.mesh._preActivate();
  31978. level.mesh._updateSubMeshesBoundingInfo(this.worldMatrixFromCache);
  31979. }
  31980. if (this.onLODLevelSelection) {
  31981. this.onLODLevelSelection(distanceToCamera, this, level.mesh);
  31982. }
  31983. return level.mesh;
  31984. }
  31985. }
  31986. if (this.onLODLevelSelection) {
  31987. this.onLODLevelSelection(distanceToCamera, this, this);
  31988. }
  31989. return this;
  31990. };
  31991. Object.defineProperty(Mesh.prototype, "geometry", {
  31992. /**
  31993. * Returns the mesh internal Geometry object.
  31994. */
  31995. get: function () {
  31996. return this._geometry;
  31997. },
  31998. enumerable: true,
  31999. configurable: true
  32000. });
  32001. /**
  32002. * Returns a positive integer : the total number of vertices within the mesh geometry or zero if the mesh has no geometry.
  32003. */
  32004. Mesh.prototype.getTotalVertices = function () {
  32005. if (this._geometry === null || this._geometry === undefined) {
  32006. return 0;
  32007. }
  32008. return this._geometry.getTotalVertices();
  32009. };
  32010. /**
  32011. * Returns an array of integers or floats, or a Float32Array, depending on the requested `kind` (positions, indices, normals, etc).
  32012. * 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.
  32013. * You can force the copy with forceCopy === true
  32014. * Returns null if the mesh has no geometry or no vertex buffer.
  32015. * Possible `kind` values :
  32016. * - BABYLON.VertexBuffer.PositionKind
  32017. * - BABYLON.VertexBuffer.UVKind
  32018. * - BABYLON.VertexBuffer.UV2Kind
  32019. * - BABYLON.VertexBuffer.UV3Kind
  32020. * - BABYLON.VertexBuffer.UV4Kind
  32021. * - BABYLON.VertexBuffer.UV5Kind
  32022. * - BABYLON.VertexBuffer.UV6Kind
  32023. * - BABYLON.VertexBuffer.ColorKind
  32024. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32025. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32026. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32027. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32028. */
  32029. Mesh.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  32030. if (!this._geometry) {
  32031. return null;
  32032. }
  32033. return this._geometry.getVerticesData(kind, copyWhenShared, forceCopy);
  32034. };
  32035. /**
  32036. * Returns the mesh VertexBuffer object from the requested `kind` : positions, indices, normals, etc.
  32037. * Returns `null` if the mesh has no geometry.
  32038. * Possible `kind` values :
  32039. * - BABYLON.VertexBuffer.PositionKind
  32040. * - BABYLON.VertexBuffer.UVKind
  32041. * - BABYLON.VertexBuffer.UV2Kind
  32042. * - BABYLON.VertexBuffer.UV3Kind
  32043. * - BABYLON.VertexBuffer.UV4Kind
  32044. * - BABYLON.VertexBuffer.UV5Kind
  32045. * - BABYLON.VertexBuffer.UV6Kind
  32046. * - BABYLON.VertexBuffer.ColorKind
  32047. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32048. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32049. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32050. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32051. */
  32052. Mesh.prototype.getVertexBuffer = function (kind) {
  32053. if (!this._geometry) {
  32054. return null;
  32055. }
  32056. return this._geometry.getVertexBuffer(kind);
  32057. };
  32058. Mesh.prototype.isVerticesDataPresent = function (kind) {
  32059. if (!this._geometry) {
  32060. if (this._delayInfo) {
  32061. return this._delayInfo.indexOf(kind) !== -1;
  32062. }
  32063. return false;
  32064. }
  32065. return this._geometry.isVerticesDataPresent(kind);
  32066. };
  32067. /**
  32068. * Returns a boolean defining if the vertex data for the requested `kind` is updatable.
  32069. * Possible `kind` values :
  32070. * - BABYLON.VertexBuffer.PositionKind
  32071. * - BABYLON.VertexBuffer.UVKind
  32072. * - BABYLON.VertexBuffer.UV2Kind
  32073. * - BABYLON.VertexBuffer.UV3Kind
  32074. * - BABYLON.VertexBuffer.UV4Kind
  32075. * - BABYLON.VertexBuffer.UV5Kind
  32076. * - BABYLON.VertexBuffer.UV6Kind
  32077. * - BABYLON.VertexBuffer.ColorKind
  32078. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32079. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32080. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32081. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32082. */
  32083. Mesh.prototype.isVertexBufferUpdatable = function (kind) {
  32084. if (!this._geometry) {
  32085. if (this._delayInfo) {
  32086. return this._delayInfo.indexOf(kind) !== -1;
  32087. }
  32088. return false;
  32089. }
  32090. return this._geometry.isVertexBufferUpdatable(kind);
  32091. };
  32092. /**
  32093. * Returns a string : the list of existing `kinds` of Vertex Data for this mesh.
  32094. * Possible `kind` values :
  32095. * - BABYLON.VertexBuffer.PositionKind
  32096. * - BABYLON.VertexBuffer.UVKind
  32097. * - BABYLON.VertexBuffer.UV2Kind
  32098. * - BABYLON.VertexBuffer.UV3Kind
  32099. * - BABYLON.VertexBuffer.UV4Kind
  32100. * - BABYLON.VertexBuffer.UV5Kind
  32101. * - BABYLON.VertexBuffer.UV6Kind
  32102. * - BABYLON.VertexBuffer.ColorKind
  32103. * - BABYLON.VertexBuffer.MatricesIndicesKind
  32104. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  32105. * - BABYLON.VertexBuffer.MatricesWeightsKind
  32106. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  32107. */
  32108. Mesh.prototype.getVerticesDataKinds = function () {
  32109. if (!this._geometry) {
  32110. var result = new Array();
  32111. if (this._delayInfo) {
  32112. this._delayInfo.forEach(function (kind, index, array) {
  32113. result.push(kind);
  32114. });
  32115. }
  32116. return result;
  32117. }
  32118. return this._geometry.getVerticesDataKinds();
  32119. };
  32120. /**
  32121. * Returns a positive integer : the total number of indices in this mesh geometry.
  32122. * Returns zero if the mesh has no geometry.
  32123. */
  32124. Mesh.prototype.getTotalIndices = function () {
  32125. if (!this._geometry) {
  32126. return 0;
  32127. }
  32128. return this._geometry.getTotalIndices();
  32129. };
  32130. /**
  32131. * Returns an array of integers or a typed array (Int32Array, Uint32Array, Uint16Array) populated with the mesh indices.
  32132. * 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.
  32133. * Returns an empty array if the mesh has no geometry.
  32134. */
  32135. Mesh.prototype.getIndices = function (copyWhenShared) {
  32136. if (!this._geometry) {
  32137. return [];
  32138. }
  32139. return this._geometry.getIndices(copyWhenShared);
  32140. };
  32141. Object.defineProperty(Mesh.prototype, "isBlocked", {
  32142. get: function () {
  32143. return this._masterMesh !== null && this._masterMesh !== undefined;
  32144. },
  32145. enumerable: true,
  32146. configurable: true
  32147. });
  32148. /**
  32149. * Determine if the current mesh is ready to be rendered
  32150. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  32151. * @param forceInstanceSupport will check if the mesh will be ready when used with instances (false by default)
  32152. * @returns true if all associated assets are ready (material, textures, shaders)
  32153. */
  32154. Mesh.prototype.isReady = function (completeCheck, forceInstanceSupport) {
  32155. if (completeCheck === void 0) { completeCheck = false; }
  32156. if (forceInstanceSupport === void 0) { forceInstanceSupport = false; }
  32157. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32158. return false;
  32159. }
  32160. if (!_super.prototype.isReady.call(this, completeCheck)) {
  32161. return false;
  32162. }
  32163. if (!this.subMeshes || this.subMeshes.length === 0) {
  32164. return true;
  32165. }
  32166. if (!completeCheck) {
  32167. return true;
  32168. }
  32169. var engine = this.getEngine();
  32170. var scene = this.getScene();
  32171. var hardwareInstancedRendering = forceInstanceSupport || engine.getCaps().instancedArrays && this.instances.length > 0;
  32172. this.computeWorldMatrix();
  32173. var mat = this.material || scene.defaultMaterial;
  32174. if (mat) {
  32175. if (mat.storeEffectOnSubMeshes) {
  32176. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32177. var subMesh = _a[_i];
  32178. var effectiveMaterial = subMesh.getMaterial();
  32179. if (effectiveMaterial) {
  32180. if (effectiveMaterial.storeEffectOnSubMeshes) {
  32181. if (!effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32182. return false;
  32183. }
  32184. }
  32185. else {
  32186. if (!effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32187. return false;
  32188. }
  32189. }
  32190. }
  32191. }
  32192. }
  32193. else {
  32194. if (!mat.isReady(this, hardwareInstancedRendering)) {
  32195. return false;
  32196. }
  32197. }
  32198. }
  32199. // Shadows
  32200. for (var _b = 0, _c = this._lightSources; _b < _c.length; _b++) {
  32201. var light = _c[_b];
  32202. var generator = light.getShadowGenerator();
  32203. if (generator) {
  32204. for (var _d = 0, _e = this.subMeshes; _d < _e.length; _d++) {
  32205. var subMesh = _e[_d];
  32206. if (!generator.isReady(subMesh, hardwareInstancedRendering)) {
  32207. return false;
  32208. }
  32209. }
  32210. }
  32211. }
  32212. // LOD
  32213. for (var _f = 0, _g = this._LODLevels; _f < _g.length; _f++) {
  32214. var lod = _g[_f];
  32215. if (lod.mesh && !lod.mesh.isReady(hardwareInstancedRendering)) {
  32216. return false;
  32217. }
  32218. }
  32219. return true;
  32220. };
  32221. Object.defineProperty(Mesh.prototype, "areNormalsFrozen", {
  32222. /**
  32223. * Boolean : true if the normals aren't to be recomputed on next mesh `positions` array update.
  32224. * This property is pertinent only for updatable parametric shapes.
  32225. */
  32226. get: function () {
  32227. return this._areNormalsFrozen;
  32228. },
  32229. enumerable: true,
  32230. configurable: true
  32231. });
  32232. /**
  32233. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32234. * It has no effect at all on other shapes.
  32235. * It prevents the mesh normals from being recomputed on next `positions` array update.
  32236. * Returns the Mesh.
  32237. */
  32238. Mesh.prototype.freezeNormals = function () {
  32239. this._areNormalsFrozen = true;
  32240. return this;
  32241. };
  32242. /**
  32243. * This function affects parametric shapes on vertex position update only : ribbons, tubes, etc.
  32244. * It has no effect at all on other shapes.
  32245. * It reactivates the mesh normals computation if it was previously frozen.
  32246. * Returns the Mesh.
  32247. */
  32248. Mesh.prototype.unfreezeNormals = function () {
  32249. this._areNormalsFrozen = false;
  32250. return this;
  32251. };
  32252. Object.defineProperty(Mesh.prototype, "overridenInstanceCount", {
  32253. /**
  32254. * Overrides instance count. Only applicable when custom instanced InterleavedVertexBuffer are used rather than InstancedMeshs
  32255. */
  32256. set: function (count) {
  32257. this._overridenInstanceCount = count;
  32258. },
  32259. enumerable: true,
  32260. configurable: true
  32261. });
  32262. // Methods
  32263. Mesh.prototype._preActivate = function () {
  32264. var sceneRenderId = this.getScene().getRenderId();
  32265. if (this._preActivateId === sceneRenderId) {
  32266. return this;
  32267. }
  32268. this._preActivateId = sceneRenderId;
  32269. this._visibleInstances = null;
  32270. return this;
  32271. };
  32272. Mesh.prototype._preActivateForIntermediateRendering = function (renderId) {
  32273. if (this._visibleInstances) {
  32274. this._visibleInstances.intermediateDefaultRenderId = renderId;
  32275. }
  32276. return this;
  32277. };
  32278. Mesh.prototype._registerInstanceForRenderId = function (instance, renderId) {
  32279. if (!this._visibleInstances) {
  32280. this._visibleInstances = {};
  32281. this._visibleInstances.defaultRenderId = renderId;
  32282. this._visibleInstances.selfDefaultRenderId = this._renderId;
  32283. }
  32284. if (!this._visibleInstances[renderId]) {
  32285. this._visibleInstances[renderId] = new Array();
  32286. }
  32287. this._visibleInstances[renderId].push(instance);
  32288. return this;
  32289. };
  32290. /**
  32291. * This method recomputes and sets a new BoundingInfo to the mesh unless it is locked.
  32292. * This means the mesh underlying bounding box and sphere are recomputed.
  32293. * Returns the Mesh.
  32294. */
  32295. Mesh.prototype.refreshBoundingInfo = function () {
  32296. return this._refreshBoundingInfo(false);
  32297. };
  32298. Mesh.prototype._refreshBoundingInfo = function (applySkeleton) {
  32299. if (this._boundingInfo && this._boundingInfo.isLocked) {
  32300. return this;
  32301. }
  32302. var data = this._getPositionData(applySkeleton);
  32303. if (data) {
  32304. var extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this.getTotalVertices());
  32305. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  32306. }
  32307. if (this.subMeshes) {
  32308. for (var index = 0; index < this.subMeshes.length; index++) {
  32309. this.subMeshes[index].refreshBoundingInfo();
  32310. }
  32311. }
  32312. this._updateBoundingInfo();
  32313. return this;
  32314. };
  32315. Mesh.prototype._getPositionData = function (applySkeleton) {
  32316. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32317. if (data && applySkeleton && this.skeleton) {
  32318. data = BABYLON.Tools.Slice(data);
  32319. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32320. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32321. if (matricesWeightsData && matricesIndicesData) {
  32322. var needExtras = this.numBoneInfluencers > 4;
  32323. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  32324. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  32325. var skeletonMatrices = this.skeleton.getTransformMatrices(this);
  32326. var tempVector = BABYLON.Tmp.Vector3[0];
  32327. var finalMatrix = BABYLON.Tmp.Matrix[0];
  32328. var tempMatrix = BABYLON.Tmp.Matrix[1];
  32329. var matWeightIdx = 0;
  32330. for (var index = 0; index < data.length; index += 3, matWeightIdx += 4) {
  32331. finalMatrix.reset();
  32332. var inf;
  32333. var weight;
  32334. for (inf = 0; inf < 4; inf++) {
  32335. weight = matricesWeightsData[matWeightIdx + inf];
  32336. if (weight <= 0)
  32337. break;
  32338. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32339. finalMatrix.addToSelf(tempMatrix);
  32340. }
  32341. if (needExtras) {
  32342. for (inf = 0; inf < 4; inf++) {
  32343. weight = matricesWeightsExtraData[matWeightIdx + inf];
  32344. if (weight <= 0)
  32345. break;
  32346. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  32347. finalMatrix.addToSelf(tempMatrix);
  32348. }
  32349. }
  32350. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(data[index], data[index + 1], data[index + 2], finalMatrix, tempVector);
  32351. tempVector.toArray(data, index);
  32352. }
  32353. }
  32354. }
  32355. return data;
  32356. };
  32357. Mesh.prototype._createGlobalSubMesh = function (force) {
  32358. var totalVertices = this.getTotalVertices();
  32359. if (!totalVertices || !this.getIndices()) {
  32360. return null;
  32361. }
  32362. // Check if we need to recreate the submeshes
  32363. if (this.subMeshes && this.subMeshes.length > 0) {
  32364. var ib = this.getIndices();
  32365. if (!ib) {
  32366. return null;
  32367. }
  32368. var totalIndices = ib.length;
  32369. var needToRecreate = false;
  32370. if (force) {
  32371. needToRecreate = true;
  32372. }
  32373. else {
  32374. for (var _i = 0, _a = this.subMeshes; _i < _a.length; _i++) {
  32375. var submesh = _a[_i];
  32376. if (submesh.indexStart + submesh.indexCount >= totalIndices) {
  32377. needToRecreate = true;
  32378. break;
  32379. }
  32380. if (submesh.verticesStart + submesh.verticesCount >= totalVertices) {
  32381. needToRecreate = true;
  32382. break;
  32383. }
  32384. }
  32385. }
  32386. if (!needToRecreate) {
  32387. return this.subMeshes[0];
  32388. }
  32389. }
  32390. this.releaseSubMeshes();
  32391. return new BABYLON.SubMesh(0, 0, totalVertices, 0, this.getTotalIndices(), this);
  32392. };
  32393. Mesh.prototype.subdivide = function (count) {
  32394. if (count < 1) {
  32395. return;
  32396. }
  32397. var totalIndices = this.getTotalIndices();
  32398. var subdivisionSize = (totalIndices / count) | 0;
  32399. var offset = 0;
  32400. // Ensure that subdivisionSize is a multiple of 3
  32401. while (subdivisionSize % 3 !== 0) {
  32402. subdivisionSize++;
  32403. }
  32404. this.releaseSubMeshes();
  32405. for (var index = 0; index < count; index++) {
  32406. if (offset >= totalIndices) {
  32407. break;
  32408. }
  32409. BABYLON.SubMesh.CreateFromIndices(0, offset, Math.min(subdivisionSize, totalIndices - offset), this);
  32410. offset += subdivisionSize;
  32411. }
  32412. this.synchronizeInstances();
  32413. };
  32414. Mesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  32415. if (updatable === void 0) { updatable = false; }
  32416. if (!this._geometry) {
  32417. var vertexData = new BABYLON.VertexData();
  32418. vertexData.set(data, kind);
  32419. var scene = this.getScene();
  32420. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32421. }
  32422. else {
  32423. this._geometry.setVerticesData(kind, data, updatable, stride);
  32424. }
  32425. return this;
  32426. };
  32427. Mesh.prototype.markVerticesDataAsUpdatable = function (kind, updatable) {
  32428. if (updatable === void 0) { updatable = true; }
  32429. var vb = this.getVertexBuffer(kind);
  32430. if (!vb || vb.isUpdatable() === updatable) {
  32431. return;
  32432. }
  32433. this.setVerticesData(kind, this.getVerticesData(kind), updatable);
  32434. };
  32435. /**
  32436. * Sets the mesh VertexBuffer.
  32437. * Returns the Mesh.
  32438. */
  32439. Mesh.prototype.setVerticesBuffer = function (buffer) {
  32440. if (!this._geometry) {
  32441. this._geometry = BABYLON.Geometry.CreateGeometryForMesh(this);
  32442. }
  32443. this._geometry.setVerticesBuffer(buffer);
  32444. return this;
  32445. };
  32446. Mesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  32447. if (!this._geometry) {
  32448. return this;
  32449. }
  32450. if (!makeItUnique) {
  32451. this._geometry.updateVerticesData(kind, data, updateExtends);
  32452. }
  32453. else {
  32454. this.makeGeometryUnique();
  32455. this.updateVerticesData(kind, data, updateExtends, false);
  32456. }
  32457. return this;
  32458. };
  32459. /**
  32460. * This method updates the vertex positions of an updatable mesh according to the `positionFunction` returned values.
  32461. * tuto : http://doc.babylonjs.com/tutorials/How_to_dynamically_morph_a_mesh#other-shapes-updatemeshpositions
  32462. * The parameter `positionFunction` is a simple JS function what is passed the mesh `positions` array. It doesn't need to return anything.
  32463. * The parameter `computeNormals` is a boolean (default true) to enable/disable the mesh normal recomputation after the vertex position update.
  32464. * Returns the Mesh.
  32465. */
  32466. Mesh.prototype.updateMeshPositions = function (positionFunction, computeNormals) {
  32467. if (computeNormals === void 0) { computeNormals = true; }
  32468. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  32469. if (!positions) {
  32470. return this;
  32471. }
  32472. positionFunction(positions);
  32473. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  32474. if (computeNormals) {
  32475. var indices = this.getIndices();
  32476. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  32477. if (!normals) {
  32478. return this;
  32479. }
  32480. BABYLON.VertexData.ComputeNormals(positions, indices, normals);
  32481. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  32482. }
  32483. return this;
  32484. };
  32485. /**
  32486. * Creates a un-shared specific occurence of the geometry for the mesh.
  32487. * Returns the Mesh.
  32488. */
  32489. Mesh.prototype.makeGeometryUnique = function () {
  32490. if (!this._geometry) {
  32491. return this;
  32492. }
  32493. var oldGeometry = this._geometry;
  32494. var geometry = this._geometry.copy(BABYLON.Geometry.RandomId());
  32495. oldGeometry.releaseForMesh(this, true);
  32496. geometry.applyToMesh(this);
  32497. return this;
  32498. };
  32499. Mesh.prototype.setIndices = function (indices, totalVertices, updatable) {
  32500. if (totalVertices === void 0) { totalVertices = null; }
  32501. if (updatable === void 0) { updatable = false; }
  32502. if (!this._geometry) {
  32503. var vertexData = new BABYLON.VertexData();
  32504. vertexData.indices = indices;
  32505. var scene = this.getScene();
  32506. new BABYLON.Geometry(BABYLON.Geometry.RandomId(), scene, vertexData, updatable, this);
  32507. }
  32508. else {
  32509. this._geometry.setIndices(indices, totalVertices, updatable);
  32510. }
  32511. return this;
  32512. };
  32513. /**
  32514. * Update the current index buffer
  32515. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array)
  32516. * Returns the Mesh.
  32517. */
  32518. Mesh.prototype.updateIndices = function (indices, offset) {
  32519. if (!this._geometry) {
  32520. return this;
  32521. }
  32522. this._geometry.updateIndices(indices, offset);
  32523. return this;
  32524. };
  32525. /**
  32526. * Invert the geometry to move from a right handed system to a left handed one.
  32527. * Returns the Mesh.
  32528. */
  32529. Mesh.prototype.toLeftHanded = function () {
  32530. if (!this._geometry) {
  32531. return this;
  32532. }
  32533. this._geometry.toLeftHanded();
  32534. return this;
  32535. };
  32536. Mesh.prototype._bind = function (subMesh, effect, fillMode) {
  32537. if (!this._geometry) {
  32538. return this;
  32539. }
  32540. var engine = this.getScene().getEngine();
  32541. // Wireframe
  32542. var indexToBind;
  32543. if (this._unIndexed) {
  32544. indexToBind = null;
  32545. }
  32546. else {
  32547. switch (fillMode) {
  32548. case BABYLON.Material.PointFillMode:
  32549. indexToBind = null;
  32550. break;
  32551. case BABYLON.Material.WireFrameFillMode:
  32552. indexToBind = subMesh.getLinesIndexBuffer(this.getIndices(), engine);
  32553. break;
  32554. default:
  32555. case BABYLON.Material.TriangleFillMode:
  32556. indexToBind = this._unIndexed ? null : this._geometry.getIndexBuffer();
  32557. break;
  32558. }
  32559. }
  32560. // VBOs
  32561. this._geometry._bind(effect, indexToBind);
  32562. return this;
  32563. };
  32564. Mesh.prototype._draw = function (subMesh, fillMode, instancesCount, alternate) {
  32565. if (alternate === void 0) { alternate = false; }
  32566. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32567. return this;
  32568. }
  32569. this.onBeforeDrawObservable.notifyObservers(this);
  32570. var scene = this.getScene();
  32571. var engine = scene.getEngine();
  32572. if (this._unIndexed || fillMode == BABYLON.Material.PointFillMode) {
  32573. // or triangles as points
  32574. engine.drawArraysType(fillMode, subMesh.verticesStart, subMesh.verticesCount, instancesCount);
  32575. }
  32576. else if (fillMode == BABYLON.Material.WireFrameFillMode) {
  32577. // Triangles as wireframe
  32578. engine.drawElementsType(fillMode, 0, subMesh.linesIndexCount, instancesCount);
  32579. }
  32580. else {
  32581. engine.drawElementsType(fillMode, subMesh.indexStart, subMesh.indexCount, instancesCount);
  32582. }
  32583. if (scene._isAlternateRenderingEnabled && !alternate) {
  32584. var effect = subMesh.effect || this._effectiveMaterial.getEffect();
  32585. if (!effect || !scene.activeCamera) {
  32586. return this;
  32587. }
  32588. scene._switchToAlternateCameraConfiguration(true);
  32589. this._effectiveMaterial.bindView(effect);
  32590. this._effectiveMaterial.bindViewProjection(effect);
  32591. engine.setViewport(scene.activeCamera._alternateCamera.viewport);
  32592. this._draw(subMesh, fillMode, instancesCount, true);
  32593. engine.setViewport(scene.activeCamera.viewport);
  32594. scene._switchToAlternateCameraConfiguration(false);
  32595. this._effectiveMaterial.bindView(effect);
  32596. this._effectiveMaterial.bindViewProjection(effect);
  32597. }
  32598. return this;
  32599. };
  32600. /**
  32601. * Registers for this mesh a javascript function called just before the rendering process.
  32602. * This function is passed the current mesh.
  32603. * Return the Mesh.
  32604. */
  32605. Mesh.prototype.registerBeforeRender = function (func) {
  32606. this.onBeforeRenderObservable.add(func);
  32607. return this;
  32608. };
  32609. /**
  32610. * Disposes a previously registered javascript function called before the rendering.
  32611. * This function is passed the current mesh.
  32612. * Returns the Mesh.
  32613. */
  32614. Mesh.prototype.unregisterBeforeRender = function (func) {
  32615. this.onBeforeRenderObservable.removeCallback(func);
  32616. return this;
  32617. };
  32618. /**
  32619. * Registers for this mesh a javascript function called just after the rendering is complete.
  32620. * This function is passed the current mesh.
  32621. * Returns the Mesh.
  32622. */
  32623. Mesh.prototype.registerAfterRender = function (func) {
  32624. this.onAfterRenderObservable.add(func);
  32625. return this;
  32626. };
  32627. /**
  32628. * Disposes a previously registered javascript function called after the rendering.
  32629. * This function is passed the current mesh.
  32630. * Return the Mesh.
  32631. */
  32632. Mesh.prototype.unregisterAfterRender = function (func) {
  32633. this.onAfterRenderObservable.removeCallback(func);
  32634. return this;
  32635. };
  32636. Mesh.prototype._getInstancesRenderList = function (subMeshId) {
  32637. var scene = this.getScene();
  32638. this._batchCache.mustReturn = false;
  32639. this._batchCache.renderSelf[subMeshId] = this.isEnabled() && this.isVisible;
  32640. this._batchCache.visibleInstances[subMeshId] = null;
  32641. if (this._visibleInstances) {
  32642. var currentRenderId = scene.getRenderId();
  32643. var defaultRenderId = (scene._isInIntermediateRendering() ? this._visibleInstances.intermediateDefaultRenderId : this._visibleInstances.defaultRenderId);
  32644. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[currentRenderId];
  32645. var selfRenderId = this._renderId;
  32646. if (!this._batchCache.visibleInstances[subMeshId] && defaultRenderId) {
  32647. this._batchCache.visibleInstances[subMeshId] = this._visibleInstances[defaultRenderId];
  32648. currentRenderId = Math.max(defaultRenderId, currentRenderId);
  32649. selfRenderId = Math.max(this._visibleInstances.selfDefaultRenderId, currentRenderId);
  32650. }
  32651. var visibleInstancesForSubMesh = this._batchCache.visibleInstances[subMeshId];
  32652. if (visibleInstancesForSubMesh && visibleInstancesForSubMesh.length) {
  32653. if (this._renderIdForInstances[subMeshId] === currentRenderId) {
  32654. this._batchCache.mustReturn = true;
  32655. return this._batchCache;
  32656. }
  32657. if (currentRenderId !== selfRenderId) {
  32658. this._batchCache.renderSelf[subMeshId] = false;
  32659. }
  32660. }
  32661. this._renderIdForInstances[subMeshId] = currentRenderId;
  32662. }
  32663. return this._batchCache;
  32664. };
  32665. Mesh.prototype._renderWithInstances = function (subMesh, fillMode, batch, effect, engine) {
  32666. var visibleInstances = batch.visibleInstances[subMesh._id];
  32667. if (!visibleInstances) {
  32668. return this;
  32669. }
  32670. var matricesCount = visibleInstances.length + 1;
  32671. var bufferSize = matricesCount * 16 * 4;
  32672. var currentInstancesBufferSize = this._instancesBufferSize;
  32673. var instancesBuffer = this._instancesBuffer;
  32674. while (this._instancesBufferSize < bufferSize) {
  32675. this._instancesBufferSize *= 2;
  32676. }
  32677. if (!this._instancesData || currentInstancesBufferSize != this._instancesBufferSize) {
  32678. this._instancesData = new Float32Array(this._instancesBufferSize / 4);
  32679. }
  32680. var offset = 0;
  32681. var instancesCount = 0;
  32682. var world = this.getWorldMatrix();
  32683. if (batch.renderSelf[subMesh._id]) {
  32684. world.copyToArray(this._instancesData, offset);
  32685. offset += 16;
  32686. instancesCount++;
  32687. }
  32688. if (visibleInstances) {
  32689. for (var instanceIndex = 0; instanceIndex < visibleInstances.length; instanceIndex++) {
  32690. var instance = visibleInstances[instanceIndex];
  32691. instance.getWorldMatrix().copyToArray(this._instancesData, offset);
  32692. offset += 16;
  32693. instancesCount++;
  32694. }
  32695. }
  32696. if (!instancesBuffer || currentInstancesBufferSize != this._instancesBufferSize) {
  32697. if (instancesBuffer) {
  32698. instancesBuffer.dispose();
  32699. }
  32700. instancesBuffer = new BABYLON.Buffer(engine, this._instancesData, true, 16, false, true);
  32701. this._instancesBuffer = instancesBuffer;
  32702. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world0", 0, 4));
  32703. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world1", 4, 4));
  32704. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world2", 8, 4));
  32705. this.setVerticesBuffer(instancesBuffer.createVertexBuffer("world3", 12, 4));
  32706. }
  32707. else {
  32708. instancesBuffer.updateDirectly(this._instancesData, 0, instancesCount);
  32709. }
  32710. this._bind(subMesh, effect, fillMode);
  32711. this._draw(subMesh, fillMode, instancesCount);
  32712. engine.unbindInstanceAttributes();
  32713. return this;
  32714. };
  32715. Mesh.prototype._processRendering = function (subMesh, effect, fillMode, batch, hardwareInstancedRendering, onBeforeDraw, effectiveMaterial) {
  32716. var scene = this.getScene();
  32717. var engine = scene.getEngine();
  32718. if (hardwareInstancedRendering) {
  32719. this._renderWithInstances(subMesh, fillMode, batch, effect, engine);
  32720. }
  32721. else {
  32722. if (batch.renderSelf[subMesh._id]) {
  32723. // Draw
  32724. if (onBeforeDraw) {
  32725. onBeforeDraw(false, this.getWorldMatrix(), effectiveMaterial);
  32726. }
  32727. this._draw(subMesh, fillMode, this._overridenInstanceCount);
  32728. }
  32729. var visibleInstancesForSubMesh = batch.visibleInstances[subMesh._id];
  32730. if (visibleInstancesForSubMesh) {
  32731. for (var instanceIndex = 0; instanceIndex < visibleInstancesForSubMesh.length; instanceIndex++) {
  32732. var instance = visibleInstancesForSubMesh[instanceIndex];
  32733. // World
  32734. var world = instance.getWorldMatrix();
  32735. if (onBeforeDraw) {
  32736. onBeforeDraw(true, world, effectiveMaterial);
  32737. }
  32738. // Draw
  32739. this._draw(subMesh, fillMode);
  32740. }
  32741. }
  32742. }
  32743. return this;
  32744. };
  32745. /**
  32746. * Triggers the draw call for the mesh.
  32747. * Usually, you don't need to call this method by your own because the mesh rendering is handled by the scene rendering manager.
  32748. * Returns the Mesh.
  32749. */
  32750. Mesh.prototype.render = function (subMesh, enableAlphaMode) {
  32751. this._checkOcclusionQuery();
  32752. if (this._isOccluded) {
  32753. return this;
  32754. }
  32755. var scene = this.getScene();
  32756. // Managing instances
  32757. var batch = this._getInstancesRenderList(subMesh._id);
  32758. if (batch.mustReturn) {
  32759. return this;
  32760. }
  32761. // Checking geometry state
  32762. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  32763. return this;
  32764. }
  32765. this.onBeforeRenderObservable.notifyObservers(this);
  32766. var engine = scene.getEngine();
  32767. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  32768. // Material
  32769. var material = subMesh.getMaterial();
  32770. if (!material) {
  32771. return this;
  32772. }
  32773. this._effectiveMaterial = material;
  32774. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32775. if (!this._effectiveMaterial.isReadyForSubMesh(this, subMesh, hardwareInstancedRendering)) {
  32776. return this;
  32777. }
  32778. }
  32779. else if (!this._effectiveMaterial.isReady(this, hardwareInstancedRendering)) {
  32780. return this;
  32781. }
  32782. // Alpha mode
  32783. if (enableAlphaMode) {
  32784. engine.setAlphaMode(this._effectiveMaterial.alphaMode);
  32785. }
  32786. // Outline - step 1
  32787. var savedDepthWrite = engine.getDepthWrite();
  32788. if (this.renderOutline) {
  32789. engine.setDepthWrite(false);
  32790. scene.getOutlineRenderer().render(subMesh, batch);
  32791. engine.setDepthWrite(savedDepthWrite);
  32792. }
  32793. var effect;
  32794. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32795. effect = subMesh.effect;
  32796. }
  32797. else {
  32798. effect = this._effectiveMaterial.getEffect();
  32799. }
  32800. if (!effect) {
  32801. return this;
  32802. }
  32803. var sideOrientation = this.overrideMaterialSideOrientation;
  32804. if (sideOrientation == null) {
  32805. sideOrientation = this._effectiveMaterial.sideOrientation;
  32806. if (this._getWorldMatrixDeterminant() < 0) {
  32807. sideOrientation = (sideOrientation === BABYLON.Material.ClockWiseSideOrientation ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation);
  32808. }
  32809. }
  32810. var reverse = this._effectiveMaterial._preBind(effect, sideOrientation);
  32811. if (this._effectiveMaterial.forceDepthWrite) {
  32812. engine.setDepthWrite(true);
  32813. }
  32814. // Bind
  32815. var fillMode = scene.forcePointsCloud ? BABYLON.Material.PointFillMode : (scene.forceWireframe ? BABYLON.Material.WireFrameFillMode : this._effectiveMaterial.fillMode);
  32816. if (!hardwareInstancedRendering) { // Binding will be done later because we need to add more info to the VB
  32817. this._bind(subMesh, effect, fillMode);
  32818. }
  32819. var world = this.getWorldMatrix();
  32820. if (this._effectiveMaterial.storeEffectOnSubMeshes) {
  32821. this._effectiveMaterial.bindForSubMesh(world, this, subMesh);
  32822. }
  32823. else {
  32824. this._effectiveMaterial.bind(world, this);
  32825. }
  32826. if (!this._effectiveMaterial.backFaceCulling && this._effectiveMaterial.separateCullingPass) {
  32827. engine.setState(true, this._effectiveMaterial.zOffset, false, !reverse);
  32828. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32829. engine.setState(true, this._effectiveMaterial.zOffset, false, reverse);
  32830. }
  32831. // Draw
  32832. this._processRendering(subMesh, effect, fillMode, batch, hardwareInstancedRendering, this._onBeforeDraw, this._effectiveMaterial);
  32833. // Unbind
  32834. this._effectiveMaterial.unbind();
  32835. // Outline - step 2
  32836. if (this.renderOutline && savedDepthWrite) {
  32837. engine.setDepthWrite(true);
  32838. engine.setColorWrite(false);
  32839. scene.getOutlineRenderer().render(subMesh, batch);
  32840. engine.setColorWrite(true);
  32841. }
  32842. // Overlay
  32843. if (this.renderOverlay) {
  32844. var currentMode = engine.getAlphaMode();
  32845. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  32846. scene.getOutlineRenderer().render(subMesh, batch, true);
  32847. engine.setAlphaMode(currentMode);
  32848. }
  32849. this.onAfterRenderObservable.notifyObservers(this);
  32850. return this;
  32851. };
  32852. Mesh.prototype._onBeforeDraw = function (isInstance, world, effectiveMaterial) {
  32853. if (isInstance && effectiveMaterial) {
  32854. effectiveMaterial.bindOnlyWorldMatrix(world);
  32855. }
  32856. };
  32857. /**
  32858. * Returns an array populated with ParticleSystem objects whose the mesh is the emitter.
  32859. */
  32860. Mesh.prototype.getEmittedParticleSystems = function () {
  32861. var results = new Array();
  32862. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32863. var particleSystem = this.getScene().particleSystems[index];
  32864. if (particleSystem.emitter === this) {
  32865. results.push(particleSystem);
  32866. }
  32867. }
  32868. return results;
  32869. };
  32870. /**
  32871. * Returns an array populated with ParticleSystem objects whose the mesh or its children are the emitter.
  32872. */
  32873. Mesh.prototype.getHierarchyEmittedParticleSystems = function () {
  32874. var results = new Array();
  32875. var descendants = this.getDescendants();
  32876. descendants.push(this);
  32877. for (var index = 0; index < this.getScene().particleSystems.length; index++) {
  32878. var particleSystem = this.getScene().particleSystems[index];
  32879. var emitter = particleSystem.emitter;
  32880. if (emitter.position && descendants.indexOf(emitter) !== -1) {
  32881. results.push(particleSystem);
  32882. }
  32883. }
  32884. return results;
  32885. };
  32886. /**
  32887. * Normalize matrix weights so that all vertices have a total weight set to 1
  32888. */
  32889. Mesh.prototype.cleanMatrixWeights = function () {
  32890. var epsilon = 1e-3;
  32891. var noInfluenceBoneIndex = 0.0;
  32892. if (this.skeleton) {
  32893. noInfluenceBoneIndex = this.skeleton.bones.length;
  32894. }
  32895. else {
  32896. return;
  32897. }
  32898. var matricesIndices = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  32899. var matricesIndicesExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  32900. var matricesWeights = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  32901. var matricesWeightsExtra = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  32902. var influencers = this.numBoneInfluencers;
  32903. var size = matricesWeights.length;
  32904. for (var i = 0; i < size; i += 4) {
  32905. var weight = 0.0;
  32906. var firstZeroWeight = -1;
  32907. for (var j = 0; j < 4; j++) {
  32908. var w = matricesWeights[i + j];
  32909. weight += w;
  32910. if (w < epsilon && firstZeroWeight < 0) {
  32911. firstZeroWeight = j;
  32912. }
  32913. }
  32914. if (matricesWeightsExtra) {
  32915. for (var j = 0; j < 4; j++) {
  32916. var w = matricesWeightsExtra[i + j];
  32917. weight += w;
  32918. if (w < epsilon && firstZeroWeight < 0) {
  32919. firstZeroWeight = j + 4;
  32920. }
  32921. }
  32922. }
  32923. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  32924. firstZeroWeight = influencers - 1;
  32925. }
  32926. if (weight > epsilon) {
  32927. var mweight = 1.0 / weight;
  32928. for (var j = 0; j < 4; j++) {
  32929. matricesWeights[i + j] *= mweight;
  32930. }
  32931. if (matricesWeightsExtra) {
  32932. for (var j = 0; j < 4; j++) {
  32933. matricesWeightsExtra[i + j] *= mweight;
  32934. }
  32935. }
  32936. }
  32937. else {
  32938. if (firstZeroWeight >= 4) {
  32939. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  32940. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  32941. }
  32942. else {
  32943. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  32944. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  32945. }
  32946. }
  32947. }
  32948. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  32949. if (matricesIndicesExtra) {
  32950. this.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  32951. }
  32952. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeights);
  32953. if (matricesWeightsExtra) {
  32954. this.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, matricesWeightsExtra);
  32955. }
  32956. };
  32957. Mesh.prototype._checkDelayState = function () {
  32958. var scene = this.getScene();
  32959. if (this._geometry) {
  32960. this._geometry.load(scene);
  32961. }
  32962. else if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  32963. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  32964. this._queueLoad(scene);
  32965. }
  32966. return this;
  32967. };
  32968. Mesh.prototype._queueLoad = function (scene) {
  32969. var _this = this;
  32970. scene._addPendingData(this);
  32971. var getBinaryData = (this.delayLoadingFile.indexOf(".babylonbinarymeshdata") !== -1);
  32972. BABYLON.Tools.LoadFile(this.delayLoadingFile, function (data) {
  32973. if (data instanceof ArrayBuffer) {
  32974. _this._delayLoadingFunction(data, _this);
  32975. }
  32976. else {
  32977. _this._delayLoadingFunction(JSON.parse(data), _this);
  32978. }
  32979. _this.instances.forEach(function (instance) {
  32980. instance._syncSubMeshes();
  32981. });
  32982. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  32983. scene._removePendingData(_this);
  32984. }, function () { }, scene.database, getBinaryData);
  32985. return this;
  32986. };
  32987. /**
  32988. * Boolean, true is the mesh in the frustum defined by the Plane objects from the `frustumPlanes` array parameter.
  32989. */
  32990. Mesh.prototype.isInFrustum = function (frustumPlanes) {
  32991. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  32992. return false;
  32993. }
  32994. if (!_super.prototype.isInFrustum.call(this, frustumPlanes)) {
  32995. return false;
  32996. }
  32997. this._checkDelayState();
  32998. return true;
  32999. };
  33000. /**
  33001. * Sets the mesh material by the material or multiMaterial `id` property.
  33002. * The material `id` is a string identifying the material or the multiMaterial.
  33003. * This method returns the Mesh.
  33004. */
  33005. Mesh.prototype.setMaterialByID = function (id) {
  33006. var materials = this.getScene().materials;
  33007. var index;
  33008. for (index = materials.length - 1; index > -1; index--) {
  33009. if (materials[index].id === id) {
  33010. this.material = materials[index];
  33011. return this;
  33012. }
  33013. }
  33014. // Multi
  33015. var multiMaterials = this.getScene().multiMaterials;
  33016. for (index = multiMaterials.length - 1; index > -1; index--) {
  33017. if (multiMaterials[index].id === id) {
  33018. this.material = multiMaterials[index];
  33019. return this;
  33020. }
  33021. }
  33022. return this;
  33023. };
  33024. /**
  33025. * Returns as a new array populated with the mesh material and/or skeleton, if any.
  33026. */
  33027. Mesh.prototype.getAnimatables = function () {
  33028. var results = new Array();
  33029. if (this.material) {
  33030. results.push(this.material);
  33031. }
  33032. if (this.skeleton) {
  33033. results.push(this.skeleton);
  33034. }
  33035. return results;
  33036. };
  33037. /**
  33038. * Modifies the mesh geometry according to the passed transformation matrix.
  33039. * This method returns nothing but it really modifies the mesh even if it's originally not set as updatable.
  33040. * The mesh normals are modified accordingly the same transformation.
  33041. * tuto : http://doc.babylonjs.com/resources/baking_transformations
  33042. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33043. * Returns the Mesh.
  33044. */
  33045. Mesh.prototype.bakeTransformIntoVertices = function (transform) {
  33046. // Position
  33047. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  33048. return this;
  33049. }
  33050. var submeshes = this.subMeshes.splice(0);
  33051. this._resetPointsArrayCache();
  33052. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33053. var temp = new Array();
  33054. var index;
  33055. for (index = 0; index < data.length; index += 3) {
  33056. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(data, index), transform).toArray(temp, index);
  33057. }
  33058. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.PositionKind).isUpdatable());
  33059. // Normals
  33060. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  33061. return this;
  33062. }
  33063. data = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33064. temp = [];
  33065. for (index = 0; index < data.length; index += 3) {
  33066. BABYLON.Vector3.TransformNormal(BABYLON.Vector3.FromArray(data, index), transform).normalize().toArray(temp, index);
  33067. }
  33068. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, temp, this.getVertexBuffer(BABYLON.VertexBuffer.NormalKind).isUpdatable());
  33069. // flip faces?
  33070. if (transform.m[0] * transform.m[5] * transform.m[10] < 0) {
  33071. this.flipFaces();
  33072. }
  33073. // Restore submeshes
  33074. this.releaseSubMeshes();
  33075. this.subMeshes = submeshes;
  33076. return this;
  33077. };
  33078. /**
  33079. * Modifies the mesh geometry according to its own current World Matrix.
  33080. * The mesh World Matrix is then reset.
  33081. * This method returns nothing but really modifies the mesh even if it's originally not set as updatable.
  33082. * tuto : tuto : http://doc.babylonjs.com/resources/baking_transformations
  33083. * Note that, under the hood, this method sets a new VertexBuffer each call.
  33084. * Returns the Mesh.
  33085. */
  33086. Mesh.prototype.bakeCurrentTransformIntoVertices = function () {
  33087. this.bakeTransformIntoVertices(this.computeWorldMatrix(true));
  33088. this.scaling.copyFromFloats(1, 1, 1);
  33089. this.position.copyFromFloats(0, 0, 0);
  33090. this.rotation.copyFromFloats(0, 0, 0);
  33091. //only if quaternion is already set
  33092. if (this.rotationQuaternion) {
  33093. this.rotationQuaternion = BABYLON.Quaternion.Identity();
  33094. }
  33095. this._worldMatrix = BABYLON.Matrix.Identity();
  33096. return this;
  33097. };
  33098. Object.defineProperty(Mesh.prototype, "_positions", {
  33099. // Cache
  33100. get: function () {
  33101. if (this._geometry) {
  33102. return this._geometry._positions;
  33103. }
  33104. return null;
  33105. },
  33106. enumerable: true,
  33107. configurable: true
  33108. });
  33109. Mesh.prototype._resetPointsArrayCache = function () {
  33110. if (this._geometry) {
  33111. this._geometry._resetPointsArrayCache();
  33112. }
  33113. return this;
  33114. };
  33115. Mesh.prototype._generatePointsArray = function () {
  33116. if (this._geometry) {
  33117. return this._geometry._generatePointsArray();
  33118. }
  33119. return false;
  33120. };
  33121. /**
  33122. * Returns a new Mesh object generated from the current mesh properties.
  33123. * This method must not get confused with createInstance().
  33124. * The parameter `name` is a string, the name given to the new mesh.
  33125. * The optional parameter `newParent` can be any Node object (default `null`).
  33126. * The optional parameter `doNotCloneChildren` (default `false`) allows/denies the recursive cloning of the original mesh children if any.
  33127. * 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.
  33128. */
  33129. Mesh.prototype.clone = function (name, newParent, doNotCloneChildren, clonePhysicsImpostor) {
  33130. if (clonePhysicsImpostor === void 0) { clonePhysicsImpostor = true; }
  33131. return new Mesh(name, this.getScene(), newParent, this, doNotCloneChildren, clonePhysicsImpostor);
  33132. };
  33133. /**
  33134. * Releases resources associated with this mesh.
  33135. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  33136. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  33137. */
  33138. Mesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  33139. var _this = this;
  33140. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  33141. this.morphTargetManager = null;
  33142. if (this._geometry) {
  33143. this._geometry.releaseForMesh(this, true);
  33144. }
  33145. // Sources
  33146. var meshes = this.getScene().meshes;
  33147. meshes.forEach(function (abstractMesh) {
  33148. var mesh = abstractMesh;
  33149. if (mesh._source && mesh._source === _this) {
  33150. mesh._source = null;
  33151. }
  33152. });
  33153. this._source = null;
  33154. // Instances
  33155. if (this._instancesBuffer) {
  33156. this._instancesBuffer.dispose();
  33157. this._instancesBuffer = null;
  33158. }
  33159. while (this.instances.length) {
  33160. this.instances[0].dispose();
  33161. }
  33162. // Effect layers.
  33163. var effectLayers = this.getScene().effectLayers;
  33164. for (var i = 0; i < effectLayers.length; i++) {
  33165. var effectLayer = effectLayers[i];
  33166. if (effectLayer) {
  33167. effectLayer._disposeMesh(this);
  33168. }
  33169. }
  33170. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  33171. };
  33172. /**
  33173. * Modifies the mesh geometry according to a displacement map.
  33174. * 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.
  33175. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33176. * This method returns nothing.
  33177. * The parameter `url` is a string, the URL from the image file is to be downloaded.
  33178. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33179. * 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.
  33180. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33181. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33182. *
  33183. * Returns the Mesh.
  33184. */
  33185. Mesh.prototype.applyDisplacementMap = function (url, minHeight, maxHeight, onSuccess, uvOffset, uvScale) {
  33186. var _this = this;
  33187. var scene = this.getScene();
  33188. var onload = function (img) {
  33189. // Getting height map data
  33190. var canvas = document.createElement("canvas");
  33191. var context = canvas.getContext("2d");
  33192. var heightMapWidth = img.width;
  33193. var heightMapHeight = img.height;
  33194. canvas.width = heightMapWidth;
  33195. canvas.height = heightMapHeight;
  33196. context.drawImage(img, 0, 0);
  33197. // Create VertexData from map data
  33198. //Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  33199. var buffer = context.getImageData(0, 0, heightMapWidth, heightMapHeight).data;
  33200. _this.applyDisplacementMapFromBuffer(buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale);
  33201. //execute success callback, if set
  33202. if (onSuccess) {
  33203. onSuccess(_this);
  33204. }
  33205. };
  33206. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  33207. return this;
  33208. };
  33209. /**
  33210. * Modifies the mesh geometry according to a displacementMap buffer.
  33211. * 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.
  33212. * The mesh must be set as updatable. Its internal geometry is directly modified, no new buffer are allocated.
  33213. * This method returns nothing.
  33214. * 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.
  33215. * The parameters `heightMapWidth` and `heightMapHeight` are positive integers to set the width and height of the buffer image.
  33216. * The parameters `minHeight` and `maxHeight` are the lower and upper limits of the displacement.
  33217. * The parameter `uvOffset` is an optional vector2 used to offset UV.
  33218. * The parameter `uvScale` is an optional vector2 used to scale UV.
  33219. *
  33220. * Returns the Mesh.
  33221. */
  33222. Mesh.prototype.applyDisplacementMapFromBuffer = function (buffer, heightMapWidth, heightMapHeight, minHeight, maxHeight, uvOffset, uvScale) {
  33223. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)
  33224. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)
  33225. || !this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  33226. BABYLON.Tools.Warn("Cannot call applyDisplacementMap: Given mesh is not complete. Position, Normal or UV are missing");
  33227. return this;
  33228. }
  33229. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33230. var normals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  33231. var uvs = this.getVerticesData(BABYLON.VertexBuffer.UVKind);
  33232. var position = BABYLON.Vector3.Zero();
  33233. var normal = BABYLON.Vector3.Zero();
  33234. var uv = BABYLON.Vector2.Zero();
  33235. uvOffset = uvOffset || BABYLON.Vector2.Zero();
  33236. uvScale = uvScale || new BABYLON.Vector2(1, 1);
  33237. for (var index = 0; index < positions.length; index += 3) {
  33238. BABYLON.Vector3.FromArrayToRef(positions, index, position);
  33239. BABYLON.Vector3.FromArrayToRef(normals, index, normal);
  33240. BABYLON.Vector2.FromArrayToRef(uvs, (index / 3) * 2, uv);
  33241. // Compute height
  33242. var u = ((Math.abs(uv.x * uvScale.x + uvOffset.x) * heightMapWidth) % heightMapWidth) | 0;
  33243. var v = ((Math.abs(uv.y * uvScale.y + uvOffset.y) * heightMapHeight) % heightMapHeight) | 0;
  33244. var pos = (u + v * heightMapWidth) * 4;
  33245. var r = buffer[pos] / 255.0;
  33246. var g = buffer[pos + 1] / 255.0;
  33247. var b = buffer[pos + 2] / 255.0;
  33248. var gradient = r * 0.3 + g * 0.59 + b * 0.11;
  33249. normal.normalize();
  33250. normal.scaleInPlace(minHeight + (maxHeight - minHeight) * gradient);
  33251. position = position.add(normal);
  33252. position.toArray(positions, index);
  33253. }
  33254. BABYLON.VertexData.ComputeNormals(positions, this.getIndices(), normals);
  33255. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  33256. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  33257. return this;
  33258. };
  33259. /**
  33260. * Modify the mesh to get a flat shading rendering.
  33261. * This means each mesh facet will then have its own normals. Usually new vertices are added in the mesh geometry to get this result.
  33262. * This method returns the Mesh.
  33263. * Warning : the mesh is really modified even if not set originally as updatable and, under the hood, a new VertexBuffer is allocated.
  33264. */
  33265. Mesh.prototype.convertToFlatShadedMesh = function () {
  33266. /// <summary>Update normals and vertices to get a flat shading rendering.</summary>
  33267. /// <summary>Warning: This may imply adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33268. var kinds = this.getVerticesDataKinds();
  33269. var vbs = {};
  33270. var data = {};
  33271. var newdata = {};
  33272. var updatableNormals = false;
  33273. var kindIndex;
  33274. var kind;
  33275. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33276. kind = kinds[kindIndex];
  33277. var vertexBuffer = this.getVertexBuffer(kind);
  33278. if (kind === BABYLON.VertexBuffer.NormalKind) {
  33279. updatableNormals = vertexBuffer.isUpdatable();
  33280. kinds.splice(kindIndex, 1);
  33281. kindIndex--;
  33282. continue;
  33283. }
  33284. vbs[kind] = vertexBuffer;
  33285. data[kind] = vbs[kind].getData();
  33286. newdata[kind] = [];
  33287. }
  33288. // Save previous submeshes
  33289. var previousSubmeshes = this.subMeshes.slice(0);
  33290. var indices = this.getIndices();
  33291. var totalIndices = this.getTotalIndices();
  33292. // Generating unique vertices per face
  33293. var index;
  33294. for (index = 0; index < totalIndices; index++) {
  33295. var vertexIndex = indices[index];
  33296. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33297. kind = kinds[kindIndex];
  33298. var stride = vbs[kind].getStrideSize();
  33299. for (var offset = 0; offset < stride; offset++) {
  33300. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33301. }
  33302. }
  33303. }
  33304. // Updating faces & normal
  33305. var normals = [];
  33306. var positions = newdata[BABYLON.VertexBuffer.PositionKind];
  33307. for (index = 0; index < totalIndices; index += 3) {
  33308. indices[index] = index;
  33309. indices[index + 1] = index + 1;
  33310. indices[index + 2] = index + 2;
  33311. var p1 = BABYLON.Vector3.FromArray(positions, index * 3);
  33312. var p2 = BABYLON.Vector3.FromArray(positions, (index + 1) * 3);
  33313. var p3 = BABYLON.Vector3.FromArray(positions, (index + 2) * 3);
  33314. var p1p2 = p1.subtract(p2);
  33315. var p3p2 = p3.subtract(p2);
  33316. var normal = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(p1p2, p3p2));
  33317. // Store same normals for every vertex
  33318. for (var localIndex = 0; localIndex < 3; localIndex++) {
  33319. normals.push(normal.x);
  33320. normals.push(normal.y);
  33321. normals.push(normal.z);
  33322. }
  33323. }
  33324. this.setIndices(indices);
  33325. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatableNormals);
  33326. // Updating vertex buffers
  33327. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33328. kind = kinds[kindIndex];
  33329. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33330. }
  33331. // Updating submeshes
  33332. this.releaseSubMeshes();
  33333. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33334. var previousOne = previousSubmeshes[submeshIndex];
  33335. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33336. }
  33337. this.synchronizeInstances();
  33338. return this;
  33339. };
  33340. /**
  33341. * This method removes all the mesh indices and add new vertices (duplication) in order to unfold facets into buffers.
  33342. * In other words, more vertices, no more indices and a single bigger VBO.
  33343. * The mesh is really modified even if not set originally as updatable. Under the hood, a new VertexBuffer is allocated.
  33344. * Returns the Mesh.
  33345. */
  33346. Mesh.prototype.convertToUnIndexedMesh = function () {
  33347. /// <summary>Remove indices by unfolding faces into buffers</summary>
  33348. /// <summary>Warning: This implies adding vertices to the mesh in order to get exactly 3 vertices per face</summary>
  33349. var kinds = this.getVerticesDataKinds();
  33350. var vbs = {};
  33351. var data = {};
  33352. var newdata = {};
  33353. var kindIndex;
  33354. var kind;
  33355. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33356. kind = kinds[kindIndex];
  33357. var vertexBuffer = this.getVertexBuffer(kind);
  33358. vbs[kind] = vertexBuffer;
  33359. data[kind] = vbs[kind].getData();
  33360. newdata[kind] = [];
  33361. }
  33362. // Save previous submeshes
  33363. var previousSubmeshes = this.subMeshes.slice(0);
  33364. var indices = this.getIndices();
  33365. var totalIndices = this.getTotalIndices();
  33366. // Generating unique vertices per face
  33367. var index;
  33368. for (index = 0; index < totalIndices; index++) {
  33369. var vertexIndex = indices[index];
  33370. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33371. kind = kinds[kindIndex];
  33372. var stride = vbs[kind].getStrideSize();
  33373. for (var offset = 0; offset < stride; offset++) {
  33374. newdata[kind].push(data[kind][vertexIndex * stride + offset]);
  33375. }
  33376. }
  33377. }
  33378. // Updating indices
  33379. for (index = 0; index < totalIndices; index += 3) {
  33380. indices[index] = index;
  33381. indices[index + 1] = index + 1;
  33382. indices[index + 2] = index + 2;
  33383. }
  33384. this.setIndices(indices);
  33385. // Updating vertex buffers
  33386. for (kindIndex = 0; kindIndex < kinds.length; kindIndex++) {
  33387. kind = kinds[kindIndex];
  33388. this.setVerticesData(kind, newdata[kind], vbs[kind].isUpdatable());
  33389. }
  33390. // Updating submeshes
  33391. this.releaseSubMeshes();
  33392. for (var submeshIndex = 0; submeshIndex < previousSubmeshes.length; submeshIndex++) {
  33393. var previousOne = previousSubmeshes[submeshIndex];
  33394. BABYLON.SubMesh.AddToMesh(previousOne.materialIndex, previousOne.indexStart, previousOne.indexCount, previousOne.indexStart, previousOne.indexCount, this);
  33395. }
  33396. this._unIndexed = true;
  33397. this.synchronizeInstances();
  33398. return this;
  33399. };
  33400. /**
  33401. * Inverses facet orientations and inverts also the normals with `flipNormals` (default `false`) if true.
  33402. * This method returns the Mesh.
  33403. * Warning : the mesh is really modified even if not set originally as updatable. A new VertexBuffer is created under the hood each call.
  33404. */
  33405. Mesh.prototype.flipFaces = function (flipNormals) {
  33406. if (flipNormals === void 0) { flipNormals = false; }
  33407. var vertex_data = BABYLON.VertexData.ExtractFromMesh(this);
  33408. var i;
  33409. if (flipNormals && this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind) && vertex_data.normals) {
  33410. for (i = 0; i < vertex_data.normals.length; i++) {
  33411. vertex_data.normals[i] *= -1;
  33412. }
  33413. }
  33414. if (vertex_data.indices) {
  33415. var temp;
  33416. for (i = 0; i < vertex_data.indices.length; i += 3) {
  33417. // reassign indices
  33418. temp = vertex_data.indices[i + 1];
  33419. vertex_data.indices[i + 1] = vertex_data.indices[i + 2];
  33420. vertex_data.indices[i + 2] = temp;
  33421. }
  33422. }
  33423. vertex_data.applyToMesh(this);
  33424. return this;
  33425. };
  33426. // Instances
  33427. /**
  33428. * Creates a new InstancedMesh object from the mesh model.
  33429. * An instance shares the same properties and the same material than its model.
  33430. * Only these properties of each instance can then be set individually :
  33431. * - position
  33432. * - rotation
  33433. * - rotationQuaternion
  33434. * - setPivotMatrix
  33435. * - scaling
  33436. * tuto : http://doc.babylonjs.com/tutorials/How_to_use_Instances
  33437. * Warning : this method is not supported for Line mesh and LineSystem
  33438. */
  33439. Mesh.prototype.createInstance = function (name) {
  33440. return new BABYLON.InstancedMesh(name, this);
  33441. };
  33442. /**
  33443. * Synchronises all the mesh instance submeshes to the current mesh submeshes, if any.
  33444. * After this call, all the mesh instances have the same submeshes than the current mesh.
  33445. * This method returns the Mesh.
  33446. */
  33447. Mesh.prototype.synchronizeInstances = function () {
  33448. for (var instanceIndex = 0; instanceIndex < this.instances.length; instanceIndex++) {
  33449. var instance = this.instances[instanceIndex];
  33450. instance._syncSubMeshes();
  33451. }
  33452. return this;
  33453. };
  33454. /**
  33455. * Simplify the mesh according to the given array of settings.
  33456. * Function will return immediately and will simplify async. It returns the Mesh.
  33457. * @param settings a collection of simplification settings.
  33458. * @param parallelProcessing should all levels calculate parallel or one after the other.
  33459. * @param type the type of simplification to run.
  33460. * @param successCallback optional success callback to be called after the simplification finished processing all settings.
  33461. */
  33462. Mesh.prototype.simplify = function (settings, parallelProcessing, simplificationType, successCallback) {
  33463. if (parallelProcessing === void 0) { parallelProcessing = true; }
  33464. if (simplificationType === void 0) { simplificationType = BABYLON.SimplificationType.QUADRATIC; }
  33465. this.getScene().simplificationQueue.addTask({
  33466. settings: settings,
  33467. parallelProcessing: parallelProcessing,
  33468. mesh: this,
  33469. simplificationType: simplificationType,
  33470. successCallback: successCallback
  33471. });
  33472. return this;
  33473. };
  33474. /**
  33475. * Optimization of the mesh's indices, in case a mesh has duplicated vertices.
  33476. * The function will only reorder the indices and will not remove unused vertices to avoid problems with submeshes.
  33477. * This should be used together with the simplification to avoid disappearing triangles.
  33478. * Returns the Mesh.
  33479. * @param successCallback an optional success callback to be called after the optimization finished.
  33480. */
  33481. Mesh.prototype.optimizeIndices = function (successCallback) {
  33482. var _this = this;
  33483. var indices = this.getIndices();
  33484. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  33485. if (!positions || !indices) {
  33486. return this;
  33487. }
  33488. var vectorPositions = new Array();
  33489. for (var pos = 0; pos < positions.length; pos = pos + 3) {
  33490. vectorPositions.push(BABYLON.Vector3.FromArray(positions, pos));
  33491. }
  33492. var dupes = new Array();
  33493. BABYLON.AsyncLoop.SyncAsyncForLoop(vectorPositions.length, 40, function (iteration) {
  33494. var realPos = vectorPositions.length - 1 - iteration;
  33495. var testedPosition = vectorPositions[realPos];
  33496. for (var j = 0; j < realPos; ++j) {
  33497. var againstPosition = vectorPositions[j];
  33498. if (testedPosition.equals(againstPosition)) {
  33499. dupes[realPos] = j;
  33500. break;
  33501. }
  33502. }
  33503. }, function () {
  33504. for (var i = 0; i < indices.length; ++i) {
  33505. indices[i] = dupes[indices[i]] || indices[i];
  33506. }
  33507. //indices are now reordered
  33508. var originalSubMeshes = _this.subMeshes.slice(0);
  33509. _this.setIndices(indices);
  33510. _this.subMeshes = originalSubMeshes;
  33511. if (successCallback) {
  33512. successCallback(_this);
  33513. }
  33514. });
  33515. return this;
  33516. };
  33517. Mesh.prototype.serialize = function (serializationObject) {
  33518. serializationObject.name = this.name;
  33519. serializationObject.id = this.id;
  33520. serializationObject.type = this.getClassName();
  33521. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  33522. serializationObject.tags = BABYLON.Tags.GetTags(this);
  33523. }
  33524. serializationObject.position = this.position.asArray();
  33525. if (this.rotationQuaternion) {
  33526. serializationObject.rotationQuaternion = this.rotationQuaternion.asArray();
  33527. }
  33528. else if (this.rotation) {
  33529. serializationObject.rotation = this.rotation.asArray();
  33530. }
  33531. serializationObject.scaling = this.scaling.asArray();
  33532. serializationObject.localMatrix = this.getPivotMatrix().asArray();
  33533. serializationObject.isEnabled = this.isEnabled(false);
  33534. serializationObject.isVisible = this.isVisible;
  33535. serializationObject.infiniteDistance = this.infiniteDistance;
  33536. serializationObject.pickable = this.isPickable;
  33537. serializationObject.receiveShadows = this.receiveShadows;
  33538. serializationObject.billboardMode = this.billboardMode;
  33539. serializationObject.visibility = this.visibility;
  33540. serializationObject.checkCollisions = this.checkCollisions;
  33541. serializationObject.isBlocker = this.isBlocker;
  33542. // Parent
  33543. if (this.parent) {
  33544. serializationObject.parentId = this.parent.id;
  33545. }
  33546. // Geometry
  33547. serializationObject.isUnIndexed = this.isUnIndexed;
  33548. var geometry = this._geometry;
  33549. if (geometry) {
  33550. var geometryId = geometry.id;
  33551. serializationObject.geometryId = geometryId;
  33552. // SubMeshes
  33553. serializationObject.subMeshes = [];
  33554. for (var subIndex = 0; subIndex < this.subMeshes.length; subIndex++) {
  33555. var subMesh = this.subMeshes[subIndex];
  33556. serializationObject.subMeshes.push({
  33557. materialIndex: subMesh.materialIndex,
  33558. verticesStart: subMesh.verticesStart,
  33559. verticesCount: subMesh.verticesCount,
  33560. indexStart: subMesh.indexStart,
  33561. indexCount: subMesh.indexCount
  33562. });
  33563. }
  33564. }
  33565. // Material
  33566. if (this.material) {
  33567. serializationObject.materialId = this.material.id;
  33568. }
  33569. else {
  33570. this.material = null;
  33571. }
  33572. // Morph targets
  33573. if (this.morphTargetManager) {
  33574. serializationObject.morphTargetManagerId = this.morphTargetManager.uniqueId;
  33575. }
  33576. // Skeleton
  33577. if (this.skeleton) {
  33578. serializationObject.skeletonId = this.skeleton.id;
  33579. }
  33580. // Physics
  33581. //TODO implement correct serialization for physics impostors.
  33582. var impostor = this.getPhysicsImpostor();
  33583. if (impostor) {
  33584. serializationObject.physicsMass = impostor.getParam("mass");
  33585. serializationObject.physicsFriction = impostor.getParam("friction");
  33586. serializationObject.physicsRestitution = impostor.getParam("mass");
  33587. serializationObject.physicsImpostor = impostor.type;
  33588. }
  33589. // Metadata
  33590. if (this.metadata) {
  33591. serializationObject.metadata = this.metadata;
  33592. }
  33593. // Instances
  33594. serializationObject.instances = [];
  33595. for (var index = 0; index < this.instances.length; index++) {
  33596. var instance = this.instances[index];
  33597. var serializationInstance = {
  33598. name: instance.name,
  33599. id: instance.id,
  33600. position: instance.position.asArray(),
  33601. scaling: instance.scaling.asArray()
  33602. };
  33603. if (instance.rotationQuaternion) {
  33604. serializationInstance.rotationQuaternion = instance.rotationQuaternion.asArray();
  33605. }
  33606. else if (instance.rotation) {
  33607. serializationInstance.rotation = instance.rotation.asArray();
  33608. }
  33609. serializationObject.instances.push(serializationInstance);
  33610. // Animations
  33611. BABYLON.Animation.AppendSerializedAnimations(instance, serializationInstance);
  33612. serializationInstance.ranges = instance.serializeAnimationRanges();
  33613. }
  33614. //
  33615. // Animations
  33616. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  33617. serializationObject.ranges = this.serializeAnimationRanges();
  33618. // Layer mask
  33619. serializationObject.layerMask = this.layerMask;
  33620. // Alpha
  33621. serializationObject.alphaIndex = this.alphaIndex;
  33622. serializationObject.hasVertexAlpha = this.hasVertexAlpha;
  33623. // Overlay
  33624. serializationObject.overlayAlpha = this.overlayAlpha;
  33625. serializationObject.overlayColor = this.overlayColor.asArray();
  33626. serializationObject.renderOverlay = this.renderOverlay;
  33627. // Fog
  33628. serializationObject.applyFog = this.applyFog;
  33629. // Action Manager
  33630. if (this.actionManager) {
  33631. serializationObject.actions = this.actionManager.serialize(this.name);
  33632. }
  33633. };
  33634. Mesh.prototype._syncGeometryWithMorphTargetManager = function () {
  33635. if (!this.geometry) {
  33636. return;
  33637. }
  33638. this._markSubMeshesAsAttributesDirty();
  33639. var morphTargetManager = this._morphTargetManager;
  33640. if (morphTargetManager && morphTargetManager.vertexCount) {
  33641. if (morphTargetManager.vertexCount !== this.getTotalVertices()) {
  33642. BABYLON.Tools.Error("Mesh is incompatible with morph targets. Targets and mesh must all have the same vertices count.");
  33643. this.morphTargetManager = null;
  33644. return;
  33645. }
  33646. for (var index = 0; index < morphTargetManager.numInfluencers; index++) {
  33647. var morphTarget = morphTargetManager.getActiveTarget(index);
  33648. var positions = morphTarget.getPositions();
  33649. if (!positions) {
  33650. BABYLON.Tools.Error("Invalid morph target. Target must have positions.");
  33651. return;
  33652. }
  33653. this.geometry.setVerticesData(BABYLON.VertexBuffer.PositionKind + index, positions, false, 3);
  33654. var normals = morphTarget.getNormals();
  33655. if (normals) {
  33656. this.geometry.setVerticesData(BABYLON.VertexBuffer.NormalKind + index, normals, false, 3);
  33657. }
  33658. var tangents = morphTarget.getTangents();
  33659. if (tangents) {
  33660. this.geometry.setVerticesData(BABYLON.VertexBuffer.TangentKind + index, tangents, false, 3);
  33661. }
  33662. }
  33663. }
  33664. else {
  33665. var index = 0;
  33666. // Positions
  33667. while (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind + index)) {
  33668. this.geometry.removeVerticesData(BABYLON.VertexBuffer.PositionKind + index);
  33669. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind + index)) {
  33670. this.geometry.removeVerticesData(BABYLON.VertexBuffer.NormalKind + index);
  33671. }
  33672. if (this.geometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind + index)) {
  33673. this.geometry.removeVerticesData(BABYLON.VertexBuffer.TangentKind + index);
  33674. }
  33675. index++;
  33676. }
  33677. }
  33678. };
  33679. // Statics
  33680. /**
  33681. * Returns a new Mesh object parsed from the source provided.
  33682. * The parameter `parsedMesh` is the source.
  33683. * The parameter `rootUrl` is a string, it's the root URL to prefix the `delayLoadingFile` property with
  33684. */
  33685. Mesh.Parse = function (parsedMesh, scene, rootUrl) {
  33686. var mesh;
  33687. if (parsedMesh.type && parsedMesh.type === "GroundMesh") {
  33688. mesh = BABYLON.GroundMesh.Parse(parsedMesh, scene);
  33689. }
  33690. else {
  33691. mesh = new Mesh(parsedMesh.name, scene);
  33692. }
  33693. mesh.id = parsedMesh.id;
  33694. if (BABYLON.Tags) {
  33695. BABYLON.Tags.AddTagsTo(mesh, parsedMesh.tags);
  33696. }
  33697. mesh.position = BABYLON.Vector3.FromArray(parsedMesh.position);
  33698. if (parsedMesh.metadata !== undefined) {
  33699. mesh.metadata = parsedMesh.metadata;
  33700. }
  33701. if (parsedMesh.rotationQuaternion) {
  33702. mesh.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedMesh.rotationQuaternion);
  33703. }
  33704. else if (parsedMesh.rotation) {
  33705. mesh.rotation = BABYLON.Vector3.FromArray(parsedMesh.rotation);
  33706. }
  33707. mesh.scaling = BABYLON.Vector3.FromArray(parsedMesh.scaling);
  33708. if (parsedMesh.localMatrix) {
  33709. mesh.setPreTransformMatrix(BABYLON.Matrix.FromArray(parsedMesh.localMatrix));
  33710. }
  33711. else if (parsedMesh.pivotMatrix) {
  33712. mesh.setPivotMatrix(BABYLON.Matrix.FromArray(parsedMesh.pivotMatrix));
  33713. }
  33714. mesh.setEnabled(parsedMesh.isEnabled);
  33715. mesh.isVisible = parsedMesh.isVisible;
  33716. mesh.infiniteDistance = parsedMesh.infiniteDistance;
  33717. mesh.showBoundingBox = parsedMesh.showBoundingBox;
  33718. mesh.showSubMeshesBoundingBox = parsedMesh.showSubMeshesBoundingBox;
  33719. if (parsedMesh.applyFog !== undefined) {
  33720. mesh.applyFog = parsedMesh.applyFog;
  33721. }
  33722. if (parsedMesh.pickable !== undefined) {
  33723. mesh.isPickable = parsedMesh.pickable;
  33724. }
  33725. if (parsedMesh.alphaIndex !== undefined) {
  33726. mesh.alphaIndex = parsedMesh.alphaIndex;
  33727. }
  33728. mesh.receiveShadows = parsedMesh.receiveShadows;
  33729. mesh.billboardMode = parsedMesh.billboardMode;
  33730. if (parsedMesh.visibility !== undefined) {
  33731. mesh.visibility = parsedMesh.visibility;
  33732. }
  33733. mesh.checkCollisions = parsedMesh.checkCollisions;
  33734. if (parsedMesh.isBlocker !== undefined) {
  33735. mesh.isBlocker = parsedMesh.isBlocker;
  33736. }
  33737. mesh._shouldGenerateFlatShading = parsedMesh.useFlatShading;
  33738. // freezeWorldMatrix
  33739. if (parsedMesh.freezeWorldMatrix) {
  33740. mesh._waitingFreezeWorldMatrix = parsedMesh.freezeWorldMatrix;
  33741. }
  33742. // Parent
  33743. if (parsedMesh.parentId) {
  33744. mesh._waitingParentId = parsedMesh.parentId;
  33745. }
  33746. // Actions
  33747. if (parsedMesh.actions !== undefined) {
  33748. mesh._waitingActions = parsedMesh.actions;
  33749. }
  33750. // Overlay
  33751. if (parsedMesh.overlayAlpha !== undefined) {
  33752. mesh.overlayAlpha = parsedMesh.overlayAlpha;
  33753. }
  33754. if (parsedMesh.overlayColor !== undefined) {
  33755. mesh.overlayColor = BABYLON.Color3.FromArray(parsedMesh.overlayColor);
  33756. }
  33757. if (parsedMesh.renderOverlay !== undefined) {
  33758. mesh.renderOverlay = parsedMesh.renderOverlay;
  33759. }
  33760. // Geometry
  33761. mesh.isUnIndexed = !!parsedMesh.isUnIndexed;
  33762. mesh.hasVertexAlpha = parsedMesh.hasVertexAlpha;
  33763. if (parsedMesh.delayLoadingFile) {
  33764. mesh.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  33765. mesh.delayLoadingFile = rootUrl + parsedMesh.delayLoadingFile;
  33766. mesh._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedMesh.boundingBoxMaximum));
  33767. if (parsedMesh._binaryInfo) {
  33768. mesh._binaryInfo = parsedMesh._binaryInfo;
  33769. }
  33770. mesh._delayInfo = [];
  33771. if (parsedMesh.hasUVs) {
  33772. mesh._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  33773. }
  33774. if (parsedMesh.hasUVs2) {
  33775. mesh._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  33776. }
  33777. if (parsedMesh.hasUVs3) {
  33778. mesh._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  33779. }
  33780. if (parsedMesh.hasUVs4) {
  33781. mesh._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  33782. }
  33783. if (parsedMesh.hasUVs5) {
  33784. mesh._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  33785. }
  33786. if (parsedMesh.hasUVs6) {
  33787. mesh._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  33788. }
  33789. if (parsedMesh.hasColors) {
  33790. mesh._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  33791. }
  33792. if (parsedMesh.hasMatricesIndices) {
  33793. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  33794. }
  33795. if (parsedMesh.hasMatricesWeights) {
  33796. mesh._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  33797. }
  33798. mesh._delayLoadingFunction = BABYLON.Geometry._ImportGeometry;
  33799. if (BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental) {
  33800. mesh._checkDelayState();
  33801. }
  33802. }
  33803. else {
  33804. BABYLON.Geometry._ImportGeometry(parsedMesh, mesh);
  33805. }
  33806. // Material
  33807. if (parsedMesh.materialId) {
  33808. mesh.setMaterialByID(parsedMesh.materialId);
  33809. }
  33810. else {
  33811. mesh.material = null;
  33812. }
  33813. // Morph targets
  33814. if (parsedMesh.morphTargetManagerId > -1) {
  33815. mesh.morphTargetManager = scene.getMorphTargetManagerById(parsedMesh.morphTargetManagerId);
  33816. }
  33817. // Skeleton
  33818. if (parsedMesh.skeletonId > -1) {
  33819. mesh.skeleton = scene.getLastSkeletonByID(parsedMesh.skeletonId);
  33820. if (parsedMesh.numBoneInfluencers) {
  33821. mesh.numBoneInfluencers = parsedMesh.numBoneInfluencers;
  33822. }
  33823. }
  33824. // Animations
  33825. if (parsedMesh.animations) {
  33826. for (var animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33827. var parsedAnimation = parsedMesh.animations[animationIndex];
  33828. mesh.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33829. }
  33830. BABYLON.Node.ParseAnimationRanges(mesh, parsedMesh, scene);
  33831. }
  33832. if (parsedMesh.autoAnimate) {
  33833. scene.beginAnimation(mesh, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33834. }
  33835. // Layer Mask
  33836. if (parsedMesh.layerMask && (!isNaN(parsedMesh.layerMask))) {
  33837. mesh.layerMask = Math.abs(parseInt(parsedMesh.layerMask));
  33838. }
  33839. else {
  33840. mesh.layerMask = 0x0FFFFFFF;
  33841. }
  33842. // Physics
  33843. if (parsedMesh.physicsImpostor) {
  33844. mesh.physicsImpostor = new BABYLON.PhysicsImpostor(mesh, parsedMesh.physicsImpostor, {
  33845. mass: parsedMesh.physicsMass,
  33846. friction: parsedMesh.physicsFriction,
  33847. restitution: parsedMesh.physicsRestitution
  33848. }, scene);
  33849. }
  33850. // Instances
  33851. if (parsedMesh.instances) {
  33852. for (var index = 0; index < parsedMesh.instances.length; index++) {
  33853. var parsedInstance = parsedMesh.instances[index];
  33854. var instance = mesh.createInstance(parsedInstance.name);
  33855. if (parsedInstance.id) {
  33856. instance.id = parsedInstance.id;
  33857. }
  33858. if (BABYLON.Tags) {
  33859. BABYLON.Tags.AddTagsTo(instance, parsedInstance.tags);
  33860. }
  33861. instance.position = BABYLON.Vector3.FromArray(parsedInstance.position);
  33862. if (parsedInstance.parentId) {
  33863. instance._waitingParentId = parsedInstance.parentId;
  33864. }
  33865. if (parsedInstance.rotationQuaternion) {
  33866. instance.rotationQuaternion = BABYLON.Quaternion.FromArray(parsedInstance.rotationQuaternion);
  33867. }
  33868. else if (parsedInstance.rotation) {
  33869. instance.rotation = BABYLON.Vector3.FromArray(parsedInstance.rotation);
  33870. }
  33871. instance.scaling = BABYLON.Vector3.FromArray(parsedInstance.scaling);
  33872. instance.checkCollisions = mesh.checkCollisions;
  33873. if (parsedMesh.animations) {
  33874. for (animationIndex = 0; animationIndex < parsedMesh.animations.length; animationIndex++) {
  33875. parsedAnimation = parsedMesh.animations[animationIndex];
  33876. instance.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  33877. }
  33878. BABYLON.Node.ParseAnimationRanges(instance, parsedMesh, scene);
  33879. if (parsedMesh.autoAnimate) {
  33880. scene.beginAnimation(instance, parsedMesh.autoAnimateFrom, parsedMesh.autoAnimateTo, parsedMesh.autoAnimateLoop, parsedMesh.autoAnimateSpeed || 1.0);
  33881. }
  33882. }
  33883. }
  33884. }
  33885. return mesh;
  33886. };
  33887. /**
  33888. * Creates a ribbon mesh.
  33889. * Please consider using the same method from the MeshBuilder class instead.
  33890. * 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.
  33891. *
  33892. * Please read this full tutorial to understand how to design a ribbon : http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  33893. * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry.
  33894. * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array.
  33895. * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array.
  33896. * 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.
  33897. * 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.
  33898. * 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
  33899. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33900. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33901. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33902. */
  33903. Mesh.CreateRibbon = function (name, pathArray, closeArray, closePath, offset, scene, updatable, sideOrientation, instance) {
  33904. if (closeArray === void 0) { closeArray = false; }
  33905. if (updatable === void 0) { updatable = false; }
  33906. return BABYLON.MeshBuilder.CreateRibbon(name, {
  33907. pathArray: pathArray,
  33908. closeArray: closeArray,
  33909. closePath: closePath,
  33910. offset: offset,
  33911. updatable: updatable,
  33912. sideOrientation: sideOrientation,
  33913. instance: instance
  33914. }, scene);
  33915. };
  33916. /**
  33917. * Creates a plane polygonal mesh. By default, this is a disc.
  33918. * Please consider using the same method from the MeshBuilder class instead.
  33919. * The parameter `radius` sets the radius size (float) of the polygon (default 0.5).
  33920. * 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.
  33921. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33922. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33923. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33924. */
  33925. Mesh.CreateDisc = function (name, radius, tessellation, scene, updatable, sideOrientation) {
  33926. if (scene === void 0) { scene = null; }
  33927. var options = {
  33928. radius: radius,
  33929. tessellation: tessellation,
  33930. sideOrientation: sideOrientation,
  33931. updatable: updatable
  33932. };
  33933. return BABYLON.MeshBuilder.CreateDisc(name, options, scene);
  33934. };
  33935. /**
  33936. * Creates a box mesh.
  33937. * Please consider using the same method from the MeshBuilder class instead.
  33938. * The parameter `size` sets the size (float) of each box side (default 1).
  33939. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33940. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33941. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33942. */
  33943. Mesh.CreateBox = function (name, size, scene, updatable, sideOrientation) {
  33944. if (scene === void 0) { scene = null; }
  33945. var options = {
  33946. size: size,
  33947. sideOrientation: sideOrientation,
  33948. updatable: updatable
  33949. };
  33950. return BABYLON.MeshBuilder.CreateBox(name, options, scene);
  33951. };
  33952. /**
  33953. * Creates a sphere mesh.
  33954. * Please consider using the same method from the MeshBuilder class instead.
  33955. * The parameter `diameter` sets the diameter size (float) of the sphere (default 1).
  33956. * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32).
  33957. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33958. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33959. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33960. */
  33961. Mesh.CreateSphere = function (name, segments, diameter, scene, updatable, sideOrientation) {
  33962. var options = {
  33963. segments: segments,
  33964. diameterX: diameter,
  33965. diameterY: diameter,
  33966. diameterZ: diameter,
  33967. sideOrientation: sideOrientation,
  33968. updatable: updatable
  33969. };
  33970. return BABYLON.MeshBuilder.CreateSphere(name, options, scene);
  33971. };
  33972. /**
  33973. * Creates a cylinder or a cone mesh.
  33974. * Please consider using the same method from the MeshBuilder class instead.
  33975. * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  33976. * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  33977. * 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.
  33978. * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  33979. * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  33980. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  33981. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  33982. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  33983. */
  33984. Mesh.CreateCylinder = function (name, height, diameterTop, diameterBottom, tessellation, subdivisions, scene, updatable, sideOrientation) {
  33985. if (scene === undefined || !(scene instanceof BABYLON.Scene)) {
  33986. if (scene !== undefined) {
  33987. sideOrientation = updatable || Mesh.DEFAULTSIDE;
  33988. updatable = scene;
  33989. }
  33990. scene = subdivisions;
  33991. subdivisions = 1;
  33992. }
  33993. var options = {
  33994. height: height,
  33995. diameterTop: diameterTop,
  33996. diameterBottom: diameterBottom,
  33997. tessellation: tessellation,
  33998. subdivisions: subdivisions,
  33999. sideOrientation: sideOrientation,
  34000. updatable: updatable
  34001. };
  34002. return BABYLON.MeshBuilder.CreateCylinder(name, options, scene);
  34003. };
  34004. // Torus (Code from SharpDX.org)
  34005. /**
  34006. * Creates a torus mesh.
  34007. * Please consider using the same method from the MeshBuilder class instead.
  34008. * The parameter `diameter` sets the diameter size (float) of the torus (default 1).
  34009. * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5).
  34010. * The parameter `tessellation` sets the number of torus sides (postive integer, default 16).
  34011. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34012. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34013. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34014. */
  34015. Mesh.CreateTorus = function (name, diameter, thickness, tessellation, scene, updatable, sideOrientation) {
  34016. var options = {
  34017. diameter: diameter,
  34018. thickness: thickness,
  34019. tessellation: tessellation,
  34020. sideOrientation: sideOrientation,
  34021. updatable: updatable
  34022. };
  34023. return BABYLON.MeshBuilder.CreateTorus(name, options, scene);
  34024. };
  34025. /**
  34026. * Creates a torus knot mesh.
  34027. * Please consider using the same method from the MeshBuilder class instead.
  34028. * The parameter `radius` sets the global radius size (float) of the torus knot (default 2).
  34029. * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32).
  34030. * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32).
  34031. * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3).
  34032. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34033. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34034. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34035. */
  34036. Mesh.CreateTorusKnot = function (name, radius, tube, radialSegments, tubularSegments, p, q, scene, updatable, sideOrientation) {
  34037. var options = {
  34038. radius: radius,
  34039. tube: tube,
  34040. radialSegments: radialSegments,
  34041. tubularSegments: tubularSegments,
  34042. p: p,
  34043. q: q,
  34044. sideOrientation: sideOrientation,
  34045. updatable: updatable
  34046. };
  34047. return BABYLON.MeshBuilder.CreateTorusKnot(name, options, scene);
  34048. };
  34049. /**
  34050. * Creates a line mesh.
  34051. * Please consider using the same method from the MeshBuilder class instead.
  34052. * 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.
  34053. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  34054. * The parameter `points` is an array successive Vector3.
  34055. * 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
  34056. * When updating an instance, remember that only point positions can change, not the number of points.
  34057. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34058. */
  34059. Mesh.CreateLines = function (name, points, scene, updatable, instance) {
  34060. if (scene === void 0) { scene = null; }
  34061. if (updatable === void 0) { updatable = false; }
  34062. if (instance === void 0) { instance = null; }
  34063. var options = {
  34064. points: points,
  34065. updatable: updatable,
  34066. instance: instance
  34067. };
  34068. return BABYLON.MeshBuilder.CreateLines(name, options, scene);
  34069. };
  34070. /**
  34071. * Creates a dashed line mesh.
  34072. * Please consider using the same method from the MeshBuilder class instead.
  34073. * 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.
  34074. * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function.
  34075. * The parameter `points` is an array successive Vector3.
  34076. * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200).
  34077. * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3).
  34078. * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1).
  34079. * 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
  34080. * When updating an instance, remember that only point positions can change, not the number of points.
  34081. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34082. */
  34083. Mesh.CreateDashedLines = function (name, points, dashSize, gapSize, dashNb, scene, updatable, instance) {
  34084. if (scene === void 0) { scene = null; }
  34085. var options = {
  34086. points: points,
  34087. dashSize: dashSize,
  34088. gapSize: gapSize,
  34089. dashNb: dashNb,
  34090. updatable: updatable,
  34091. instance: instance
  34092. };
  34093. return BABYLON.MeshBuilder.CreateDashedLines(name, options, scene);
  34094. };
  34095. /**
  34096. * Creates a polygon mesh.
  34097. * Please consider using the same method from the MeshBuilder class instead.
  34098. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh.
  34099. * 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.
  34100. * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34101. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34102. * Remember you can only change the shape positions, not their number when updating a polygon.
  34103. */
  34104. Mesh.CreatePolygon = function (name, shape, scene, holes, updatable, sideOrientation) {
  34105. var options = {
  34106. shape: shape,
  34107. holes: holes,
  34108. updatable: updatable,
  34109. sideOrientation: sideOrientation
  34110. };
  34111. return BABYLON.MeshBuilder.CreatePolygon(name, options, scene);
  34112. };
  34113. /**
  34114. * Creates an extruded polygon mesh, with depth in the Y direction.
  34115. * Please consider using the same method from the MeshBuilder class instead.
  34116. */
  34117. Mesh.ExtrudePolygon = function (name, shape, depth, scene, holes, updatable, sideOrientation) {
  34118. var options = {
  34119. shape: shape,
  34120. holes: holes,
  34121. depth: depth,
  34122. updatable: updatable,
  34123. sideOrientation: sideOrientation
  34124. };
  34125. return BABYLON.MeshBuilder.ExtrudePolygon(name, options, scene);
  34126. };
  34127. /**
  34128. * Creates an extruded shape mesh.
  34129. * 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.
  34130. * Please consider using the same method from the MeshBuilder class instead.
  34131. *
  34132. * Please read this full tutorial to understand how to design an extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34133. * 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
  34134. * extruded along the Z axis.
  34135. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34136. * 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.
  34137. * The parameter `scale` (float, default 1) is the value to scale the shape.
  34138. * 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
  34139. * 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
  34140. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34141. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34142. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34143. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34144. */
  34145. Mesh.ExtrudeShape = function (name, shape, path, scale, rotation, cap, scene, updatable, sideOrientation, instance) {
  34146. if (scene === void 0) { scene = null; }
  34147. var options = {
  34148. shape: shape,
  34149. path: path,
  34150. scale: scale,
  34151. rotation: rotation,
  34152. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34153. sideOrientation: sideOrientation,
  34154. instance: instance,
  34155. updatable: updatable
  34156. };
  34157. return BABYLON.MeshBuilder.ExtrudeShape(name, options, scene);
  34158. };
  34159. /**
  34160. * Creates an custom extruded shape mesh.
  34161. * 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.
  34162. * Please consider using the same method from the MeshBuilder class instead.
  34163. *
  34164. * Please read this full tutorial to understand how to design a custom extruded shape : http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  34165. * 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
  34166. * extruded along the Z axis.
  34167. * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  34168. * 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
  34169. * and the distance of this point from the begining of the path :
  34170. * ```javascript
  34171. * var rotationFunction = function(i, distance) {
  34172. * // do things
  34173. * return rotationValue; }
  34174. * ```
  34175. * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  34176. * 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
  34177. * and the distance of this point from the begining of the path :
  34178. * ```javascript
  34179. * var scaleFunction = function(i, distance) {
  34180. * // do things
  34181. * return scaleValue;}
  34182. * ```
  34183. * It must returns a float value that will be the scale value applied to the shape on each path point.
  34184. * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`.
  34185. * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`.
  34186. * 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
  34187. * 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
  34188. * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  34189. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34190. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34191. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34192. */
  34193. Mesh.ExtrudeShapeCustom = function (name, shape, path, scaleFunction, rotationFunction, ribbonCloseArray, ribbonClosePath, cap, scene, updatable, sideOrientation, instance) {
  34194. var options = {
  34195. shape: shape,
  34196. path: path,
  34197. scaleFunction: scaleFunction,
  34198. rotationFunction: rotationFunction,
  34199. ribbonCloseArray: ribbonCloseArray,
  34200. ribbonClosePath: ribbonClosePath,
  34201. cap: (cap === 0) ? 0 : cap || Mesh.NO_CAP,
  34202. sideOrientation: sideOrientation,
  34203. instance: instance,
  34204. updatable: updatable
  34205. };
  34206. return BABYLON.MeshBuilder.ExtrudeShapeCustom(name, options, scene);
  34207. };
  34208. /**
  34209. * Creates lathe mesh.
  34210. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe.
  34211. * Please consider using the same method from the MeshBuilder class instead.
  34212. * 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
  34213. * rotated around the Y axis. It's usually a 2D shape, so the Vector3 z coordinates are often set to zero.
  34214. * The parameter `radius` (positive float, default 1) is the radius value of the lathe.
  34215. * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe.
  34216. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34217. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34218. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34219. */
  34220. Mesh.CreateLathe = function (name, shape, radius, tessellation, scene, updatable, sideOrientation) {
  34221. var options = {
  34222. shape: shape,
  34223. radius: radius,
  34224. tessellation: tessellation,
  34225. sideOrientation: sideOrientation,
  34226. updatable: updatable
  34227. };
  34228. return BABYLON.MeshBuilder.CreateLathe(name, options, scene);
  34229. };
  34230. /**
  34231. * Creates a plane mesh.
  34232. * Please consider using the same method from the MeshBuilder class instead.
  34233. * The parameter `size` sets the size (float) of both sides of the plane at once (default 1).
  34234. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34235. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34236. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34237. */
  34238. Mesh.CreatePlane = function (name, size, scene, updatable, sideOrientation) {
  34239. var options = {
  34240. size: size,
  34241. width: size,
  34242. height: size,
  34243. sideOrientation: sideOrientation,
  34244. updatable: updatable
  34245. };
  34246. return BABYLON.MeshBuilder.CreatePlane(name, options, scene);
  34247. };
  34248. /**
  34249. * Creates a ground mesh.
  34250. * Please consider using the same method from the MeshBuilder class instead.
  34251. * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground.
  34252. * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side.
  34253. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34254. */
  34255. Mesh.CreateGround = function (name, width, height, subdivisions, scene, updatable) {
  34256. var options = {
  34257. width: width,
  34258. height: height,
  34259. subdivisions: subdivisions,
  34260. updatable: updatable
  34261. };
  34262. return BABYLON.MeshBuilder.CreateGround(name, options, scene);
  34263. };
  34264. /**
  34265. * Creates a tiled ground mesh.
  34266. * Please consider using the same method from the MeshBuilder class instead.
  34267. * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates.
  34268. * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates.
  34269. * The parameter `subdivisions` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 6, h: 6}`). `w` and `h` are the
  34270. * numbers of subdivisions on the ground width and height. Each subdivision is called a tile.
  34271. * The parameter `precision` is a javascript object `{w: positive integer, h: positive integer}` (default `{w: 2, h: 2}`). `w` and `h` are the
  34272. * numbers of subdivisions on the ground width and height of each tile.
  34273. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34274. */
  34275. Mesh.CreateTiledGround = function (name, xmin, zmin, xmax, zmax, subdivisions, precision, scene, updatable) {
  34276. var options = {
  34277. xmin: xmin,
  34278. zmin: zmin,
  34279. xmax: xmax,
  34280. zmax: zmax,
  34281. subdivisions: subdivisions,
  34282. precision: precision,
  34283. updatable: updatable
  34284. };
  34285. return BABYLON.MeshBuilder.CreateTiledGround(name, options, scene);
  34286. };
  34287. /**
  34288. * Creates a ground mesh from a height map.
  34289. * tuto : http://doc.babylonjs.com/babylon101/height_map
  34290. * Please consider using the same method from the MeshBuilder class instead.
  34291. * The parameter `url` sets the URL of the height map image resource.
  34292. * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  34293. * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  34294. * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  34295. * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  34296. * 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).
  34297. * This function is passed the newly built mesh :
  34298. * ```javascript
  34299. * function(mesh) { // do things
  34300. * return; }
  34301. * ```
  34302. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34303. */
  34304. Mesh.CreateGroundFromHeightMap = function (name, url, width, height, subdivisions, minHeight, maxHeight, scene, updatable, onReady) {
  34305. var options = {
  34306. width: width,
  34307. height: height,
  34308. subdivisions: subdivisions,
  34309. minHeight: minHeight,
  34310. maxHeight: maxHeight,
  34311. updatable: updatable,
  34312. onReady: onReady
  34313. };
  34314. return BABYLON.MeshBuilder.CreateGroundFromHeightMap(name, url, options, scene);
  34315. };
  34316. /**
  34317. * Creates a tube mesh.
  34318. * 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.
  34319. * Please consider using the same method from the MeshBuilder class instead.
  34320. * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube.
  34321. * The parameter `radius` (positive float, default 1) sets the tube radius size.
  34322. * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface.
  34323. * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`.
  34324. * 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.
  34325. * It must return a radius value (positive float) :
  34326. * ```javascript
  34327. * var radiusFunction = function(i, distance) {
  34328. * // do things
  34329. * return radius; }
  34330. * ```
  34331. * 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
  34332. * 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
  34333. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34334. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34335. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34336. */
  34337. Mesh.CreateTube = function (name, path, radius, tessellation, radiusFunction, cap, scene, updatable, sideOrientation, instance) {
  34338. var options = {
  34339. path: path,
  34340. radius: radius,
  34341. tessellation: tessellation,
  34342. radiusFunction: radiusFunction,
  34343. arc: 1,
  34344. cap: cap,
  34345. updatable: updatable,
  34346. sideOrientation: sideOrientation,
  34347. instance: instance
  34348. };
  34349. return BABYLON.MeshBuilder.CreateTube(name, options, scene);
  34350. };
  34351. /**
  34352. * Creates a polyhedron mesh.
  34353. * Please consider using the same method from the MeshBuilder class instead.
  34354. * 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
  34355. * to choose the wanted type.
  34356. * The parameter `size` (positive float, default 1) sets the polygon size.
  34357. * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value).
  34358. * 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`.
  34359. * 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
  34360. * 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)`).
  34361. * 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
  34362. * 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.
  34363. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34364. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34365. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34366. */
  34367. Mesh.CreatePolyhedron = function (name, options, scene) {
  34368. return BABYLON.MeshBuilder.CreatePolyhedron(name, options, scene);
  34369. };
  34370. /**
  34371. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided.
  34372. * Please consider using the same method from the MeshBuilder class instead.
  34373. * The parameter `radius` sets the radius size (float) of the icosphere (default 1).
  34374. * 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`).
  34375. * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size.
  34376. * 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.
  34377. * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  34378. * Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  34379. * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  34380. */
  34381. Mesh.CreateIcoSphere = function (name, options, scene) {
  34382. return BABYLON.MeshBuilder.CreateIcoSphere(name, options, scene);
  34383. };
  34384. /**
  34385. * Creates a decal mesh.
  34386. * Please consider using the same method from the MeshBuilder class instead.
  34387. * 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.
  34388. * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates.
  34389. * The parameter `normal` (Vector3, default Vector3.Up) sets the normal of the mesh where the decal is applied onto in World coordinates.
  34390. * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling.
  34391. * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal.
  34392. */
  34393. Mesh.CreateDecal = function (name, sourceMesh, position, normal, size, angle) {
  34394. var options = {
  34395. position: position,
  34396. normal: normal,
  34397. size: size,
  34398. angle: angle
  34399. };
  34400. return BABYLON.MeshBuilder.CreateDecal(name, sourceMesh, options);
  34401. };
  34402. // Skeletons
  34403. /**
  34404. * @returns original positions used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34405. */
  34406. Mesh.prototype.setPositionsForCPUSkinning = function () {
  34407. if (!this._sourcePositions) {
  34408. var source = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34409. if (!source) {
  34410. return this._sourcePositions;
  34411. }
  34412. this._sourcePositions = new Float32Array(source);
  34413. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  34414. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, source, true);
  34415. }
  34416. }
  34417. return this._sourcePositions;
  34418. };
  34419. /**
  34420. * @returns original normals used for CPU skinning. Useful for integrating Morphing with skeletons in same mesh.
  34421. */
  34422. Mesh.prototype.setNormalsForCPUSkinning = function () {
  34423. if (!this._sourceNormals) {
  34424. var source = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34425. if (!source) {
  34426. return this._sourceNormals;
  34427. }
  34428. this._sourceNormals = new Float32Array(source);
  34429. if (!this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  34430. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, source, true);
  34431. }
  34432. }
  34433. return this._sourceNormals;
  34434. };
  34435. /**
  34436. * Updates the vertex buffer by applying transformation from the bones.
  34437. * Returns the Mesh.
  34438. *
  34439. * @param {skeleton} skeleton to apply
  34440. */
  34441. Mesh.prototype.applySkeleton = function (skeleton) {
  34442. if (!this.geometry) {
  34443. return this;
  34444. }
  34445. if (this.geometry._softwareSkinningRenderId == this.getScene().getRenderId()) {
  34446. return this;
  34447. }
  34448. this.geometry._softwareSkinningRenderId = this.getScene().getRenderId();
  34449. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  34450. return this;
  34451. }
  34452. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  34453. return this;
  34454. }
  34455. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  34456. return this;
  34457. }
  34458. if (!this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  34459. return this;
  34460. }
  34461. if (!this._sourcePositions) {
  34462. var submeshes = this.subMeshes.slice();
  34463. this.setPositionsForCPUSkinning();
  34464. this.subMeshes = submeshes;
  34465. }
  34466. if (!this._sourceNormals) {
  34467. this.setNormalsForCPUSkinning();
  34468. }
  34469. // positionsData checks for not being Float32Array will only pass at most once
  34470. var positionsData = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34471. if (!positionsData) {
  34472. return this;
  34473. }
  34474. if (!(positionsData instanceof Float32Array)) {
  34475. positionsData = new Float32Array(positionsData);
  34476. }
  34477. // normalsData checks for not being Float32Array will only pass at most once
  34478. var normalsData = this.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  34479. if (!normalsData) {
  34480. return this;
  34481. }
  34482. if (!(normalsData instanceof Float32Array)) {
  34483. normalsData = new Float32Array(normalsData);
  34484. }
  34485. var matricesIndicesData = this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  34486. var matricesWeightsData = this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind);
  34487. if (!matricesWeightsData || !matricesIndicesData) {
  34488. return this;
  34489. }
  34490. var needExtras = this.numBoneInfluencers > 4;
  34491. var matricesIndicesExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind) : null;
  34492. var matricesWeightsExtraData = needExtras ? this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind) : null;
  34493. var skeletonMatrices = skeleton.getTransformMatrices(this);
  34494. var tempVector3 = BABYLON.Vector3.Zero();
  34495. var finalMatrix = new BABYLON.Matrix();
  34496. var tempMatrix = new BABYLON.Matrix();
  34497. var matWeightIdx = 0;
  34498. var inf;
  34499. for (var index = 0; index < positionsData.length; index += 3, matWeightIdx += 4) {
  34500. var weight;
  34501. for (inf = 0; inf < 4; inf++) {
  34502. weight = matricesWeightsData[matWeightIdx + inf];
  34503. if (weight > 0) {
  34504. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34505. finalMatrix.addToSelf(tempMatrix);
  34506. }
  34507. else
  34508. break;
  34509. }
  34510. if (needExtras) {
  34511. for (inf = 0; inf < 4; inf++) {
  34512. weight = matricesWeightsExtraData[matWeightIdx + inf];
  34513. if (weight > 0) {
  34514. BABYLON.Matrix.FromFloat32ArrayToRefScaled(skeletonMatrices, Math.floor(matricesIndicesExtraData[matWeightIdx + inf] * 16), weight, tempMatrix);
  34515. finalMatrix.addToSelf(tempMatrix);
  34516. }
  34517. else
  34518. break;
  34519. }
  34520. }
  34521. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(this._sourcePositions[index], this._sourcePositions[index + 1], this._sourcePositions[index + 2], finalMatrix, tempVector3);
  34522. tempVector3.toArray(positionsData, index);
  34523. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._sourceNormals[index], this._sourceNormals[index + 1], this._sourceNormals[index + 2], finalMatrix, tempVector3);
  34524. tempVector3.toArray(normalsData, index);
  34525. finalMatrix.reset();
  34526. }
  34527. this.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData);
  34528. this.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData);
  34529. return this;
  34530. };
  34531. // Tools
  34532. /**
  34533. * Returns an object `{min:` Vector3`, max:` Vector3`}`
  34534. * This min and max Vector3 are the minimum and maximum vectors of each mesh bounding box from the passed array, in the World system
  34535. */
  34536. Mesh.MinMax = function (meshes) {
  34537. var minVector = null;
  34538. var maxVector = null;
  34539. meshes.forEach(function (mesh, index, array) {
  34540. var boundingInfo = mesh.getBoundingInfo();
  34541. var boundingBox = boundingInfo.boundingBox;
  34542. if (!minVector || !maxVector) {
  34543. minVector = boundingBox.minimumWorld;
  34544. maxVector = boundingBox.maximumWorld;
  34545. }
  34546. else {
  34547. minVector.minimizeInPlace(boundingBox.minimumWorld);
  34548. maxVector.maximizeInPlace(boundingBox.maximumWorld);
  34549. }
  34550. });
  34551. if (!minVector || !maxVector) {
  34552. return {
  34553. min: BABYLON.Vector3.Zero(),
  34554. max: BABYLON.Vector3.Zero()
  34555. };
  34556. }
  34557. return {
  34558. min: minVector,
  34559. max: maxVector
  34560. };
  34561. };
  34562. /**
  34563. * Returns a Vector3, the center of the `{min:` Vector3`, max:` Vector3`}` or the center of MinMax vector3 computed from a mesh array.
  34564. */
  34565. Mesh.Center = function (meshesOrMinMaxVector) {
  34566. var minMaxVector = (meshesOrMinMaxVector instanceof Array) ? Mesh.MinMax(meshesOrMinMaxVector) : meshesOrMinMaxVector;
  34567. return BABYLON.Vector3.Center(minMaxVector.min, minMaxVector.max);
  34568. };
  34569. /**
  34570. * Merge the array of meshes into a single mesh for performance reasons.
  34571. * @param {Array<Mesh>} meshes - The vertices source. They should all be of the same material. Entries can empty
  34572. * @param {boolean} disposeSource - When true (default), dispose of the vertices from the source meshes
  34573. * @param {boolean} allow32BitsIndices - When the sum of the vertices > 64k, this must be set to true.
  34574. * @param {Mesh} meshSubclass - When set, vertices inserted into this Mesh. Meshes can then be merged into a Mesh sub-class.
  34575. * @param {boolean} subdivideWithSubMeshes - When true (false default), subdivide mesh to his subMesh array with meshes source.
  34576. */
  34577. Mesh.MergeMeshes = function (meshes, disposeSource, allow32BitsIndices, meshSubclass, subdivideWithSubMeshes) {
  34578. if (disposeSource === void 0) { disposeSource = true; }
  34579. var index;
  34580. if (!allow32BitsIndices) {
  34581. var totalVertices = 0;
  34582. // Counting vertices
  34583. for (index = 0; index < meshes.length; index++) {
  34584. if (meshes[index]) {
  34585. totalVertices += meshes[index].getTotalVertices();
  34586. if (totalVertices > 65536) {
  34587. BABYLON.Tools.Warn("Cannot merge meshes because resulting mesh will have more than 65536 vertices. Please use allow32BitsIndices = true to use 32 bits indices");
  34588. return null;
  34589. }
  34590. }
  34591. }
  34592. }
  34593. // Merge
  34594. var vertexData = null;
  34595. var otherVertexData;
  34596. var indiceArray = new Array();
  34597. var source = null;
  34598. for (index = 0; index < meshes.length; index++) {
  34599. if (meshes[index]) {
  34600. meshes[index].computeWorldMatrix(true);
  34601. otherVertexData = BABYLON.VertexData.ExtractFromMesh(meshes[index], true, true);
  34602. otherVertexData.transform(meshes[index].getWorldMatrix());
  34603. if (vertexData) {
  34604. vertexData.merge(otherVertexData);
  34605. }
  34606. else {
  34607. vertexData = otherVertexData;
  34608. source = meshes[index];
  34609. }
  34610. if (subdivideWithSubMeshes) {
  34611. indiceArray.push(meshes[index].getTotalIndices());
  34612. }
  34613. }
  34614. }
  34615. source = source;
  34616. if (!meshSubclass) {
  34617. meshSubclass = new Mesh(source.name + "_merged", source.getScene());
  34618. }
  34619. vertexData.applyToMesh(meshSubclass);
  34620. // Setting properties
  34621. meshSubclass.material = source.material;
  34622. meshSubclass.checkCollisions = source.checkCollisions;
  34623. // Cleaning
  34624. if (disposeSource) {
  34625. for (index = 0; index < meshes.length; index++) {
  34626. if (meshes[index]) {
  34627. meshes[index].dispose();
  34628. }
  34629. }
  34630. }
  34631. // Subdivide
  34632. if (subdivideWithSubMeshes) {
  34633. //-- removal of global submesh
  34634. meshSubclass.releaseSubMeshes();
  34635. index = 0;
  34636. var offset = 0;
  34637. //-- apply subdivision according to index table
  34638. while (index < indiceArray.length) {
  34639. BABYLON.SubMesh.CreateFromIndices(0, offset, indiceArray[index], meshSubclass);
  34640. offset += indiceArray[index];
  34641. index++;
  34642. }
  34643. }
  34644. return meshSubclass;
  34645. };
  34646. // Consts
  34647. Mesh._FRONTSIDE = 0;
  34648. Mesh._BACKSIDE = 1;
  34649. Mesh._DOUBLESIDE = 2;
  34650. Mesh._DEFAULTSIDE = 0;
  34651. Mesh._NO_CAP = 0;
  34652. Mesh._CAP_START = 1;
  34653. Mesh._CAP_END = 2;
  34654. Mesh._CAP_ALL = 3;
  34655. return Mesh;
  34656. }(BABYLON.AbstractMesh));
  34657. BABYLON.Mesh = Mesh;
  34658. })(BABYLON || (BABYLON = {}));
  34659. //# sourceMappingURL=babylon.mesh.js.map
  34660. var BABYLON;
  34661. (function (BABYLON) {
  34662. var BaseSubMesh = /** @class */ (function () {
  34663. function BaseSubMesh() {
  34664. }
  34665. Object.defineProperty(BaseSubMesh.prototype, "effect", {
  34666. get: function () {
  34667. return this._materialEffect;
  34668. },
  34669. enumerable: true,
  34670. configurable: true
  34671. });
  34672. BaseSubMesh.prototype.setEffect = function (effect, defines) {
  34673. if (defines === void 0) { defines = null; }
  34674. if (this._materialEffect === effect) {
  34675. if (!effect) {
  34676. this._materialDefines = null;
  34677. }
  34678. return;
  34679. }
  34680. this._materialDefines = defines;
  34681. this._materialEffect = effect;
  34682. };
  34683. return BaseSubMesh;
  34684. }());
  34685. BABYLON.BaseSubMesh = BaseSubMesh;
  34686. var SubMesh = /** @class */ (function (_super) {
  34687. __extends(SubMesh, _super);
  34688. function SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34689. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34690. var _this = _super.call(this) || this;
  34691. _this.materialIndex = materialIndex;
  34692. _this.verticesStart = verticesStart;
  34693. _this.verticesCount = verticesCount;
  34694. _this.indexStart = indexStart;
  34695. _this.indexCount = indexCount;
  34696. _this._renderId = 0;
  34697. _this._mesh = mesh;
  34698. _this._renderingMesh = renderingMesh || mesh;
  34699. mesh.subMeshes.push(_this);
  34700. _this._trianglePlanes = [];
  34701. _this._id = mesh.subMeshes.length - 1;
  34702. if (createBoundingBox) {
  34703. _this.refreshBoundingInfo();
  34704. mesh.computeWorldMatrix(true);
  34705. }
  34706. return _this;
  34707. }
  34708. SubMesh.AddToMesh = function (materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox) {
  34709. if (createBoundingBox === void 0) { createBoundingBox = true; }
  34710. return new SubMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh, renderingMesh, createBoundingBox);
  34711. };
  34712. Object.defineProperty(SubMesh.prototype, "IsGlobal", {
  34713. get: function () {
  34714. return (this.verticesStart === 0 && this.verticesCount == this._mesh.getTotalVertices());
  34715. },
  34716. enumerable: true,
  34717. configurable: true
  34718. });
  34719. /**
  34720. * Returns the submesh BoudingInfo object.
  34721. */
  34722. SubMesh.prototype.getBoundingInfo = function () {
  34723. if (this.IsGlobal) {
  34724. return this._mesh.getBoundingInfo();
  34725. }
  34726. return this._boundingInfo;
  34727. };
  34728. /**
  34729. * Sets the submesh BoundingInfo.
  34730. * Return the SubMesh.
  34731. */
  34732. SubMesh.prototype.setBoundingInfo = function (boundingInfo) {
  34733. this._boundingInfo = boundingInfo;
  34734. return this;
  34735. };
  34736. /**
  34737. * Returns the mesh of the current submesh.
  34738. */
  34739. SubMesh.prototype.getMesh = function () {
  34740. return this._mesh;
  34741. };
  34742. /**
  34743. * Returns the rendering mesh of the submesh.
  34744. */
  34745. SubMesh.prototype.getRenderingMesh = function () {
  34746. return this._renderingMesh;
  34747. };
  34748. /**
  34749. * Returns the submesh material.
  34750. */
  34751. SubMesh.prototype.getMaterial = function () {
  34752. var rootMaterial = this._renderingMesh.material;
  34753. if (rootMaterial === null || rootMaterial === undefined) {
  34754. return this._mesh.getScene().defaultMaterial;
  34755. }
  34756. else if (rootMaterial.getSubMaterial) {
  34757. var multiMaterial = rootMaterial;
  34758. var effectiveMaterial = multiMaterial.getSubMaterial(this.materialIndex);
  34759. if (this._currentMaterial !== effectiveMaterial) {
  34760. this._currentMaterial = effectiveMaterial;
  34761. this._materialDefines = null;
  34762. }
  34763. return effectiveMaterial;
  34764. }
  34765. return rootMaterial;
  34766. };
  34767. // Methods
  34768. /**
  34769. * Sets a new updated BoundingInfo object to the submesh.
  34770. * Returns the SubMesh.
  34771. */
  34772. SubMesh.prototype.refreshBoundingInfo = function () {
  34773. this._lastColliderWorldVertices = null;
  34774. if (this.IsGlobal || !this._renderingMesh || !this._renderingMesh.geometry) {
  34775. return this;
  34776. }
  34777. var data = this._renderingMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  34778. if (!data) {
  34779. this._boundingInfo = this._mesh.getBoundingInfo();
  34780. return this;
  34781. }
  34782. var indices = this._renderingMesh.getIndices();
  34783. var extend;
  34784. //is this the only submesh?
  34785. if (this.indexStart === 0 && this.indexCount === indices.length) {
  34786. var boundingInfo = this._renderingMesh.getBoundingInfo();
  34787. //the rendering mesh's bounding info can be used, it is the standard submesh for all indices.
  34788. extend = { minimum: boundingInfo.minimum.clone(), maximum: boundingInfo.maximum.clone() };
  34789. }
  34790. else {
  34791. extend = BABYLON.Tools.ExtractMinAndMaxIndexed(data, indices, this.indexStart, this.indexCount, this._renderingMesh.geometry.boundingBias);
  34792. }
  34793. this._boundingInfo = new BABYLON.BoundingInfo(extend.minimum, extend.maximum);
  34794. return this;
  34795. };
  34796. SubMesh.prototype._checkCollision = function (collider) {
  34797. var boundingInfo = this.getBoundingInfo();
  34798. return boundingInfo._checkCollision(collider);
  34799. };
  34800. /**
  34801. * Updates the submesh BoundingInfo.
  34802. * Returns the Submesh.
  34803. */
  34804. SubMesh.prototype.updateBoundingInfo = function (world) {
  34805. var boundingInfo = this.getBoundingInfo();
  34806. if (!boundingInfo) {
  34807. this.refreshBoundingInfo();
  34808. boundingInfo = this.getBoundingInfo();
  34809. }
  34810. boundingInfo.update(world);
  34811. return this;
  34812. };
  34813. /**
  34814. * True is the submesh bounding box intersects the frustum defined by the passed array of planes.
  34815. * Boolean returned.
  34816. */
  34817. SubMesh.prototype.isInFrustum = function (frustumPlanes) {
  34818. var boundingInfo = this.getBoundingInfo();
  34819. if (!boundingInfo) {
  34820. return false;
  34821. }
  34822. return boundingInfo.isInFrustum(frustumPlanes);
  34823. };
  34824. /**
  34825. * True is the submesh bounding box is completely inside the frustum defined by the passed array of planes.
  34826. * Boolean returned.
  34827. */
  34828. SubMesh.prototype.isCompletelyInFrustum = function (frustumPlanes) {
  34829. var boundingInfo = this.getBoundingInfo();
  34830. if (!boundingInfo) {
  34831. return false;
  34832. }
  34833. return boundingInfo.isCompletelyInFrustum(frustumPlanes);
  34834. };
  34835. /**
  34836. * Renders the submesh.
  34837. * Returns it.
  34838. */
  34839. SubMesh.prototype.render = function (enableAlphaMode) {
  34840. this._renderingMesh.render(this, enableAlphaMode);
  34841. return this;
  34842. };
  34843. /**
  34844. * Returns a new Index Buffer.
  34845. * Type returned : WebGLBuffer.
  34846. */
  34847. SubMesh.prototype.getLinesIndexBuffer = function (indices, engine) {
  34848. if (!this._linesIndexBuffer) {
  34849. var linesIndices = [];
  34850. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34851. linesIndices.push(indices[index], indices[index + 1], indices[index + 1], indices[index + 2], indices[index + 2], indices[index]);
  34852. }
  34853. this._linesIndexBuffer = engine.createIndexBuffer(linesIndices);
  34854. this.linesIndexCount = linesIndices.length;
  34855. }
  34856. return this._linesIndexBuffer;
  34857. };
  34858. /**
  34859. * True is the passed Ray intersects the submesh bounding box.
  34860. * Boolean returned.
  34861. */
  34862. SubMesh.prototype.canIntersects = function (ray) {
  34863. var boundingInfo = this.getBoundingInfo();
  34864. if (!boundingInfo) {
  34865. return false;
  34866. }
  34867. return ray.intersectsBox(boundingInfo.boundingBox);
  34868. };
  34869. /**
  34870. * Returns an object IntersectionInfo.
  34871. */
  34872. SubMesh.prototype.intersects = function (ray, positions, indices, fastCheck) {
  34873. var intersectInfo = null;
  34874. var material = this.getMaterial();
  34875. if (!material) {
  34876. return null;
  34877. }
  34878. switch (material.fillMode) {
  34879. case BABYLON.Material.PointListDrawMode:
  34880. case BABYLON.Material.LineListDrawMode:
  34881. case BABYLON.Material.LineLoopDrawMode:
  34882. case BABYLON.Material.LineStripDrawMode:
  34883. case BABYLON.Material.TriangleFanDrawMode:
  34884. case BABYLON.Material.TriangleStripDrawMode:
  34885. return null;
  34886. }
  34887. // LineMesh first as it's also a Mesh...
  34888. if (BABYLON.LinesMesh && this._mesh instanceof BABYLON.LinesMesh) {
  34889. var lineMesh = this._mesh;
  34890. // Line test
  34891. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 2) {
  34892. var p0 = positions[indices[index]];
  34893. var p1 = positions[indices[index + 1]];
  34894. var length = ray.intersectionSegment(p0, p1, lineMesh.intersectionThreshold);
  34895. if (length < 0) {
  34896. continue;
  34897. }
  34898. if (fastCheck || !intersectInfo || length < intersectInfo.distance) {
  34899. intersectInfo = new BABYLON.IntersectionInfo(null, null, length);
  34900. if (fastCheck) {
  34901. break;
  34902. }
  34903. }
  34904. }
  34905. }
  34906. else {
  34907. // Triangles test
  34908. for (var index = this.indexStart; index < this.indexStart + this.indexCount; index += 3) {
  34909. var p0 = positions[indices[index]];
  34910. var p1 = positions[indices[index + 1]];
  34911. var p2 = positions[indices[index + 2]];
  34912. var currentIntersectInfo = ray.intersectsTriangle(p0, p1, p2);
  34913. if (currentIntersectInfo) {
  34914. if (currentIntersectInfo.distance < 0) {
  34915. continue;
  34916. }
  34917. if (fastCheck || !intersectInfo || currentIntersectInfo.distance < intersectInfo.distance) {
  34918. intersectInfo = currentIntersectInfo;
  34919. intersectInfo.faceId = index / 3;
  34920. if (fastCheck) {
  34921. break;
  34922. }
  34923. }
  34924. }
  34925. }
  34926. }
  34927. return intersectInfo;
  34928. };
  34929. SubMesh.prototype._rebuild = function () {
  34930. if (this._linesIndexBuffer) {
  34931. this._linesIndexBuffer = null;
  34932. }
  34933. };
  34934. // Clone
  34935. /**
  34936. * Creates a new Submesh from the passed Mesh.
  34937. */
  34938. SubMesh.prototype.clone = function (newMesh, newRenderingMesh) {
  34939. var result = new SubMesh(this.materialIndex, this.verticesStart, this.verticesCount, this.indexStart, this.indexCount, newMesh, newRenderingMesh, false);
  34940. if (!this.IsGlobal) {
  34941. var boundingInfo = this.getBoundingInfo();
  34942. if (!boundingInfo) {
  34943. return result;
  34944. }
  34945. result._boundingInfo = new BABYLON.BoundingInfo(boundingInfo.minimum, boundingInfo.maximum);
  34946. }
  34947. return result;
  34948. };
  34949. // Dispose
  34950. /**
  34951. * Disposes the Submesh.
  34952. * Returns nothing.
  34953. */
  34954. SubMesh.prototype.dispose = function () {
  34955. if (this._linesIndexBuffer) {
  34956. this._mesh.getScene().getEngine()._releaseBuffer(this._linesIndexBuffer);
  34957. this._linesIndexBuffer = null;
  34958. }
  34959. // Remove from mesh
  34960. var index = this._mesh.subMeshes.indexOf(this);
  34961. this._mesh.subMeshes.splice(index, 1);
  34962. };
  34963. // Statics
  34964. /**
  34965. * Creates a new Submesh from the passed parameters :
  34966. * - materialIndex (integer) : the index of the main mesh material.
  34967. * - startIndex (integer) : the index where to start the copy in the mesh indices array.
  34968. * - indexCount (integer) : the number of indices to copy then from the startIndex.
  34969. * - mesh (Mesh) : the main mesh to create the submesh from.
  34970. * - renderingMesh (optional Mesh) : rendering mesh.
  34971. */
  34972. SubMesh.CreateFromIndices = function (materialIndex, startIndex, indexCount, mesh, renderingMesh) {
  34973. var minVertexIndex = Number.MAX_VALUE;
  34974. var maxVertexIndex = -Number.MAX_VALUE;
  34975. renderingMesh = (renderingMesh || mesh);
  34976. var indices = renderingMesh.getIndices();
  34977. for (var index = startIndex; index < startIndex + indexCount; index++) {
  34978. var vertexIndex = indices[index];
  34979. if (vertexIndex < minVertexIndex)
  34980. minVertexIndex = vertexIndex;
  34981. if (vertexIndex > maxVertexIndex)
  34982. maxVertexIndex = vertexIndex;
  34983. }
  34984. return new SubMesh(materialIndex, minVertexIndex, maxVertexIndex - minVertexIndex + 1, startIndex, indexCount, mesh, renderingMesh);
  34985. };
  34986. return SubMesh;
  34987. }(BaseSubMesh));
  34988. BABYLON.SubMesh = SubMesh;
  34989. })(BABYLON || (BABYLON = {}));
  34990. //# sourceMappingURL=babylon.subMesh.js.map
  34991. var __assign = (this && this.__assign) || Object.assign || function(t) {
  34992. for (var s, i = 1, n = arguments.length; i < n; i++) {
  34993. s = arguments[i];
  34994. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  34995. t[p] = s[p];
  34996. }
  34997. return t;
  34998. };
  34999. var BABYLON;
  35000. (function (BABYLON) {
  35001. /**
  35002. * Manages the defines for the Material
  35003. */
  35004. var MaterialDefines = /** @class */ (function () {
  35005. function MaterialDefines() {
  35006. this._isDirty = true;
  35007. /** @hidden */
  35008. this._areLightsDirty = true;
  35009. /** @hidden */
  35010. this._areAttributesDirty = true;
  35011. /** @hidden */
  35012. this._areTexturesDirty = true;
  35013. /** @hidden */
  35014. this._areFresnelDirty = true;
  35015. /** @hidden */
  35016. this._areMiscDirty = true;
  35017. /** @hidden */
  35018. this._areImageProcessingDirty = true;
  35019. /** @hidden */
  35020. this._normals = false;
  35021. /** @hidden */
  35022. this._uvs = false;
  35023. /** @hidden */
  35024. this._needNormals = false;
  35025. /** @hidden */
  35026. this._needUVs = false;
  35027. }
  35028. Object.defineProperty(MaterialDefines.prototype, "isDirty", {
  35029. /**
  35030. * Specifies if the material needs to be re-calculated
  35031. */
  35032. get: function () {
  35033. return this._isDirty;
  35034. },
  35035. enumerable: true,
  35036. configurable: true
  35037. });
  35038. /**
  35039. * Marks the material to indicate that it has been re-calculated
  35040. */
  35041. MaterialDefines.prototype.markAsProcessed = function () {
  35042. this._isDirty = false;
  35043. this._areAttributesDirty = false;
  35044. this._areTexturesDirty = false;
  35045. this._areFresnelDirty = false;
  35046. this._areLightsDirty = false;
  35047. this._areMiscDirty = false;
  35048. this._areImageProcessingDirty = false;
  35049. };
  35050. /**
  35051. * Marks the material to indicate that it needs to be re-calculated
  35052. */
  35053. MaterialDefines.prototype.markAsUnprocessed = function () {
  35054. this._isDirty = true;
  35055. };
  35056. /**
  35057. * Marks the material to indicate all of its defines need to be re-calculated
  35058. */
  35059. MaterialDefines.prototype.markAllAsDirty = function () {
  35060. this._areTexturesDirty = true;
  35061. this._areAttributesDirty = true;
  35062. this._areLightsDirty = true;
  35063. this._areFresnelDirty = true;
  35064. this._areMiscDirty = true;
  35065. this._areImageProcessingDirty = true;
  35066. this._isDirty = true;
  35067. };
  35068. /**
  35069. * Marks the material to indicate that image processing needs to be re-calculated
  35070. */
  35071. MaterialDefines.prototype.markAsImageProcessingDirty = function () {
  35072. this._areImageProcessingDirty = true;
  35073. this._isDirty = true;
  35074. };
  35075. /**
  35076. * Marks the material to indicate the lights need to be re-calculated
  35077. */
  35078. MaterialDefines.prototype.markAsLightDirty = function () {
  35079. this._areLightsDirty = true;
  35080. this._isDirty = true;
  35081. };
  35082. /**
  35083. * Marks the attribute state as changed
  35084. */
  35085. MaterialDefines.prototype.markAsAttributesDirty = function () {
  35086. this._areAttributesDirty = true;
  35087. this._isDirty = true;
  35088. };
  35089. /**
  35090. * Marks the texture state as changed
  35091. */
  35092. MaterialDefines.prototype.markAsTexturesDirty = function () {
  35093. this._areTexturesDirty = true;
  35094. this._isDirty = true;
  35095. };
  35096. /**
  35097. * Marks the fresnel state as changed
  35098. */
  35099. MaterialDefines.prototype.markAsFresnelDirty = function () {
  35100. this._areFresnelDirty = true;
  35101. this._isDirty = true;
  35102. };
  35103. /**
  35104. * Marks the misc state as changed
  35105. */
  35106. MaterialDefines.prototype.markAsMiscDirty = function () {
  35107. this._areMiscDirty = true;
  35108. this._isDirty = true;
  35109. };
  35110. /**
  35111. * Rebuilds the material defines
  35112. */
  35113. MaterialDefines.prototype.rebuild = function () {
  35114. if (this._keys) {
  35115. delete this._keys;
  35116. }
  35117. this._keys = [];
  35118. for (var _i = 0, _a = Object.keys(this); _i < _a.length; _i++) {
  35119. var key = _a[_i];
  35120. if (key[0] === "_") {
  35121. continue;
  35122. }
  35123. this._keys.push(key);
  35124. }
  35125. };
  35126. /**
  35127. * Specifies if two material defines are equal
  35128. * @param other - A material define instance to compare to
  35129. * @returns - Boolean indicating if the material defines are equal (true) or not (false)
  35130. */
  35131. MaterialDefines.prototype.isEqual = function (other) {
  35132. if (this._keys.length !== other._keys.length) {
  35133. return false;
  35134. }
  35135. for (var index = 0; index < this._keys.length; index++) {
  35136. var prop = this._keys[index];
  35137. if (this[prop] !== other[prop]) {
  35138. return false;
  35139. }
  35140. }
  35141. return true;
  35142. };
  35143. /**
  35144. * Clones this instance's defines to another instance
  35145. * @param other - material defines to clone values to
  35146. */
  35147. MaterialDefines.prototype.cloneTo = function (other) {
  35148. if (this._keys.length !== other._keys.length) {
  35149. other._keys = this._keys.slice(0);
  35150. }
  35151. for (var index = 0; index < this._keys.length; index++) {
  35152. var prop = this._keys[index];
  35153. other[prop] = this[prop];
  35154. }
  35155. };
  35156. /**
  35157. * Resets the material define values
  35158. */
  35159. MaterialDefines.prototype.reset = function () {
  35160. for (var index = 0; index < this._keys.length; index++) {
  35161. var prop = this._keys[index];
  35162. var type = typeof this[prop];
  35163. switch (type) {
  35164. case "number":
  35165. this[prop] = 0;
  35166. break;
  35167. case "string":
  35168. this[prop] = "";
  35169. break;
  35170. default:
  35171. this[prop] = false;
  35172. break;
  35173. }
  35174. }
  35175. };
  35176. /**
  35177. * Converts the material define values to a string
  35178. * @returns - String of material define information
  35179. */
  35180. MaterialDefines.prototype.toString = function () {
  35181. var result = "";
  35182. for (var index = 0; index < this._keys.length; index++) {
  35183. var prop = this._keys[index];
  35184. var value = this[prop];
  35185. var type = typeof value;
  35186. switch (type) {
  35187. case "number":
  35188. case "string":
  35189. result += "#define " + prop + " " + value + "\n";
  35190. break;
  35191. default:
  35192. if (value) {
  35193. result += "#define " + prop + "\n";
  35194. }
  35195. break;
  35196. }
  35197. }
  35198. return result;
  35199. };
  35200. return MaterialDefines;
  35201. }());
  35202. BABYLON.MaterialDefines = MaterialDefines;
  35203. /**
  35204. * Base class for the main features of a material in Babylon.js
  35205. */
  35206. var Material = /** @class */ (function () {
  35207. /**
  35208. * Creates a material instance
  35209. * @param name defines the name of the material
  35210. * @param scene defines the scene to reference
  35211. * @param doNotAdd specifies if the material should be added to the scene
  35212. */
  35213. function Material(name, scene, doNotAdd) {
  35214. /**
  35215. * Specifies if the ready state should be checked on each call
  35216. */
  35217. this.checkReadyOnEveryCall = false;
  35218. /**
  35219. * Specifies if the ready state should be checked once
  35220. */
  35221. this.checkReadyOnlyOnce = false;
  35222. /**
  35223. * The state of the material
  35224. */
  35225. this.state = "";
  35226. /**
  35227. * The alpha value of the material
  35228. */
  35229. this._alpha = 1.0;
  35230. /**
  35231. * Specifies if back face culling is enabled
  35232. */
  35233. this._backFaceCulling = true;
  35234. /**
  35235. * Specifies if the material should be serialized
  35236. */
  35237. this.doNotSerialize = false;
  35238. /**
  35239. * Specifies if the effect should be stored on sub meshes
  35240. */
  35241. this.storeEffectOnSubMeshes = false;
  35242. /**
  35243. * An event triggered when the material is disposed
  35244. */
  35245. this.onDisposeObservable = new BABYLON.Observable();
  35246. /**
  35247. * An event triggered when the material is bound
  35248. */
  35249. this.onBindObservable = new BABYLON.Observable();
  35250. /**
  35251. * An event triggered when the material is unbound
  35252. */
  35253. this.onUnBindObservable = new BABYLON.Observable();
  35254. /**
  35255. * Stores the value of the alpha mode
  35256. */
  35257. this._alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  35258. /**
  35259. * Stores the state of the need depth pre-pass value
  35260. */
  35261. this._needDepthPrePass = false;
  35262. /**
  35263. * Specifies if depth writing should be disabled
  35264. */
  35265. this.disableDepthWrite = false;
  35266. /**
  35267. * Specifies if depth writing should be forced
  35268. */
  35269. this.forceDepthWrite = false;
  35270. /**
  35271. * Specifies if there should be a separate pass for culling
  35272. */
  35273. this.separateCullingPass = false;
  35274. /**
  35275. * Stores the state specifing if fog should be enabled
  35276. */
  35277. this._fogEnabled = true;
  35278. /**
  35279. * Stores the size of points
  35280. */
  35281. this.pointSize = 1.0;
  35282. /**
  35283. * Stores the z offset value
  35284. */
  35285. this.zOffset = 0;
  35286. /**
  35287. * Specifies if the material was previously ready
  35288. */
  35289. this._wasPreviouslyReady = false;
  35290. /**
  35291. * Stores the fill mode state
  35292. */
  35293. this._fillMode = Material.TriangleFillMode;
  35294. this.name = name;
  35295. this.id = name || BABYLON.Tools.RandomId();
  35296. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  35297. this.uniqueId = this._scene.getUniqueId();
  35298. if (this._scene.useRightHandedSystem) {
  35299. this.sideOrientation = Material.ClockWiseSideOrientation;
  35300. }
  35301. else {
  35302. this.sideOrientation = Material.CounterClockWiseSideOrientation;
  35303. }
  35304. this._uniformBuffer = new BABYLON.UniformBuffer(this._scene.getEngine());
  35305. this._useUBO = this.getScene().getEngine().supportsUniformBuffers;
  35306. if (!doNotAdd) {
  35307. this._scene.materials.push(this);
  35308. }
  35309. }
  35310. Object.defineProperty(Material, "TriangleFillMode", {
  35311. /**
  35312. * Returns the triangle fill mode
  35313. */
  35314. get: function () {
  35315. return Material._TriangleFillMode;
  35316. },
  35317. enumerable: true,
  35318. configurable: true
  35319. });
  35320. Object.defineProperty(Material, "WireFrameFillMode", {
  35321. /**
  35322. * Returns the wireframe mode
  35323. */
  35324. get: function () {
  35325. return Material._WireFrameFillMode;
  35326. },
  35327. enumerable: true,
  35328. configurable: true
  35329. });
  35330. Object.defineProperty(Material, "PointFillMode", {
  35331. /**
  35332. * Returns the point fill mode
  35333. */
  35334. get: function () {
  35335. return Material._PointFillMode;
  35336. },
  35337. enumerable: true,
  35338. configurable: true
  35339. });
  35340. Object.defineProperty(Material, "PointListDrawMode", {
  35341. /**
  35342. * Returns the point list draw mode
  35343. */
  35344. get: function () {
  35345. return Material._PointListDrawMode;
  35346. },
  35347. enumerable: true,
  35348. configurable: true
  35349. });
  35350. Object.defineProperty(Material, "LineListDrawMode", {
  35351. /**
  35352. * Returns the line list draw mode
  35353. */
  35354. get: function () {
  35355. return Material._LineListDrawMode;
  35356. },
  35357. enumerable: true,
  35358. configurable: true
  35359. });
  35360. Object.defineProperty(Material, "LineLoopDrawMode", {
  35361. /**
  35362. * Returns the line loop draw mode
  35363. */
  35364. get: function () {
  35365. return Material._LineLoopDrawMode;
  35366. },
  35367. enumerable: true,
  35368. configurable: true
  35369. });
  35370. Object.defineProperty(Material, "LineStripDrawMode", {
  35371. /**
  35372. * Returns the line strip draw mode
  35373. */
  35374. get: function () {
  35375. return Material._LineStripDrawMode;
  35376. },
  35377. enumerable: true,
  35378. configurable: true
  35379. });
  35380. Object.defineProperty(Material, "TriangleStripDrawMode", {
  35381. /**
  35382. * Returns the triangle strip draw mode
  35383. */
  35384. get: function () {
  35385. return Material._TriangleStripDrawMode;
  35386. },
  35387. enumerable: true,
  35388. configurable: true
  35389. });
  35390. Object.defineProperty(Material, "TriangleFanDrawMode", {
  35391. /**
  35392. * Returns the triangle fan draw mode
  35393. */
  35394. get: function () {
  35395. return Material._TriangleFanDrawMode;
  35396. },
  35397. enumerable: true,
  35398. configurable: true
  35399. });
  35400. Object.defineProperty(Material, "ClockWiseSideOrientation", {
  35401. /**
  35402. * Returns the clock-wise side orientation
  35403. */
  35404. get: function () {
  35405. return Material._ClockWiseSideOrientation;
  35406. },
  35407. enumerable: true,
  35408. configurable: true
  35409. });
  35410. Object.defineProperty(Material, "CounterClockWiseSideOrientation", {
  35411. /**
  35412. * Returns the counter clock-wise side orientation
  35413. */
  35414. get: function () {
  35415. return Material._CounterClockWiseSideOrientation;
  35416. },
  35417. enumerable: true,
  35418. configurable: true
  35419. });
  35420. Object.defineProperty(Material, "TextureDirtyFlag", {
  35421. /**
  35422. * Returns the dirty texture flag value
  35423. */
  35424. get: function () {
  35425. return Material._TextureDirtyFlag;
  35426. },
  35427. enumerable: true,
  35428. configurable: true
  35429. });
  35430. Object.defineProperty(Material, "LightDirtyFlag", {
  35431. /**
  35432. * Returns the dirty light flag value
  35433. */
  35434. get: function () {
  35435. return Material._LightDirtyFlag;
  35436. },
  35437. enumerable: true,
  35438. configurable: true
  35439. });
  35440. Object.defineProperty(Material, "FresnelDirtyFlag", {
  35441. /**
  35442. * Returns the dirty fresnel flag value
  35443. */
  35444. get: function () {
  35445. return Material._FresnelDirtyFlag;
  35446. },
  35447. enumerable: true,
  35448. configurable: true
  35449. });
  35450. Object.defineProperty(Material, "AttributesDirtyFlag", {
  35451. /**
  35452. * Returns the dirty attributes flag value
  35453. */
  35454. get: function () {
  35455. return Material._AttributesDirtyFlag;
  35456. },
  35457. enumerable: true,
  35458. configurable: true
  35459. });
  35460. Object.defineProperty(Material, "MiscDirtyFlag", {
  35461. /**
  35462. * Returns the dirty misc flag value
  35463. */
  35464. get: function () {
  35465. return Material._MiscDirtyFlag;
  35466. },
  35467. enumerable: true,
  35468. configurable: true
  35469. });
  35470. Object.defineProperty(Material.prototype, "alpha", {
  35471. /**
  35472. * Gets the alpha value of the material
  35473. */
  35474. get: function () {
  35475. return this._alpha;
  35476. },
  35477. /**
  35478. * Sets the alpha value of the material
  35479. */
  35480. set: function (value) {
  35481. if (this._alpha === value) {
  35482. return;
  35483. }
  35484. this._alpha = value;
  35485. this.markAsDirty(Material.MiscDirtyFlag);
  35486. },
  35487. enumerable: true,
  35488. configurable: true
  35489. });
  35490. Object.defineProperty(Material.prototype, "backFaceCulling", {
  35491. /**
  35492. * Gets the back-face culling state
  35493. */
  35494. get: function () {
  35495. return this._backFaceCulling;
  35496. },
  35497. /**
  35498. * Sets the back-face culling state
  35499. */
  35500. set: function (value) {
  35501. if (this._backFaceCulling === value) {
  35502. return;
  35503. }
  35504. this._backFaceCulling = value;
  35505. this.markAsDirty(Material.TextureDirtyFlag);
  35506. },
  35507. enumerable: true,
  35508. configurable: true
  35509. });
  35510. Object.defineProperty(Material.prototype, "onDispose", {
  35511. /**
  35512. * Called during a dispose event
  35513. */
  35514. set: function (callback) {
  35515. if (this._onDisposeObserver) {
  35516. this.onDisposeObservable.remove(this._onDisposeObserver);
  35517. }
  35518. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  35519. },
  35520. enumerable: true,
  35521. configurable: true
  35522. });
  35523. Object.defineProperty(Material.prototype, "onBind", {
  35524. /**
  35525. * Called during a bind event
  35526. */
  35527. set: function (callback) {
  35528. if (this._onBindObserver) {
  35529. this.onBindObservable.remove(this._onBindObserver);
  35530. }
  35531. this._onBindObserver = this.onBindObservable.add(callback);
  35532. },
  35533. enumerable: true,
  35534. configurable: true
  35535. });
  35536. Object.defineProperty(Material.prototype, "alphaMode", {
  35537. /**
  35538. * Gets the value of the alpha mode
  35539. */
  35540. get: function () {
  35541. return this._alphaMode;
  35542. },
  35543. /**
  35544. * Sets the value of the alpha mode.
  35545. *
  35546. * | Value | Type | Description |
  35547. * | --- | --- | --- |
  35548. * | 0 | ALPHA_DISABLE | |
  35549. * | 1 | ALPHA_ADD | |
  35550. * | 2 | ALPHA_COMBINE | |
  35551. * | 3 | ALPHA_SUBTRACT | |
  35552. * | 4 | ALPHA_MULTIPLY | |
  35553. * | 5 | ALPHA_MAXIMIZED | |
  35554. * | 6 | ALPHA_ONEONE | |
  35555. * | 7 | ALPHA_PREMULTIPLIED | |
  35556. * | 8 | ALPHA_PREMULTIPLIED_PORTERDUFF | |
  35557. * | 9 | ALPHA_INTERPOLATE | |
  35558. * | 10 | ALPHA_SCREENMODE | |
  35559. *
  35560. */
  35561. set: function (value) {
  35562. if (this._alphaMode === value) {
  35563. return;
  35564. }
  35565. this._alphaMode = value;
  35566. this.markAsDirty(Material.TextureDirtyFlag);
  35567. },
  35568. enumerable: true,
  35569. configurable: true
  35570. });
  35571. Object.defineProperty(Material.prototype, "needDepthPrePass", {
  35572. /**
  35573. * Gets the depth pre-pass value
  35574. */
  35575. get: function () {
  35576. return this._needDepthPrePass;
  35577. },
  35578. /**
  35579. * Sets the need depth pre-pass value
  35580. */
  35581. set: function (value) {
  35582. if (this._needDepthPrePass === value) {
  35583. return;
  35584. }
  35585. this._needDepthPrePass = value;
  35586. if (this._needDepthPrePass) {
  35587. this.checkReadyOnEveryCall = true;
  35588. }
  35589. },
  35590. enumerable: true,
  35591. configurable: true
  35592. });
  35593. Object.defineProperty(Material.prototype, "fogEnabled", {
  35594. /**
  35595. * Gets the value of the fog enabled state
  35596. */
  35597. get: function () {
  35598. return this._fogEnabled;
  35599. },
  35600. /**
  35601. * Sets the state for enabling fog
  35602. */
  35603. set: function (value) {
  35604. if (this._fogEnabled === value) {
  35605. return;
  35606. }
  35607. this._fogEnabled = value;
  35608. this.markAsDirty(Material.MiscDirtyFlag);
  35609. },
  35610. enumerable: true,
  35611. configurable: true
  35612. });
  35613. Object.defineProperty(Material.prototype, "wireframe", {
  35614. /**
  35615. * Gets a value specifying if wireframe mode is enabled
  35616. */
  35617. get: function () {
  35618. switch (this._fillMode) {
  35619. case Material.WireFrameFillMode:
  35620. case Material.LineListDrawMode:
  35621. case Material.LineLoopDrawMode:
  35622. case Material.LineStripDrawMode:
  35623. return true;
  35624. }
  35625. return this._scene.forceWireframe;
  35626. },
  35627. /**
  35628. * Sets the state of wireframe mode
  35629. */
  35630. set: function (value) {
  35631. this.fillMode = (value ? Material.WireFrameFillMode : Material.TriangleFillMode);
  35632. },
  35633. enumerable: true,
  35634. configurable: true
  35635. });
  35636. Object.defineProperty(Material.prototype, "pointsCloud", {
  35637. /**
  35638. * Gets the value specifying if point clouds are enabled
  35639. */
  35640. get: function () {
  35641. switch (this._fillMode) {
  35642. case Material.PointFillMode:
  35643. case Material.PointListDrawMode:
  35644. return true;
  35645. }
  35646. return this._scene.forcePointsCloud;
  35647. },
  35648. /**
  35649. * Sets the state of point cloud mode
  35650. */
  35651. set: function (value) {
  35652. this.fillMode = (value ? Material.PointFillMode : Material.TriangleFillMode);
  35653. },
  35654. enumerable: true,
  35655. configurable: true
  35656. });
  35657. Object.defineProperty(Material.prototype, "fillMode", {
  35658. /**
  35659. * Gets the material fill mode
  35660. */
  35661. get: function () {
  35662. return this._fillMode;
  35663. },
  35664. /**
  35665. * Sets the material fill mode
  35666. */
  35667. set: function (value) {
  35668. if (this._fillMode === value) {
  35669. return;
  35670. }
  35671. this._fillMode = value;
  35672. this.markAsDirty(Material.MiscDirtyFlag);
  35673. },
  35674. enumerable: true,
  35675. configurable: true
  35676. });
  35677. /**
  35678. * Returns a string representation of the current material
  35679. * @param fullDetails defines a boolean indicating which levels of logging is desired
  35680. * @returns a string with material information
  35681. */
  35682. Material.prototype.toString = function (fullDetails) {
  35683. var ret = "Name: " + this.name;
  35684. if (fullDetails) {
  35685. }
  35686. return ret;
  35687. };
  35688. /**
  35689. * Gets the class name of the material
  35690. * @returns a string with the class name of the material
  35691. */
  35692. Material.prototype.getClassName = function () {
  35693. return "Material";
  35694. };
  35695. Object.defineProperty(Material.prototype, "isFrozen", {
  35696. /**
  35697. * Specifies if updates for the material been locked
  35698. */
  35699. get: function () {
  35700. return this.checkReadyOnlyOnce;
  35701. },
  35702. enumerable: true,
  35703. configurable: true
  35704. });
  35705. /**
  35706. * Locks updates for the material
  35707. */
  35708. Material.prototype.freeze = function () {
  35709. this.checkReadyOnlyOnce = true;
  35710. };
  35711. /**
  35712. * Unlocks updates for the material
  35713. */
  35714. Material.prototype.unfreeze = function () {
  35715. this.checkReadyOnlyOnce = false;
  35716. };
  35717. /**
  35718. * Specifies if the material is ready to be used
  35719. * @param mesh defines the mesh to check
  35720. * @param useInstances specifies if instances should be used
  35721. * @returns a boolean indicating if the material is ready to be used
  35722. */
  35723. Material.prototype.isReady = function (mesh, useInstances) {
  35724. return true;
  35725. };
  35726. /**
  35727. * Specifies that the submesh is ready to be used
  35728. * @param mesh defines the mesh to check
  35729. * @param subMesh defines which submesh to check
  35730. * @param useInstances specifies that instances should be used
  35731. * @returns a boolean indicating that the submesh is ready or not
  35732. */
  35733. Material.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  35734. return false;
  35735. };
  35736. /**
  35737. * Returns the material effect
  35738. * @returns the effect associated with the material
  35739. */
  35740. Material.prototype.getEffect = function () {
  35741. return this._effect;
  35742. };
  35743. /**
  35744. * Returns the current scene
  35745. * @returns a Scene
  35746. */
  35747. Material.prototype.getScene = function () {
  35748. return this._scene;
  35749. };
  35750. /**
  35751. * Specifies if the material will require alpha blending
  35752. * @returns a boolean specifying if alpha blending is needed
  35753. */
  35754. Material.prototype.needAlphaBlending = function () {
  35755. return (this.alpha < 1.0);
  35756. };
  35757. /**
  35758. * Specifies if the mesh will require alpha blending
  35759. * @param mesh defines the mesh to check
  35760. * @returns a boolean specifying if alpha blending is needed for the mesh
  35761. */
  35762. Material.prototype.needAlphaBlendingForMesh = function (mesh) {
  35763. return this.needAlphaBlending() || (mesh.visibility < 1.0) || mesh.hasVertexAlpha;
  35764. };
  35765. /**
  35766. * Specifies if this material should be rendered in alpha test mode
  35767. * @returns a boolean specifying if an alpha test is needed.
  35768. */
  35769. Material.prototype.needAlphaTesting = function () {
  35770. return false;
  35771. };
  35772. /**
  35773. * Gets the texture used for the alpha test
  35774. * @returns the texture to use for alpha testing
  35775. */
  35776. Material.prototype.getAlphaTestTexture = function () {
  35777. return null;
  35778. };
  35779. /**
  35780. * Marks the material to indicate that it needs to be re-calculated
  35781. */
  35782. Material.prototype.markDirty = function () {
  35783. this._wasPreviouslyReady = false;
  35784. };
  35785. /** @hidden */
  35786. Material.prototype._preBind = function (effect, overrideOrientation) {
  35787. if (overrideOrientation === void 0) { overrideOrientation = null; }
  35788. var engine = this._scene.getEngine();
  35789. var orientation = (overrideOrientation == null) ? this.sideOrientation : overrideOrientation;
  35790. var reverse = orientation === Material.ClockWiseSideOrientation;
  35791. engine.enableEffect(effect ? effect : this._effect);
  35792. engine.setState(this.backFaceCulling, this.zOffset, false, reverse);
  35793. return reverse;
  35794. };
  35795. /**
  35796. * Binds the material to the mesh
  35797. * @param world defines the world transformation matrix
  35798. * @param mesh defines the mesh to bind the material to
  35799. */
  35800. Material.prototype.bind = function (world, mesh) {
  35801. };
  35802. /**
  35803. * Binds the submesh to the material
  35804. * @param world defines the world transformation matrix
  35805. * @param mesh defines the mesh containing the submesh
  35806. * @param subMesh defines the submesh to bind the material to
  35807. */
  35808. Material.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  35809. };
  35810. /**
  35811. * Binds the world matrix to the material
  35812. * @param world defines the world transformation matrix
  35813. */
  35814. Material.prototype.bindOnlyWorldMatrix = function (world) {
  35815. };
  35816. /**
  35817. * Binds the scene's uniform buffer to the effect.
  35818. * @param effect defines the effect to bind to the scene uniform buffer
  35819. * @param sceneUbo defines the uniform buffer storing scene data
  35820. */
  35821. Material.prototype.bindSceneUniformBuffer = function (effect, sceneUbo) {
  35822. sceneUbo.bindToEffect(effect, "Scene");
  35823. };
  35824. /**
  35825. * Binds the view matrix to the effect
  35826. * @param effect defines the effect to bind the view matrix to
  35827. */
  35828. Material.prototype.bindView = function (effect) {
  35829. if (!this._useUBO) {
  35830. effect.setMatrix("view", this.getScene().getViewMatrix());
  35831. }
  35832. else {
  35833. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35834. }
  35835. };
  35836. /**
  35837. * Binds the view projection matrix to the effect
  35838. * @param effect defines the effect to bind the view projection matrix to
  35839. */
  35840. Material.prototype.bindViewProjection = function (effect) {
  35841. if (!this._useUBO) {
  35842. effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  35843. }
  35844. else {
  35845. this.bindSceneUniformBuffer(effect, this.getScene().getSceneUniformBuffer());
  35846. }
  35847. };
  35848. /**
  35849. * Specifies if material alpha testing should be turned on for the mesh
  35850. * @param mesh defines the mesh to check
  35851. */
  35852. Material.prototype._shouldTurnAlphaTestOn = function (mesh) {
  35853. return (!this.needAlphaBlendingForMesh(mesh) && this.needAlphaTesting());
  35854. };
  35855. /**
  35856. * Processes to execute after binding the material to a mesh
  35857. * @param mesh defines the rendered mesh
  35858. */
  35859. Material.prototype._afterBind = function (mesh) {
  35860. this._scene._cachedMaterial = this;
  35861. if (mesh) {
  35862. this._scene._cachedVisibility = mesh.visibility;
  35863. }
  35864. else {
  35865. this._scene._cachedVisibility = 1;
  35866. }
  35867. if (mesh) {
  35868. this.onBindObservable.notifyObservers(mesh);
  35869. }
  35870. if (this.disableDepthWrite) {
  35871. var engine = this._scene.getEngine();
  35872. this._cachedDepthWriteState = engine.getDepthWrite();
  35873. engine.setDepthWrite(false);
  35874. }
  35875. };
  35876. /**
  35877. * Unbinds the material from the mesh
  35878. */
  35879. Material.prototype.unbind = function () {
  35880. this.onUnBindObservable.notifyObservers(this);
  35881. if (this.disableDepthWrite) {
  35882. var engine = this._scene.getEngine();
  35883. engine.setDepthWrite(this._cachedDepthWriteState);
  35884. }
  35885. };
  35886. /**
  35887. * Gets the active textures from the material
  35888. * @returns an array of textures
  35889. */
  35890. Material.prototype.getActiveTextures = function () {
  35891. return [];
  35892. };
  35893. /**
  35894. * Specifies if the material uses a texture
  35895. * @param texture defines the texture to check against the material
  35896. * @returns a boolean specifying if the material uses the texture
  35897. */
  35898. Material.prototype.hasTexture = function (texture) {
  35899. return false;
  35900. };
  35901. /**
  35902. * Makes a duplicate of the material, and gives it a new name
  35903. * @param name defines the new name for the duplicated material
  35904. * @returns the cloned material
  35905. */
  35906. Material.prototype.clone = function (name) {
  35907. return null;
  35908. };
  35909. /**
  35910. * Gets the meshes bound to the material
  35911. * @returns an array of meshes bound to the material
  35912. */
  35913. Material.prototype.getBindedMeshes = function () {
  35914. var result = new Array();
  35915. for (var index = 0; index < this._scene.meshes.length; index++) {
  35916. var mesh = this._scene.meshes[index];
  35917. if (mesh.material === this) {
  35918. result.push(mesh);
  35919. }
  35920. }
  35921. return result;
  35922. };
  35923. /**
  35924. * Force shader compilation
  35925. * @param mesh defines the mesh associated with this material
  35926. * @param onCompiled defines a function to execute once the material is compiled
  35927. * @param options defines the options to configure the compilation
  35928. */
  35929. Material.prototype.forceCompilation = function (mesh, onCompiled, options) {
  35930. var _this = this;
  35931. var localOptions = __assign({ clipPlane: false }, options);
  35932. var subMesh = new BABYLON.BaseSubMesh();
  35933. var scene = this.getScene();
  35934. var checkReady = function () {
  35935. if (!_this._scene || !_this._scene.getEngine()) {
  35936. return;
  35937. }
  35938. if (subMesh._materialDefines) {
  35939. subMesh._materialDefines._renderId = -1;
  35940. }
  35941. var clipPlaneState = scene.clipPlane;
  35942. if (localOptions.clipPlane) {
  35943. scene.clipPlane = new BABYLON.Plane(0, 0, 0, 1);
  35944. }
  35945. if (_this.storeEffectOnSubMeshes) {
  35946. if (_this.isReadyForSubMesh(mesh, subMesh)) {
  35947. if (onCompiled) {
  35948. onCompiled(_this);
  35949. }
  35950. }
  35951. else {
  35952. setTimeout(checkReady, 16);
  35953. }
  35954. }
  35955. else {
  35956. if (_this.isReady(mesh)) {
  35957. if (onCompiled) {
  35958. onCompiled(_this);
  35959. }
  35960. }
  35961. else {
  35962. setTimeout(checkReady, 16);
  35963. }
  35964. }
  35965. if (localOptions.clipPlane) {
  35966. scene.clipPlane = clipPlaneState;
  35967. }
  35968. };
  35969. checkReady();
  35970. };
  35971. /**
  35972. * Force shader compilation
  35973. * @param mesh defines the mesh that will use this material
  35974. * @param options defines additional options for compiling the shaders
  35975. * @returns a promise that resolves when the compilation completes
  35976. */
  35977. Material.prototype.forceCompilationAsync = function (mesh, options) {
  35978. var _this = this;
  35979. return new Promise(function (resolve) {
  35980. _this.forceCompilation(mesh, function () {
  35981. resolve();
  35982. }, options);
  35983. });
  35984. };
  35985. /**
  35986. * Marks a define in the material to indicate that it needs to be re-computed
  35987. * @param flag defines a flag used to determine which parts of the material have to be marked as dirty
  35988. */
  35989. Material.prototype.markAsDirty = function (flag) {
  35990. if (flag & Material.TextureDirtyFlag) {
  35991. this._markAllSubMeshesAsTexturesDirty();
  35992. }
  35993. if (flag & Material.LightDirtyFlag) {
  35994. this._markAllSubMeshesAsLightsDirty();
  35995. }
  35996. if (flag & Material.FresnelDirtyFlag) {
  35997. this._markAllSubMeshesAsFresnelDirty();
  35998. }
  35999. if (flag & Material.AttributesDirtyFlag) {
  36000. this._markAllSubMeshesAsAttributesDirty();
  36001. }
  36002. if (flag & Material.MiscDirtyFlag) {
  36003. this._markAllSubMeshesAsMiscDirty();
  36004. }
  36005. this.getScene().resetCachedMaterial();
  36006. };
  36007. /**
  36008. * Marks all submeshes of a material to indicate that their material defines need to be re-calculated
  36009. * @param func defines a function which checks material defines against the submeshes
  36010. */
  36011. Material.prototype._markAllSubMeshesAsDirty = function (func) {
  36012. for (var _i = 0, _a = this.getScene().meshes; _i < _a.length; _i++) {
  36013. var mesh = _a[_i];
  36014. if (!mesh.subMeshes) {
  36015. continue;
  36016. }
  36017. for (var _b = 0, _c = mesh.subMeshes; _b < _c.length; _b++) {
  36018. var subMesh = _c[_b];
  36019. if (subMesh.getMaterial() !== this) {
  36020. continue;
  36021. }
  36022. if (!subMesh._materialDefines) {
  36023. continue;
  36024. }
  36025. func(subMesh._materialDefines);
  36026. }
  36027. }
  36028. };
  36029. /**
  36030. * Indicates that image processing needs to be re-calculated for all submeshes
  36031. */
  36032. Material.prototype._markAllSubMeshesAsImageProcessingDirty = function () {
  36033. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsImageProcessingDirty(); });
  36034. };
  36035. /**
  36036. * Indicates that textures need to be re-calculated for all submeshes
  36037. */
  36038. Material.prototype._markAllSubMeshesAsTexturesDirty = function () {
  36039. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsTexturesDirty(); });
  36040. };
  36041. /**
  36042. * Indicates that fresnel needs to be re-calculated for all submeshes
  36043. */
  36044. Material.prototype._markAllSubMeshesAsFresnelDirty = function () {
  36045. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsFresnelDirty(); });
  36046. };
  36047. /**
  36048. * Indicates that fresnel and misc need to be re-calculated for all submeshes
  36049. */
  36050. Material.prototype._markAllSubMeshesAsFresnelAndMiscDirty = function () {
  36051. this._markAllSubMeshesAsDirty(function (defines) {
  36052. defines.markAsFresnelDirty();
  36053. defines.markAsMiscDirty();
  36054. });
  36055. };
  36056. /**
  36057. * Indicates that lights need to be re-calculated for all submeshes
  36058. */
  36059. Material.prototype._markAllSubMeshesAsLightsDirty = function () {
  36060. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsLightDirty(); });
  36061. };
  36062. /**
  36063. * Indicates that attributes need to be re-calculated for all submeshes
  36064. */
  36065. Material.prototype._markAllSubMeshesAsAttributesDirty = function () {
  36066. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsAttributesDirty(); });
  36067. };
  36068. /**
  36069. * Indicates that misc needs to be re-calculated for all submeshes
  36070. */
  36071. Material.prototype._markAllSubMeshesAsMiscDirty = function () {
  36072. this._markAllSubMeshesAsDirty(function (defines) { return defines.markAsMiscDirty(); });
  36073. };
  36074. /**
  36075. * Indicates that textures and misc need to be re-calculated for all submeshes
  36076. */
  36077. Material.prototype._markAllSubMeshesAsTexturesAndMiscDirty = function () {
  36078. this._markAllSubMeshesAsDirty(function (defines) {
  36079. defines.markAsTexturesDirty();
  36080. defines.markAsMiscDirty();
  36081. });
  36082. };
  36083. /**
  36084. * Disposes the material
  36085. * @param forceDisposeEffect specifies if effects should be forcefully disposed
  36086. * @param forceDisposeTextures specifies if textures should be forcefully disposed
  36087. */
  36088. Material.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  36089. // Animations
  36090. this.getScene().stopAnimation(this);
  36091. this.getScene().freeProcessedMaterials();
  36092. // Remove from scene
  36093. var index = this._scene.materials.indexOf(this);
  36094. if (index >= 0) {
  36095. this._scene.materials.splice(index, 1);
  36096. }
  36097. // Remove from meshes
  36098. for (index = 0; index < this._scene.meshes.length; index++) {
  36099. var mesh = this._scene.meshes[index];
  36100. if (mesh.material === this) {
  36101. mesh.material = null;
  36102. if (mesh.geometry) {
  36103. var geometry = (mesh.geometry);
  36104. if (this.storeEffectOnSubMeshes) {
  36105. for (var _i = 0, _a = mesh.subMeshes; _i < _a.length; _i++) {
  36106. var subMesh = _a[_i];
  36107. geometry._releaseVertexArrayObject(subMesh._materialEffect);
  36108. if (forceDisposeEffect && subMesh._materialEffect) {
  36109. this._scene.getEngine()._releaseEffect(subMesh._materialEffect);
  36110. }
  36111. }
  36112. }
  36113. else {
  36114. geometry._releaseVertexArrayObject(this._effect);
  36115. }
  36116. }
  36117. }
  36118. }
  36119. this._uniformBuffer.dispose();
  36120. // Shader are kept in cache for further use but we can get rid of this by using forceDisposeEffect
  36121. if (forceDisposeEffect && this._effect) {
  36122. if (!this.storeEffectOnSubMeshes) {
  36123. this._scene.getEngine()._releaseEffect(this._effect);
  36124. }
  36125. this._effect = null;
  36126. }
  36127. // Callback
  36128. this.onDisposeObservable.notifyObservers(this);
  36129. this.onDisposeObservable.clear();
  36130. this.onBindObservable.clear();
  36131. this.onUnBindObservable.clear();
  36132. };
  36133. /**
  36134. * Serializes this material
  36135. * @returns the serialized material object
  36136. */
  36137. Material.prototype.serialize = function () {
  36138. return BABYLON.SerializationHelper.Serialize(this);
  36139. };
  36140. /**
  36141. * Creates a MultiMaterial from parsed MultiMaterial data.
  36142. * @param parsedMultiMaterial defines parsed MultiMaterial data.
  36143. * @param scene defines the hosting scene
  36144. * @returns a new MultiMaterial
  36145. */
  36146. Material.ParseMultiMaterial = function (parsedMultiMaterial, scene) {
  36147. var multiMaterial = new BABYLON.MultiMaterial(parsedMultiMaterial.name, scene);
  36148. multiMaterial.id = parsedMultiMaterial.id;
  36149. if (BABYLON.Tags) {
  36150. BABYLON.Tags.AddTagsTo(multiMaterial, parsedMultiMaterial.tags);
  36151. }
  36152. for (var matIndex = 0; matIndex < parsedMultiMaterial.materials.length; matIndex++) {
  36153. var subMatId = parsedMultiMaterial.materials[matIndex];
  36154. if (subMatId) {
  36155. multiMaterial.subMaterials.push(scene.getMaterialByID(subMatId));
  36156. }
  36157. else {
  36158. multiMaterial.subMaterials.push(null);
  36159. }
  36160. }
  36161. return multiMaterial;
  36162. };
  36163. /**
  36164. * Creates a material from parsed material data
  36165. * @param parsedMaterial defines parsed material data
  36166. * @param scene defines the hosting scene
  36167. * @param rootUrl defines the root URL to use to load textures
  36168. * @returns a new material
  36169. */
  36170. Material.Parse = function (parsedMaterial, scene, rootUrl) {
  36171. if (!parsedMaterial.customType || parsedMaterial.customType === "BABYLON.StandardMaterial") {
  36172. return BABYLON.StandardMaterial.Parse(parsedMaterial, scene, rootUrl);
  36173. }
  36174. if (parsedMaterial.customType === "BABYLON.PBRMaterial" && parsedMaterial.overloadedAlbedo) {
  36175. parsedMaterial.customType = "BABYLON.LegacyPBRMaterial";
  36176. if (!BABYLON.LegacyPBRMaterial) {
  36177. BABYLON.Tools.Error("Your scene is trying to load a legacy version of the PBRMaterial, please, include it from the materials library.");
  36178. return;
  36179. }
  36180. }
  36181. var materialType = BABYLON.Tools.Instantiate(parsedMaterial.customType);
  36182. return materialType.Parse(parsedMaterial, scene, rootUrl);
  36183. };
  36184. // Triangle views
  36185. Material._TriangleFillMode = 0;
  36186. Material._WireFrameFillMode = 1;
  36187. Material._PointFillMode = 2;
  36188. // Draw modes
  36189. Material._PointListDrawMode = 3;
  36190. Material._LineListDrawMode = 4;
  36191. Material._LineLoopDrawMode = 5;
  36192. Material._LineStripDrawMode = 6;
  36193. Material._TriangleStripDrawMode = 7;
  36194. Material._TriangleFanDrawMode = 8;
  36195. /**
  36196. * Stores the clock-wise side orientation
  36197. */
  36198. Material._ClockWiseSideOrientation = 0;
  36199. /**
  36200. * Stores the counter clock-wise side orientation
  36201. */
  36202. Material._CounterClockWiseSideOrientation = 1;
  36203. /**
  36204. * The dirty texture flag value
  36205. */
  36206. Material._TextureDirtyFlag = 1;
  36207. /**
  36208. * The dirty light flag value
  36209. */
  36210. Material._LightDirtyFlag = 2;
  36211. /**
  36212. * The dirty fresnel flag value
  36213. */
  36214. Material._FresnelDirtyFlag = 4;
  36215. /**
  36216. * The dirty attribute flag value
  36217. */
  36218. Material._AttributesDirtyFlag = 8;
  36219. /**
  36220. * The dirty misc flag value
  36221. */
  36222. Material._MiscDirtyFlag = 16;
  36223. __decorate([
  36224. BABYLON.serialize()
  36225. ], Material.prototype, "id", void 0);
  36226. __decorate([
  36227. BABYLON.serialize()
  36228. ], Material.prototype, "uniqueId", void 0);
  36229. __decorate([
  36230. BABYLON.serialize()
  36231. ], Material.prototype, "name", void 0);
  36232. __decorate([
  36233. BABYLON.serialize()
  36234. ], Material.prototype, "checkReadyOnEveryCall", void 0);
  36235. __decorate([
  36236. BABYLON.serialize()
  36237. ], Material.prototype, "checkReadyOnlyOnce", void 0);
  36238. __decorate([
  36239. BABYLON.serialize()
  36240. ], Material.prototype, "state", void 0);
  36241. __decorate([
  36242. BABYLON.serialize("alpha")
  36243. ], Material.prototype, "_alpha", void 0);
  36244. __decorate([
  36245. BABYLON.serialize("backFaceCulling")
  36246. ], Material.prototype, "_backFaceCulling", void 0);
  36247. __decorate([
  36248. BABYLON.serialize()
  36249. ], Material.prototype, "sideOrientation", void 0);
  36250. __decorate([
  36251. BABYLON.serialize("alphaMode")
  36252. ], Material.prototype, "_alphaMode", void 0);
  36253. __decorate([
  36254. BABYLON.serialize()
  36255. ], Material.prototype, "_needDepthPrePass", void 0);
  36256. __decorate([
  36257. BABYLON.serialize()
  36258. ], Material.prototype, "disableDepthWrite", void 0);
  36259. __decorate([
  36260. BABYLON.serialize()
  36261. ], Material.prototype, "forceDepthWrite", void 0);
  36262. __decorate([
  36263. BABYLON.serialize()
  36264. ], Material.prototype, "separateCullingPass", void 0);
  36265. __decorate([
  36266. BABYLON.serialize("fogEnabled")
  36267. ], Material.prototype, "_fogEnabled", void 0);
  36268. __decorate([
  36269. BABYLON.serialize()
  36270. ], Material.prototype, "pointSize", void 0);
  36271. __decorate([
  36272. BABYLON.serialize()
  36273. ], Material.prototype, "zOffset", void 0);
  36274. __decorate([
  36275. BABYLON.serialize()
  36276. ], Material.prototype, "wireframe", null);
  36277. __decorate([
  36278. BABYLON.serialize()
  36279. ], Material.prototype, "pointsCloud", null);
  36280. __decorate([
  36281. BABYLON.serialize()
  36282. ], Material.prototype, "fillMode", null);
  36283. return Material;
  36284. }());
  36285. BABYLON.Material = Material;
  36286. })(BABYLON || (BABYLON = {}));
  36287. //# sourceMappingURL=babylon.material.js.map
  36288. var BABYLON;
  36289. (function (BABYLON) {
  36290. var UniformBuffer = /** @class */ (function () {
  36291. /**
  36292. * Uniform buffer objects.
  36293. *
  36294. * Handles blocks of uniform on the GPU.
  36295. *
  36296. * If WebGL 2 is not available, this class falls back on traditionnal setUniformXXX calls.
  36297. *
  36298. * For more information, please refer to :
  36299. * https://www.khronos.org/opengl/wiki/Uniform_Buffer_Object
  36300. */
  36301. function UniformBuffer(engine, data, dynamic) {
  36302. this._engine = engine;
  36303. this._noUBO = !engine.supportsUniformBuffers;
  36304. this._dynamic = dynamic;
  36305. this._data = data || [];
  36306. this._uniformLocations = {};
  36307. this._uniformSizes = {};
  36308. this._uniformLocationPointer = 0;
  36309. this._needSync = false;
  36310. if (this._noUBO) {
  36311. this.updateMatrix3x3 = this._updateMatrix3x3ForEffect;
  36312. this.updateMatrix2x2 = this._updateMatrix2x2ForEffect;
  36313. this.updateFloat = this._updateFloatForEffect;
  36314. this.updateFloat2 = this._updateFloat2ForEffect;
  36315. this.updateFloat3 = this._updateFloat3ForEffect;
  36316. this.updateFloat4 = this._updateFloat4ForEffect;
  36317. this.updateMatrix = this._updateMatrixForEffect;
  36318. this.updateVector3 = this._updateVector3ForEffect;
  36319. this.updateVector4 = this._updateVector4ForEffect;
  36320. this.updateColor3 = this._updateColor3ForEffect;
  36321. this.updateColor4 = this._updateColor4ForEffect;
  36322. }
  36323. else {
  36324. this._engine._uniformBuffers.push(this);
  36325. this.updateMatrix3x3 = this._updateMatrix3x3ForUniform;
  36326. this.updateMatrix2x2 = this._updateMatrix2x2ForUniform;
  36327. this.updateFloat = this._updateFloatForUniform;
  36328. this.updateFloat2 = this._updateFloat2ForUniform;
  36329. this.updateFloat3 = this._updateFloat3ForUniform;
  36330. this.updateFloat4 = this._updateFloat4ForUniform;
  36331. this.updateMatrix = this._updateMatrixForUniform;
  36332. this.updateVector3 = this._updateVector3ForUniform;
  36333. this.updateVector4 = this._updateVector4ForUniform;
  36334. this.updateColor3 = this._updateColor3ForUniform;
  36335. this.updateColor4 = this._updateColor4ForUniform;
  36336. }
  36337. }
  36338. Object.defineProperty(UniformBuffer.prototype, "useUbo", {
  36339. // Properties
  36340. /**
  36341. * Indicates if the buffer is using the WebGL2 UBO implementation,
  36342. * or just falling back on setUniformXXX calls.
  36343. */
  36344. get: function () {
  36345. return !this._noUBO;
  36346. },
  36347. enumerable: true,
  36348. configurable: true
  36349. });
  36350. Object.defineProperty(UniformBuffer.prototype, "isSync", {
  36351. /**
  36352. * Indicates if the WebGL underlying uniform buffer is in sync
  36353. * with the javascript cache data.
  36354. */
  36355. get: function () {
  36356. return !this._needSync;
  36357. },
  36358. enumerable: true,
  36359. configurable: true
  36360. });
  36361. /**
  36362. * Indicates if the WebGL underlying uniform buffer is dynamic.
  36363. * Also, a dynamic UniformBuffer will disable cache verification and always
  36364. * update the underlying WebGL uniform buffer to the GPU.
  36365. */
  36366. UniformBuffer.prototype.isDynamic = function () {
  36367. return this._dynamic !== undefined;
  36368. };
  36369. /**
  36370. * The data cache on JS side.
  36371. */
  36372. UniformBuffer.prototype.getData = function () {
  36373. return this._bufferData;
  36374. };
  36375. /**
  36376. * The underlying WebGL Uniform buffer.
  36377. */
  36378. UniformBuffer.prototype.getBuffer = function () {
  36379. return this._buffer;
  36380. };
  36381. /**
  36382. * std140 layout specifies how to align data within an UBO structure.
  36383. * See https://khronos.org/registry/OpenGL/specs/gl/glspec45.core.pdf#page=159
  36384. * for specs.
  36385. */
  36386. UniformBuffer.prototype._fillAlignment = function (size) {
  36387. // This code has been simplified because we only use floats, vectors of 1, 2, 3, 4 components
  36388. // and 4x4 matrices
  36389. // TODO : change if other types are used
  36390. var alignment;
  36391. if (size <= 2) {
  36392. alignment = size;
  36393. }
  36394. else {
  36395. alignment = 4;
  36396. }
  36397. if ((this._uniformLocationPointer % alignment) !== 0) {
  36398. var oldPointer = this._uniformLocationPointer;
  36399. this._uniformLocationPointer += alignment - (this._uniformLocationPointer % alignment);
  36400. var diff = this._uniformLocationPointer - oldPointer;
  36401. for (var i = 0; i < diff; i++) {
  36402. this._data.push(0);
  36403. }
  36404. }
  36405. };
  36406. /**
  36407. * Adds an uniform in the buffer.
  36408. * Warning : the subsequents calls of this function must be in the same order as declared in the shader
  36409. * for the layout to be correct !
  36410. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36411. * @param {number|number[]} size Data size, or data directly.
  36412. */
  36413. UniformBuffer.prototype.addUniform = function (name, size) {
  36414. if (this._noUBO) {
  36415. return;
  36416. }
  36417. if (this._uniformLocations[name] !== undefined) {
  36418. // Already existing uniform
  36419. return;
  36420. }
  36421. // This function must be called in the order of the shader layout !
  36422. // size can be the size of the uniform, or data directly
  36423. var data;
  36424. if (size instanceof Array) {
  36425. data = size;
  36426. size = data.length;
  36427. }
  36428. else {
  36429. size = size;
  36430. data = [];
  36431. // Fill with zeros
  36432. for (var i = 0; i < size; i++) {
  36433. data.push(0);
  36434. }
  36435. }
  36436. this._fillAlignment(size);
  36437. this._uniformSizes[name] = size;
  36438. this._uniformLocations[name] = this._uniformLocationPointer;
  36439. this._uniformLocationPointer += size;
  36440. for (var i = 0; i < size; i++) {
  36441. this._data.push(data[i]);
  36442. }
  36443. this._needSync = true;
  36444. };
  36445. /**
  36446. * Wrapper for addUniform.
  36447. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36448. * @param {Matrix} mat A 4x4 matrix.
  36449. */
  36450. UniformBuffer.prototype.addMatrix = function (name, mat) {
  36451. this.addUniform(name, Array.prototype.slice.call(mat.toArray()));
  36452. };
  36453. /**
  36454. * Wrapper for addUniform.
  36455. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36456. * @param {number} x
  36457. * @param {number} y
  36458. */
  36459. UniformBuffer.prototype.addFloat2 = function (name, x, y) {
  36460. var temp = [x, y];
  36461. this.addUniform(name, temp);
  36462. };
  36463. /**
  36464. * Wrapper for addUniform.
  36465. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36466. * @param {number} x
  36467. * @param {number} y
  36468. * @param {number} z
  36469. */
  36470. UniformBuffer.prototype.addFloat3 = function (name, x, y, z) {
  36471. var temp = [x, y, z];
  36472. this.addUniform(name, temp);
  36473. };
  36474. /**
  36475. * Wrapper for addUniform.
  36476. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36477. * @param {Color3} color
  36478. */
  36479. UniformBuffer.prototype.addColor3 = function (name, color) {
  36480. var temp = new Array();
  36481. color.toArray(temp);
  36482. this.addUniform(name, temp);
  36483. };
  36484. /**
  36485. * Wrapper for addUniform.
  36486. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36487. * @param {Color3} color
  36488. * @param {number} alpha
  36489. */
  36490. UniformBuffer.prototype.addColor4 = function (name, color, alpha) {
  36491. var temp = new Array();
  36492. color.toArray(temp);
  36493. temp.push(alpha);
  36494. this.addUniform(name, temp);
  36495. };
  36496. /**
  36497. * Wrapper for addUniform.
  36498. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36499. * @param {Vector3} vector
  36500. */
  36501. UniformBuffer.prototype.addVector3 = function (name, vector) {
  36502. var temp = new Array();
  36503. vector.toArray(temp);
  36504. this.addUniform(name, temp);
  36505. };
  36506. /**
  36507. * Wrapper for addUniform.
  36508. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36509. */
  36510. UniformBuffer.prototype.addMatrix3x3 = function (name) {
  36511. this.addUniform(name, 12);
  36512. };
  36513. /**
  36514. * Wrapper for addUniform.
  36515. * @param {string} name Name of the uniform, as used in the uniform block in the shader.
  36516. */
  36517. UniformBuffer.prototype.addMatrix2x2 = function (name) {
  36518. this.addUniform(name, 8);
  36519. };
  36520. /**
  36521. * Effectively creates the WebGL Uniform Buffer, once layout is completed with `addUniform`.
  36522. */
  36523. UniformBuffer.prototype.create = function () {
  36524. if (this._noUBO) {
  36525. return;
  36526. }
  36527. if (this._buffer) {
  36528. return; // nothing to do
  36529. }
  36530. // See spec, alignment must be filled as a vec4
  36531. this._fillAlignment(4);
  36532. this._bufferData = new Float32Array(this._data);
  36533. this._rebuild();
  36534. this._needSync = true;
  36535. };
  36536. UniformBuffer.prototype._rebuild = function () {
  36537. if (this._noUBO) {
  36538. return;
  36539. }
  36540. if (this._dynamic) {
  36541. this._buffer = this._engine.createDynamicUniformBuffer(this._bufferData);
  36542. }
  36543. else {
  36544. this._buffer = this._engine.createUniformBuffer(this._bufferData);
  36545. }
  36546. };
  36547. /**
  36548. * Updates the WebGL Uniform Buffer on the GPU.
  36549. * If the `dynamic` flag is set to true, no cache comparison is done.
  36550. * Otherwise, the buffer will be updated only if the cache differs.
  36551. */
  36552. UniformBuffer.prototype.update = function () {
  36553. if (!this._buffer) {
  36554. this.create();
  36555. return;
  36556. }
  36557. if (!this._dynamic && !this._needSync) {
  36558. return;
  36559. }
  36560. this._engine.updateUniformBuffer(this._buffer, this._bufferData);
  36561. this._needSync = false;
  36562. };
  36563. /**
  36564. * Updates the value of an uniform. The `update` method must be called afterwards to make it effective in the GPU.
  36565. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36566. * @param {number[]|Float32Array} data Flattened data
  36567. * @param {number} size Size of the data.
  36568. */
  36569. UniformBuffer.prototype.updateUniform = function (uniformName, data, size) {
  36570. var location = this._uniformLocations[uniformName];
  36571. if (location === undefined) {
  36572. if (this._buffer) {
  36573. // Cannot add an uniform if the buffer is already created
  36574. BABYLON.Tools.Error("Cannot add an uniform after UBO has been created.");
  36575. return;
  36576. }
  36577. this.addUniform(uniformName, size);
  36578. location = this._uniformLocations[uniformName];
  36579. }
  36580. if (!this._buffer) {
  36581. this.create();
  36582. }
  36583. if (!this._dynamic) {
  36584. // Cache for static uniform buffers
  36585. var changed = false;
  36586. for (var i = 0; i < size; i++) {
  36587. if (this._bufferData[location + i] !== data[i]) {
  36588. changed = true;
  36589. this._bufferData[location + i] = data[i];
  36590. }
  36591. }
  36592. this._needSync = this._needSync || changed;
  36593. }
  36594. else {
  36595. // No cache for dynamic
  36596. for (var i = 0; i < size; i++) {
  36597. this._bufferData[location + i] = data[i];
  36598. }
  36599. }
  36600. };
  36601. // Update methods
  36602. UniformBuffer.prototype._updateMatrix3x3ForUniform = function (name, matrix) {
  36603. // To match std140, matrix must be realigned
  36604. for (var i = 0; i < 3; i++) {
  36605. UniformBuffer._tempBuffer[i * 4] = matrix[i * 3];
  36606. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 3 + 1];
  36607. UniformBuffer._tempBuffer[i * 4 + 2] = matrix[i * 3 + 2];
  36608. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36609. }
  36610. this.updateUniform(name, UniformBuffer._tempBuffer, 12);
  36611. };
  36612. UniformBuffer.prototype._updateMatrix3x3ForEffect = function (name, matrix) {
  36613. this._currentEffect.setMatrix3x3(name, matrix);
  36614. };
  36615. UniformBuffer.prototype._updateMatrix2x2ForEffect = function (name, matrix) {
  36616. this._currentEffect.setMatrix2x2(name, matrix);
  36617. };
  36618. UniformBuffer.prototype._updateMatrix2x2ForUniform = function (name, matrix) {
  36619. // To match std140, matrix must be realigned
  36620. for (var i = 0; i < 2; i++) {
  36621. UniformBuffer._tempBuffer[i * 4] = matrix[i * 2];
  36622. UniformBuffer._tempBuffer[i * 4 + 1] = matrix[i * 2 + 1];
  36623. UniformBuffer._tempBuffer[i * 4 + 2] = 0.0;
  36624. UniformBuffer._tempBuffer[i * 4 + 3] = 0.0;
  36625. }
  36626. this.updateUniform(name, UniformBuffer._tempBuffer, 8);
  36627. };
  36628. UniformBuffer.prototype._updateFloatForEffect = function (name, x) {
  36629. this._currentEffect.setFloat(name, x);
  36630. };
  36631. UniformBuffer.prototype._updateFloatForUniform = function (name, x) {
  36632. UniformBuffer._tempBuffer[0] = x;
  36633. this.updateUniform(name, UniformBuffer._tempBuffer, 1);
  36634. };
  36635. UniformBuffer.prototype._updateFloat2ForEffect = function (name, x, y, suffix) {
  36636. if (suffix === void 0) { suffix = ""; }
  36637. this._currentEffect.setFloat2(name + suffix, x, y);
  36638. };
  36639. UniformBuffer.prototype._updateFloat2ForUniform = function (name, x, y, suffix) {
  36640. if (suffix === void 0) { suffix = ""; }
  36641. UniformBuffer._tempBuffer[0] = x;
  36642. UniformBuffer._tempBuffer[1] = y;
  36643. this.updateUniform(name, UniformBuffer._tempBuffer, 2);
  36644. };
  36645. UniformBuffer.prototype._updateFloat3ForEffect = function (name, x, y, z, suffix) {
  36646. if (suffix === void 0) { suffix = ""; }
  36647. this._currentEffect.setFloat3(name + suffix, x, y, z);
  36648. };
  36649. UniformBuffer.prototype._updateFloat3ForUniform = function (name, x, y, z, suffix) {
  36650. if (suffix === void 0) { suffix = ""; }
  36651. UniformBuffer._tempBuffer[0] = x;
  36652. UniformBuffer._tempBuffer[1] = y;
  36653. UniformBuffer._tempBuffer[2] = z;
  36654. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36655. };
  36656. UniformBuffer.prototype._updateFloat4ForEffect = function (name, x, y, z, w, suffix) {
  36657. if (suffix === void 0) { suffix = ""; }
  36658. this._currentEffect.setFloat4(name + suffix, x, y, z, w);
  36659. };
  36660. UniformBuffer.prototype._updateFloat4ForUniform = function (name, x, y, z, w, suffix) {
  36661. if (suffix === void 0) { suffix = ""; }
  36662. UniformBuffer._tempBuffer[0] = x;
  36663. UniformBuffer._tempBuffer[1] = y;
  36664. UniformBuffer._tempBuffer[2] = z;
  36665. UniformBuffer._tempBuffer[3] = w;
  36666. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36667. };
  36668. UniformBuffer.prototype._updateMatrixForEffect = function (name, mat) {
  36669. this._currentEffect.setMatrix(name, mat);
  36670. };
  36671. UniformBuffer.prototype._updateMatrixForUniform = function (name, mat) {
  36672. this.updateUniform(name, mat.toArray(), 16);
  36673. };
  36674. UniformBuffer.prototype._updateVector3ForEffect = function (name, vector) {
  36675. this._currentEffect.setVector3(name, vector);
  36676. };
  36677. UniformBuffer.prototype._updateVector3ForUniform = function (name, vector) {
  36678. vector.toArray(UniformBuffer._tempBuffer);
  36679. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36680. };
  36681. UniformBuffer.prototype._updateVector4ForEffect = function (name, vector) {
  36682. this._currentEffect.setVector4(name, vector);
  36683. };
  36684. UniformBuffer.prototype._updateVector4ForUniform = function (name, vector) {
  36685. vector.toArray(UniformBuffer._tempBuffer);
  36686. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36687. };
  36688. UniformBuffer.prototype._updateColor3ForEffect = function (name, color, suffix) {
  36689. if (suffix === void 0) { suffix = ""; }
  36690. this._currentEffect.setColor3(name + suffix, color);
  36691. };
  36692. UniformBuffer.prototype._updateColor3ForUniform = function (name, color, suffix) {
  36693. if (suffix === void 0) { suffix = ""; }
  36694. color.toArray(UniformBuffer._tempBuffer);
  36695. this.updateUniform(name, UniformBuffer._tempBuffer, 3);
  36696. };
  36697. UniformBuffer.prototype._updateColor4ForEffect = function (name, color, alpha, suffix) {
  36698. if (suffix === void 0) { suffix = ""; }
  36699. this._currentEffect.setColor4(name + suffix, color, alpha);
  36700. };
  36701. UniformBuffer.prototype._updateColor4ForUniform = function (name, color, alpha, suffix) {
  36702. if (suffix === void 0) { suffix = ""; }
  36703. color.toArray(UniformBuffer._tempBuffer);
  36704. UniformBuffer._tempBuffer[3] = alpha;
  36705. this.updateUniform(name, UniformBuffer._tempBuffer, 4);
  36706. };
  36707. /**
  36708. * Sets a sampler uniform on the effect.
  36709. * @param {string} name Name of the sampler.
  36710. * @param {Texture} texture
  36711. */
  36712. UniformBuffer.prototype.setTexture = function (name, texture) {
  36713. this._currentEffect.setTexture(name, texture);
  36714. };
  36715. /**
  36716. * Directly updates the value of the uniform in the cache AND on the GPU.
  36717. * @param {string} uniformName Name of the uniform, as used in the uniform block in the shader.
  36718. * @param {number[]|Float32Array} data Flattened data
  36719. */
  36720. UniformBuffer.prototype.updateUniformDirectly = function (uniformName, data) {
  36721. this.updateUniform(uniformName, data, data.length);
  36722. this.update();
  36723. };
  36724. /**
  36725. * Binds this uniform buffer to an effect.
  36726. * @param {Effect} effect
  36727. * @param {string} name Name of the uniform block in the shader.
  36728. */
  36729. UniformBuffer.prototype.bindToEffect = function (effect, name) {
  36730. this._currentEffect = effect;
  36731. if (this._noUBO || !this._buffer) {
  36732. return;
  36733. }
  36734. effect.bindUniformBuffer(this._buffer, name);
  36735. };
  36736. /**
  36737. * Disposes the uniform buffer.
  36738. */
  36739. UniformBuffer.prototype.dispose = function () {
  36740. if (this._noUBO) {
  36741. return;
  36742. }
  36743. var index = this._engine._uniformBuffers.indexOf(this);
  36744. if (index !== -1) {
  36745. this._engine._uniformBuffers.splice(index, 1);
  36746. }
  36747. if (!this._buffer) {
  36748. return;
  36749. }
  36750. if (this._engine._releaseBuffer(this._buffer)) {
  36751. this._buffer = null;
  36752. }
  36753. };
  36754. // Pool for avoiding memory leaks
  36755. UniformBuffer._MAX_UNIFORM_SIZE = 256;
  36756. UniformBuffer._tempBuffer = new Float32Array(UniformBuffer._MAX_UNIFORM_SIZE);
  36757. return UniformBuffer;
  36758. }());
  36759. BABYLON.UniformBuffer = UniformBuffer;
  36760. })(BABYLON || (BABYLON = {}));
  36761. //# sourceMappingURL=babylon.uniformBuffer.js.map
  36762. var BABYLON;
  36763. (function (BABYLON) {
  36764. /**
  36765. * This class contains the various kinds of data on every vertex of a mesh used in determining its shape and appearance
  36766. */
  36767. var VertexData = /** @class */ (function () {
  36768. function VertexData() {
  36769. }
  36770. /**
  36771. * Uses the passed data array to set the set the values for the specified kind of data
  36772. * @param data a linear array of floating numbers
  36773. * @param kind the type of data that is being set, eg positions, colors etc
  36774. */
  36775. VertexData.prototype.set = function (data, kind) {
  36776. switch (kind) {
  36777. case BABYLON.VertexBuffer.PositionKind:
  36778. this.positions = data;
  36779. break;
  36780. case BABYLON.VertexBuffer.NormalKind:
  36781. this.normals = data;
  36782. break;
  36783. case BABYLON.VertexBuffer.TangentKind:
  36784. this.tangents = data;
  36785. break;
  36786. case BABYLON.VertexBuffer.UVKind:
  36787. this.uvs = data;
  36788. break;
  36789. case BABYLON.VertexBuffer.UV2Kind:
  36790. this.uvs2 = data;
  36791. break;
  36792. case BABYLON.VertexBuffer.UV3Kind:
  36793. this.uvs3 = data;
  36794. break;
  36795. case BABYLON.VertexBuffer.UV4Kind:
  36796. this.uvs4 = data;
  36797. break;
  36798. case BABYLON.VertexBuffer.UV5Kind:
  36799. this.uvs5 = data;
  36800. break;
  36801. case BABYLON.VertexBuffer.UV6Kind:
  36802. this.uvs6 = data;
  36803. break;
  36804. case BABYLON.VertexBuffer.ColorKind:
  36805. this.colors = data;
  36806. break;
  36807. case BABYLON.VertexBuffer.MatricesIndicesKind:
  36808. this.matricesIndices = data;
  36809. break;
  36810. case BABYLON.VertexBuffer.MatricesWeightsKind:
  36811. this.matricesWeights = data;
  36812. break;
  36813. case BABYLON.VertexBuffer.MatricesIndicesExtraKind:
  36814. this.matricesIndicesExtra = data;
  36815. break;
  36816. case BABYLON.VertexBuffer.MatricesWeightsExtraKind:
  36817. this.matricesWeightsExtra = data;
  36818. break;
  36819. }
  36820. };
  36821. /**
  36822. * Associates the vertexData to the passed Mesh.
  36823. * Sets it as updatable or not (default `false`)
  36824. * @param mesh the mesh the vertexData is applied to
  36825. * @param updatable when used and having the value true allows new data to update the vertexData
  36826. * @returns the VertexData
  36827. */
  36828. VertexData.prototype.applyToMesh = function (mesh, updatable) {
  36829. this._applyTo(mesh, updatable);
  36830. return this;
  36831. };
  36832. /**
  36833. * Associates the vertexData to the passed Geometry.
  36834. * Sets it as updatable or not (default `false`)
  36835. * @param geometry the geometry the vertexData is applied to
  36836. * @param updatable when used and having the value true allows new data to update the vertexData
  36837. * @returns VertexData
  36838. */
  36839. VertexData.prototype.applyToGeometry = function (geometry, updatable) {
  36840. this._applyTo(geometry, updatable);
  36841. return this;
  36842. };
  36843. /**
  36844. * Updates the associated mesh
  36845. * @param mesh the mesh to be updated
  36846. * @param updateExtends when true the mesh BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36847. * @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
  36848. * @returns VertexData
  36849. */
  36850. VertexData.prototype.updateMesh = function (mesh, updateExtends, makeItUnique) {
  36851. this._update(mesh);
  36852. return this;
  36853. };
  36854. /**
  36855. * Updates the associated geometry
  36856. * @param geometry the geometry to be updated
  36857. * @param updateExtends when true BoundingInfo will be renewed when and if position kind is updated, optional with default false
  36858. * @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
  36859. * @returns VertexData.
  36860. */
  36861. VertexData.prototype.updateGeometry = function (geometry, updateExtends, makeItUnique) {
  36862. this._update(geometry);
  36863. return this;
  36864. };
  36865. VertexData.prototype._applyTo = function (meshOrGeometry, updatable) {
  36866. if (updatable === void 0) { updatable = false; }
  36867. if (this.positions) {
  36868. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updatable);
  36869. }
  36870. if (this.normals) {
  36871. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updatable);
  36872. }
  36873. if (this.tangents) {
  36874. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updatable);
  36875. }
  36876. if (this.uvs) {
  36877. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updatable);
  36878. }
  36879. if (this.uvs2) {
  36880. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updatable);
  36881. }
  36882. if (this.uvs3) {
  36883. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updatable);
  36884. }
  36885. if (this.uvs4) {
  36886. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updatable);
  36887. }
  36888. if (this.uvs5) {
  36889. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updatable);
  36890. }
  36891. if (this.uvs6) {
  36892. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updatable);
  36893. }
  36894. if (this.colors) {
  36895. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updatable);
  36896. }
  36897. if (this.matricesIndices) {
  36898. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updatable);
  36899. }
  36900. if (this.matricesWeights) {
  36901. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updatable);
  36902. }
  36903. if (this.matricesIndicesExtra) {
  36904. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updatable);
  36905. }
  36906. if (this.matricesWeightsExtra) {
  36907. meshOrGeometry.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updatable);
  36908. }
  36909. if (this.indices) {
  36910. meshOrGeometry.setIndices(this.indices, null, updatable);
  36911. }
  36912. else {
  36913. meshOrGeometry.setIndices([], null);
  36914. }
  36915. return this;
  36916. };
  36917. VertexData.prototype._update = function (meshOrGeometry, updateExtends, makeItUnique) {
  36918. if (this.positions) {
  36919. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this.positions, updateExtends, makeItUnique);
  36920. }
  36921. if (this.normals) {
  36922. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this.normals, updateExtends, makeItUnique);
  36923. }
  36924. if (this.tangents) {
  36925. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.TangentKind, this.tangents, updateExtends, makeItUnique);
  36926. }
  36927. if (this.uvs) {
  36928. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UVKind, this.uvs, updateExtends, makeItUnique);
  36929. }
  36930. if (this.uvs2) {
  36931. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV2Kind, this.uvs2, updateExtends, makeItUnique);
  36932. }
  36933. if (this.uvs3) {
  36934. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV3Kind, this.uvs3, updateExtends, makeItUnique);
  36935. }
  36936. if (this.uvs4) {
  36937. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV4Kind, this.uvs4, updateExtends, makeItUnique);
  36938. }
  36939. if (this.uvs5) {
  36940. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV5Kind, this.uvs5, updateExtends, makeItUnique);
  36941. }
  36942. if (this.uvs6) {
  36943. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.UV6Kind, this.uvs6, updateExtends, makeItUnique);
  36944. }
  36945. if (this.colors) {
  36946. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this.colors, updateExtends, makeItUnique);
  36947. }
  36948. if (this.matricesIndices) {
  36949. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices, updateExtends, makeItUnique);
  36950. }
  36951. if (this.matricesWeights) {
  36952. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights, updateExtends, makeItUnique);
  36953. }
  36954. if (this.matricesIndicesExtra) {
  36955. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra, updateExtends, makeItUnique);
  36956. }
  36957. if (this.matricesWeightsExtra) {
  36958. meshOrGeometry.updateVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra, updateExtends, makeItUnique);
  36959. }
  36960. if (this.indices) {
  36961. meshOrGeometry.setIndices(this.indices, null);
  36962. }
  36963. return this;
  36964. };
  36965. /**
  36966. * Transforms each position and each normal of the vertexData according to the passed Matrix
  36967. * @param matrix the transforming matrix
  36968. * @returns the VertexData
  36969. */
  36970. VertexData.prototype.transform = function (matrix) {
  36971. var flip = matrix.m[0] * matrix.m[5] * matrix.m[10] < 0;
  36972. var transformed = BABYLON.Vector3.Zero();
  36973. var index;
  36974. if (this.positions) {
  36975. var position = BABYLON.Vector3.Zero();
  36976. for (index = 0; index < this.positions.length; index += 3) {
  36977. BABYLON.Vector3.FromArrayToRef(this.positions, index, position);
  36978. BABYLON.Vector3.TransformCoordinatesToRef(position, matrix, transformed);
  36979. this.positions[index] = transformed.x;
  36980. this.positions[index + 1] = transformed.y;
  36981. this.positions[index + 2] = transformed.z;
  36982. }
  36983. }
  36984. if (this.normals) {
  36985. var normal = BABYLON.Vector3.Zero();
  36986. for (index = 0; index < this.normals.length; index += 3) {
  36987. BABYLON.Vector3.FromArrayToRef(this.normals, index, normal);
  36988. BABYLON.Vector3.TransformNormalToRef(normal, matrix, transformed);
  36989. this.normals[index] = transformed.x;
  36990. this.normals[index + 1] = transformed.y;
  36991. this.normals[index + 2] = transformed.z;
  36992. }
  36993. }
  36994. if (this.tangents) {
  36995. var tangent = BABYLON.Vector4.Zero();
  36996. var tangentTransformed = BABYLON.Vector4.Zero();
  36997. for (index = 0; index < this.tangents.length; index += 4) {
  36998. BABYLON.Vector4.FromArrayToRef(this.tangents, index, tangent);
  36999. BABYLON.Vector4.TransformNormalToRef(tangent, matrix, tangentTransformed);
  37000. this.tangents[index] = tangentTransformed.x;
  37001. this.tangents[index + 1] = tangentTransformed.y;
  37002. this.tangents[index + 2] = tangentTransformed.z;
  37003. this.tangents[index + 3] = tangentTransformed.w;
  37004. }
  37005. }
  37006. if (flip && this.indices) {
  37007. for (index = 0; index < this.indices.length; index += 3) {
  37008. var tmp = this.indices[index + 1];
  37009. this.indices[index + 1] = this.indices[index + 2];
  37010. this.indices[index + 2] = tmp;
  37011. }
  37012. }
  37013. return this;
  37014. };
  37015. /**
  37016. * Merges the passed VertexData into the current one
  37017. * @param other the VertexData to be merged into the current one
  37018. * @returns the modified VertexData
  37019. */
  37020. VertexData.prototype.merge = function (other) {
  37021. this._validate();
  37022. other._validate();
  37023. if (!this.normals !== !other.normals ||
  37024. !this.tangents !== !other.tangents ||
  37025. !this.uvs !== !other.uvs ||
  37026. !this.uvs2 !== !other.uvs2 ||
  37027. !this.uvs3 !== !other.uvs3 ||
  37028. !this.uvs4 !== !other.uvs4 ||
  37029. !this.uvs5 !== !other.uvs5 ||
  37030. !this.uvs6 !== !other.uvs6 ||
  37031. !this.colors !== !other.colors ||
  37032. !this.matricesIndices !== !other.matricesIndices ||
  37033. !this.matricesWeights !== !other.matricesWeights ||
  37034. !this.matricesIndicesExtra !== !other.matricesIndicesExtra ||
  37035. !this.matricesWeightsExtra !== !other.matricesWeightsExtra) {
  37036. throw new Error("Cannot merge vertex data that do not have the same set of attributes");
  37037. }
  37038. if (other.indices) {
  37039. if (!this.indices) {
  37040. this.indices = [];
  37041. }
  37042. var offset = this.positions ? this.positions.length / 3 : 0;
  37043. for (var index = 0; index < other.indices.length; index++) {
  37044. //TODO check type - if Int32Array | Uint32Array | Uint16Array!
  37045. this.indices.push(other.indices[index] + offset);
  37046. }
  37047. }
  37048. this.positions = this._mergeElement(this.positions, other.positions);
  37049. this.normals = this._mergeElement(this.normals, other.normals);
  37050. this.tangents = this._mergeElement(this.tangents, other.tangents);
  37051. this.uvs = this._mergeElement(this.uvs, other.uvs);
  37052. this.uvs2 = this._mergeElement(this.uvs2, other.uvs2);
  37053. this.uvs3 = this._mergeElement(this.uvs3, other.uvs3);
  37054. this.uvs4 = this._mergeElement(this.uvs4, other.uvs4);
  37055. this.uvs5 = this._mergeElement(this.uvs5, other.uvs5);
  37056. this.uvs6 = this._mergeElement(this.uvs6, other.uvs6);
  37057. this.colors = this._mergeElement(this.colors, other.colors);
  37058. this.matricesIndices = this._mergeElement(this.matricesIndices, other.matricesIndices);
  37059. this.matricesWeights = this._mergeElement(this.matricesWeights, other.matricesWeights);
  37060. this.matricesIndicesExtra = this._mergeElement(this.matricesIndicesExtra, other.matricesIndicesExtra);
  37061. this.matricesWeightsExtra = this._mergeElement(this.matricesWeightsExtra, other.matricesWeightsExtra);
  37062. return this;
  37063. };
  37064. VertexData.prototype._mergeElement = function (source, other) {
  37065. if (!source) {
  37066. return other;
  37067. }
  37068. if (!other) {
  37069. return source;
  37070. }
  37071. var len = other.length + source.length;
  37072. var isSrcTypedArray = source instanceof Float32Array;
  37073. var isOthTypedArray = other instanceof Float32Array;
  37074. // use non-loop method when the source is Float32Array
  37075. if (isSrcTypedArray) {
  37076. var ret32 = new Float32Array(len);
  37077. ret32.set(source);
  37078. ret32.set(other, source.length);
  37079. return ret32;
  37080. // source is number[], when other is also use concat
  37081. }
  37082. else if (!isOthTypedArray) {
  37083. return source.concat(other);
  37084. // source is a number[], but other is a Float32Array, loop required
  37085. }
  37086. else {
  37087. var ret = source.slice(0); // copy source to a separate array
  37088. for (var i = 0, len = other.length; i < len; i++) {
  37089. ret.push(other[i]);
  37090. }
  37091. return ret;
  37092. }
  37093. };
  37094. VertexData.prototype._validate = function () {
  37095. if (!this.positions) {
  37096. throw new Error("Positions are required");
  37097. }
  37098. var getElementCount = function (kind, values) {
  37099. var stride = BABYLON.VertexBuffer.DeduceStride(kind);
  37100. if ((values.length % stride) !== 0) {
  37101. throw new Error("The " + kind + "s array count must be a multiple of " + stride);
  37102. }
  37103. return values.length / stride;
  37104. };
  37105. var positionsElementCount = getElementCount(BABYLON.VertexBuffer.PositionKind, this.positions);
  37106. var validateElementCount = function (kind, values) {
  37107. var elementCount = getElementCount(kind, values);
  37108. if (elementCount !== positionsElementCount) {
  37109. throw new Error("The " + kind + "s element count (" + elementCount + ") does not match the positions count (" + positionsElementCount + ")");
  37110. }
  37111. };
  37112. if (this.normals)
  37113. validateElementCount(BABYLON.VertexBuffer.NormalKind, this.normals);
  37114. if (this.tangents)
  37115. validateElementCount(BABYLON.VertexBuffer.TangentKind, this.tangents);
  37116. if (this.uvs)
  37117. validateElementCount(BABYLON.VertexBuffer.UVKind, this.uvs);
  37118. if (this.uvs2)
  37119. validateElementCount(BABYLON.VertexBuffer.UV2Kind, this.uvs2);
  37120. if (this.uvs3)
  37121. validateElementCount(BABYLON.VertexBuffer.UV3Kind, this.uvs3);
  37122. if (this.uvs4)
  37123. validateElementCount(BABYLON.VertexBuffer.UV4Kind, this.uvs4);
  37124. if (this.uvs5)
  37125. validateElementCount(BABYLON.VertexBuffer.UV5Kind, this.uvs5);
  37126. if (this.uvs6)
  37127. validateElementCount(BABYLON.VertexBuffer.UV6Kind, this.uvs6);
  37128. if (this.colors)
  37129. validateElementCount(BABYLON.VertexBuffer.ColorKind, this.colors);
  37130. if (this.matricesIndices)
  37131. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesKind, this.matricesIndices);
  37132. if (this.matricesWeights)
  37133. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsKind, this.matricesWeights);
  37134. if (this.matricesIndicesExtra)
  37135. validateElementCount(BABYLON.VertexBuffer.MatricesIndicesExtraKind, this.matricesIndicesExtra);
  37136. if (this.matricesWeightsExtra)
  37137. validateElementCount(BABYLON.VertexBuffer.MatricesWeightsExtraKind, this.matricesWeightsExtra);
  37138. };
  37139. /**
  37140. * Serializes the VertexData
  37141. * @returns a serialized object
  37142. */
  37143. VertexData.prototype.serialize = function () {
  37144. var serializationObject = this.serialize();
  37145. if (this.positions) {
  37146. serializationObject.positions = this.positions;
  37147. }
  37148. if (this.normals) {
  37149. serializationObject.normals = this.normals;
  37150. }
  37151. if (this.tangents) {
  37152. serializationObject.tangents = this.tangents;
  37153. }
  37154. if (this.uvs) {
  37155. serializationObject.uvs = this.uvs;
  37156. }
  37157. if (this.uvs2) {
  37158. serializationObject.uvs2 = this.uvs2;
  37159. }
  37160. if (this.uvs3) {
  37161. serializationObject.uvs3 = this.uvs3;
  37162. }
  37163. if (this.uvs4) {
  37164. serializationObject.uvs4 = this.uvs4;
  37165. }
  37166. if (this.uvs5) {
  37167. serializationObject.uvs5 = this.uvs5;
  37168. }
  37169. if (this.uvs6) {
  37170. serializationObject.uvs6 = this.uvs6;
  37171. }
  37172. if (this.colors) {
  37173. serializationObject.colors = this.colors;
  37174. }
  37175. if (this.matricesIndices) {
  37176. serializationObject.matricesIndices = this.matricesIndices;
  37177. serializationObject.matricesIndices._isExpanded = true;
  37178. }
  37179. if (this.matricesWeights) {
  37180. serializationObject.matricesWeights = this.matricesWeights;
  37181. }
  37182. if (this.matricesIndicesExtra) {
  37183. serializationObject.matricesIndicesExtra = this.matricesIndicesExtra;
  37184. serializationObject.matricesIndicesExtra._isExpanded = true;
  37185. }
  37186. if (this.matricesWeightsExtra) {
  37187. serializationObject.matricesWeightsExtra = this.matricesWeightsExtra;
  37188. }
  37189. serializationObject.indices = this.indices;
  37190. return serializationObject;
  37191. };
  37192. // Statics
  37193. /**
  37194. * Extracts the vertexData from a mesh
  37195. * @param mesh the mesh from which to extract the VertexData
  37196. * @param copyWhenShared defines if the VertexData must be cloned when shared between multiple meshes, optional, default false
  37197. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37198. * @returns the object VertexData associated to the passed mesh
  37199. */
  37200. VertexData.ExtractFromMesh = function (mesh, copyWhenShared, forceCopy) {
  37201. return VertexData._ExtractFrom(mesh, copyWhenShared, forceCopy);
  37202. };
  37203. /**
  37204. * Extracts the vertexData from the geometry
  37205. * @param geometry the geometry from which to extract the VertexData
  37206. * @param copyWhenShared defines if the VertexData must be cloned when the geometrty is shared between multiple meshes, optional, default false
  37207. * @param forceCopy indicating that the VertexData must be cloned, optional, default false
  37208. * @returns the object VertexData associated to the passed mesh
  37209. */
  37210. VertexData.ExtractFromGeometry = function (geometry, copyWhenShared, forceCopy) {
  37211. return VertexData._ExtractFrom(geometry, copyWhenShared, forceCopy);
  37212. };
  37213. VertexData._ExtractFrom = function (meshOrGeometry, copyWhenShared, forceCopy) {
  37214. var result = new VertexData();
  37215. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  37216. result.positions = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.PositionKind, copyWhenShared, forceCopy);
  37217. }
  37218. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  37219. result.normals = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.NormalKind, copyWhenShared, forceCopy);
  37220. }
  37221. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  37222. result.tangents = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.TangentKind, copyWhenShared, forceCopy);
  37223. }
  37224. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  37225. result.uvs = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UVKind, copyWhenShared, forceCopy);
  37226. }
  37227. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  37228. result.uvs2 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV2Kind, copyWhenShared, forceCopy);
  37229. }
  37230. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  37231. result.uvs3 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV3Kind, copyWhenShared, forceCopy);
  37232. }
  37233. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  37234. result.uvs4 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV4Kind, copyWhenShared, forceCopy);
  37235. }
  37236. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  37237. result.uvs5 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV5Kind, copyWhenShared, forceCopy);
  37238. }
  37239. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  37240. result.uvs6 = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.UV6Kind, copyWhenShared, forceCopy);
  37241. }
  37242. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  37243. result.colors = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.ColorKind, copyWhenShared, forceCopy);
  37244. }
  37245. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  37246. result.matricesIndices = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, copyWhenShared, forceCopy);
  37247. }
  37248. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  37249. result.matricesWeights = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, copyWhenShared, forceCopy);
  37250. }
  37251. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesExtraKind)) {
  37252. result.matricesIndicesExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, copyWhenShared, forceCopy);
  37253. }
  37254. if (meshOrGeometry.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsExtraKind)) {
  37255. result.matricesWeightsExtra = meshOrGeometry.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, copyWhenShared, forceCopy);
  37256. }
  37257. result.indices = meshOrGeometry.getIndices(copyWhenShared);
  37258. return result;
  37259. };
  37260. /**
  37261. * Creates the VertexData for a Ribbon
  37262. * @param options an object used to set the following optional parameters for the ribbon, required but can be empty
  37263. * * pathArray array of paths, each of which an array of successive Vector3
  37264. * * closeArray creates a seam between the first and the last paths of the pathArray, optional, default false
  37265. * * closePath creates a seam between the first and the last points of each path of the path array, optional, default false
  37266. * * 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
  37267. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37268. * * 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)
  37269. * * 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)
  37270. * * invertUV swaps in the U and V coordinates when applying a texture, optional, default false
  37271. * * uvs a linear array, of length 2 * number of vertices, of custom UV values, optional
  37272. * * colors a linear array, of length 4 * number of vertices, of custom color values, optional
  37273. * @returns the VertexData of the ribbon
  37274. */
  37275. VertexData.CreateRibbon = function (options) {
  37276. var pathArray = options.pathArray;
  37277. var closeArray = options.closeArray || false;
  37278. var closePath = options.closePath || false;
  37279. var invertUV = options.invertUV || false;
  37280. var defaultOffset = Math.floor(pathArray[0].length / 2);
  37281. var offset = options.offset || defaultOffset;
  37282. offset = offset > defaultOffset ? defaultOffset : Math.floor(offset); // offset max allowed : defaultOffset
  37283. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37284. var customUV = options.uvs;
  37285. var customColors = options.colors;
  37286. var positions = [];
  37287. var indices = [];
  37288. var normals = [];
  37289. var uvs = [];
  37290. var us = []; // us[path_id] = [uDist1, uDist2, uDist3 ... ] distances between points on path path_id
  37291. var vs = []; // vs[i] = [vDist1, vDist2, vDist3, ... ] distances between points i of consecutives paths from pathArray
  37292. var uTotalDistance = []; // uTotalDistance[p] : total distance of path p
  37293. var vTotalDistance = []; // vTotalDistance[i] : total distance between points i of first and last path from pathArray
  37294. var minlg; // minimal length among all paths from pathArray
  37295. var lg = []; // array of path lengths : nb of vertex per path
  37296. var idx = []; // array of path indexes : index of each path (first vertex) in the total vertex number
  37297. var p; // path iterator
  37298. var i; // point iterator
  37299. var j; // point iterator
  37300. // if single path in pathArray
  37301. if (pathArray.length < 2) {
  37302. var ar1 = [];
  37303. var ar2 = [];
  37304. for (i = 0; i < pathArray[0].length - offset; i++) {
  37305. ar1.push(pathArray[0][i]);
  37306. ar2.push(pathArray[0][i + offset]);
  37307. }
  37308. pathArray = [ar1, ar2];
  37309. }
  37310. // positions and horizontal distances (u)
  37311. var idc = 0;
  37312. var closePathCorr = (closePath) ? 1 : 0; // the final index will be +1 if closePath
  37313. var path;
  37314. var l;
  37315. minlg = pathArray[0].length;
  37316. var vectlg;
  37317. var dist;
  37318. for (p = 0; p < pathArray.length; p++) {
  37319. uTotalDistance[p] = 0;
  37320. us[p] = [0];
  37321. path = pathArray[p];
  37322. l = path.length;
  37323. minlg = (minlg < l) ? minlg : l;
  37324. j = 0;
  37325. while (j < l) {
  37326. positions.push(path[j].x, path[j].y, path[j].z);
  37327. if (j > 0) {
  37328. vectlg = path[j].subtract(path[j - 1]).length();
  37329. dist = vectlg + uTotalDistance[p];
  37330. us[p].push(dist);
  37331. uTotalDistance[p] = dist;
  37332. }
  37333. j++;
  37334. }
  37335. if (closePath) { // an extra hidden vertex is added in the "positions" array
  37336. j--;
  37337. positions.push(path[0].x, path[0].y, path[0].z);
  37338. vectlg = path[j].subtract(path[0]).length();
  37339. dist = vectlg + uTotalDistance[p];
  37340. us[p].push(dist);
  37341. uTotalDistance[p] = dist;
  37342. }
  37343. lg[p] = l + closePathCorr;
  37344. idx[p] = idc;
  37345. idc += (l + closePathCorr);
  37346. }
  37347. // vertical distances (v)
  37348. var path1;
  37349. var path2;
  37350. var vertex1 = null;
  37351. var vertex2 = null;
  37352. for (i = 0; i < minlg + closePathCorr; i++) {
  37353. vTotalDistance[i] = 0;
  37354. vs[i] = [0];
  37355. for (p = 0; p < pathArray.length - 1; p++) {
  37356. path1 = pathArray[p];
  37357. path2 = pathArray[p + 1];
  37358. if (i === minlg) { // closePath
  37359. vertex1 = path1[0];
  37360. vertex2 = path2[0];
  37361. }
  37362. else {
  37363. vertex1 = path1[i];
  37364. vertex2 = path2[i];
  37365. }
  37366. vectlg = vertex2.subtract(vertex1).length();
  37367. dist = vectlg + vTotalDistance[i];
  37368. vs[i].push(dist);
  37369. vTotalDistance[i] = dist;
  37370. }
  37371. if (closeArray && vertex2 && vertex1) {
  37372. path1 = pathArray[p];
  37373. path2 = pathArray[0];
  37374. if (i === minlg) { // closePath
  37375. vertex2 = path2[0];
  37376. }
  37377. vectlg = vertex2.subtract(vertex1).length();
  37378. dist = vectlg + vTotalDistance[i];
  37379. vTotalDistance[i] = dist;
  37380. }
  37381. }
  37382. // uvs
  37383. var u;
  37384. var v;
  37385. if (customUV) {
  37386. for (p = 0; p < customUV.length; p++) {
  37387. uvs.push(customUV[p].x, customUV[p].y);
  37388. }
  37389. }
  37390. else {
  37391. for (p = 0; p < pathArray.length; p++) {
  37392. for (i = 0; i < minlg + closePathCorr; i++) {
  37393. u = (uTotalDistance[p] != 0.0) ? us[p][i] / uTotalDistance[p] : 0.0;
  37394. v = (vTotalDistance[i] != 0.0) ? vs[i][p] / vTotalDistance[i] : 0.0;
  37395. if (invertUV) {
  37396. uvs.push(v, u);
  37397. }
  37398. else {
  37399. uvs.push(u, v);
  37400. }
  37401. }
  37402. }
  37403. }
  37404. // indices
  37405. p = 0; // path index
  37406. var pi = 0; // positions array index
  37407. var l1 = lg[p] - 1; // path1 length
  37408. var l2 = lg[p + 1] - 1; // path2 length
  37409. var min = (l1 < l2) ? l1 : l2; // current path stop index
  37410. var shft = idx[1] - idx[0]; // shift
  37411. var path1nb = closeArray ? lg.length : lg.length - 1; // number of path1 to iterate on
  37412. while (pi <= min && p < path1nb) { // stay under min and don't go over next to last path
  37413. // 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
  37414. indices.push(pi, pi + shft, pi + 1);
  37415. indices.push(pi + shft + 1, pi + 1, pi + shft);
  37416. pi += 1;
  37417. if (pi === min) { // if end of one of two consecutive paths reached, go to next existing path
  37418. p++;
  37419. if (p === lg.length - 1) { // last path of pathArray reached <=> closeArray == true
  37420. shft = idx[0] - idx[p];
  37421. l1 = lg[p] - 1;
  37422. l2 = lg[0] - 1;
  37423. }
  37424. else {
  37425. shft = idx[p + 1] - idx[p];
  37426. l1 = lg[p] - 1;
  37427. l2 = lg[p + 1] - 1;
  37428. }
  37429. pi = idx[p];
  37430. min = (l1 < l2) ? l1 + pi : l2 + pi;
  37431. }
  37432. }
  37433. // normals
  37434. VertexData.ComputeNormals(positions, indices, normals);
  37435. if (closePath) { // update both the first and last vertex normals to their average value
  37436. var indexFirst = 0;
  37437. var indexLast = 0;
  37438. for (p = 0; p < pathArray.length; p++) {
  37439. indexFirst = idx[p] * 3;
  37440. if (p + 1 < pathArray.length) {
  37441. indexLast = (idx[p + 1] - 1) * 3;
  37442. }
  37443. else {
  37444. indexLast = normals.length - 3;
  37445. }
  37446. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  37447. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  37448. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  37449. normals[indexLast] = normals[indexFirst];
  37450. normals[indexLast + 1] = normals[indexFirst + 1];
  37451. normals[indexLast + 2] = normals[indexFirst + 2];
  37452. }
  37453. }
  37454. // sides
  37455. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37456. // Colors
  37457. var colors = null;
  37458. if (customColors) {
  37459. colors = new Float32Array(customColors.length * 4);
  37460. for (var c = 0; c < customColors.length; c++) {
  37461. colors[c * 4] = customColors[c].r;
  37462. colors[c * 4 + 1] = customColors[c].g;
  37463. colors[c * 4 + 2] = customColors[c].b;
  37464. colors[c * 4 + 3] = customColors[c].a;
  37465. }
  37466. }
  37467. // Result
  37468. var vertexData = new VertexData();
  37469. var positions32 = new Float32Array(positions);
  37470. var normals32 = new Float32Array(normals);
  37471. var uvs32 = new Float32Array(uvs);
  37472. vertexData.indices = indices;
  37473. vertexData.positions = positions32;
  37474. vertexData.normals = normals32;
  37475. vertexData.uvs = uvs32;
  37476. if (colors) {
  37477. vertexData.set(colors, BABYLON.VertexBuffer.ColorKind);
  37478. }
  37479. if (closePath) {
  37480. vertexData._idx = idx;
  37481. }
  37482. return vertexData;
  37483. };
  37484. /**
  37485. * Creates the VertexData for a box
  37486. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37487. * * size sets the width, height and depth of the box to the value of size, optional default 1
  37488. * * width sets the width (x direction) of the box, overwrites the width set by size, optional, default size
  37489. * * height sets the height (y direction) of the box, overwrites the height set by size, optional, default size
  37490. * * depth sets the depth (z direction) of the box, overwrites the depth set by size, optional, default size
  37491. * * faceUV an array of 6 Vector4 elements used to set different images to each box side
  37492. * * faceColors an array of 6 Color3 elements used to set different colors to each box side
  37493. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37494. * * frontUvs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the front side, optional, default vector4 (0, 0, 1, 1)
  37495. * * backUVs only usable when you create a double-sided mesh, used to choose what parts of the texture image to crop and apply on the back side, optional, default vector4 (0, 0, 1, 1)
  37496. * @returns the VertexData of the box
  37497. */
  37498. VertexData.CreateBox = function (options) {
  37499. var normalsSource = [
  37500. new BABYLON.Vector3(0, 0, 1),
  37501. new BABYLON.Vector3(0, 0, -1),
  37502. new BABYLON.Vector3(1, 0, 0),
  37503. new BABYLON.Vector3(-1, 0, 0),
  37504. new BABYLON.Vector3(0, 1, 0),
  37505. new BABYLON.Vector3(0, -1, 0)
  37506. ];
  37507. var indices = [];
  37508. var positions = [];
  37509. var normals = [];
  37510. var uvs = [];
  37511. var width = options.width || options.size || 1;
  37512. var height = options.height || options.size || 1;
  37513. var depth = options.depth || options.size || 1;
  37514. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37515. var faceUV = options.faceUV || new Array(6);
  37516. var faceColors = options.faceColors;
  37517. var colors = [];
  37518. // default face colors and UV if undefined
  37519. for (var f = 0; f < 6; f++) {
  37520. if (faceUV[f] === undefined) {
  37521. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37522. }
  37523. if (faceColors && faceColors[f] === undefined) {
  37524. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37525. }
  37526. }
  37527. var scaleVector = new BABYLON.Vector3(width / 2, height / 2, depth / 2);
  37528. // Create each face in turn.
  37529. for (var index = 0; index < normalsSource.length; index++) {
  37530. var normal = normalsSource[index];
  37531. // Get two vectors perpendicular to the face normal and to each other.
  37532. var side1 = new BABYLON.Vector3(normal.y, normal.z, normal.x);
  37533. var side2 = BABYLON.Vector3.Cross(normal, side1);
  37534. // Six indices (two triangles) per face.
  37535. var verticesLength = positions.length / 3;
  37536. indices.push(verticesLength);
  37537. indices.push(verticesLength + 1);
  37538. indices.push(verticesLength + 2);
  37539. indices.push(verticesLength);
  37540. indices.push(verticesLength + 2);
  37541. indices.push(verticesLength + 3);
  37542. // Four vertices per face.
  37543. var vertex = normal.subtract(side1).subtract(side2).multiply(scaleVector);
  37544. positions.push(vertex.x, vertex.y, vertex.z);
  37545. normals.push(normal.x, normal.y, normal.z);
  37546. uvs.push(faceUV[index].z, faceUV[index].w);
  37547. if (faceColors) {
  37548. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37549. }
  37550. vertex = normal.subtract(side1).add(side2).multiply(scaleVector);
  37551. positions.push(vertex.x, vertex.y, vertex.z);
  37552. normals.push(normal.x, normal.y, normal.z);
  37553. uvs.push(faceUV[index].x, faceUV[index].w);
  37554. if (faceColors) {
  37555. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37556. }
  37557. vertex = normal.add(side1).add(side2).multiply(scaleVector);
  37558. positions.push(vertex.x, vertex.y, vertex.z);
  37559. normals.push(normal.x, normal.y, normal.z);
  37560. uvs.push(faceUV[index].x, faceUV[index].y);
  37561. if (faceColors) {
  37562. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37563. }
  37564. vertex = normal.add(side1).subtract(side2).multiply(scaleVector);
  37565. positions.push(vertex.x, vertex.y, vertex.z);
  37566. normals.push(normal.x, normal.y, normal.z);
  37567. uvs.push(faceUV[index].z, faceUV[index].y);
  37568. if (faceColors) {
  37569. colors.push(faceColors[index].r, faceColors[index].g, faceColors[index].b, faceColors[index].a);
  37570. }
  37571. }
  37572. // sides
  37573. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37574. // Result
  37575. var vertexData = new VertexData();
  37576. vertexData.indices = indices;
  37577. vertexData.positions = positions;
  37578. vertexData.normals = normals;
  37579. vertexData.uvs = uvs;
  37580. if (faceColors) {
  37581. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  37582. vertexData.colors = totalColors;
  37583. }
  37584. return vertexData;
  37585. };
  37586. /**
  37587. * Creates the VertexData for an ellipsoid, defaults to a sphere
  37588. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37589. * * segments sets the number of horizontal strips optional, default 32
  37590. * * diameter sets the axes dimensions, diameterX, diameterY and diameterZ to the value of diameter, optional default 1
  37591. * * diameterX sets the diameterX (x direction) of the ellipsoid, overwrites the diameterX set by diameter, optional, default diameter
  37592. * * diameterY sets the diameterY (y direction) of the ellipsoid, overwrites the diameterY set by diameter, optional, default diameter
  37593. * * diameterZ sets the diameterZ (z direction) of the ellipsoid, overwrites the diameterZ set by diameter, optional, default diameter
  37594. * * 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
  37595. * * 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
  37596. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37597. * * 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)
  37598. * * 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)
  37599. * @returns the VertexData of the ellipsoid
  37600. */
  37601. VertexData.CreateSphere = function (options) {
  37602. var segments = options.segments || 32;
  37603. var diameterX = options.diameterX || options.diameter || 1;
  37604. var diameterY = options.diameterY || options.diameter || 1;
  37605. var diameterZ = options.diameterZ || options.diameter || 1;
  37606. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37607. var slice = options.slice && (options.slice <= 0) ? 1.0 : options.slice || 1.0;
  37608. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37609. var radius = new BABYLON.Vector3(diameterX / 2, diameterY / 2, diameterZ / 2);
  37610. var totalZRotationSteps = 2 + segments;
  37611. var totalYRotationSteps = 2 * totalZRotationSteps;
  37612. var indices = [];
  37613. var positions = [];
  37614. var normals = [];
  37615. var uvs = [];
  37616. for (var zRotationStep = 0; zRotationStep <= totalZRotationSteps; zRotationStep++) {
  37617. var normalizedZ = zRotationStep / totalZRotationSteps;
  37618. var angleZ = normalizedZ * Math.PI * slice;
  37619. for (var yRotationStep = 0; yRotationStep <= totalYRotationSteps; yRotationStep++) {
  37620. var normalizedY = yRotationStep / totalYRotationSteps;
  37621. var angleY = normalizedY * Math.PI * 2 * arc;
  37622. var rotationZ = BABYLON.Matrix.RotationZ(-angleZ);
  37623. var rotationY = BABYLON.Matrix.RotationY(angleY);
  37624. var afterRotZ = BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.Up(), rotationZ);
  37625. var complete = BABYLON.Vector3.TransformCoordinates(afterRotZ, rotationY);
  37626. var vertex = complete.multiply(radius);
  37627. var normal = complete.divide(radius).normalize();
  37628. positions.push(vertex.x, vertex.y, vertex.z);
  37629. normals.push(normal.x, normal.y, normal.z);
  37630. uvs.push(normalizedY, normalizedZ);
  37631. }
  37632. if (zRotationStep > 0) {
  37633. var verticesCount = positions.length / 3;
  37634. for (var firstIndex = verticesCount - 2 * (totalYRotationSteps + 1); (firstIndex + totalYRotationSteps + 2) < verticesCount; firstIndex++) {
  37635. indices.push((firstIndex));
  37636. indices.push((firstIndex + 1));
  37637. indices.push(firstIndex + totalYRotationSteps + 1);
  37638. indices.push((firstIndex + totalYRotationSteps + 1));
  37639. indices.push((firstIndex + 1));
  37640. indices.push((firstIndex + totalYRotationSteps + 2));
  37641. }
  37642. }
  37643. }
  37644. // Sides
  37645. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37646. // Result
  37647. var vertexData = new VertexData();
  37648. vertexData.indices = indices;
  37649. vertexData.positions = positions;
  37650. vertexData.normals = normals;
  37651. vertexData.uvs = uvs;
  37652. return vertexData;
  37653. };
  37654. /**
  37655. * Creates the VertexData for a cylinder, cone or prism
  37656. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37657. * * height sets the height (y direction) of the cylinder, optional, default 2
  37658. * * diameterTop sets the diameter of the top of the cone, overwrites diameter, optional, default diameter
  37659. * * diameterBottom sets the diameter of the bottom of the cone, overwrites diameter, optional, default diameter
  37660. * * diameter sets the diameter of the top and bottom of the cone, optional default 1
  37661. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37662. * * subdivisions` the number of rings along the cylinder height, optional, default 1
  37663. * * 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
  37664. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  37665. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  37666. * * hasRings when true makes each subdivision independantly treated as a face for faceUV and faceColors, optional, default false
  37667. * * enclose when true closes an open cylinder by adding extra flat faces between the height axis and vertical edges, think cut cake
  37668. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37669. * * 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)
  37670. * * 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)
  37671. * @returns the VertexData of the cylinder, cone or prism
  37672. */
  37673. VertexData.CreateCylinder = function (options) {
  37674. var height = options.height || 2;
  37675. var diameterTop = (options.diameterTop === 0) ? 0 : options.diameterTop || options.diameter || 1;
  37676. var diameterBottom = (options.diameterBottom === 0) ? 0 : options.diameterBottom || options.diameter || 1;
  37677. var tessellation = options.tessellation || 24;
  37678. var subdivisions = options.subdivisions || 1;
  37679. var hasRings = options.hasRings ? true : false;
  37680. var enclose = options.enclose ? true : false;
  37681. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  37682. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37683. var faceUV = options.faceUV || new Array(3);
  37684. var faceColors = options.faceColors;
  37685. // default face colors and UV if undefined
  37686. var quadNb = (arc !== 1 && enclose) ? 2 : 0;
  37687. var ringNb = (hasRings) ? subdivisions : 1;
  37688. var surfaceNb = 2 + (1 + quadNb) * ringNb;
  37689. var f;
  37690. for (f = 0; f < surfaceNb; f++) {
  37691. if (faceColors && faceColors[f] === undefined) {
  37692. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  37693. }
  37694. }
  37695. for (f = 0; f < surfaceNb; f++) {
  37696. if (faceUV && faceUV[f] === undefined) {
  37697. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  37698. }
  37699. }
  37700. var indices = new Array();
  37701. var positions = new Array();
  37702. var normals = new Array();
  37703. var uvs = new Array();
  37704. var colors = new Array();
  37705. var angle_step = Math.PI * 2 * arc / tessellation;
  37706. var angle;
  37707. var h;
  37708. var radius;
  37709. var tan = (diameterBottom - diameterTop) / 2 / height;
  37710. var ringVertex = BABYLON.Vector3.Zero();
  37711. var ringNormal = BABYLON.Vector3.Zero();
  37712. var ringFirstVertex = BABYLON.Vector3.Zero();
  37713. var ringFirstNormal = BABYLON.Vector3.Zero();
  37714. var quadNormal = BABYLON.Vector3.Zero();
  37715. var Y = BABYLON.Axis.Y;
  37716. // positions, normals, uvs
  37717. var i;
  37718. var j;
  37719. var r;
  37720. var ringIdx = 1;
  37721. var s = 1; // surface index
  37722. var cs = 0;
  37723. var v = 0;
  37724. for (i = 0; i <= subdivisions; i++) {
  37725. h = i / subdivisions;
  37726. radius = (h * (diameterTop - diameterBottom) + diameterBottom) / 2;
  37727. ringIdx = (hasRings && i !== 0 && i !== subdivisions) ? 2 : 1;
  37728. for (r = 0; r < ringIdx; r++) {
  37729. if (hasRings) {
  37730. s += r;
  37731. }
  37732. if (enclose) {
  37733. s += 2 * r;
  37734. }
  37735. for (j = 0; j <= tessellation; j++) {
  37736. angle = j * angle_step;
  37737. // position
  37738. ringVertex.x = Math.cos(-angle) * radius;
  37739. ringVertex.y = -height / 2 + h * height;
  37740. ringVertex.z = Math.sin(-angle) * radius;
  37741. // normal
  37742. if (diameterTop === 0 && i === subdivisions) {
  37743. // if no top cap, reuse former normals
  37744. ringNormal.x = normals[normals.length - (tessellation + 1) * 3];
  37745. ringNormal.y = normals[normals.length - (tessellation + 1) * 3 + 1];
  37746. ringNormal.z = normals[normals.length - (tessellation + 1) * 3 + 2];
  37747. }
  37748. else {
  37749. ringNormal.x = ringVertex.x;
  37750. ringNormal.z = ringVertex.z;
  37751. ringNormal.y = Math.sqrt(ringNormal.x * ringNormal.x + ringNormal.z * ringNormal.z) * tan;
  37752. ringNormal.normalize();
  37753. }
  37754. // keep first ring vertex values for enclose
  37755. if (j === 0) {
  37756. ringFirstVertex.copyFrom(ringVertex);
  37757. ringFirstNormal.copyFrom(ringNormal);
  37758. }
  37759. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37760. normals.push(ringNormal.x, ringNormal.y, ringNormal.z);
  37761. if (hasRings) {
  37762. v = (cs !== s) ? faceUV[s].y : faceUV[s].w;
  37763. }
  37764. else {
  37765. v = faceUV[s].y + (faceUV[s].w - faceUV[s].y) * h;
  37766. }
  37767. uvs.push(faceUV[s].x + (faceUV[s].z - faceUV[s].x) * j / tessellation, v);
  37768. if (faceColors) {
  37769. colors.push(faceColors[s].r, faceColors[s].g, faceColors[s].b, faceColors[s].a);
  37770. }
  37771. }
  37772. // if enclose, add four vertices and their dedicated normals
  37773. if (arc !== 1 && enclose) {
  37774. positions.push(ringVertex.x, ringVertex.y, ringVertex.z);
  37775. positions.push(0, ringVertex.y, 0);
  37776. positions.push(0, ringVertex.y, 0);
  37777. positions.push(ringFirstVertex.x, ringFirstVertex.y, ringFirstVertex.z);
  37778. BABYLON.Vector3.CrossToRef(Y, ringNormal, quadNormal);
  37779. quadNormal.normalize();
  37780. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37781. BABYLON.Vector3.CrossToRef(ringFirstNormal, Y, quadNormal);
  37782. quadNormal.normalize();
  37783. normals.push(quadNormal.x, quadNormal.y, quadNormal.z, quadNormal.x, quadNormal.y, quadNormal.z);
  37784. if (hasRings) {
  37785. v = (cs !== s) ? faceUV[s + 1].y : faceUV[s + 1].w;
  37786. }
  37787. else {
  37788. v = faceUV[s + 1].y + (faceUV[s + 1].w - faceUV[s + 1].y) * h;
  37789. }
  37790. uvs.push(faceUV[s + 1].x, v);
  37791. uvs.push(faceUV[s + 1].z, v);
  37792. if (hasRings) {
  37793. v = (cs !== s) ? faceUV[s + 2].y : faceUV[s + 2].w;
  37794. }
  37795. else {
  37796. v = faceUV[s + 2].y + (faceUV[s + 2].w - faceUV[s + 2].y) * h;
  37797. }
  37798. uvs.push(faceUV[s + 2].x, v);
  37799. uvs.push(faceUV[s + 2].z, v);
  37800. if (faceColors) {
  37801. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37802. colors.push(faceColors[s + 1].r, faceColors[s + 1].g, faceColors[s + 1].b, faceColors[s + 1].a);
  37803. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37804. colors.push(faceColors[s + 2].r, faceColors[s + 2].g, faceColors[s + 2].b, faceColors[s + 2].a);
  37805. }
  37806. }
  37807. if (cs !== s) {
  37808. cs = s;
  37809. }
  37810. }
  37811. }
  37812. // indices
  37813. var e = (arc !== 1 && enclose) ? tessellation + 4 : tessellation; // correction of number of iteration if enclose
  37814. var s;
  37815. i = 0;
  37816. for (s = 0; s < subdivisions; s++) {
  37817. var i0 = 0;
  37818. var i1 = 0;
  37819. var i2 = 0;
  37820. var i3 = 0;
  37821. for (j = 0; j < tessellation; j++) {
  37822. i0 = i * (e + 1) + j;
  37823. i1 = (i + 1) * (e + 1) + j;
  37824. i2 = i * (e + 1) + (j + 1);
  37825. i3 = (i + 1) * (e + 1) + (j + 1);
  37826. indices.push(i0, i1, i2);
  37827. indices.push(i3, i2, i1);
  37828. }
  37829. if (arc !== 1 && enclose) { // if enclose, add two quads
  37830. indices.push(i0 + 2, i1 + 2, i2 + 2);
  37831. indices.push(i3 + 2, i2 + 2, i1 + 2);
  37832. indices.push(i0 + 4, i1 + 4, i2 + 4);
  37833. indices.push(i3 + 4, i2 + 4, i1 + 4);
  37834. }
  37835. i = (hasRings) ? (i + 2) : (i + 1);
  37836. }
  37837. // Caps
  37838. var createCylinderCap = function (isTop) {
  37839. var radius = isTop ? diameterTop / 2 : diameterBottom / 2;
  37840. if (radius === 0) {
  37841. return;
  37842. }
  37843. // Cap positions, normals & uvs
  37844. var angle;
  37845. var circleVector;
  37846. var i;
  37847. var u = (isTop) ? faceUV[surfaceNb - 1] : faceUV[0];
  37848. var c = null;
  37849. if (faceColors) {
  37850. c = (isTop) ? faceColors[surfaceNb - 1] : faceColors[0];
  37851. }
  37852. // cap center
  37853. var vbase = positions.length / 3;
  37854. var offset = isTop ? height / 2 : -height / 2;
  37855. var center = new BABYLON.Vector3(0, offset, 0);
  37856. positions.push(center.x, center.y, center.z);
  37857. normals.push(0, isTop ? 1 : -1, 0);
  37858. uvs.push(u.x + (u.z - u.x) * 0.5, u.y + (u.w - u.y) * 0.5);
  37859. if (c) {
  37860. colors.push(c.r, c.g, c.b, c.a);
  37861. }
  37862. var textureScale = new BABYLON.Vector2(0.5, 0.5);
  37863. for (i = 0; i <= tessellation; i++) {
  37864. angle = Math.PI * 2 * i * arc / tessellation;
  37865. var cos = Math.cos(-angle);
  37866. var sin = Math.sin(-angle);
  37867. circleVector = new BABYLON.Vector3(cos * radius, offset, sin * radius);
  37868. var textureCoordinate = new BABYLON.Vector2(cos * textureScale.x + 0.5, sin * textureScale.y + 0.5);
  37869. positions.push(circleVector.x, circleVector.y, circleVector.z);
  37870. normals.push(0, isTop ? 1 : -1, 0);
  37871. uvs.push(u.x + (u.z - u.x) * textureCoordinate.x, u.y + (u.w - u.y) * textureCoordinate.y);
  37872. if (c) {
  37873. colors.push(c.r, c.g, c.b, c.a);
  37874. }
  37875. }
  37876. // Cap indices
  37877. for (i = 0; i < tessellation; i++) {
  37878. if (!isTop) {
  37879. indices.push(vbase);
  37880. indices.push(vbase + (i + 1));
  37881. indices.push(vbase + (i + 2));
  37882. }
  37883. else {
  37884. indices.push(vbase);
  37885. indices.push(vbase + (i + 2));
  37886. indices.push(vbase + (i + 1));
  37887. }
  37888. }
  37889. };
  37890. // add caps to geometry
  37891. createCylinderCap(false);
  37892. createCylinderCap(true);
  37893. // Sides
  37894. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37895. var vertexData = new VertexData();
  37896. vertexData.indices = indices;
  37897. vertexData.positions = positions;
  37898. vertexData.normals = normals;
  37899. vertexData.uvs = uvs;
  37900. if (faceColors) {
  37901. vertexData.colors = colors;
  37902. }
  37903. return vertexData;
  37904. };
  37905. /**
  37906. * Creates the VertexData for a torus
  37907. * @param options an object used to set the following optional parameters for the box, required but can be empty
  37908. * * diameter the diameter of the torus, optional default 1
  37909. * * thickness the diameter of the tube forming the torus, optional default 0.5
  37910. * * tessellation the number of prism sides, 3 for a triangular prism, optional, default 24
  37911. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  37912. * * 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)
  37913. * * 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)
  37914. * @returns the VertexData of the torus
  37915. */
  37916. VertexData.CreateTorus = function (options) {
  37917. var indices = [];
  37918. var positions = [];
  37919. var normals = [];
  37920. var uvs = [];
  37921. var diameter = options.diameter || 1;
  37922. var thickness = options.thickness || 0.5;
  37923. var tessellation = options.tessellation || 16;
  37924. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  37925. var stride = tessellation + 1;
  37926. for (var i = 0; i <= tessellation; i++) {
  37927. var u = i / tessellation;
  37928. var outerAngle = i * Math.PI * 2.0 / tessellation - Math.PI / 2.0;
  37929. var transform = BABYLON.Matrix.Translation(diameter / 2.0, 0, 0).multiply(BABYLON.Matrix.RotationY(outerAngle));
  37930. for (var j = 0; j <= tessellation; j++) {
  37931. var v = 1 - j / tessellation;
  37932. var innerAngle = j * Math.PI * 2.0 / tessellation + Math.PI;
  37933. var dx = Math.cos(innerAngle);
  37934. var dy = Math.sin(innerAngle);
  37935. // Create a vertex.
  37936. var normal = new BABYLON.Vector3(dx, dy, 0);
  37937. var position = normal.scale(thickness / 2);
  37938. var textureCoordinate = new BABYLON.Vector2(u, v);
  37939. position = BABYLON.Vector3.TransformCoordinates(position, transform);
  37940. normal = BABYLON.Vector3.TransformNormal(normal, transform);
  37941. positions.push(position.x, position.y, position.z);
  37942. normals.push(normal.x, normal.y, normal.z);
  37943. uvs.push(textureCoordinate.x, textureCoordinate.y);
  37944. // And create indices for two triangles.
  37945. var nextI = (i + 1) % stride;
  37946. var nextJ = (j + 1) % stride;
  37947. indices.push(i * stride + j);
  37948. indices.push(i * stride + nextJ);
  37949. indices.push(nextI * stride + j);
  37950. indices.push(i * stride + nextJ);
  37951. indices.push(nextI * stride + nextJ);
  37952. indices.push(nextI * stride + j);
  37953. }
  37954. }
  37955. // Sides
  37956. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  37957. // Result
  37958. var vertexData = new VertexData();
  37959. vertexData.indices = indices;
  37960. vertexData.positions = positions;
  37961. vertexData.normals = normals;
  37962. vertexData.uvs = uvs;
  37963. return vertexData;
  37964. };
  37965. /**
  37966. * Creates the VertexData of the LineSystem
  37967. * @param options an object used to set the following optional parameters for the LineSystem, required but can be empty
  37968. * - lines an array of lines, each line being an array of successive Vector3
  37969. * - colors an array of line colors, each of the line colors being an array of successive Color4, one per line point
  37970. * @returns the VertexData of the LineSystem
  37971. */
  37972. VertexData.CreateLineSystem = function (options) {
  37973. var indices = [];
  37974. var positions = [];
  37975. var lines = options.lines;
  37976. var colors = options.colors;
  37977. var vertexColors = [];
  37978. var idx = 0;
  37979. for (var l = 0; l < lines.length; l++) {
  37980. var points = lines[l];
  37981. for (var index = 0; index < points.length; index++) {
  37982. positions.push(points[index].x, points[index].y, points[index].z);
  37983. if (colors) {
  37984. var color = colors[l];
  37985. vertexColors.push(color[index].r, color[index].g, color[index].b, color[index].a);
  37986. }
  37987. if (index > 0) {
  37988. indices.push(idx - 1);
  37989. indices.push(idx);
  37990. }
  37991. idx++;
  37992. }
  37993. }
  37994. var vertexData = new VertexData();
  37995. vertexData.indices = indices;
  37996. vertexData.positions = positions;
  37997. if (colors) {
  37998. vertexData.colors = vertexColors;
  37999. }
  38000. return vertexData;
  38001. };
  38002. /**
  38003. * Create the VertexData for a DashedLines
  38004. * @param options an object used to set the following optional parameters for the DashedLines, required but can be empty
  38005. * - points an array successive Vector3
  38006. * - dashSize the size of the dashes relative to the dash number, optional, default 3
  38007. * - gapSize the size of the gap between two successive dashes relative to the dash number, optional, default 1
  38008. * - dashNb the intended total number of dashes, optional, default 200
  38009. * @returns the VertexData for the DashedLines
  38010. */
  38011. VertexData.CreateDashedLines = function (options) {
  38012. var dashSize = options.dashSize || 3;
  38013. var gapSize = options.gapSize || 1;
  38014. var dashNb = options.dashNb || 200;
  38015. var points = options.points;
  38016. var positions = new Array();
  38017. var indices = new Array();
  38018. var curvect = BABYLON.Vector3.Zero();
  38019. var lg = 0;
  38020. var nb = 0;
  38021. var shft = 0;
  38022. var dashshft = 0;
  38023. var curshft = 0;
  38024. var idx = 0;
  38025. var i = 0;
  38026. for (i = 0; i < points.length - 1; i++) {
  38027. points[i + 1].subtractToRef(points[i], curvect);
  38028. lg += curvect.length();
  38029. }
  38030. shft = lg / dashNb;
  38031. dashshft = dashSize * shft / (dashSize + gapSize);
  38032. for (i = 0; i < points.length - 1; i++) {
  38033. points[i + 1].subtractToRef(points[i], curvect);
  38034. nb = Math.floor(curvect.length() / shft);
  38035. curvect.normalize();
  38036. for (var j = 0; j < nb; j++) {
  38037. curshft = shft * j;
  38038. positions.push(points[i].x + curshft * curvect.x, points[i].y + curshft * curvect.y, points[i].z + curshft * curvect.z);
  38039. positions.push(points[i].x + (curshft + dashshft) * curvect.x, points[i].y + (curshft + dashshft) * curvect.y, points[i].z + (curshft + dashshft) * curvect.z);
  38040. indices.push(idx, idx + 1);
  38041. idx += 2;
  38042. }
  38043. }
  38044. // Result
  38045. var vertexData = new VertexData();
  38046. vertexData.positions = positions;
  38047. vertexData.indices = indices;
  38048. return vertexData;
  38049. };
  38050. /**
  38051. * Creates the VertexData for a Ground
  38052. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38053. * - width the width (x direction) of the ground, optional, default 1
  38054. * - height the height (z direction) of the ground, optional, default 1
  38055. * - subdivisions the number of subdivisions per side, optional, default 1
  38056. * @returns the VertexData of the Ground
  38057. */
  38058. VertexData.CreateGround = function (options) {
  38059. var indices = [];
  38060. var positions = [];
  38061. var normals = [];
  38062. var uvs = [];
  38063. var row, col;
  38064. var width = options.width || 1;
  38065. var height = options.height || 1;
  38066. var subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  38067. var subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  38068. for (row = 0; row <= subdivisionsY; row++) {
  38069. for (col = 0; col <= subdivisionsX; col++) {
  38070. var position = new BABYLON.Vector3((col * width) / subdivisionsX - (width / 2.0), 0, ((subdivisionsY - row) * height) / subdivisionsY - (height / 2.0));
  38071. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38072. positions.push(position.x, position.y, position.z);
  38073. normals.push(normal.x, normal.y, normal.z);
  38074. uvs.push(col / subdivisionsX, 1.0 - row / subdivisionsY);
  38075. }
  38076. }
  38077. for (row = 0; row < subdivisionsY; row++) {
  38078. for (col = 0; col < subdivisionsX; col++) {
  38079. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38080. indices.push(col + 1 + row * (subdivisionsX + 1));
  38081. indices.push(col + row * (subdivisionsX + 1));
  38082. indices.push(col + (row + 1) * (subdivisionsX + 1));
  38083. indices.push(col + 1 + (row + 1) * (subdivisionsX + 1));
  38084. indices.push(col + row * (subdivisionsX + 1));
  38085. }
  38086. }
  38087. // Result
  38088. var vertexData = new VertexData();
  38089. vertexData.indices = indices;
  38090. vertexData.positions = positions;
  38091. vertexData.normals = normals;
  38092. vertexData.uvs = uvs;
  38093. return vertexData;
  38094. };
  38095. /**
  38096. * Creates the VertexData for a TiledGround by subdividing the ground into tiles
  38097. * @param options an object used to set the following optional parameters for the Ground, required but can be empty
  38098. * * xmin the ground minimum X coordinate, optional, default -1
  38099. * * zmin the ground minimum Z coordinate, optional, default -1
  38100. * * xmax the ground maximum X coordinate, optional, default 1
  38101. * * zmax the ground maximum Z coordinate, optional, default 1
  38102. * * 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}
  38103. * * 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}
  38104. * @returns the VertexData of the TiledGround
  38105. */
  38106. VertexData.CreateTiledGround = function (options) {
  38107. var xmin = (options.xmin !== undefined && options.xmin !== null) ? options.xmin : -1.0;
  38108. var zmin = (options.zmin !== undefined && options.zmin !== null) ? options.zmin : -1.0;
  38109. var xmax = (options.xmax !== undefined && options.xmax !== null) ? options.xmax : 1.0;
  38110. var zmax = (options.zmax !== undefined && options.zmax !== null) ? options.zmax : 1.0;
  38111. var subdivisions = options.subdivisions || { w: 1, h: 1 };
  38112. var precision = options.precision || { w: 1, h: 1 };
  38113. var indices = new Array();
  38114. var positions = new Array();
  38115. var normals = new Array();
  38116. var uvs = new Array();
  38117. var row, col, tileRow, tileCol;
  38118. subdivisions.h = (subdivisions.h < 1) ? 1 : subdivisions.h;
  38119. subdivisions.w = (subdivisions.w < 1) ? 1 : subdivisions.w;
  38120. precision.w = (precision.w < 1) ? 1 : precision.w;
  38121. precision.h = (precision.h < 1) ? 1 : precision.h;
  38122. var tileSize = {
  38123. 'w': (xmax - xmin) / subdivisions.w,
  38124. 'h': (zmax - zmin) / subdivisions.h
  38125. };
  38126. function applyTile(xTileMin, zTileMin, xTileMax, zTileMax) {
  38127. // Indices
  38128. var base = positions.length / 3;
  38129. var rowLength = precision.w + 1;
  38130. for (row = 0; row < precision.h; row++) {
  38131. for (col = 0; col < precision.w; col++) {
  38132. var square = [
  38133. base + col + row * rowLength,
  38134. base + (col + 1) + row * rowLength,
  38135. base + (col + 1) + (row + 1) * rowLength,
  38136. base + col + (row + 1) * rowLength
  38137. ];
  38138. indices.push(square[1]);
  38139. indices.push(square[2]);
  38140. indices.push(square[3]);
  38141. indices.push(square[0]);
  38142. indices.push(square[1]);
  38143. indices.push(square[3]);
  38144. }
  38145. }
  38146. // Position, normals and uvs
  38147. var position = BABYLON.Vector3.Zero();
  38148. var normal = new BABYLON.Vector3(0, 1.0, 0);
  38149. for (row = 0; row <= precision.h; row++) {
  38150. position.z = (row * (zTileMax - zTileMin)) / precision.h + zTileMin;
  38151. for (col = 0; col <= precision.w; col++) {
  38152. position.x = (col * (xTileMax - xTileMin)) / precision.w + xTileMin;
  38153. position.y = 0;
  38154. positions.push(position.x, position.y, position.z);
  38155. normals.push(normal.x, normal.y, normal.z);
  38156. uvs.push(col / precision.w, row / precision.h);
  38157. }
  38158. }
  38159. }
  38160. for (tileRow = 0; tileRow < subdivisions.h; tileRow++) {
  38161. for (tileCol = 0; tileCol < subdivisions.w; tileCol++) {
  38162. applyTile(xmin + tileCol * tileSize.w, zmin + tileRow * tileSize.h, xmin + (tileCol + 1) * tileSize.w, zmin + (tileRow + 1) * tileSize.h);
  38163. }
  38164. }
  38165. // Result
  38166. var vertexData = new VertexData();
  38167. vertexData.indices = indices;
  38168. vertexData.positions = positions;
  38169. vertexData.normals = normals;
  38170. vertexData.uvs = uvs;
  38171. return vertexData;
  38172. };
  38173. /**
  38174. * Creates the VertexData of the Ground designed from a heightmap
  38175. * @param options an object used to set the following parameters for the Ground, required and provided by MeshBuilder.CreateGroundFromHeightMap
  38176. * * width the width (x direction) of the ground
  38177. * * height the height (z direction) of the ground
  38178. * * subdivisions the number of subdivisions per side
  38179. * * minHeight the minimum altitude on the ground, optional, default 0
  38180. * * maxHeight the maximum altitude on the ground, optional default 1
  38181. * * colorFilter the filter to apply to the image pixel colors to compute the height, optional Color3, default (0.3, 0.59, 0.11)
  38182. * * buffer the array holding the image color data
  38183. * * bufferWidth the width of image
  38184. * * bufferHeight the height of image
  38185. * @returns the VertexData of the Ground designed from a heightmap
  38186. */
  38187. VertexData.CreateGroundFromHeightMap = function (options) {
  38188. var indices = [];
  38189. var positions = [];
  38190. var normals = [];
  38191. var uvs = [];
  38192. var row, col;
  38193. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  38194. // Vertices
  38195. for (row = 0; row <= options.subdivisions; row++) {
  38196. for (col = 0; col <= options.subdivisions; col++) {
  38197. 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));
  38198. // Compute height
  38199. var heightMapX = (((position.x + options.width / 2) / options.width) * (options.bufferWidth - 1)) | 0;
  38200. var heightMapY = ((1.0 - (position.z + options.height / 2) / options.height) * (options.bufferHeight - 1)) | 0;
  38201. var pos = (heightMapX + heightMapY * options.bufferWidth) * 4;
  38202. var r = options.buffer[pos] / 255.0;
  38203. var g = options.buffer[pos + 1] / 255.0;
  38204. var b = options.buffer[pos + 2] / 255.0;
  38205. var gradient = r * filter.r + g * filter.g + b * filter.b;
  38206. position.y = options.minHeight + (options.maxHeight - options.minHeight) * gradient;
  38207. // Add vertex
  38208. positions.push(position.x, position.y, position.z);
  38209. normals.push(0, 0, 0);
  38210. uvs.push(col / options.subdivisions, 1.0 - row / options.subdivisions);
  38211. }
  38212. }
  38213. // Indices
  38214. for (row = 0; row < options.subdivisions; row++) {
  38215. for (col = 0; col < options.subdivisions; col++) {
  38216. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38217. indices.push(col + 1 + row * (options.subdivisions + 1));
  38218. indices.push(col + row * (options.subdivisions + 1));
  38219. indices.push(col + (row + 1) * (options.subdivisions + 1));
  38220. indices.push(col + 1 + (row + 1) * (options.subdivisions + 1));
  38221. indices.push(col + row * (options.subdivisions + 1));
  38222. }
  38223. }
  38224. // Normals
  38225. VertexData.ComputeNormals(positions, indices, normals);
  38226. // Result
  38227. var vertexData = new VertexData();
  38228. vertexData.indices = indices;
  38229. vertexData.positions = positions;
  38230. vertexData.normals = normals;
  38231. vertexData.uvs = uvs;
  38232. return vertexData;
  38233. };
  38234. /**
  38235. * Creates the VertexData for a Plane
  38236. * @param options an object used to set the following optional parameters for the plane, required but can be empty
  38237. * * size sets the width and height of the plane to the value of size, optional default 1
  38238. * * width sets the width (x direction) of the plane, overwrites the width set by size, optional, default size
  38239. * * height sets the height (y direction) of the plane, overwrites the height set by size, optional, default size
  38240. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38241. * * 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)
  38242. * * 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)
  38243. * @returns the VertexData of the box
  38244. */
  38245. VertexData.CreatePlane = function (options) {
  38246. var indices = [];
  38247. var positions = [];
  38248. var normals = [];
  38249. var uvs = [];
  38250. var width = options.width || options.size || 1;
  38251. var height = options.height || options.size || 1;
  38252. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38253. // Vertices
  38254. var halfWidth = width / 2.0;
  38255. var halfHeight = height / 2.0;
  38256. positions.push(-halfWidth, -halfHeight, 0);
  38257. normals.push(0, 0, -1.0);
  38258. uvs.push(0.0, 0.0);
  38259. positions.push(halfWidth, -halfHeight, 0);
  38260. normals.push(0, 0, -1.0);
  38261. uvs.push(1.0, 0.0);
  38262. positions.push(halfWidth, halfHeight, 0);
  38263. normals.push(0, 0, -1.0);
  38264. uvs.push(1.0, 1.0);
  38265. positions.push(-halfWidth, halfHeight, 0);
  38266. normals.push(0, 0, -1.0);
  38267. uvs.push(0.0, 1.0);
  38268. // Indices
  38269. indices.push(0);
  38270. indices.push(1);
  38271. indices.push(2);
  38272. indices.push(0);
  38273. indices.push(2);
  38274. indices.push(3);
  38275. // Sides
  38276. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38277. // Result
  38278. var vertexData = new VertexData();
  38279. vertexData.indices = indices;
  38280. vertexData.positions = positions;
  38281. vertexData.normals = normals;
  38282. vertexData.uvs = uvs;
  38283. return vertexData;
  38284. };
  38285. /**
  38286. * Creates the VertexData of the Disc or regular Polygon
  38287. * @param options an object used to set the following optional parameters for the disc, required but can be empty
  38288. * * radius the radius of the disc, optional default 0.5
  38289. * * tessellation the number of polygon sides, optional, default 64
  38290. * * 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
  38291. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38292. * * 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)
  38293. * * 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)
  38294. * @returns the VertexData of the box
  38295. */
  38296. VertexData.CreateDisc = function (options) {
  38297. var positions = new Array();
  38298. var indices = new Array();
  38299. var normals = new Array();
  38300. var uvs = new Array();
  38301. var radius = options.radius || 0.5;
  38302. var tessellation = options.tessellation || 64;
  38303. var arc = options.arc && (options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc || 1.0;
  38304. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38305. // positions and uvs
  38306. positions.push(0, 0, 0); // disc center first
  38307. uvs.push(0.5, 0.5);
  38308. var theta = Math.PI * 2 * arc;
  38309. var step = theta / tessellation;
  38310. for (var a = 0; a < theta; a += step) {
  38311. var x = Math.cos(a);
  38312. var y = Math.sin(a);
  38313. var u = (x + 1) / 2;
  38314. var v = (1 - y) / 2;
  38315. positions.push(radius * x, radius * y, 0);
  38316. uvs.push(u, v);
  38317. }
  38318. if (arc === 1) {
  38319. positions.push(positions[3], positions[4], positions[5]); // close the circle
  38320. uvs.push(uvs[2], uvs[3]);
  38321. }
  38322. //indices
  38323. var vertexNb = positions.length / 3;
  38324. for (var i = 1; i < vertexNb - 1; i++) {
  38325. indices.push(i + 1, 0, i);
  38326. }
  38327. // result
  38328. VertexData.ComputeNormals(positions, indices, normals);
  38329. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38330. var vertexData = new VertexData();
  38331. vertexData.indices = indices;
  38332. vertexData.positions = positions;
  38333. vertexData.normals = normals;
  38334. vertexData.uvs = uvs;
  38335. return vertexData;
  38336. };
  38337. /**
  38338. * Creates the VertexData for an irregular Polygon in the XoZ plane using a mesh built by polygonTriangulation.build()
  38339. * All parameters are provided by MeshBuilder.CreatePolygon as needed
  38340. * @param polygon a mesh built from polygonTriangulation.build()
  38341. * @param sideOrientation takes the values BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38342. * @param fUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38343. * @param fColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38344. * @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)
  38345. * @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)
  38346. * @returns the VertexData of the Polygon
  38347. */
  38348. VertexData.CreatePolygon = function (polygon, sideOrientation, fUV, fColors, frontUVs, backUVs) {
  38349. var faceUV = fUV || new Array(3);
  38350. var faceColors = fColors;
  38351. var colors = [];
  38352. // default face colors and UV if undefined
  38353. for (var f = 0; f < 3; f++) {
  38354. if (faceUV[f] === undefined) {
  38355. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38356. }
  38357. if (faceColors && faceColors[f] === undefined) {
  38358. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38359. }
  38360. }
  38361. var positions = polygon.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  38362. var normals = polygon.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  38363. var uvs = polygon.getVerticesData(BABYLON.VertexBuffer.UVKind);
  38364. var indices = polygon.getIndices();
  38365. // set face colours and textures
  38366. var idx = 0;
  38367. var face = 0;
  38368. for (var index = 0; index < normals.length; index += 3) {
  38369. //Edge Face no. 1
  38370. if (Math.abs(normals[index + 1]) < 0.001) {
  38371. face = 1;
  38372. }
  38373. //Top Face no. 0
  38374. if (Math.abs(normals[index + 1] - 1) < 0.001) {
  38375. face = 0;
  38376. }
  38377. //Bottom Face no. 2
  38378. if (Math.abs(normals[index + 1] + 1) < 0.001) {
  38379. face = 2;
  38380. }
  38381. idx = index / 3;
  38382. uvs[2 * idx] = (1 - uvs[2 * idx]) * faceUV[face].x + uvs[2 * idx] * faceUV[face].z;
  38383. uvs[2 * idx + 1] = (1 - uvs[2 * idx + 1]) * faceUV[face].y + uvs[2 * idx + 1] * faceUV[face].w;
  38384. if (faceColors) {
  38385. colors.push(faceColors[face].r, faceColors[face].g, faceColors[face].b, faceColors[face].a);
  38386. }
  38387. }
  38388. // sides
  38389. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs);
  38390. // Result
  38391. var vertexData = new VertexData();
  38392. vertexData.indices = indices;
  38393. vertexData.positions = positions;
  38394. vertexData.normals = normals;
  38395. vertexData.uvs = uvs;
  38396. if (faceColors) {
  38397. var totalColors = (sideOrientation === BABYLON.Mesh.DOUBLESIDE) ? colors.concat(colors) : colors;
  38398. vertexData.colors = totalColors;
  38399. }
  38400. return vertexData;
  38401. };
  38402. /**
  38403. * Creates the VertexData of the IcoSphere
  38404. * @param options an object used to set the following optional parameters for the IcoSphere, required but can be empty
  38405. * * radius the radius of the IcoSphere, optional default 1
  38406. * * radiusX allows stretching in the x direction, optional, default radius
  38407. * * radiusY allows stretching in the y direction, optional, default radius
  38408. * * radiusZ allows stretching in the z direction, optional, default radius
  38409. * * flat when true creates a flat shaded mesh, optional, default true
  38410. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38411. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38412. * * 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)
  38413. * * 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)
  38414. * @returns the VertexData of the IcoSphere
  38415. */
  38416. VertexData.CreateIcoSphere = function (options) {
  38417. var sideOrientation = options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38418. var radius = options.radius || 1;
  38419. var flat = (options.flat === undefined) ? true : options.flat;
  38420. var subdivisions = options.subdivisions || 4;
  38421. var radiusX = options.radiusX || radius;
  38422. var radiusY = options.radiusY || radius;
  38423. var radiusZ = options.radiusZ || radius;
  38424. var t = (1 + Math.sqrt(5)) / 2;
  38425. // 12 vertex x,y,z
  38426. var ico_vertices = [
  38427. -1, t, -0, 1, t, 0, -1, -t, 0, 1, -t, 0,
  38428. 0, -1, -t, 0, 1, -t, 0, -1, t, 0, 1, t,
  38429. t, 0, 1, t, 0, -1, -t, 0, 1, -t, 0, -1 // v8-11
  38430. ];
  38431. // index of 3 vertex makes a face of icopshere
  38432. var ico_indices = [
  38433. 0, 11, 5, 0, 5, 1, 0, 1, 7, 0, 7, 10, 12, 22, 23,
  38434. 1, 5, 20, 5, 11, 4, 23, 22, 13, 22, 18, 6, 7, 1, 8,
  38435. 14, 21, 4, 14, 4, 2, 16, 13, 6, 15, 6, 19, 3, 8, 9,
  38436. 4, 21, 5, 13, 17, 23, 6, 13, 22, 19, 6, 18, 9, 8, 1
  38437. ];
  38438. // vertex for uv have aliased position, not for UV
  38439. var vertices_unalias_id = [
  38440. 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11,
  38441. // vertex alias
  38442. 0,
  38443. 2,
  38444. 3,
  38445. 3,
  38446. 3,
  38447. 4,
  38448. 7,
  38449. 8,
  38450. 9,
  38451. 9,
  38452. 10,
  38453. 11 // 23: B + 12
  38454. ];
  38455. // uv as integer step (not pixels !)
  38456. var ico_vertexuv = [
  38457. 5, 1, 3, 1, 6, 4, 0, 0,
  38458. 5, 3, 4, 2, 2, 2, 4, 0,
  38459. 2, 0, 1, 1, 6, 0, 6, 2,
  38460. // vertex alias (for same vertex on different faces)
  38461. 0, 4,
  38462. 3, 3,
  38463. 4, 4,
  38464. 3, 1,
  38465. 4, 2,
  38466. 4, 4,
  38467. 0, 2,
  38468. 1, 1,
  38469. 2, 2,
  38470. 3, 3,
  38471. 1, 3,
  38472. 2, 4 // 23: B + 12
  38473. ];
  38474. // Vertices[0, 1, ...9, A, B] : position on UV plane
  38475. // '+' indicate duplicate position to be fixed (3,9:0,2,3,4,7,8,A,B)
  38476. // First island of uv mapping
  38477. // v = 4h 3+ 2
  38478. // v = 3h 9+ 4
  38479. // v = 2h 9+ 5 B
  38480. // v = 1h 9 1 0
  38481. // v = 0h 3 8 7 A
  38482. // u = 0 1 2 3 4 5 6 *a
  38483. // Second island of uv mapping
  38484. // v = 4h 0+ B+ 4+
  38485. // v = 3h A+ 2+
  38486. // v = 2h 7+ 6 3+
  38487. // v = 1h 8+ 3+
  38488. // v = 0h
  38489. // u = 0 1 2 3 4 5 6 *a
  38490. // Face layout on texture UV mapping
  38491. // ============
  38492. // \ 4 /\ 16 / ======
  38493. // \ / \ / /\ 11 /
  38494. // \/ 7 \/ / \ /
  38495. // ======= / 10 \/
  38496. // /\ 17 /\ =======
  38497. // / \ / \ \ 15 /\
  38498. // / 8 \/ 12 \ \ / \
  38499. // ============ \/ 6 \
  38500. // \ 18 /\ ============
  38501. // \ / \ \ 5 /\ 0 /
  38502. // \/ 13 \ \ / \ /
  38503. // ======= \/ 1 \/
  38504. // =============
  38505. // /\ 19 /\ 2 /\
  38506. // / \ / \ / \
  38507. // / 14 \/ 9 \/ 3 \
  38508. // ===================
  38509. // uv step is u:1 or 0.5, v:cos(30)=sqrt(3)/2, ratio approx is 84/97
  38510. var ustep = 138 / 1024;
  38511. var vstep = 239 / 1024;
  38512. var uoffset = 60 / 1024;
  38513. var voffset = 26 / 1024;
  38514. // Second island should have margin, not to touch the first island
  38515. // avoid any borderline artefact in pixel rounding
  38516. var island_u_offset = -40 / 1024;
  38517. var island_v_offset = +20 / 1024;
  38518. // face is either island 0 or 1 :
  38519. // second island is for faces : [4, 7, 8, 12, 13, 16, 17, 18]
  38520. var island = [
  38521. 0, 0, 0, 0, 1,
  38522. 0, 0, 1, 1, 0,
  38523. 0, 0, 1, 1, 0,
  38524. 0, 1, 1, 1, 0 // 15 - 19
  38525. ];
  38526. var indices = new Array();
  38527. var positions = new Array();
  38528. var normals = new Array();
  38529. var uvs = new Array();
  38530. var current_indice = 0;
  38531. // prepare array of 3 vector (empty) (to be worked in place, shared for each face)
  38532. var face_vertex_pos = new Array(3);
  38533. var face_vertex_uv = new Array(3);
  38534. var v012;
  38535. for (v012 = 0; v012 < 3; v012++) {
  38536. face_vertex_pos[v012] = BABYLON.Vector3.Zero();
  38537. face_vertex_uv[v012] = BABYLON.Vector2.Zero();
  38538. }
  38539. // create all with normals
  38540. for (var face = 0; face < 20; face++) {
  38541. // 3 vertex per face
  38542. for (v012 = 0; v012 < 3; v012++) {
  38543. // look up vertex 0,1,2 to its index in 0 to 11 (or 23 including alias)
  38544. var v_id = ico_indices[3 * face + v012];
  38545. // vertex have 3D position (x,y,z)
  38546. 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]);
  38547. // Normalize to get normal, then scale to radius
  38548. face_vertex_pos[v012].normalize().scaleInPlace(radius);
  38549. // uv Coordinates from vertex ID
  38550. 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);
  38551. }
  38552. // Subdivide the face (interpolate pos, norm, uv)
  38553. // - pos is linear interpolation, then projected to sphere (converge polyhedron to sphere)
  38554. // - norm is linear interpolation of vertex corner normal
  38555. // (to be checked if better to re-calc from face vertex, or if approximation is OK ??? )
  38556. // - uv is linear interpolation
  38557. //
  38558. // Topology is as below for sub-divide by 2
  38559. // vertex shown as v0,v1,v2
  38560. // interp index is i1 to progress in range [v0,v1[
  38561. // interp index is i2 to progress in range [v0,v2[
  38562. // face index as (i1,i2) for /\ : (i1,i2),(i1+1,i2),(i1,i2+1)
  38563. // and (i1,i2)' for \/ : (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38564. //
  38565. //
  38566. // i2 v2
  38567. // ^ ^
  38568. // / / \
  38569. // / / \
  38570. // / / \
  38571. // / / (0,1) \
  38572. // / #---------\
  38573. // / / \ (0,0)'/ \
  38574. // / / \ / \
  38575. // / / \ / \
  38576. // / / (0,0) \ / (1,0) \
  38577. // / #---------#---------\
  38578. // v0 v1
  38579. //
  38580. // --------------------> i1
  38581. //
  38582. // interp of (i1,i2):
  38583. // along i2 : x0=lerp(v0,v2, i2/S) <---> x1=lerp(v1,v2, i2/S)
  38584. // along i1 : lerp(x0,x1, i1/(S-i2))
  38585. //
  38586. // centroid of triangle is needed to get help normal computation
  38587. // (c1,c2) are used for centroid location
  38588. var interp_vertex = function (i1, i2, c1, c2) {
  38589. // vertex is interpolated from
  38590. // - face_vertex_pos[0..2]
  38591. // - face_vertex_uv[0..2]
  38592. var pos_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], i2 / subdivisions);
  38593. var pos_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], i2 / subdivisions);
  38594. var pos_interp = (subdivisions === i2) ? face_vertex_pos[2] : BABYLON.Vector3.Lerp(pos_x0, pos_x1, i1 / (subdivisions - i2));
  38595. pos_interp.normalize();
  38596. var vertex_normal;
  38597. if (flat) {
  38598. // in flat mode, recalculate normal as face centroid normal
  38599. var centroid_x0 = BABYLON.Vector3.Lerp(face_vertex_pos[0], face_vertex_pos[2], c2 / subdivisions);
  38600. var centroid_x1 = BABYLON.Vector3.Lerp(face_vertex_pos[1], face_vertex_pos[2], c2 / subdivisions);
  38601. vertex_normal = BABYLON.Vector3.Lerp(centroid_x0, centroid_x1, c1 / (subdivisions - c2));
  38602. }
  38603. else {
  38604. // in smooth mode, recalculate normal from each single vertex position
  38605. vertex_normal = new BABYLON.Vector3(pos_interp.x, pos_interp.y, pos_interp.z);
  38606. }
  38607. // Vertex normal need correction due to X,Y,Z radius scaling
  38608. vertex_normal.x /= radiusX;
  38609. vertex_normal.y /= radiusY;
  38610. vertex_normal.z /= radiusZ;
  38611. vertex_normal.normalize();
  38612. var uv_x0 = BABYLON.Vector2.Lerp(face_vertex_uv[0], face_vertex_uv[2], i2 / subdivisions);
  38613. var uv_x1 = BABYLON.Vector2.Lerp(face_vertex_uv[1], face_vertex_uv[2], i2 / subdivisions);
  38614. var uv_interp = (subdivisions === i2) ? face_vertex_uv[2] : BABYLON.Vector2.Lerp(uv_x0, uv_x1, i1 / (subdivisions - i2));
  38615. positions.push(pos_interp.x * radiusX, pos_interp.y * radiusY, pos_interp.z * radiusZ);
  38616. normals.push(vertex_normal.x, vertex_normal.y, vertex_normal.z);
  38617. uvs.push(uv_interp.x, uv_interp.y);
  38618. // push each vertex has member of a face
  38619. // Same vertex can bleong to multiple face, it is pushed multiple time (duplicate vertex are present)
  38620. indices.push(current_indice);
  38621. current_indice++;
  38622. };
  38623. for (var i2 = 0; i2 < subdivisions; i2++) {
  38624. for (var i1 = 0; i1 + i2 < subdivisions; i1++) {
  38625. // face : (i1,i2) for /\ :
  38626. // interp for : (i1,i2),(i1+1,i2),(i1,i2+1)
  38627. interp_vertex(i1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38628. interp_vertex(i1 + 1, i2, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38629. interp_vertex(i1, i2 + 1, i1 + 1.0 / 3, i2 + 1.0 / 3);
  38630. if (i1 + i2 + 1 < subdivisions) {
  38631. // face : (i1,i2)' for \/ :
  38632. // interp for (i1+1,i2),(i1+1,i2+1),(i1,i2+1)
  38633. interp_vertex(i1 + 1, i2, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38634. interp_vertex(i1 + 1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38635. interp_vertex(i1, i2 + 1, i1 + 2.0 / 3, i2 + 2.0 / 3);
  38636. }
  38637. }
  38638. }
  38639. }
  38640. // Sides
  38641. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38642. // Result
  38643. var vertexData = new VertexData();
  38644. vertexData.indices = indices;
  38645. vertexData.positions = positions;
  38646. vertexData.normals = normals;
  38647. vertexData.uvs = uvs;
  38648. return vertexData;
  38649. };
  38650. // inspired from // http://stemkoski.github.io/Three.js/Polyhedra.html
  38651. /**
  38652. * Creates the VertexData for a Polyhedron
  38653. * @param options an object used to set the following optional parameters for the polyhedron, required but can be empty
  38654. * * type provided types are:
  38655. * * 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38656. * * 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)
  38657. * * size the size of the IcoSphere, optional default 1
  38658. * * sizeX allows stretching in the x direction, optional, default size
  38659. * * sizeY allows stretching in the y direction, optional, default size
  38660. * * sizeZ allows stretching in the z direction, optional, default size
  38661. * * 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
  38662. * * faceUV an array of Vector4 elements used to set different images to the top, rings and bottom respectively
  38663. * * faceColors an array of Color3 elements used to set different colors to the top, rings and bottom respectively
  38664. * * flat when true creates a flat shaded mesh, optional, default true
  38665. * * subdivisions increasing the subdivisions increases the number of faces, optional, default 4
  38666. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38667. * * 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)
  38668. * * 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)
  38669. * @returns the VertexData of the Polyhedron
  38670. */
  38671. VertexData.CreatePolyhedron = function (options) {
  38672. // provided polyhedron types :
  38673. // 0 : Tetrahedron, 1 : Octahedron, 2 : Dodecahedron, 3 : Icosahedron, 4 : Rhombicuboctahedron, 5 : Triangular Prism, 6 : Pentagonal Prism, 7 : Hexagonal Prism, 8 : Square Pyramid (J1)
  38674. // 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)
  38675. var polyhedra = [];
  38676. 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]] };
  38677. 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]] };
  38678. polyhedra[2] = {
  38679. 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]],
  38680. 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]]
  38681. };
  38682. polyhedra[3] = {
  38683. 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]],
  38684. 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]]
  38685. };
  38686. polyhedra[4] = {
  38687. 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]],
  38688. 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]]
  38689. };
  38690. 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]] };
  38691. 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]] };
  38692. 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]] };
  38693. 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]] };
  38694. 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]] };
  38695. 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]] };
  38696. 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]] };
  38697. 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]] };
  38698. 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]] };
  38699. polyhedra[14] = {
  38700. 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]],
  38701. 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]]
  38702. };
  38703. var type = options.type && (options.type < 0 || options.type >= polyhedra.length) ? 0 : options.type || 0;
  38704. var size = options.size;
  38705. var sizeX = options.sizeX || size || 1;
  38706. var sizeY = options.sizeY || size || 1;
  38707. var sizeZ = options.sizeZ || size || 1;
  38708. var data = options.custom || polyhedra[type];
  38709. var nbfaces = data.face.length;
  38710. var faceUV = options.faceUV || new Array(nbfaces);
  38711. var faceColors = options.faceColors;
  38712. var flat = (options.flat === undefined) ? true : options.flat;
  38713. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38714. var positions = new Array();
  38715. var indices = new Array();
  38716. var normals = new Array();
  38717. var uvs = new Array();
  38718. var colors = new Array();
  38719. var index = 0;
  38720. var faceIdx = 0; // face cursor in the array "indexes"
  38721. var indexes = new Array();
  38722. var i = 0;
  38723. var f = 0;
  38724. var u, v, ang, x, y, tmp;
  38725. // default face colors and UV if undefined
  38726. if (flat) {
  38727. for (f = 0; f < nbfaces; f++) {
  38728. if (faceColors && faceColors[f] === undefined) {
  38729. faceColors[f] = new BABYLON.Color4(1, 1, 1, 1);
  38730. }
  38731. if (faceUV && faceUV[f] === undefined) {
  38732. faceUV[f] = new BABYLON.Vector4(0, 0, 1, 1);
  38733. }
  38734. }
  38735. }
  38736. if (!flat) {
  38737. for (i = 0; i < data.vertex.length; i++) {
  38738. positions.push(data.vertex[i][0] * sizeX, data.vertex[i][1] * sizeY, data.vertex[i][2] * sizeZ);
  38739. uvs.push(0, 0);
  38740. }
  38741. for (f = 0; f < nbfaces; f++) {
  38742. for (i = 0; i < data.face[f].length - 2; i++) {
  38743. indices.push(data.face[f][0], data.face[f][i + 2], data.face[f][i + 1]);
  38744. }
  38745. }
  38746. }
  38747. else {
  38748. for (f = 0; f < nbfaces; f++) {
  38749. var fl = data.face[f].length; // number of vertices of the current face
  38750. ang = 2 * Math.PI / fl;
  38751. x = 0.5 * Math.tan(ang / 2);
  38752. y = 0.5;
  38753. // positions, uvs, colors
  38754. for (i = 0; i < fl; i++) {
  38755. // positions
  38756. 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);
  38757. indexes.push(index);
  38758. index++;
  38759. // uvs
  38760. u = faceUV[f].x + (faceUV[f].z - faceUV[f].x) * (0.5 + x);
  38761. v = faceUV[f].y + (faceUV[f].w - faceUV[f].y) * (y - 0.5);
  38762. uvs.push(u, v);
  38763. tmp = x * Math.cos(ang) - y * Math.sin(ang);
  38764. y = x * Math.sin(ang) + y * Math.cos(ang);
  38765. x = tmp;
  38766. // colors
  38767. if (faceColors) {
  38768. colors.push(faceColors[f].r, faceColors[f].g, faceColors[f].b, faceColors[f].a);
  38769. }
  38770. }
  38771. // indices from indexes
  38772. for (i = 0; i < fl - 2; i++) {
  38773. indices.push(indexes[0 + faceIdx], indexes[i + 2 + faceIdx], indexes[i + 1 + faceIdx]);
  38774. }
  38775. faceIdx += fl;
  38776. }
  38777. }
  38778. VertexData.ComputeNormals(positions, indices, normals);
  38779. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38780. var vertexData = new VertexData();
  38781. vertexData.positions = positions;
  38782. vertexData.indices = indices;
  38783. vertexData.normals = normals;
  38784. vertexData.uvs = uvs;
  38785. if (faceColors && flat) {
  38786. vertexData.colors = colors;
  38787. }
  38788. return vertexData;
  38789. };
  38790. // based on http://code.google.com/p/away3d/source/browse/trunk/fp10/Away3D/src/away3d/primitives/TorusKnot.as?spec=svn2473&r=2473
  38791. /**
  38792. * Creates the VertexData for a TorusKnot
  38793. * @param options an object used to set the following optional parameters for the TorusKnot, required but can be empty
  38794. * * radius the radius of the torus knot, optional, default 2
  38795. * * tube the thickness of the tube, optional, default 0.5
  38796. * * radialSegments the number of sides on each tube segments, optional, default 32
  38797. * * tubularSegments the number of tubes to decompose the knot into, optional, default 32
  38798. * * p the number of windings around the z axis, optional, default 2
  38799. * * q the number of windings around the x axis, optional, default 3
  38800. * * sideOrientation optional and takes the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  38801. * * 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)
  38802. * * 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)
  38803. * @returns the VertexData of the Torus Knot
  38804. */
  38805. VertexData.CreateTorusKnot = function (options) {
  38806. var indices = new Array();
  38807. var positions = new Array();
  38808. var normals = new Array();
  38809. var uvs = new Array();
  38810. var radius = options.radius || 2;
  38811. var tube = options.tube || 0.5;
  38812. var radialSegments = options.radialSegments || 32;
  38813. var tubularSegments = options.tubularSegments || 32;
  38814. var p = options.p || 2;
  38815. var q = options.q || 3;
  38816. var sideOrientation = (options.sideOrientation === 0) ? 0 : options.sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  38817. // Helper
  38818. var getPos = function (angle) {
  38819. var cu = Math.cos(angle);
  38820. var su = Math.sin(angle);
  38821. var quOverP = q / p * angle;
  38822. var cs = Math.cos(quOverP);
  38823. var tx = radius * (2 + cs) * 0.5 * cu;
  38824. var ty = radius * (2 + cs) * su * 0.5;
  38825. var tz = radius * Math.sin(quOverP) * 0.5;
  38826. return new BABYLON.Vector3(tx, ty, tz);
  38827. };
  38828. // Vertices
  38829. var i;
  38830. var j;
  38831. for (i = 0; i <= radialSegments; i++) {
  38832. var modI = i % radialSegments;
  38833. var u = modI / radialSegments * 2 * p * Math.PI;
  38834. var p1 = getPos(u);
  38835. var p2 = getPos(u + 0.01);
  38836. var tang = p2.subtract(p1);
  38837. var n = p2.add(p1);
  38838. var bitan = BABYLON.Vector3.Cross(tang, n);
  38839. n = BABYLON.Vector3.Cross(bitan, tang);
  38840. bitan.normalize();
  38841. n.normalize();
  38842. for (j = 0; j < tubularSegments; j++) {
  38843. var modJ = j % tubularSegments;
  38844. var v = modJ / tubularSegments * 2 * Math.PI;
  38845. var cx = -tube * Math.cos(v);
  38846. var cy = tube * Math.sin(v);
  38847. positions.push(p1.x + cx * n.x + cy * bitan.x);
  38848. positions.push(p1.y + cx * n.y + cy * bitan.y);
  38849. positions.push(p1.z + cx * n.z + cy * bitan.z);
  38850. uvs.push(i / radialSegments);
  38851. uvs.push(j / tubularSegments);
  38852. }
  38853. }
  38854. for (i = 0; i < radialSegments; i++) {
  38855. for (j = 0; j < tubularSegments; j++) {
  38856. var jNext = (j + 1) % tubularSegments;
  38857. var a = i * tubularSegments + j;
  38858. var b = (i + 1) * tubularSegments + j;
  38859. var c = (i + 1) * tubularSegments + jNext;
  38860. var d = i * tubularSegments + jNext;
  38861. indices.push(d);
  38862. indices.push(b);
  38863. indices.push(a);
  38864. indices.push(d);
  38865. indices.push(c);
  38866. indices.push(b);
  38867. }
  38868. }
  38869. // Normals
  38870. VertexData.ComputeNormals(positions, indices, normals);
  38871. // Sides
  38872. VertexData._ComputeSides(sideOrientation, positions, indices, normals, uvs, options.frontUVs, options.backUVs);
  38873. // Result
  38874. var vertexData = new VertexData();
  38875. vertexData.indices = indices;
  38876. vertexData.positions = positions;
  38877. vertexData.normals = normals;
  38878. vertexData.uvs = uvs;
  38879. return vertexData;
  38880. };
  38881. // Tools
  38882. /**
  38883. * Compute normals for given positions and indices
  38884. * @param positions an array of vertex positions, [...., x, y, z, ......]
  38885. * @param indices an array of indices in groups of three for each triangular facet, [...., i, j, k, ......]
  38886. * @param normals an array of vertex normals, [...., x, y, z, ......]
  38887. * @param options an object used to set the following optional parameters for the TorusKnot, optional
  38888. * * facetNormals : optional array of facet normals (vector3)
  38889. * * facetPositions : optional array of facet positions (vector3)
  38890. * * facetPartitioning : optional partitioning array. facetPositions is required for facetPartitioning computation
  38891. * * ratio : optional partitioning ratio / bounding box, required for facetPartitioning computation
  38892. * * bInfo : optional bounding info, required for facetPartitioning computation
  38893. * * bbSize : optional bounding box size data, required for facetPartitioning computation
  38894. * * subDiv : optional partitioning data about subdivsions on each axis (int), required for facetPartitioning computation
  38895. * * useRightHandedSystem: optional boolean to for right handed system computation
  38896. * * depthSort : optional boolean to enable the facet depth sort computation
  38897. * * distanceTo : optional Vector3 to compute the facet depth from this location
  38898. * * depthSortedFacets : optional array of depthSortedFacets to store the facet distances from the reference location
  38899. */
  38900. VertexData.ComputeNormals = function (positions, indices, normals, options) {
  38901. // temporary scalar variables
  38902. var index = 0; // facet index
  38903. var p1p2x = 0.0; // p1p2 vector x coordinate
  38904. var p1p2y = 0.0; // p1p2 vector y coordinate
  38905. var p1p2z = 0.0; // p1p2 vector z coordinate
  38906. var p3p2x = 0.0; // p3p2 vector x coordinate
  38907. var p3p2y = 0.0; // p3p2 vector y coordinate
  38908. var p3p2z = 0.0; // p3p2 vector z coordinate
  38909. var faceNormalx = 0.0; // facet normal x coordinate
  38910. var faceNormaly = 0.0; // facet normal y coordinate
  38911. var faceNormalz = 0.0; // facet normal z coordinate
  38912. var length = 0.0; // facet normal length before normalization
  38913. var v1x = 0; // vector1 x index in the positions array
  38914. var v1y = 0; // vector1 y index in the positions array
  38915. var v1z = 0; // vector1 z index in the positions array
  38916. var v2x = 0; // vector2 x index in the positions array
  38917. var v2y = 0; // vector2 y index in the positions array
  38918. var v2z = 0; // vector2 z index in the positions array
  38919. var v3x = 0; // vector3 x index in the positions array
  38920. var v3y = 0; // vector3 y index in the positions array
  38921. var v3z = 0; // vector3 z index in the positions array
  38922. var computeFacetNormals = false;
  38923. var computeFacetPositions = false;
  38924. var computeFacetPartitioning = false;
  38925. var computeDepthSort = false;
  38926. var faceNormalSign = 1;
  38927. var ratio = 0;
  38928. var distanceTo = null;
  38929. if (options) {
  38930. computeFacetNormals = (options.facetNormals) ? true : false;
  38931. computeFacetPositions = (options.facetPositions) ? true : false;
  38932. computeFacetPartitioning = (options.facetPartitioning) ? true : false;
  38933. faceNormalSign = (options.useRightHandedSystem === true) ? -1 : 1;
  38934. ratio = options.ratio || 0;
  38935. computeDepthSort = (options.depthSort) ? true : false;
  38936. distanceTo = (options.distanceTo);
  38937. if (computeDepthSort) {
  38938. if (distanceTo === undefined) {
  38939. distanceTo = BABYLON.Vector3.Zero();
  38940. }
  38941. var depthSortedFacets = options.depthSortedFacets;
  38942. }
  38943. }
  38944. // facetPartitioning reinit if needed
  38945. var xSubRatio = 0;
  38946. var ySubRatio = 0;
  38947. var zSubRatio = 0;
  38948. var subSq = 0;
  38949. if (computeFacetPartitioning && options && options.bbSize) {
  38950. var ox = 0; // X partitioning index for facet position
  38951. var oy = 0; // Y partinioning index for facet position
  38952. var oz = 0; // Z partinioning index for facet position
  38953. var b1x = 0; // X partitioning index for facet v1 vertex
  38954. var b1y = 0; // Y partitioning index for facet v1 vertex
  38955. var b1z = 0; // z partitioning index for facet v1 vertex
  38956. var b2x = 0; // X partitioning index for facet v2 vertex
  38957. var b2y = 0; // Y partitioning index for facet v2 vertex
  38958. var b2z = 0; // Z partitioning index for facet v2 vertex
  38959. var b3x = 0; // X partitioning index for facet v3 vertex
  38960. var b3y = 0; // Y partitioning index for facet v3 vertex
  38961. var b3z = 0; // Z partitioning index for facet v3 vertex
  38962. var block_idx_o = 0; // facet barycenter block index
  38963. var block_idx_v1 = 0; // v1 vertex block index
  38964. var block_idx_v2 = 0; // v2 vertex block index
  38965. var block_idx_v3 = 0; // v3 vertex block index
  38966. var bbSizeMax = (options.bbSize.x > options.bbSize.y) ? options.bbSize.x : options.bbSize.y;
  38967. bbSizeMax = (bbSizeMax > options.bbSize.z) ? bbSizeMax : options.bbSize.z;
  38968. xSubRatio = options.subDiv.X * ratio / options.bbSize.x;
  38969. ySubRatio = options.subDiv.Y * ratio / options.bbSize.y;
  38970. zSubRatio = options.subDiv.Z * ratio / options.bbSize.z;
  38971. subSq = options.subDiv.max * options.subDiv.max;
  38972. options.facetPartitioning.length = 0;
  38973. }
  38974. // reset the normals
  38975. for (index = 0; index < positions.length; index++) {
  38976. normals[index] = 0.0;
  38977. }
  38978. // Loop : 1 indice triplet = 1 facet
  38979. var nbFaces = (indices.length / 3) | 0;
  38980. for (index = 0; index < nbFaces; index++) {
  38981. // get the indexes of the coordinates of each vertex of the facet
  38982. v1x = indices[index * 3] * 3;
  38983. v1y = v1x + 1;
  38984. v1z = v1x + 2;
  38985. v2x = indices[index * 3 + 1] * 3;
  38986. v2y = v2x + 1;
  38987. v2z = v2x + 2;
  38988. v3x = indices[index * 3 + 2] * 3;
  38989. v3y = v3x + 1;
  38990. v3z = v3x + 2;
  38991. p1p2x = positions[v1x] - positions[v2x]; // compute two vectors per facet : p1p2 and p3p2
  38992. p1p2y = positions[v1y] - positions[v2y];
  38993. p1p2z = positions[v1z] - positions[v2z];
  38994. p3p2x = positions[v3x] - positions[v2x];
  38995. p3p2y = positions[v3y] - positions[v2y];
  38996. p3p2z = positions[v3z] - positions[v2z];
  38997. // compute the face normal with the cross product
  38998. faceNormalx = faceNormalSign * (p1p2y * p3p2z - p1p2z * p3p2y);
  38999. faceNormaly = faceNormalSign * (p1p2z * p3p2x - p1p2x * p3p2z);
  39000. faceNormalz = faceNormalSign * (p1p2x * p3p2y - p1p2y * p3p2x);
  39001. // normalize this normal and store it in the array facetData
  39002. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39003. length = (length === 0) ? 1.0 : length;
  39004. faceNormalx /= length;
  39005. faceNormaly /= length;
  39006. faceNormalz /= length;
  39007. if (computeFacetNormals && options) {
  39008. options.facetNormals[index].x = faceNormalx;
  39009. options.facetNormals[index].y = faceNormaly;
  39010. options.facetNormals[index].z = faceNormalz;
  39011. }
  39012. if (computeFacetPositions && options) {
  39013. // compute and the facet barycenter coordinates in the array facetPositions
  39014. options.facetPositions[index].x = (positions[v1x] + positions[v2x] + positions[v3x]) / 3.0;
  39015. options.facetPositions[index].y = (positions[v1y] + positions[v2y] + positions[v3y]) / 3.0;
  39016. options.facetPositions[index].z = (positions[v1z] + positions[v2z] + positions[v3z]) / 3.0;
  39017. }
  39018. if (computeFacetPartitioning && options) {
  39019. // store the facet indexes in arrays in the main facetPartitioning array :
  39020. // compute each facet vertex (+ facet barycenter) index in the partiniong array
  39021. ox = Math.floor((options.facetPositions[index].x - options.bInfo.minimum.x * ratio) * xSubRatio);
  39022. oy = Math.floor((options.facetPositions[index].y - options.bInfo.minimum.y * ratio) * ySubRatio);
  39023. oz = Math.floor((options.facetPositions[index].z - options.bInfo.minimum.z * ratio) * zSubRatio);
  39024. b1x = Math.floor((positions[v1x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39025. b1y = Math.floor((positions[v1y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39026. b1z = Math.floor((positions[v1z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39027. b2x = Math.floor((positions[v2x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39028. b2y = Math.floor((positions[v2y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39029. b2z = Math.floor((positions[v2z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39030. b3x = Math.floor((positions[v3x] - options.bInfo.minimum.x * ratio) * xSubRatio);
  39031. b3y = Math.floor((positions[v3y] - options.bInfo.minimum.y * ratio) * ySubRatio);
  39032. b3z = Math.floor((positions[v3z] - options.bInfo.minimum.z * ratio) * zSubRatio);
  39033. block_idx_v1 = b1x + options.subDiv.max * b1y + subSq * b1z;
  39034. block_idx_v2 = b2x + options.subDiv.max * b2y + subSq * b2z;
  39035. block_idx_v3 = b3x + options.subDiv.max * b3y + subSq * b3z;
  39036. block_idx_o = ox + options.subDiv.max * oy + subSq * oz;
  39037. options.facetPartitioning[block_idx_o] = options.facetPartitioning[block_idx_o] ? options.facetPartitioning[block_idx_o] : new Array();
  39038. options.facetPartitioning[block_idx_v1] = options.facetPartitioning[block_idx_v1] ? options.facetPartitioning[block_idx_v1] : new Array();
  39039. options.facetPartitioning[block_idx_v2] = options.facetPartitioning[block_idx_v2] ? options.facetPartitioning[block_idx_v2] : new Array();
  39040. options.facetPartitioning[block_idx_v3] = options.facetPartitioning[block_idx_v3] ? options.facetPartitioning[block_idx_v3] : new Array();
  39041. // push each facet index in each block containing the vertex
  39042. options.facetPartitioning[block_idx_v1].push(index);
  39043. if (block_idx_v2 != block_idx_v1) {
  39044. options.facetPartitioning[block_idx_v2].push(index);
  39045. }
  39046. if (!(block_idx_v3 == block_idx_v2 || block_idx_v3 == block_idx_v1)) {
  39047. options.facetPartitioning[block_idx_v3].push(index);
  39048. }
  39049. if (!(block_idx_o == block_idx_v1 || block_idx_o == block_idx_v2 || block_idx_o == block_idx_v3)) {
  39050. options.facetPartitioning[block_idx_o].push(index);
  39051. }
  39052. }
  39053. if (computeDepthSort && options && options.facetPositions) {
  39054. var dsf = depthSortedFacets[index];
  39055. dsf.ind = index * 3;
  39056. dsf.sqDistance = BABYLON.Vector3.DistanceSquared(options.facetPositions[index], distanceTo);
  39057. }
  39058. // compute the normals anyway
  39059. normals[v1x] += faceNormalx; // accumulate all the normals per face
  39060. normals[v1y] += faceNormaly;
  39061. normals[v1z] += faceNormalz;
  39062. normals[v2x] += faceNormalx;
  39063. normals[v2y] += faceNormaly;
  39064. normals[v2z] += faceNormalz;
  39065. normals[v3x] += faceNormalx;
  39066. normals[v3y] += faceNormaly;
  39067. normals[v3z] += faceNormalz;
  39068. }
  39069. // last normalization of each normal
  39070. for (index = 0; index < normals.length / 3; index++) {
  39071. faceNormalx = normals[index * 3];
  39072. faceNormaly = normals[index * 3 + 1];
  39073. faceNormalz = normals[index * 3 + 2];
  39074. length = Math.sqrt(faceNormalx * faceNormalx + faceNormaly * faceNormaly + faceNormalz * faceNormalz);
  39075. length = (length === 0) ? 1.0 : length;
  39076. faceNormalx /= length;
  39077. faceNormaly /= length;
  39078. faceNormalz /= length;
  39079. normals[index * 3] = faceNormalx;
  39080. normals[index * 3 + 1] = faceNormaly;
  39081. normals[index * 3 + 2] = faceNormalz;
  39082. }
  39083. };
  39084. VertexData._ComputeSides = function (sideOrientation, positions, indices, normals, uvs, frontUVs, backUVs) {
  39085. var li = indices.length;
  39086. var ln = normals.length;
  39087. var i;
  39088. var n;
  39089. sideOrientation = sideOrientation || BABYLON.Mesh.DEFAULTSIDE;
  39090. switch (sideOrientation) {
  39091. case BABYLON.Mesh.FRONTSIDE:
  39092. // nothing changed
  39093. break;
  39094. case BABYLON.Mesh.BACKSIDE:
  39095. var tmp;
  39096. // indices
  39097. for (i = 0; i < li; i += 3) {
  39098. tmp = indices[i];
  39099. indices[i] = indices[i + 2];
  39100. indices[i + 2] = tmp;
  39101. }
  39102. // normals
  39103. for (n = 0; n < ln; n++) {
  39104. normals[n] = -normals[n];
  39105. }
  39106. break;
  39107. case BABYLON.Mesh.DOUBLESIDE:
  39108. // positions
  39109. var lp = positions.length;
  39110. var l = lp / 3;
  39111. for (var p = 0; p < lp; p++) {
  39112. positions[lp + p] = positions[p];
  39113. }
  39114. // indices
  39115. for (i = 0; i < li; i += 3) {
  39116. indices[i + li] = indices[i + 2] + l;
  39117. indices[i + 1 + li] = indices[i + 1] + l;
  39118. indices[i + 2 + li] = indices[i] + l;
  39119. }
  39120. // normals
  39121. for (n = 0; n < ln; n++) {
  39122. normals[ln + n] = -normals[n];
  39123. }
  39124. // uvs
  39125. var lu = uvs.length;
  39126. var u = 0;
  39127. for (u = 0; u < lu; u++) {
  39128. uvs[u + lu] = uvs[u];
  39129. }
  39130. frontUVs = frontUVs ? frontUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39131. backUVs = backUVs ? backUVs : new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  39132. u = 0;
  39133. for (i = 0; i < lu / 2; i++) {
  39134. uvs[u] = frontUVs.x + (frontUVs.z - frontUVs.x) * uvs[u];
  39135. uvs[u + 1] = frontUVs.y + (frontUVs.w - frontUVs.y) * uvs[u + 1];
  39136. uvs[u + lu] = backUVs.x + (backUVs.z - backUVs.x) * uvs[u + lu];
  39137. uvs[u + lu + 1] = backUVs.y + (backUVs.w - backUVs.y) * uvs[u + lu + 1];
  39138. u += 2;
  39139. }
  39140. break;
  39141. }
  39142. };
  39143. /**
  39144. * Applies VertexData created from the imported parameters to the geometry
  39145. * @param parsedVertexData the parsed data from an imported file
  39146. * @param geometry the geometry to apply the VertexData to
  39147. */
  39148. VertexData.ImportVertexData = function (parsedVertexData, geometry) {
  39149. var vertexData = new VertexData();
  39150. // positions
  39151. var positions = parsedVertexData.positions;
  39152. if (positions) {
  39153. vertexData.set(positions, BABYLON.VertexBuffer.PositionKind);
  39154. }
  39155. // normals
  39156. var normals = parsedVertexData.normals;
  39157. if (normals) {
  39158. vertexData.set(normals, BABYLON.VertexBuffer.NormalKind);
  39159. }
  39160. // tangents
  39161. var tangents = parsedVertexData.tangents;
  39162. if (tangents) {
  39163. vertexData.set(tangents, BABYLON.VertexBuffer.TangentKind);
  39164. }
  39165. // uvs
  39166. var uvs = parsedVertexData.uvs;
  39167. if (uvs) {
  39168. vertexData.set(uvs, BABYLON.VertexBuffer.UVKind);
  39169. }
  39170. // uv2s
  39171. var uv2s = parsedVertexData.uv2s;
  39172. if (uv2s) {
  39173. vertexData.set(uv2s, BABYLON.VertexBuffer.UV2Kind);
  39174. }
  39175. // uv3s
  39176. var uv3s = parsedVertexData.uv3s;
  39177. if (uv3s) {
  39178. vertexData.set(uv3s, BABYLON.VertexBuffer.UV3Kind);
  39179. }
  39180. // uv4s
  39181. var uv4s = parsedVertexData.uv4s;
  39182. if (uv4s) {
  39183. vertexData.set(uv4s, BABYLON.VertexBuffer.UV4Kind);
  39184. }
  39185. // uv5s
  39186. var uv5s = parsedVertexData.uv5s;
  39187. if (uv5s) {
  39188. vertexData.set(uv5s, BABYLON.VertexBuffer.UV5Kind);
  39189. }
  39190. // uv6s
  39191. var uv6s = parsedVertexData.uv6s;
  39192. if (uv6s) {
  39193. vertexData.set(uv6s, BABYLON.VertexBuffer.UV6Kind);
  39194. }
  39195. // colors
  39196. var colors = parsedVertexData.colors;
  39197. if (colors) {
  39198. vertexData.set(BABYLON.Color4.CheckColors4(colors, positions.length / 3), BABYLON.VertexBuffer.ColorKind);
  39199. }
  39200. // matricesIndices
  39201. var matricesIndices = parsedVertexData.matricesIndices;
  39202. if (matricesIndices) {
  39203. vertexData.set(matricesIndices, BABYLON.VertexBuffer.MatricesIndicesKind);
  39204. }
  39205. // matricesWeights
  39206. var matricesWeights = parsedVertexData.matricesWeights;
  39207. if (matricesWeights) {
  39208. vertexData.set(matricesWeights, BABYLON.VertexBuffer.MatricesWeightsKind);
  39209. }
  39210. // indices
  39211. var indices = parsedVertexData.indices;
  39212. if (indices) {
  39213. vertexData.indices = indices;
  39214. }
  39215. geometry.setAllVerticesData(vertexData, parsedVertexData.updatable);
  39216. };
  39217. return VertexData;
  39218. }());
  39219. BABYLON.VertexData = VertexData;
  39220. })(BABYLON || (BABYLON = {}));
  39221. //# sourceMappingURL=babylon.mesh.vertexData.js.map
  39222. var BABYLON;
  39223. (function (BABYLON) {
  39224. /**
  39225. * Class used to store geometry data (vertex buffers + index buffer)
  39226. */
  39227. var Geometry = /** @class */ (function () {
  39228. /**
  39229. * Creates a new geometry
  39230. * @param id defines the unique ID
  39231. * @param scene defines the hosting scene
  39232. * @param vertexData defines the {BABYLON.VertexData} used to get geometry data
  39233. * @param updatable defines if geometry must be updatable (false by default)
  39234. * @param mesh defines the mesh that will be associated with the geometry
  39235. */
  39236. function Geometry(id, scene, vertexData, updatable, mesh) {
  39237. if (updatable === void 0) { updatable = false; }
  39238. if (mesh === void 0) { mesh = null; }
  39239. /**
  39240. * Gets the delay loading state of the geometry (none by default which means not delayed)
  39241. */
  39242. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39243. this._totalVertices = 0;
  39244. this._isDisposed = false;
  39245. this._indexBufferIsUpdatable = false;
  39246. this.id = id;
  39247. this._engine = scene.getEngine();
  39248. this._meshes = [];
  39249. this._scene = scene;
  39250. //Init vertex buffer cache
  39251. this._vertexBuffers = {};
  39252. this._indices = [];
  39253. this._updatable = updatable;
  39254. // vertexData
  39255. if (vertexData) {
  39256. this.setAllVerticesData(vertexData, updatable);
  39257. }
  39258. else {
  39259. this._totalVertices = 0;
  39260. this._indices = [];
  39261. }
  39262. if (this._engine.getCaps().vertexArrayObject) {
  39263. this._vertexArrayObjects = {};
  39264. }
  39265. // applyToMesh
  39266. if (mesh) {
  39267. if (mesh.getClassName() === "LinesMesh") {
  39268. this.boundingBias = new BABYLON.Vector2(0, mesh.intersectionThreshold);
  39269. this._updateExtend();
  39270. }
  39271. this.applyToMesh(mesh);
  39272. mesh.computeWorldMatrix(true);
  39273. }
  39274. }
  39275. Object.defineProperty(Geometry.prototype, "boundingBias", {
  39276. /**
  39277. * 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
  39278. */
  39279. get: function () {
  39280. return this._boundingBias;
  39281. },
  39282. /**
  39283. * 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
  39284. */
  39285. set: function (value) {
  39286. if (this._boundingBias && this._boundingBias.equals(value)) {
  39287. return;
  39288. }
  39289. this._boundingBias = value.clone();
  39290. this._updateBoundingInfo(true, null);
  39291. },
  39292. enumerable: true,
  39293. configurable: true
  39294. });
  39295. /**
  39296. * Static function used to attach a new empty geometry to a mesh
  39297. * @param mesh defines the mesh to attach the geometry to
  39298. * @returns the new {BABYLON.Geometry}
  39299. */
  39300. Geometry.CreateGeometryForMesh = function (mesh) {
  39301. var geometry = new Geometry(Geometry.RandomId(), mesh.getScene());
  39302. geometry.applyToMesh(mesh);
  39303. return geometry;
  39304. };
  39305. Object.defineProperty(Geometry.prototype, "extend", {
  39306. /**
  39307. * Gets the current extend of the geometry
  39308. */
  39309. get: function () {
  39310. return this._extend;
  39311. },
  39312. enumerable: true,
  39313. configurable: true
  39314. });
  39315. /**
  39316. * Gets the hosting scene
  39317. * @returns the hosting {BABYLON.Scene}
  39318. */
  39319. Geometry.prototype.getScene = function () {
  39320. return this._scene;
  39321. };
  39322. /**
  39323. * Gets the hosting engine
  39324. * @returns the hosting {BABYLON.Engine}
  39325. */
  39326. Geometry.prototype.getEngine = function () {
  39327. return this._engine;
  39328. };
  39329. /**
  39330. * Defines if the geometry is ready to use
  39331. * @returns true if the geometry is ready to be used
  39332. */
  39333. Geometry.prototype.isReady = function () {
  39334. return this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE;
  39335. };
  39336. Object.defineProperty(Geometry.prototype, "doNotSerialize", {
  39337. /**
  39338. * Gets a value indicating that the geometry should not be serialized
  39339. */
  39340. get: function () {
  39341. for (var index = 0; index < this._meshes.length; index++) {
  39342. if (!this._meshes[index].doNotSerialize) {
  39343. return false;
  39344. }
  39345. }
  39346. return true;
  39347. },
  39348. enumerable: true,
  39349. configurable: true
  39350. });
  39351. /** @hidden */
  39352. Geometry.prototype._rebuild = function () {
  39353. if (this._vertexArrayObjects) {
  39354. this._vertexArrayObjects = {};
  39355. }
  39356. // Index buffer
  39357. if (this._meshes.length !== 0 && this._indices) {
  39358. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39359. }
  39360. // Vertex buffers
  39361. for (var key in this._vertexBuffers) {
  39362. var vertexBuffer = this._vertexBuffers[key];
  39363. vertexBuffer._rebuild();
  39364. }
  39365. };
  39366. /**
  39367. * Affects all geometry data in one call
  39368. * @param vertexData defines the geometry data
  39369. * @param updatable defines if the geometry must be flagged as updatable (false as default)
  39370. */
  39371. Geometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  39372. vertexData.applyToGeometry(this, updatable);
  39373. this.notifyUpdate();
  39374. };
  39375. /**
  39376. * Set specific vertex data
  39377. * @param kind defines the data kind (Position, normal, etc...)
  39378. * @param data defines the vertex data to use
  39379. * @param updatable defines if the vertex must be flagged as updatable (false as default)
  39380. * @param stride defines the stride to use (0 by default). This value is deduced from the kind value if not specified
  39381. */
  39382. Geometry.prototype.setVerticesData = function (kind, data, updatable, stride) {
  39383. if (updatable === void 0) { updatable = false; }
  39384. var buffer = new BABYLON.VertexBuffer(this._engine, data, kind, updatable, this._meshes.length === 0, stride);
  39385. this.setVerticesBuffer(buffer);
  39386. };
  39387. /**
  39388. * Removes a specific vertex data
  39389. * @param kind defines the data kind (Position, normal, etc...)
  39390. */
  39391. Geometry.prototype.removeVerticesData = function (kind) {
  39392. if (this._vertexBuffers[kind]) {
  39393. this._vertexBuffers[kind].dispose();
  39394. delete this._vertexBuffers[kind];
  39395. }
  39396. };
  39397. /**
  39398. * Affect a vertex buffer to the geometry. the vertexBuffer.getKind() function is used to determine where to store the data
  39399. * @param buffer defines the vertex buffer to use
  39400. * @param totalVertices defines the total number of vertices for position kind (could be null)
  39401. */
  39402. Geometry.prototype.setVerticesBuffer = function (buffer, totalVertices) {
  39403. if (totalVertices === void 0) { totalVertices = null; }
  39404. var kind = buffer.getKind();
  39405. if (this._vertexBuffers[kind]) {
  39406. this._vertexBuffers[kind].dispose();
  39407. }
  39408. this._vertexBuffers[kind] = buffer;
  39409. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39410. var data = buffer.getData();
  39411. if (totalVertices != null) {
  39412. this._totalVertices = totalVertices;
  39413. }
  39414. else {
  39415. if (data != null) {
  39416. this._totalVertices = data.length / (buffer.byteStride / 4);
  39417. }
  39418. }
  39419. this._updateExtend(data);
  39420. this._resetPointsArrayCache();
  39421. var meshes = this._meshes;
  39422. var numOfMeshes = meshes.length;
  39423. for (var index = 0; index < numOfMeshes; index++) {
  39424. var mesh = meshes[index];
  39425. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39426. mesh._createGlobalSubMesh(false);
  39427. mesh.computeWorldMatrix(true);
  39428. }
  39429. }
  39430. this.notifyUpdate(kind);
  39431. if (this._vertexArrayObjects) {
  39432. this._disposeVertexArrayObjects();
  39433. this._vertexArrayObjects = {}; // Will trigger a rebuild of the VAO if supported
  39434. }
  39435. };
  39436. /**
  39437. * Update a specific vertex buffer
  39438. * This function will directly update the underlying WebGLBuffer according to the passed numeric array or Float32Array
  39439. * It will do nothing if the buffer is not updatable
  39440. * @param kind defines the data kind (Position, normal, etc...)
  39441. * @param data defines the data to use
  39442. * @param offset defines the offset in the target buffer where to store the data
  39443. * @param useBytes set to true if the offset is in bytes
  39444. */
  39445. Geometry.prototype.updateVerticesDataDirectly = function (kind, data, offset, useBytes) {
  39446. if (useBytes === void 0) { useBytes = false; }
  39447. var vertexBuffer = this.getVertexBuffer(kind);
  39448. if (!vertexBuffer) {
  39449. return;
  39450. }
  39451. vertexBuffer.updateDirectly(data, offset, useBytes);
  39452. this.notifyUpdate(kind);
  39453. };
  39454. /**
  39455. * Update a specific vertex buffer
  39456. * This function will create a new buffer if the current one is not updatable
  39457. * @param kind defines the data kind (Position, normal, etc...)
  39458. * @param data defines the data to use
  39459. * @param updateExtends defines if the geometry extends must be recomputed (false by default)
  39460. */
  39461. Geometry.prototype.updateVerticesData = function (kind, data, updateExtends) {
  39462. if (updateExtends === void 0) { updateExtends = false; }
  39463. var vertexBuffer = this.getVertexBuffer(kind);
  39464. if (!vertexBuffer) {
  39465. return;
  39466. }
  39467. vertexBuffer.update(data);
  39468. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39469. this._updateBoundingInfo(updateExtends, data);
  39470. }
  39471. this.notifyUpdate(kind);
  39472. };
  39473. Geometry.prototype._updateBoundingInfo = function (updateExtends, data) {
  39474. if (updateExtends) {
  39475. this._updateExtend(data);
  39476. }
  39477. var meshes = this._meshes;
  39478. var numOfMeshes = meshes.length;
  39479. this._resetPointsArrayCache();
  39480. for (var index = 0; index < numOfMeshes; index++) {
  39481. var mesh = meshes[index];
  39482. if (updateExtends) {
  39483. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39484. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  39485. var subMesh = mesh.subMeshes[subIndex];
  39486. subMesh.refreshBoundingInfo();
  39487. }
  39488. }
  39489. }
  39490. };
  39491. /** @hidden */
  39492. Geometry.prototype._bind = function (effect, indexToBind) {
  39493. if (!effect) {
  39494. return;
  39495. }
  39496. if (indexToBind === undefined) {
  39497. indexToBind = this._indexBuffer;
  39498. }
  39499. var vbs = this.getVertexBuffers();
  39500. if (!vbs) {
  39501. return;
  39502. }
  39503. if (indexToBind != this._indexBuffer || !this._vertexArrayObjects) {
  39504. this._engine.bindBuffers(vbs, indexToBind, effect);
  39505. return;
  39506. }
  39507. // Using VAO
  39508. if (!this._vertexArrayObjects[effect.key]) {
  39509. this._vertexArrayObjects[effect.key] = this._engine.recordVertexArrayObject(vbs, indexToBind, effect);
  39510. }
  39511. this._engine.bindVertexArrayObject(this._vertexArrayObjects[effect.key], indexToBind);
  39512. };
  39513. /**
  39514. * Gets total number of vertices
  39515. * @returns the total number of vertices
  39516. */
  39517. Geometry.prototype.getTotalVertices = function () {
  39518. if (!this.isReady()) {
  39519. return 0;
  39520. }
  39521. return this._totalVertices;
  39522. };
  39523. /**
  39524. * Gets a specific vertex data attached to this geometry. Float data is constructed if the vertex buffer data cannot be returned directly.
  39525. * @param kind defines the data kind (Position, normal, etc...)
  39526. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39527. * @param forceCopy defines a boolean indicating that the returned array must be cloned upon returning it
  39528. * @returns a float array containing vertex data
  39529. */
  39530. Geometry.prototype.getVerticesData = function (kind, copyWhenShared, forceCopy) {
  39531. var vertexBuffer = this.getVertexBuffer(kind);
  39532. if (!vertexBuffer) {
  39533. return null;
  39534. }
  39535. var data = vertexBuffer.getData();
  39536. if (!data) {
  39537. return null;
  39538. }
  39539. var tightlyPackedByteStride = vertexBuffer.getSize() * BABYLON.VertexBuffer.GetTypeByteLength(vertexBuffer.type);
  39540. var count = this._totalVertices * vertexBuffer.getSize();
  39541. if (vertexBuffer.type !== BABYLON.VertexBuffer.FLOAT || vertexBuffer.byteStride !== tightlyPackedByteStride) {
  39542. var copy_1 = new Array(count);
  39543. vertexBuffer.forEach(count, function (value, index) {
  39544. copy_1[index] = value;
  39545. });
  39546. return copy_1;
  39547. }
  39548. if (!((data instanceof Array) || (data instanceof Float32Array)) || vertexBuffer.byteOffset !== 0 || data.length !== count) {
  39549. if (data instanceof Array) {
  39550. var offset = vertexBuffer.byteOffset / 4;
  39551. return BABYLON.Tools.Slice(data, offset, offset + count);
  39552. }
  39553. else if (data instanceof ArrayBuffer) {
  39554. return new Float32Array(data, vertexBuffer.byteOffset, count);
  39555. }
  39556. else {
  39557. return new Float32Array(data.buffer, data.byteOffset + vertexBuffer.byteOffset, count);
  39558. }
  39559. }
  39560. if (forceCopy || (copyWhenShared && this._meshes.length !== 1)) {
  39561. return BABYLON.Tools.Slice(data);
  39562. }
  39563. return data;
  39564. };
  39565. /**
  39566. * Returns a boolean defining if the vertex data for the requested `kind` is updatable
  39567. * @param kind defines the data kind (Position, normal, etc...)
  39568. * @returns true if the vertex buffer with the specified kind is updatable
  39569. */
  39570. Geometry.prototype.isVertexBufferUpdatable = function (kind) {
  39571. var vb = this._vertexBuffers[kind];
  39572. if (!vb) {
  39573. return false;
  39574. }
  39575. return vb.isUpdatable();
  39576. };
  39577. /**
  39578. * Gets a specific vertex buffer
  39579. * @param kind defines the data kind (Position, normal, etc...)
  39580. * @returns a {BABYLON.VertexBuffer}
  39581. */
  39582. Geometry.prototype.getVertexBuffer = function (kind) {
  39583. if (!this.isReady()) {
  39584. return null;
  39585. }
  39586. return this._vertexBuffers[kind];
  39587. };
  39588. /**
  39589. * Returns all vertex buffers
  39590. * @return an object holding all vertex buffers indexed by kind
  39591. */
  39592. Geometry.prototype.getVertexBuffers = function () {
  39593. if (!this.isReady()) {
  39594. return null;
  39595. }
  39596. return this._vertexBuffers;
  39597. };
  39598. /**
  39599. * Gets a boolean indicating if specific vertex buffer is present
  39600. * @param kind defines the data kind (Position, normal, etc...)
  39601. * @returns true if data is present
  39602. */
  39603. Geometry.prototype.isVerticesDataPresent = function (kind) {
  39604. if (!this._vertexBuffers) {
  39605. if (this._delayInfo) {
  39606. return this._delayInfo.indexOf(kind) !== -1;
  39607. }
  39608. return false;
  39609. }
  39610. return this._vertexBuffers[kind] !== undefined;
  39611. };
  39612. /**
  39613. * Gets a list of all attached data kinds (Position, normal, etc...)
  39614. * @returns a list of string containing all kinds
  39615. */
  39616. Geometry.prototype.getVerticesDataKinds = function () {
  39617. var result = [];
  39618. var kind;
  39619. if (!this._vertexBuffers && this._delayInfo) {
  39620. for (kind in this._delayInfo) {
  39621. result.push(kind);
  39622. }
  39623. }
  39624. else {
  39625. for (kind in this._vertexBuffers) {
  39626. result.push(kind);
  39627. }
  39628. }
  39629. return result;
  39630. };
  39631. /**
  39632. * Update index buffer
  39633. * @param indices defines the indices to store in the index buffer
  39634. * @param offset defines the offset in the target buffer where to store the data
  39635. */
  39636. Geometry.prototype.updateIndices = function (indices, offset) {
  39637. if (!this._indexBuffer) {
  39638. return;
  39639. }
  39640. if (!this._indexBufferIsUpdatable) {
  39641. this.setIndices(indices, null, true);
  39642. }
  39643. else {
  39644. this._engine.updateDynamicIndexBuffer(this._indexBuffer, indices, offset);
  39645. }
  39646. };
  39647. /**
  39648. * Creates a new index buffer
  39649. * @param indices defines the indices to store in the index buffer
  39650. * @param totalVertices defines the total number of vertices (could be null)
  39651. * @param updatable defines if the index buffer must be flagged as updatable (false by default)
  39652. */
  39653. Geometry.prototype.setIndices = function (indices, totalVertices, updatable) {
  39654. if (totalVertices === void 0) { totalVertices = null; }
  39655. if (updatable === void 0) { updatable = false; }
  39656. if (this._indexBuffer) {
  39657. this._engine._releaseBuffer(this._indexBuffer);
  39658. }
  39659. this._disposeVertexArrayObjects();
  39660. this._indices = indices;
  39661. this._indexBufferIsUpdatable = updatable;
  39662. if (this._meshes.length !== 0 && this._indices) {
  39663. this._indexBuffer = this._engine.createIndexBuffer(this._indices, updatable);
  39664. }
  39665. if (totalVertices != undefined) { // including null and undefined
  39666. this._totalVertices = totalVertices;
  39667. }
  39668. var meshes = this._meshes;
  39669. var numOfMeshes = meshes.length;
  39670. for (var index = 0; index < numOfMeshes; index++) {
  39671. meshes[index]._createGlobalSubMesh(true);
  39672. }
  39673. this.notifyUpdate();
  39674. };
  39675. /**
  39676. * Return the total number of indices
  39677. * @returns the total number of indices
  39678. */
  39679. Geometry.prototype.getTotalIndices = function () {
  39680. if (!this.isReady()) {
  39681. return 0;
  39682. }
  39683. return this._indices.length;
  39684. };
  39685. /**
  39686. * Gets the index buffer array
  39687. * @param copyWhenShared defines if the returned array must be cloned upon returning it if the current geometry is shared between multiple meshes
  39688. * @returns the index buffer array
  39689. */
  39690. Geometry.prototype.getIndices = function (copyWhenShared) {
  39691. if (!this.isReady()) {
  39692. return null;
  39693. }
  39694. var orig = this._indices;
  39695. if (!copyWhenShared || this._meshes.length === 1) {
  39696. return orig;
  39697. }
  39698. else {
  39699. var len = orig.length;
  39700. var copy = [];
  39701. for (var i = 0; i < len; i++) {
  39702. copy.push(orig[i]);
  39703. }
  39704. return copy;
  39705. }
  39706. };
  39707. /**
  39708. * Gets the index buffer
  39709. * @return the index buffer
  39710. */
  39711. Geometry.prototype.getIndexBuffer = function () {
  39712. if (!this.isReady()) {
  39713. return null;
  39714. }
  39715. return this._indexBuffer;
  39716. };
  39717. /** @hidden */
  39718. Geometry.prototype._releaseVertexArrayObject = function (effect) {
  39719. if (effect === void 0) { effect = null; }
  39720. if (!effect || !this._vertexArrayObjects) {
  39721. return;
  39722. }
  39723. if (this._vertexArrayObjects[effect.key]) {
  39724. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[effect.key]);
  39725. delete this._vertexArrayObjects[effect.key];
  39726. }
  39727. };
  39728. /**
  39729. * Release the associated resources for a specific mesh
  39730. * @param mesh defines the source mesh
  39731. * @param shouldDispose defines if the geometry must be disposed if there is no more mesh pointing to it
  39732. */
  39733. Geometry.prototype.releaseForMesh = function (mesh, shouldDispose) {
  39734. var meshes = this._meshes;
  39735. var index = meshes.indexOf(mesh);
  39736. if (index === -1) {
  39737. return;
  39738. }
  39739. meshes.splice(index, 1);
  39740. mesh._geometry = null;
  39741. if (meshes.length === 0 && shouldDispose) {
  39742. this.dispose();
  39743. }
  39744. };
  39745. /**
  39746. * Apply current geometry to a given mesh
  39747. * @param mesh defines the mesh to apply geometry to
  39748. */
  39749. Geometry.prototype.applyToMesh = function (mesh) {
  39750. if (mesh._geometry === this) {
  39751. return;
  39752. }
  39753. var previousGeometry = mesh._geometry;
  39754. if (previousGeometry) {
  39755. previousGeometry.releaseForMesh(mesh);
  39756. }
  39757. var meshes = this._meshes;
  39758. // must be done before setting vertexBuffers because of mesh._createGlobalSubMesh()
  39759. mesh._geometry = this;
  39760. this._scene.pushGeometry(this);
  39761. meshes.push(mesh);
  39762. if (this.isReady()) {
  39763. this._applyToMesh(mesh);
  39764. }
  39765. else {
  39766. mesh._boundingInfo = this._boundingInfo;
  39767. }
  39768. };
  39769. Geometry.prototype._updateExtend = function (data) {
  39770. if (data === void 0) { data = null; }
  39771. if (!data) {
  39772. data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39773. }
  39774. this._extend = BABYLON.Tools.ExtractMinAndMax(data, 0, this._totalVertices, this.boundingBias, 3);
  39775. };
  39776. Geometry.prototype._applyToMesh = function (mesh) {
  39777. var numOfMeshes = this._meshes.length;
  39778. // vertexBuffers
  39779. for (var kind in this._vertexBuffers) {
  39780. if (numOfMeshes === 1) {
  39781. this._vertexBuffers[kind].create();
  39782. }
  39783. var buffer = this._vertexBuffers[kind].getBuffer();
  39784. if (buffer)
  39785. buffer.references = numOfMeshes;
  39786. if (kind === BABYLON.VertexBuffer.PositionKind) {
  39787. if (!this._extend) {
  39788. this._updateExtend();
  39789. }
  39790. mesh._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39791. mesh._createGlobalSubMesh(false);
  39792. //bounding info was just created again, world matrix should be applied again.
  39793. mesh._updateBoundingInfo();
  39794. }
  39795. }
  39796. // indexBuffer
  39797. if (numOfMeshes === 1 && this._indices && this._indices.length > 0) {
  39798. this._indexBuffer = this._engine.createIndexBuffer(this._indices);
  39799. }
  39800. if (this._indexBuffer) {
  39801. this._indexBuffer.references = numOfMeshes;
  39802. }
  39803. };
  39804. Geometry.prototype.notifyUpdate = function (kind) {
  39805. if (this.onGeometryUpdated) {
  39806. this.onGeometryUpdated(this, kind);
  39807. }
  39808. for (var _i = 0, _a = this._meshes; _i < _a.length; _i++) {
  39809. var mesh = _a[_i];
  39810. mesh._markSubMeshesAsAttributesDirty();
  39811. }
  39812. };
  39813. /**
  39814. * Load the geometry if it was flagged as delay loaded
  39815. * @param scene defines the hosting scene
  39816. * @param onLoaded defines a callback called when the geometry is loaded
  39817. */
  39818. Geometry.prototype.load = function (scene, onLoaded) {
  39819. if (this.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADING) {
  39820. return;
  39821. }
  39822. if (this.isReady()) {
  39823. if (onLoaded) {
  39824. onLoaded();
  39825. }
  39826. return;
  39827. }
  39828. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADING;
  39829. this._queueLoad(scene, onLoaded);
  39830. };
  39831. Geometry.prototype._queueLoad = function (scene, onLoaded) {
  39832. var _this = this;
  39833. if (!this.delayLoadingFile) {
  39834. return;
  39835. }
  39836. scene._addPendingData(this);
  39837. scene._loadFile(this.delayLoadingFile, function (data) {
  39838. if (!_this._delayLoadingFunction) {
  39839. return;
  39840. }
  39841. _this._delayLoadingFunction(JSON.parse(data), _this);
  39842. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  39843. _this._delayInfo = [];
  39844. scene._removePendingData(_this);
  39845. var meshes = _this._meshes;
  39846. var numOfMeshes = meshes.length;
  39847. for (var index = 0; index < numOfMeshes; index++) {
  39848. _this._applyToMesh(meshes[index]);
  39849. }
  39850. if (onLoaded) {
  39851. onLoaded();
  39852. }
  39853. }, undefined, true);
  39854. };
  39855. /**
  39856. * Invert the geometry to move from a right handed system to a left handed one.
  39857. */
  39858. Geometry.prototype.toLeftHanded = function () {
  39859. // Flip faces
  39860. var tIndices = this.getIndices(false);
  39861. if (tIndices != null && tIndices.length > 0) {
  39862. for (var i = 0; i < tIndices.length; i += 3) {
  39863. var tTemp = tIndices[i + 0];
  39864. tIndices[i + 0] = tIndices[i + 2];
  39865. tIndices[i + 2] = tTemp;
  39866. }
  39867. this.setIndices(tIndices);
  39868. }
  39869. // Negate position.z
  39870. var tPositions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind, false);
  39871. if (tPositions != null && tPositions.length > 0) {
  39872. for (var i = 0; i < tPositions.length; i += 3) {
  39873. tPositions[i + 2] = -tPositions[i + 2];
  39874. }
  39875. this.setVerticesData(BABYLON.VertexBuffer.PositionKind, tPositions, false);
  39876. }
  39877. // Negate normal.z
  39878. var tNormals = this.getVerticesData(BABYLON.VertexBuffer.NormalKind, false);
  39879. if (tNormals != null && tNormals.length > 0) {
  39880. for (var i = 0; i < tNormals.length; i += 3) {
  39881. tNormals[i + 2] = -tNormals[i + 2];
  39882. }
  39883. this.setVerticesData(BABYLON.VertexBuffer.NormalKind, tNormals, false);
  39884. }
  39885. };
  39886. // Cache
  39887. /** @hidden */
  39888. Geometry.prototype._resetPointsArrayCache = function () {
  39889. this._positions = null;
  39890. };
  39891. /** @hidden */
  39892. Geometry.prototype._generatePointsArray = function () {
  39893. if (this._positions)
  39894. return true;
  39895. var data = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  39896. if (!data || data.length === 0) {
  39897. return false;
  39898. }
  39899. this._positions = [];
  39900. for (var index = 0; index < data.length; index += 3) {
  39901. this._positions.push(BABYLON.Vector3.FromArray(data, index));
  39902. }
  39903. return true;
  39904. };
  39905. /**
  39906. * Gets a value indicating if the geometry is disposed
  39907. * @returns true if the geometry was disposed
  39908. */
  39909. Geometry.prototype.isDisposed = function () {
  39910. return this._isDisposed;
  39911. };
  39912. Geometry.prototype._disposeVertexArrayObjects = function () {
  39913. if (this._vertexArrayObjects) {
  39914. for (var kind in this._vertexArrayObjects) {
  39915. this._engine.releaseVertexArrayObject(this._vertexArrayObjects[kind]);
  39916. }
  39917. this._vertexArrayObjects = {};
  39918. }
  39919. };
  39920. /**
  39921. * Free all associated resources
  39922. */
  39923. Geometry.prototype.dispose = function () {
  39924. var meshes = this._meshes;
  39925. var numOfMeshes = meshes.length;
  39926. var index;
  39927. for (index = 0; index < numOfMeshes; index++) {
  39928. this.releaseForMesh(meshes[index]);
  39929. }
  39930. this._meshes = [];
  39931. this._disposeVertexArrayObjects();
  39932. for (var kind in this._vertexBuffers) {
  39933. this._vertexBuffers[kind].dispose();
  39934. }
  39935. this._vertexBuffers = {};
  39936. this._totalVertices = 0;
  39937. if (this._indexBuffer) {
  39938. this._engine._releaseBuffer(this._indexBuffer);
  39939. }
  39940. this._indexBuffer = null;
  39941. this._indices = [];
  39942. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NONE;
  39943. this.delayLoadingFile = null;
  39944. this._delayLoadingFunction = null;
  39945. this._delayInfo = [];
  39946. this._boundingInfo = null;
  39947. this._scene.removeGeometry(this);
  39948. this._isDisposed = true;
  39949. };
  39950. /**
  39951. * Clone the current geometry into a new geometry
  39952. * @param id defines the unique ID of the new geometry
  39953. * @returns a new geometry object
  39954. */
  39955. Geometry.prototype.copy = function (id) {
  39956. var vertexData = new BABYLON.VertexData();
  39957. vertexData.indices = [];
  39958. var indices = this.getIndices();
  39959. if (indices) {
  39960. for (var index = 0; index < indices.length; index++) {
  39961. vertexData.indices.push(indices[index]);
  39962. }
  39963. }
  39964. var updatable = false;
  39965. var stopChecking = false;
  39966. var kind;
  39967. for (kind in this._vertexBuffers) {
  39968. // using slice() to make a copy of the array and not just reference it
  39969. var data = this.getVerticesData(kind);
  39970. if (data instanceof Float32Array) {
  39971. vertexData.set(new Float32Array(data), kind);
  39972. }
  39973. else {
  39974. vertexData.set(data.slice(0), kind);
  39975. }
  39976. if (!stopChecking) {
  39977. var vb = this.getVertexBuffer(kind);
  39978. if (vb) {
  39979. updatable = vb.isUpdatable();
  39980. stopChecking = !updatable;
  39981. }
  39982. }
  39983. }
  39984. var geometry = new Geometry(id, this._scene, vertexData, updatable);
  39985. geometry.delayLoadState = this.delayLoadState;
  39986. geometry.delayLoadingFile = this.delayLoadingFile;
  39987. geometry._delayLoadingFunction = this._delayLoadingFunction;
  39988. for (kind in this._delayInfo) {
  39989. geometry._delayInfo = geometry._delayInfo || [];
  39990. geometry._delayInfo.push(kind);
  39991. }
  39992. // Bounding info
  39993. geometry._boundingInfo = new BABYLON.BoundingInfo(this._extend.minimum, this._extend.maximum);
  39994. return geometry;
  39995. };
  39996. /**
  39997. * Serialize the current geometry info (and not the vertices data) into a JSON object
  39998. * @return a JSON representation of the current geometry data (without the vertices data)
  39999. */
  40000. Geometry.prototype.serialize = function () {
  40001. var serializationObject = {};
  40002. serializationObject.id = this.id;
  40003. serializationObject.updatable = this._updatable;
  40004. if (BABYLON.Tags && BABYLON.Tags.HasTags(this)) {
  40005. serializationObject.tags = BABYLON.Tags.GetTags(this);
  40006. }
  40007. return serializationObject;
  40008. };
  40009. Geometry.prototype.toNumberArray = function (origin) {
  40010. if (Array.isArray(origin)) {
  40011. return origin;
  40012. }
  40013. else {
  40014. return Array.prototype.slice.call(origin);
  40015. }
  40016. };
  40017. /**
  40018. * Serialize all vertices data into a JSON oject
  40019. * @returns a JSON representation of the current geometry data
  40020. */
  40021. Geometry.prototype.serializeVerticeData = function () {
  40022. var serializationObject = this.serialize();
  40023. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.PositionKind)) {
  40024. serializationObject.positions = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  40025. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.PositionKind)) {
  40026. serializationObject.positions._updatable = true;
  40027. }
  40028. }
  40029. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  40030. serializationObject.normals = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  40031. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.NormalKind)) {
  40032. serializationObject.normals._updatable = true;
  40033. }
  40034. }
  40035. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  40036. serializationObject.tangets = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  40037. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.TangentKind)) {
  40038. serializationObject.tangets._updatable = true;
  40039. }
  40040. }
  40041. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  40042. serializationObject.uvs = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UVKind));
  40043. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UVKind)) {
  40044. serializationObject.uvs._updatable = true;
  40045. }
  40046. }
  40047. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  40048. serializationObject.uv2s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV2Kind));
  40049. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV2Kind)) {
  40050. serializationObject.uv2s._updatable = true;
  40051. }
  40052. }
  40053. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV3Kind)) {
  40054. serializationObject.uv3s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV3Kind));
  40055. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV3Kind)) {
  40056. serializationObject.uv3s._updatable = true;
  40057. }
  40058. }
  40059. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV4Kind)) {
  40060. serializationObject.uv4s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV4Kind));
  40061. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV4Kind)) {
  40062. serializationObject.uv4s._updatable = true;
  40063. }
  40064. }
  40065. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV5Kind)) {
  40066. serializationObject.uv5s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV5Kind));
  40067. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV5Kind)) {
  40068. serializationObject.uv5s._updatable = true;
  40069. }
  40070. }
  40071. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.UV6Kind)) {
  40072. serializationObject.uv6s = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.UV6Kind));
  40073. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.UV6Kind)) {
  40074. serializationObject.uv6s._updatable = true;
  40075. }
  40076. }
  40077. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  40078. serializationObject.colors = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.ColorKind));
  40079. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.ColorKind)) {
  40080. serializationObject.colors._updatable = true;
  40081. }
  40082. }
  40083. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40084. serializationObject.matricesIndices = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind));
  40085. serializationObject.matricesIndices._isExpanded = true;
  40086. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesIndicesKind)) {
  40087. serializationObject.matricesIndices._updatable = true;
  40088. }
  40089. }
  40090. if (this.isVerticesDataPresent(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40091. serializationObject.matricesWeights = this.toNumberArray(this.getVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind));
  40092. if (this.isVertexBufferUpdatable(BABYLON.VertexBuffer.MatricesWeightsKind)) {
  40093. serializationObject.matricesWeights._updatable = true;
  40094. }
  40095. }
  40096. serializationObject.indices = this.toNumberArray(this.getIndices());
  40097. return serializationObject;
  40098. };
  40099. // Statics
  40100. /**
  40101. * Extracts a clone of a mesh geometry
  40102. * @param mesh defines the source mesh
  40103. * @param id defines the unique ID of the new geometry object
  40104. * @returns the new geometry object
  40105. */
  40106. Geometry.ExtractFromMesh = function (mesh, id) {
  40107. var geometry = mesh._geometry;
  40108. if (!geometry) {
  40109. return null;
  40110. }
  40111. return geometry.copy(id);
  40112. };
  40113. /**
  40114. * You should now use Tools.RandomId(), this method is still here for legacy reasons.
  40115. * Implementation from http://stackoverflow.com/questions/105034/how-to-create-a-guid-uuid-in-javascript/2117523#answer-2117523
  40116. * Be aware Math.random() could cause collisions, but:
  40117. * "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"
  40118. * @returns a string containing a new GUID
  40119. */
  40120. Geometry.RandomId = function () {
  40121. return BABYLON.Tools.RandomId();
  40122. };
  40123. /** @hidden */
  40124. Geometry._ImportGeometry = function (parsedGeometry, mesh) {
  40125. var scene = mesh.getScene();
  40126. // Geometry
  40127. var geometryId = parsedGeometry.geometryId;
  40128. if (geometryId) {
  40129. var geometry = scene.getGeometryByID(geometryId);
  40130. if (geometry) {
  40131. geometry.applyToMesh(mesh);
  40132. }
  40133. }
  40134. else if (parsedGeometry instanceof ArrayBuffer) {
  40135. var binaryInfo = mesh._binaryInfo;
  40136. if (binaryInfo.positionsAttrDesc && binaryInfo.positionsAttrDesc.count > 0) {
  40137. var positionsData = new Float32Array(parsedGeometry, binaryInfo.positionsAttrDesc.offset, binaryInfo.positionsAttrDesc.count);
  40138. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positionsData, false);
  40139. }
  40140. if (binaryInfo.normalsAttrDesc && binaryInfo.normalsAttrDesc.count > 0) {
  40141. var normalsData = new Float32Array(parsedGeometry, binaryInfo.normalsAttrDesc.offset, binaryInfo.normalsAttrDesc.count);
  40142. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normalsData, false);
  40143. }
  40144. if (binaryInfo.tangetsAttrDesc && binaryInfo.tangetsAttrDesc.count > 0) {
  40145. var tangentsData = new Float32Array(parsedGeometry, binaryInfo.tangetsAttrDesc.offset, binaryInfo.tangetsAttrDesc.count);
  40146. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, tangentsData, false);
  40147. }
  40148. if (binaryInfo.uvsAttrDesc && binaryInfo.uvsAttrDesc.count > 0) {
  40149. var uvsData = new Float32Array(parsedGeometry, binaryInfo.uvsAttrDesc.offset, binaryInfo.uvsAttrDesc.count);
  40150. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvsData, false);
  40151. }
  40152. if (binaryInfo.uvs2AttrDesc && binaryInfo.uvs2AttrDesc.count > 0) {
  40153. var uvs2Data = new Float32Array(parsedGeometry, binaryInfo.uvs2AttrDesc.offset, binaryInfo.uvs2AttrDesc.count);
  40154. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, uvs2Data, false);
  40155. }
  40156. if (binaryInfo.uvs3AttrDesc && binaryInfo.uvs3AttrDesc.count > 0) {
  40157. var uvs3Data = new Float32Array(parsedGeometry, binaryInfo.uvs3AttrDesc.offset, binaryInfo.uvs3AttrDesc.count);
  40158. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, uvs3Data, false);
  40159. }
  40160. if (binaryInfo.uvs4AttrDesc && binaryInfo.uvs4AttrDesc.count > 0) {
  40161. var uvs4Data = new Float32Array(parsedGeometry, binaryInfo.uvs4AttrDesc.offset, binaryInfo.uvs4AttrDesc.count);
  40162. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, uvs4Data, false);
  40163. }
  40164. if (binaryInfo.uvs5AttrDesc && binaryInfo.uvs5AttrDesc.count > 0) {
  40165. var uvs5Data = new Float32Array(parsedGeometry, binaryInfo.uvs5AttrDesc.offset, binaryInfo.uvs5AttrDesc.count);
  40166. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, uvs5Data, false);
  40167. }
  40168. if (binaryInfo.uvs6AttrDesc && binaryInfo.uvs6AttrDesc.count > 0) {
  40169. var uvs6Data = new Float32Array(parsedGeometry, binaryInfo.uvs6AttrDesc.offset, binaryInfo.uvs6AttrDesc.count);
  40170. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, uvs6Data, false);
  40171. }
  40172. if (binaryInfo.colorsAttrDesc && binaryInfo.colorsAttrDesc.count > 0) {
  40173. var colorsData = new Float32Array(parsedGeometry, binaryInfo.colorsAttrDesc.offset, binaryInfo.colorsAttrDesc.count);
  40174. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, colorsData, false, binaryInfo.colorsAttrDesc.stride);
  40175. }
  40176. if (binaryInfo.matricesIndicesAttrDesc && binaryInfo.matricesIndicesAttrDesc.count > 0) {
  40177. var matricesIndicesData = new Int32Array(parsedGeometry, binaryInfo.matricesIndicesAttrDesc.offset, binaryInfo.matricesIndicesAttrDesc.count);
  40178. var floatIndices = [];
  40179. for (var i = 0; i < matricesIndicesData.length; i++) {
  40180. var index = matricesIndicesData[i];
  40181. floatIndices.push(index & 0x000000FF);
  40182. floatIndices.push((index & 0x0000FF00) >> 8);
  40183. floatIndices.push((index & 0x00FF0000) >> 16);
  40184. floatIndices.push(index >> 24);
  40185. }
  40186. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, false);
  40187. }
  40188. if (binaryInfo.matricesWeightsAttrDesc && binaryInfo.matricesWeightsAttrDesc.count > 0) {
  40189. var matricesWeightsData = new Float32Array(parsedGeometry, binaryInfo.matricesWeightsAttrDesc.offset, binaryInfo.matricesWeightsAttrDesc.count);
  40190. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, matricesWeightsData, false);
  40191. }
  40192. if (binaryInfo.indicesAttrDesc && binaryInfo.indicesAttrDesc.count > 0) {
  40193. var indicesData = new Int32Array(parsedGeometry, binaryInfo.indicesAttrDesc.offset, binaryInfo.indicesAttrDesc.count);
  40194. mesh.setIndices(indicesData, null);
  40195. }
  40196. if (binaryInfo.subMeshesAttrDesc && binaryInfo.subMeshesAttrDesc.count > 0) {
  40197. var subMeshesData = new Int32Array(parsedGeometry, binaryInfo.subMeshesAttrDesc.offset, binaryInfo.subMeshesAttrDesc.count * 5);
  40198. mesh.subMeshes = [];
  40199. for (var i = 0; i < binaryInfo.subMeshesAttrDesc.count; i++) {
  40200. var materialIndex = subMeshesData[(i * 5) + 0];
  40201. var verticesStart = subMeshesData[(i * 5) + 1];
  40202. var verticesCount = subMeshesData[(i * 5) + 2];
  40203. var indexStart = subMeshesData[(i * 5) + 3];
  40204. var indexCount = subMeshesData[(i * 5) + 4];
  40205. BABYLON.SubMesh.AddToMesh(materialIndex, verticesStart, verticesCount, indexStart, indexCount, mesh);
  40206. }
  40207. }
  40208. }
  40209. else if (parsedGeometry.positions && parsedGeometry.normals && parsedGeometry.indices) {
  40210. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, parsedGeometry.positions, parsedGeometry.positions._updatable);
  40211. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, parsedGeometry.normals, parsedGeometry.normals._updatable);
  40212. if (parsedGeometry.tangents) {
  40213. mesh.setVerticesData(BABYLON.VertexBuffer.TangentKind, parsedGeometry.tangents, parsedGeometry.tangents._updatable);
  40214. }
  40215. if (parsedGeometry.uvs) {
  40216. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, parsedGeometry.uvs, parsedGeometry.uvs._updatable);
  40217. }
  40218. if (parsedGeometry.uvs2) {
  40219. mesh.setVerticesData(BABYLON.VertexBuffer.UV2Kind, parsedGeometry.uvs2, parsedGeometry.uvs2._updatable);
  40220. }
  40221. if (parsedGeometry.uvs3) {
  40222. mesh.setVerticesData(BABYLON.VertexBuffer.UV3Kind, parsedGeometry.uvs3, parsedGeometry.uvs3._updatable);
  40223. }
  40224. if (parsedGeometry.uvs4) {
  40225. mesh.setVerticesData(BABYLON.VertexBuffer.UV4Kind, parsedGeometry.uvs4, parsedGeometry.uvs4._updatable);
  40226. }
  40227. if (parsedGeometry.uvs5) {
  40228. mesh.setVerticesData(BABYLON.VertexBuffer.UV5Kind, parsedGeometry.uvs5, parsedGeometry.uvs5._updatable);
  40229. }
  40230. if (parsedGeometry.uvs6) {
  40231. mesh.setVerticesData(BABYLON.VertexBuffer.UV6Kind, parsedGeometry.uvs6, parsedGeometry.uvs6._updatable);
  40232. }
  40233. if (parsedGeometry.colors) {
  40234. mesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, BABYLON.Color4.CheckColors4(parsedGeometry.colors, parsedGeometry.positions.length / 3), parsedGeometry.colors._updatable);
  40235. }
  40236. if (parsedGeometry.matricesIndices) {
  40237. if (!parsedGeometry.matricesIndices._isExpanded) {
  40238. var floatIndices = [];
  40239. for (var i = 0; i < parsedGeometry.matricesIndices.length; i++) {
  40240. var matricesIndex = parsedGeometry.matricesIndices[i];
  40241. floatIndices.push(matricesIndex & 0x000000FF);
  40242. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40243. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40244. floatIndices.push(matricesIndex >> 24);
  40245. }
  40246. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, floatIndices, parsedGeometry.matricesIndices._updatable);
  40247. }
  40248. else {
  40249. delete parsedGeometry.matricesIndices._isExpanded;
  40250. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, parsedGeometry.matricesIndices, parsedGeometry.matricesIndices._updatable);
  40251. }
  40252. }
  40253. if (parsedGeometry.matricesIndicesExtra) {
  40254. if (!parsedGeometry.matricesIndicesExtra._isExpanded) {
  40255. var floatIndices = [];
  40256. for (var i = 0; i < parsedGeometry.matricesIndicesExtra.length; i++) {
  40257. var matricesIndex = parsedGeometry.matricesIndicesExtra[i];
  40258. floatIndices.push(matricesIndex & 0x000000FF);
  40259. floatIndices.push((matricesIndex & 0x0000FF00) >> 8);
  40260. floatIndices.push((matricesIndex & 0x00FF0000) >> 16);
  40261. floatIndices.push(matricesIndex >> 24);
  40262. }
  40263. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, floatIndices, parsedGeometry.matricesIndicesExtra._updatable);
  40264. }
  40265. else {
  40266. delete parsedGeometry.matricesIndices._isExpanded;
  40267. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, parsedGeometry.matricesIndicesExtra, parsedGeometry.matricesIndicesExtra._updatable);
  40268. }
  40269. }
  40270. if (parsedGeometry.matricesWeights) {
  40271. Geometry._CleanMatricesWeights(parsedGeometry, mesh);
  40272. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsKind, parsedGeometry.matricesWeights, parsedGeometry.matricesWeights._updatable);
  40273. }
  40274. if (parsedGeometry.matricesWeightsExtra) {
  40275. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesWeightsExtraKind, parsedGeometry.matricesWeightsExtra, parsedGeometry.matricesWeights._updatable);
  40276. }
  40277. mesh.setIndices(parsedGeometry.indices, null);
  40278. }
  40279. // SubMeshes
  40280. if (parsedGeometry.subMeshes) {
  40281. mesh.subMeshes = [];
  40282. for (var subIndex = 0; subIndex < parsedGeometry.subMeshes.length; subIndex++) {
  40283. var parsedSubMesh = parsedGeometry.subMeshes[subIndex];
  40284. BABYLON.SubMesh.AddToMesh(parsedSubMesh.materialIndex, parsedSubMesh.verticesStart, parsedSubMesh.verticesCount, parsedSubMesh.indexStart, parsedSubMesh.indexCount, mesh);
  40285. }
  40286. }
  40287. // Flat shading
  40288. if (mesh._shouldGenerateFlatShading) {
  40289. mesh.convertToFlatShadedMesh();
  40290. delete mesh._shouldGenerateFlatShading;
  40291. }
  40292. // Update
  40293. mesh.computeWorldMatrix(true);
  40294. // Octree
  40295. var sceneOctree = scene.selectionOctree;
  40296. if (sceneOctree !== undefined && sceneOctree !== null) {
  40297. sceneOctree.addMesh(mesh);
  40298. }
  40299. };
  40300. Geometry._CleanMatricesWeights = function (parsedGeometry, mesh) {
  40301. var epsilon = 1e-3;
  40302. if (!BABYLON.SceneLoader.CleanBoneMatrixWeights) {
  40303. return;
  40304. }
  40305. var noInfluenceBoneIndex = 0.0;
  40306. if (parsedGeometry.skeletonId > -1) {
  40307. var skeleton = mesh.getScene().getLastSkeletonByID(parsedGeometry.skeletonId);
  40308. if (!skeleton) {
  40309. return;
  40310. }
  40311. noInfluenceBoneIndex = skeleton.bones.length;
  40312. }
  40313. else {
  40314. return;
  40315. }
  40316. var matricesIndices = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind);
  40317. var matricesIndicesExtra = mesh.getVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  40318. var matricesWeights = parsedGeometry.matricesWeights;
  40319. var matricesWeightsExtra = parsedGeometry.matricesWeightsExtra;
  40320. var influencers = parsedGeometry.numBoneInfluencer;
  40321. var size = matricesWeights.length;
  40322. for (var i = 0; i < size; i += 4) {
  40323. var weight = 0.0;
  40324. var firstZeroWeight = -1;
  40325. for (var j = 0; j < 4; j++) {
  40326. var w = matricesWeights[i + j];
  40327. weight += w;
  40328. if (w < epsilon && firstZeroWeight < 0) {
  40329. firstZeroWeight = j;
  40330. }
  40331. }
  40332. if (matricesWeightsExtra) {
  40333. for (var j = 0; j < 4; j++) {
  40334. var w = matricesWeightsExtra[i + j];
  40335. weight += w;
  40336. if (w < epsilon && firstZeroWeight < 0) {
  40337. firstZeroWeight = j + 4;
  40338. }
  40339. }
  40340. }
  40341. if (firstZeroWeight < 0 || firstZeroWeight > (influencers - 1)) {
  40342. firstZeroWeight = influencers - 1;
  40343. }
  40344. if (weight > epsilon) {
  40345. var mweight = 1.0 / weight;
  40346. for (var j = 0; j < 4; j++) {
  40347. matricesWeights[i + j] *= mweight;
  40348. }
  40349. if (matricesWeightsExtra) {
  40350. for (var j = 0; j < 4; j++) {
  40351. matricesWeightsExtra[i + j] *= mweight;
  40352. }
  40353. }
  40354. }
  40355. else {
  40356. if (firstZeroWeight >= 4) {
  40357. matricesWeightsExtra[i + firstZeroWeight - 4] = 1.0 - weight;
  40358. matricesIndicesExtra[i + firstZeroWeight - 4] = noInfluenceBoneIndex;
  40359. }
  40360. else {
  40361. matricesWeights[i + firstZeroWeight] = 1.0 - weight;
  40362. matricesIndices[i + firstZeroWeight] = noInfluenceBoneIndex;
  40363. }
  40364. }
  40365. }
  40366. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesKind, matricesIndices);
  40367. if (parsedGeometry.matricesWeightsExtra) {
  40368. mesh.setVerticesData(BABYLON.VertexBuffer.MatricesIndicesExtraKind, matricesIndicesExtra);
  40369. }
  40370. };
  40371. /**
  40372. * Create a new geometry from persisted data (Using .babylon file format)
  40373. * @param parsedVertexData defines the persisted data
  40374. * @param scene defines the hosting scene
  40375. * @param rootUrl defines the root url to use to load assets (like delayed data)
  40376. * @returns the new geometry object
  40377. */
  40378. Geometry.Parse = function (parsedVertexData, scene, rootUrl) {
  40379. if (scene.getGeometryByID(parsedVertexData.id)) {
  40380. return null; // null since geometry could be something else than a box...
  40381. }
  40382. var geometry = new Geometry(parsedVertexData.id, scene, undefined, parsedVertexData.updatable);
  40383. if (BABYLON.Tags) {
  40384. BABYLON.Tags.AddTagsTo(geometry, parsedVertexData.tags);
  40385. }
  40386. if (parsedVertexData.delayLoadingFile) {
  40387. geometry.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  40388. geometry.delayLoadingFile = rootUrl + parsedVertexData.delayLoadingFile;
  40389. geometry._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMinimum), BABYLON.Vector3.FromArray(parsedVertexData.boundingBoxMaximum));
  40390. geometry._delayInfo = [];
  40391. if (parsedVertexData.hasUVs) {
  40392. geometry._delayInfo.push(BABYLON.VertexBuffer.UVKind);
  40393. }
  40394. if (parsedVertexData.hasUVs2) {
  40395. geometry._delayInfo.push(BABYLON.VertexBuffer.UV2Kind);
  40396. }
  40397. if (parsedVertexData.hasUVs3) {
  40398. geometry._delayInfo.push(BABYLON.VertexBuffer.UV3Kind);
  40399. }
  40400. if (parsedVertexData.hasUVs4) {
  40401. geometry._delayInfo.push(BABYLON.VertexBuffer.UV4Kind);
  40402. }
  40403. if (parsedVertexData.hasUVs5) {
  40404. geometry._delayInfo.push(BABYLON.VertexBuffer.UV5Kind);
  40405. }
  40406. if (parsedVertexData.hasUVs6) {
  40407. geometry._delayInfo.push(BABYLON.VertexBuffer.UV6Kind);
  40408. }
  40409. if (parsedVertexData.hasColors) {
  40410. geometry._delayInfo.push(BABYLON.VertexBuffer.ColorKind);
  40411. }
  40412. if (parsedVertexData.hasMatricesIndices) {
  40413. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  40414. }
  40415. if (parsedVertexData.hasMatricesWeights) {
  40416. geometry._delayInfo.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  40417. }
  40418. geometry._delayLoadingFunction = BABYLON.VertexData.ImportVertexData;
  40419. }
  40420. else {
  40421. BABYLON.VertexData.ImportVertexData(parsedVertexData, geometry);
  40422. }
  40423. scene.pushGeometry(geometry, true);
  40424. return geometry;
  40425. };
  40426. return Geometry;
  40427. }());
  40428. BABYLON.Geometry = Geometry;
  40429. // Primitives
  40430. /// Abstract class
  40431. /**
  40432. * Abstract class used to provide common services for all typed geometries
  40433. * @hidden
  40434. */
  40435. var _PrimitiveGeometry = /** @class */ (function (_super) {
  40436. __extends(_PrimitiveGeometry, _super);
  40437. /**
  40438. * Creates a new typed geometry
  40439. * @param id defines the unique ID of the geometry
  40440. * @param scene defines the hosting scene
  40441. * @param _canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40442. * @param mesh defines the hosting mesh (can be null)
  40443. */
  40444. function _PrimitiveGeometry(id, scene, _canBeRegenerated, mesh) {
  40445. if (_canBeRegenerated === void 0) { _canBeRegenerated = false; }
  40446. if (mesh === void 0) { mesh = null; }
  40447. var _this = _super.call(this, id, scene, undefined, false, mesh) || this;
  40448. _this._canBeRegenerated = _canBeRegenerated;
  40449. _this._beingRegenerated = true;
  40450. _this.regenerate();
  40451. _this._beingRegenerated = false;
  40452. return _this;
  40453. }
  40454. /**
  40455. * Gets a value indicating if the geometry supports being regenerated with new parameters (false by default)
  40456. * @returns true if the geometry can be regenerated
  40457. */
  40458. _PrimitiveGeometry.prototype.canBeRegenerated = function () {
  40459. return this._canBeRegenerated;
  40460. };
  40461. /**
  40462. * If the geometry supports regeneration, the function will recreates the geometry with updated parameter values
  40463. */
  40464. _PrimitiveGeometry.prototype.regenerate = function () {
  40465. if (!this._canBeRegenerated) {
  40466. return;
  40467. }
  40468. this._beingRegenerated = true;
  40469. this.setAllVerticesData(this._regenerateVertexData(), false);
  40470. this._beingRegenerated = false;
  40471. };
  40472. /**
  40473. * Clone the geometry
  40474. * @param id defines the unique ID of the new geometry
  40475. * @returns the new geometry
  40476. */
  40477. _PrimitiveGeometry.prototype.asNewGeometry = function (id) {
  40478. return _super.prototype.copy.call(this, id);
  40479. };
  40480. // overrides
  40481. _PrimitiveGeometry.prototype.setAllVerticesData = function (vertexData, updatable) {
  40482. if (!this._beingRegenerated) {
  40483. return;
  40484. }
  40485. _super.prototype.setAllVerticesData.call(this, vertexData, false);
  40486. };
  40487. _PrimitiveGeometry.prototype.setVerticesData = function (kind, data, updatable) {
  40488. if (!this._beingRegenerated) {
  40489. return;
  40490. }
  40491. _super.prototype.setVerticesData.call(this, kind, data, false);
  40492. };
  40493. // to override
  40494. /** @hidden */
  40495. _PrimitiveGeometry.prototype._regenerateVertexData = function () {
  40496. throw new Error("Abstract method");
  40497. };
  40498. _PrimitiveGeometry.prototype.copy = function (id) {
  40499. throw new Error("Must be overriden in sub-classes.");
  40500. };
  40501. _PrimitiveGeometry.prototype.serialize = function () {
  40502. var serializationObject = _super.prototype.serialize.call(this);
  40503. serializationObject.canBeRegenerated = this.canBeRegenerated();
  40504. return serializationObject;
  40505. };
  40506. return _PrimitiveGeometry;
  40507. }(Geometry));
  40508. BABYLON._PrimitiveGeometry = _PrimitiveGeometry;
  40509. /**
  40510. * Creates a ribbon geometry
  40511. * @description See http://doc.babylonjs.com/how_to/ribbon_tutorial, http://doc.babylonjs.com/resources/maths_make_ribbons
  40512. */
  40513. var RibbonGeometry = /** @class */ (function (_super) {
  40514. __extends(RibbonGeometry, _super);
  40515. /**
  40516. * Creates a ribbon geometry
  40517. * @param id defines the unique ID of the geometry
  40518. * @param scene defines the hosting scene
  40519. * @param pathArray defines the array of paths to use
  40520. * @param closeArray defines if the last path and the first path must be joined
  40521. * @param closePath defines if the last and first points of each path in your pathArray must be joined
  40522. * @param offset defines the offset between points
  40523. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40524. * @param mesh defines the hosting mesh (can be null)
  40525. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40526. */
  40527. function RibbonGeometry(id, scene,
  40528. /**
  40529. * Defines the array of paths to use
  40530. */
  40531. pathArray,
  40532. /**
  40533. * Defines if the last and first points of each path in your pathArray must be joined
  40534. */
  40535. closeArray,
  40536. /**
  40537. * Defines if the last and first points of each path in your pathArray must be joined
  40538. */
  40539. closePath,
  40540. /**
  40541. * Defines the offset between points
  40542. */
  40543. offset, canBeRegenerated, mesh,
  40544. /**
  40545. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40546. */
  40547. side) {
  40548. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40549. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40550. _this.pathArray = pathArray;
  40551. _this.closeArray = closeArray;
  40552. _this.closePath = closePath;
  40553. _this.offset = offset;
  40554. _this.side = side;
  40555. return _this;
  40556. }
  40557. /** @hidden */
  40558. RibbonGeometry.prototype._regenerateVertexData = function () {
  40559. return BABYLON.VertexData.CreateRibbon({ pathArray: this.pathArray, closeArray: this.closeArray, closePath: this.closePath, offset: this.offset, sideOrientation: this.side });
  40560. };
  40561. RibbonGeometry.prototype.copy = function (id) {
  40562. return new RibbonGeometry(id, this.getScene(), this.pathArray, this.closeArray, this.closePath, this.offset, this.canBeRegenerated(), undefined, this.side);
  40563. };
  40564. return RibbonGeometry;
  40565. }(_PrimitiveGeometry));
  40566. BABYLON.RibbonGeometry = RibbonGeometry;
  40567. /**
  40568. * Creates a box geometry
  40569. * @description see http://doc.babylonjs.com/how_to/set_shapes#box
  40570. */
  40571. var BoxGeometry = /** @class */ (function (_super) {
  40572. __extends(BoxGeometry, _super);
  40573. /**
  40574. * Creates a box geometry
  40575. * @param id defines the unique ID of the geometry
  40576. * @param scene defines the hosting scene
  40577. * @param size defines the zise of the box (width, height and depth are the same)
  40578. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40579. * @param mesh defines the hosting mesh (can be null)
  40580. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40581. */
  40582. function BoxGeometry(id, scene,
  40583. /**
  40584. * Defines the zise of the box (width, height and depth are the same)
  40585. */
  40586. size, canBeRegenerated, mesh,
  40587. /**
  40588. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40589. */
  40590. side) {
  40591. if (mesh === void 0) { mesh = null; }
  40592. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40593. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40594. _this.size = size;
  40595. _this.side = side;
  40596. return _this;
  40597. }
  40598. BoxGeometry.prototype._regenerateVertexData = function () {
  40599. return BABYLON.VertexData.CreateBox({ size: this.size, sideOrientation: this.side });
  40600. };
  40601. BoxGeometry.prototype.copy = function (id) {
  40602. return new BoxGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), undefined, this.side);
  40603. };
  40604. BoxGeometry.prototype.serialize = function () {
  40605. var serializationObject = _super.prototype.serialize.call(this);
  40606. serializationObject.size = this.size;
  40607. return serializationObject;
  40608. };
  40609. BoxGeometry.Parse = function (parsedBox, scene) {
  40610. if (scene.getGeometryByID(parsedBox.id)) {
  40611. return null; // null since geometry could be something else than a box...
  40612. }
  40613. var box = new BoxGeometry(parsedBox.id, scene, parsedBox.size, parsedBox.canBeRegenerated, null);
  40614. if (BABYLON.Tags) {
  40615. BABYLON.Tags.AddTagsTo(box, parsedBox.tags);
  40616. }
  40617. scene.pushGeometry(box, true);
  40618. return box;
  40619. };
  40620. return BoxGeometry;
  40621. }(_PrimitiveGeometry));
  40622. BABYLON.BoxGeometry = BoxGeometry;
  40623. /**
  40624. * Creates a sphere geometry
  40625. * @description see http://doc.babylonjs.com/how_to/set_shapes#sphere
  40626. */
  40627. var SphereGeometry = /** @class */ (function (_super) {
  40628. __extends(SphereGeometry, _super);
  40629. /**
  40630. * Create a new sphere geometry
  40631. * @param id defines the unique ID of the geometry
  40632. * @param scene defines the hosting scene
  40633. * @param segments defines the number of segments to use to create the sphere
  40634. * @param diameter defines the diameter of the sphere
  40635. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40636. * @param mesh defines the hosting mesh (can be null)
  40637. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40638. */
  40639. function SphereGeometry(id, scene,
  40640. /**
  40641. * Defines the number of segments to use to create the sphere
  40642. */
  40643. segments,
  40644. /**
  40645. * Defines the diameter of the sphere
  40646. */
  40647. diameter, canBeRegenerated, mesh,
  40648. /**
  40649. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40650. */
  40651. side) {
  40652. if (mesh === void 0) { mesh = null; }
  40653. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40654. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40655. _this.segments = segments;
  40656. _this.diameter = diameter;
  40657. _this.side = side;
  40658. return _this;
  40659. }
  40660. SphereGeometry.prototype._regenerateVertexData = function () {
  40661. return BABYLON.VertexData.CreateSphere({ segments: this.segments, diameter: this.diameter, sideOrientation: this.side });
  40662. };
  40663. SphereGeometry.prototype.copy = function (id) {
  40664. return new SphereGeometry(id, this.getScene(), this.segments, this.diameter, this.canBeRegenerated(), null, this.side);
  40665. };
  40666. SphereGeometry.prototype.serialize = function () {
  40667. var serializationObject = _super.prototype.serialize.call(this);
  40668. serializationObject.segments = this.segments;
  40669. serializationObject.diameter = this.diameter;
  40670. return serializationObject;
  40671. };
  40672. SphereGeometry.Parse = function (parsedSphere, scene) {
  40673. if (scene.getGeometryByID(parsedSphere.id)) {
  40674. return null; // null since geometry could be something else than a sphere...
  40675. }
  40676. var sphere = new SphereGeometry(parsedSphere.id, scene, parsedSphere.segments, parsedSphere.diameter, parsedSphere.canBeRegenerated, null);
  40677. if (BABYLON.Tags) {
  40678. BABYLON.Tags.AddTagsTo(sphere, parsedSphere.tags);
  40679. }
  40680. scene.pushGeometry(sphere, true);
  40681. return sphere;
  40682. };
  40683. return SphereGeometry;
  40684. }(_PrimitiveGeometry));
  40685. BABYLON.SphereGeometry = SphereGeometry;
  40686. /**
  40687. * Creates a disc geometry
  40688. * @description see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  40689. */
  40690. var DiscGeometry = /** @class */ (function (_super) {
  40691. __extends(DiscGeometry, _super);
  40692. /**
  40693. * Creates a new disc geometry
  40694. * @param id defines the unique ID of the geometry
  40695. * @param scene defines the hosting scene
  40696. * @param radius defines the radius of the disc
  40697. * @param tessellation defines the tesselation factor to apply to the disc
  40698. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40699. * @param mesh defines the hosting mesh (can be null)
  40700. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40701. */
  40702. function DiscGeometry(id, scene,
  40703. /**
  40704. * Defines the radius of the disc
  40705. */
  40706. radius,
  40707. /**
  40708. * Defines the tesselation factor to apply to the disc
  40709. */
  40710. tessellation, canBeRegenerated, mesh,
  40711. /**
  40712. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40713. */
  40714. side) {
  40715. if (mesh === void 0) { mesh = null; }
  40716. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40717. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40718. _this.radius = radius;
  40719. _this.tessellation = tessellation;
  40720. _this.side = side;
  40721. return _this;
  40722. }
  40723. DiscGeometry.prototype._regenerateVertexData = function () {
  40724. return BABYLON.VertexData.CreateDisc({ radius: this.radius, tessellation: this.tessellation, sideOrientation: this.side });
  40725. };
  40726. DiscGeometry.prototype.copy = function (id) {
  40727. return new DiscGeometry(id, this.getScene(), this.radius, this.tessellation, this.canBeRegenerated(), null, this.side);
  40728. };
  40729. return DiscGeometry;
  40730. }(_PrimitiveGeometry));
  40731. BABYLON.DiscGeometry = DiscGeometry;
  40732. /**
  40733. * Creates a new cylinder geometry
  40734. * @description see http://doc.babylonjs.com/how_to/set_shapes#cylinder-or-cone
  40735. */
  40736. var CylinderGeometry = /** @class */ (function (_super) {
  40737. __extends(CylinderGeometry, _super);
  40738. /**
  40739. * Creates a new cylinder geometry
  40740. * @param id defines the unique ID of the geometry
  40741. * @param scene defines the hosting scene
  40742. * @param height defines the height of the cylinder
  40743. * @param diameterTop defines the diameter of the cylinder's top cap
  40744. * @param diameterBottom defines the diameter of the cylinder's bottom cap
  40745. * @param tessellation defines the tessellation factor to apply to the cylinder (number of radial sides)
  40746. * @param subdivisions defines the number of subdivisions to apply to the cylinder (number of rings) (1 by default)
  40747. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40748. * @param mesh defines the hosting mesh (can be null)
  40749. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40750. */
  40751. function CylinderGeometry(id, scene,
  40752. /**
  40753. * Defines the height of the cylinder
  40754. */
  40755. height,
  40756. /**
  40757. * Defines the diameter of the cylinder's top cap
  40758. */
  40759. diameterTop,
  40760. /**
  40761. * Defines the diameter of the cylinder's bottom cap
  40762. */
  40763. diameterBottom,
  40764. /**
  40765. * Defines the tessellation factor to apply to the cylinder
  40766. */
  40767. tessellation,
  40768. /**
  40769. * Defines the number of subdivisions to apply to the cylinder (1 by default)
  40770. */
  40771. subdivisions, canBeRegenerated, mesh,
  40772. /**
  40773. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40774. */
  40775. side) {
  40776. if (subdivisions === void 0) { subdivisions = 1; }
  40777. if (mesh === void 0) { mesh = null; }
  40778. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40779. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40780. _this.height = height;
  40781. _this.diameterTop = diameterTop;
  40782. _this.diameterBottom = diameterBottom;
  40783. _this.tessellation = tessellation;
  40784. _this.subdivisions = subdivisions;
  40785. _this.side = side;
  40786. return _this;
  40787. }
  40788. CylinderGeometry.prototype._regenerateVertexData = function () {
  40789. return BABYLON.VertexData.CreateCylinder({ height: this.height, diameterTop: this.diameterTop, diameterBottom: this.diameterBottom, tessellation: this.tessellation, subdivisions: this.subdivisions, sideOrientation: this.side });
  40790. };
  40791. CylinderGeometry.prototype.copy = function (id) {
  40792. return new CylinderGeometry(id, this.getScene(), this.height, this.diameterTop, this.diameterBottom, this.tessellation, this.subdivisions, this.canBeRegenerated(), null, this.side);
  40793. };
  40794. CylinderGeometry.prototype.serialize = function () {
  40795. var serializationObject = _super.prototype.serialize.call(this);
  40796. serializationObject.height = this.height;
  40797. serializationObject.diameterTop = this.diameterTop;
  40798. serializationObject.diameterBottom = this.diameterBottom;
  40799. serializationObject.tessellation = this.tessellation;
  40800. return serializationObject;
  40801. };
  40802. CylinderGeometry.Parse = function (parsedCylinder, scene) {
  40803. if (scene.getGeometryByID(parsedCylinder.id)) {
  40804. return null; // null since geometry could be something else than a cylinder...
  40805. }
  40806. var cylinder = new CylinderGeometry(parsedCylinder.id, scene, parsedCylinder.height, parsedCylinder.diameterTop, parsedCylinder.diameterBottom, parsedCylinder.tessellation, parsedCylinder.subdivisions, parsedCylinder.canBeRegenerated, null);
  40807. if (BABYLON.Tags) {
  40808. BABYLON.Tags.AddTagsTo(cylinder, parsedCylinder.tags);
  40809. }
  40810. scene.pushGeometry(cylinder, true);
  40811. return cylinder;
  40812. };
  40813. return CylinderGeometry;
  40814. }(_PrimitiveGeometry));
  40815. BABYLON.CylinderGeometry = CylinderGeometry;
  40816. /**
  40817. * Creates a new torus geometry
  40818. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus
  40819. */
  40820. var TorusGeometry = /** @class */ (function (_super) {
  40821. __extends(TorusGeometry, _super);
  40822. /**
  40823. * Creates a new torus geometry
  40824. * @param id defines the unique ID of the geometry
  40825. * @param scene defines the hosting scene
  40826. * @param diameter defines the diameter of the torus
  40827. * @param thickness defines the thickness of the torus (ie. internal diameter)
  40828. * @param tessellation defines the tesselation factor to apply to the torus (number of segments along the circle)
  40829. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40830. * @param mesh defines the hosting mesh (can be null)
  40831. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40832. */
  40833. function TorusGeometry(id, scene,
  40834. /**
  40835. * Defines the diameter of the torus
  40836. */
  40837. diameter,
  40838. /**
  40839. * Defines the thickness of the torus (ie. internal diameter)
  40840. */
  40841. thickness,
  40842. /**
  40843. * Defines the tesselation factor to apply to the torus
  40844. */
  40845. tessellation, canBeRegenerated, mesh,
  40846. /**
  40847. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  40848. */
  40849. side) {
  40850. if (mesh === void 0) { mesh = null; }
  40851. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  40852. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40853. _this.diameter = diameter;
  40854. _this.thickness = thickness;
  40855. _this.tessellation = tessellation;
  40856. _this.side = side;
  40857. return _this;
  40858. }
  40859. TorusGeometry.prototype._regenerateVertexData = function () {
  40860. return BABYLON.VertexData.CreateTorus({ diameter: this.diameter, thickness: this.thickness, tessellation: this.tessellation, sideOrientation: this.side });
  40861. };
  40862. TorusGeometry.prototype.copy = function (id) {
  40863. return new TorusGeometry(id, this.getScene(), this.diameter, this.thickness, this.tessellation, this.canBeRegenerated(), null, this.side);
  40864. };
  40865. TorusGeometry.prototype.serialize = function () {
  40866. var serializationObject = _super.prototype.serialize.call(this);
  40867. serializationObject.diameter = this.diameter;
  40868. serializationObject.thickness = this.thickness;
  40869. serializationObject.tessellation = this.tessellation;
  40870. return serializationObject;
  40871. };
  40872. TorusGeometry.Parse = function (parsedTorus, scene) {
  40873. if (scene.getGeometryByID(parsedTorus.id)) {
  40874. return null; // null since geometry could be something else than a torus...
  40875. }
  40876. var torus = new TorusGeometry(parsedTorus.id, scene, parsedTorus.diameter, parsedTorus.thickness, parsedTorus.tessellation, parsedTorus.canBeRegenerated, null);
  40877. if (BABYLON.Tags) {
  40878. BABYLON.Tags.AddTagsTo(torus, parsedTorus.tags);
  40879. }
  40880. scene.pushGeometry(torus, true);
  40881. return torus;
  40882. };
  40883. return TorusGeometry;
  40884. }(_PrimitiveGeometry));
  40885. BABYLON.TorusGeometry = TorusGeometry;
  40886. /**
  40887. * Creates a new ground geometry
  40888. * @description see http://doc.babylonjs.com/how_to/set_shapes#ground
  40889. */
  40890. var GroundGeometry = /** @class */ (function (_super) {
  40891. __extends(GroundGeometry, _super);
  40892. /**
  40893. * Creates a new ground geometry
  40894. * @param id defines the unique ID of the geometry
  40895. * @param scene defines the hosting scene
  40896. * @param width defines the width of the ground
  40897. * @param height defines the height of the ground
  40898. * @param subdivisions defines the subdivisions to apply to the ground
  40899. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40900. * @param mesh defines the hosting mesh (can be null)
  40901. */
  40902. function GroundGeometry(id, scene,
  40903. /**
  40904. * Defines the width of the ground
  40905. */
  40906. width,
  40907. /**
  40908. * Defines the height of the ground
  40909. */
  40910. height,
  40911. /**
  40912. * Defines the subdivisions to apply to the ground
  40913. */
  40914. subdivisions, canBeRegenerated, mesh) {
  40915. if (mesh === void 0) { mesh = null; }
  40916. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40917. _this.width = width;
  40918. _this.height = height;
  40919. _this.subdivisions = subdivisions;
  40920. return _this;
  40921. }
  40922. GroundGeometry.prototype._regenerateVertexData = function () {
  40923. return BABYLON.VertexData.CreateGround({ width: this.width, height: this.height, subdivisions: this.subdivisions });
  40924. };
  40925. GroundGeometry.prototype.copy = function (id) {
  40926. return new GroundGeometry(id, this.getScene(), this.width, this.height, this.subdivisions, this.canBeRegenerated(), null);
  40927. };
  40928. GroundGeometry.prototype.serialize = function () {
  40929. var serializationObject = _super.prototype.serialize.call(this);
  40930. serializationObject.width = this.width;
  40931. serializationObject.height = this.height;
  40932. serializationObject.subdivisions = this.subdivisions;
  40933. return serializationObject;
  40934. };
  40935. GroundGeometry.Parse = function (parsedGround, scene) {
  40936. if (scene.getGeometryByID(parsedGround.id)) {
  40937. return null; // null since geometry could be something else than a ground...
  40938. }
  40939. var ground = new GroundGeometry(parsedGround.id, scene, parsedGround.width, parsedGround.height, parsedGround.subdivisions, parsedGround.canBeRegenerated, null);
  40940. if (BABYLON.Tags) {
  40941. BABYLON.Tags.AddTagsTo(ground, parsedGround.tags);
  40942. }
  40943. scene.pushGeometry(ground, true);
  40944. return ground;
  40945. };
  40946. return GroundGeometry;
  40947. }(_PrimitiveGeometry));
  40948. BABYLON.GroundGeometry = GroundGeometry;
  40949. /**
  40950. * Creates a tiled ground geometry
  40951. * @description see http://doc.babylonjs.com/how_to/set_shapes#tiled-ground
  40952. */
  40953. var TiledGroundGeometry = /** @class */ (function (_super) {
  40954. __extends(TiledGroundGeometry, _super);
  40955. /**
  40956. * Creates a tiled ground geometry
  40957. * @param id defines the unique ID of the geometry
  40958. * @param scene defines the hosting scene
  40959. * @param xmin defines the minimum value on X axis
  40960. * @param zmin defines the minimum value on Z axis
  40961. * @param xmax defines the maximum value on X axis
  40962. * @param zmax defines the maximum value on Z axis
  40963. * @param subdivisions defines the subdivisions to apply to the ground (number of subdivisions (tiles) on the height and the width of the map)
  40964. * @param precision defines the precision to use when computing the tiles
  40965. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  40966. * @param mesh defines the hosting mesh (can be null)
  40967. */
  40968. function TiledGroundGeometry(id, scene,
  40969. /**
  40970. * Defines the minimum value on X axis
  40971. */
  40972. xmin,
  40973. /**
  40974. * Defines the minimum value on Z axis
  40975. */
  40976. zmin,
  40977. /**
  40978. * Defines the maximum value on X axis
  40979. */
  40980. xmax,
  40981. /**
  40982. * Defines the maximum value on Z axis
  40983. */
  40984. zmax,
  40985. /**
  40986. * Defines the subdivisions to apply to the ground
  40987. */
  40988. subdivisions,
  40989. /**
  40990. * Defines the precision to use when computing the tiles
  40991. */
  40992. precision, canBeRegenerated, mesh) {
  40993. if (mesh === void 0) { mesh = null; }
  40994. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  40995. _this.xmin = xmin;
  40996. _this.zmin = zmin;
  40997. _this.xmax = xmax;
  40998. _this.zmax = zmax;
  40999. _this.subdivisions = subdivisions;
  41000. _this.precision = precision;
  41001. return _this;
  41002. }
  41003. TiledGroundGeometry.prototype._regenerateVertexData = function () {
  41004. return BABYLON.VertexData.CreateTiledGround({ xmin: this.xmin, zmin: this.zmin, xmax: this.xmax, zmax: this.zmax, subdivisions: this.subdivisions, precision: this.precision });
  41005. };
  41006. TiledGroundGeometry.prototype.copy = function (id) {
  41007. return new TiledGroundGeometry(id, this.getScene(), this.xmin, this.zmin, this.xmax, this.zmax, this.subdivisions, this.precision, this.canBeRegenerated(), null);
  41008. };
  41009. return TiledGroundGeometry;
  41010. }(_PrimitiveGeometry));
  41011. BABYLON.TiledGroundGeometry = TiledGroundGeometry;
  41012. /**
  41013. * Creates a plane geometry
  41014. * @description see http://doc.babylonjs.com/how_to/set_shapes#plane
  41015. */
  41016. var PlaneGeometry = /** @class */ (function (_super) {
  41017. __extends(PlaneGeometry, _super);
  41018. /**
  41019. * Creates a plane geometry
  41020. * @param id defines the unique ID of the geometry
  41021. * @param scene defines the hosting scene
  41022. * @param size defines the size of the plane (width === height)
  41023. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41024. * @param mesh defines the hosting mesh (can be null)
  41025. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41026. */
  41027. function PlaneGeometry(id, scene,
  41028. /**
  41029. * Defines the size of the plane (width === height)
  41030. */
  41031. size, canBeRegenerated, mesh,
  41032. /**
  41033. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41034. */
  41035. side) {
  41036. if (mesh === void 0) { mesh = null; }
  41037. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41038. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41039. _this.size = size;
  41040. _this.side = side;
  41041. return _this;
  41042. }
  41043. PlaneGeometry.prototype._regenerateVertexData = function () {
  41044. return BABYLON.VertexData.CreatePlane({ size: this.size, sideOrientation: this.side });
  41045. };
  41046. PlaneGeometry.prototype.copy = function (id) {
  41047. return new PlaneGeometry(id, this.getScene(), this.size, this.canBeRegenerated(), null, this.side);
  41048. };
  41049. PlaneGeometry.prototype.serialize = function () {
  41050. var serializationObject = _super.prototype.serialize.call(this);
  41051. serializationObject.size = this.size;
  41052. return serializationObject;
  41053. };
  41054. PlaneGeometry.Parse = function (parsedPlane, scene) {
  41055. if (scene.getGeometryByID(parsedPlane.id)) {
  41056. return null; // null since geometry could be something else than a ground...
  41057. }
  41058. var plane = new PlaneGeometry(parsedPlane.id, scene, parsedPlane.size, parsedPlane.canBeRegenerated, null);
  41059. if (BABYLON.Tags) {
  41060. BABYLON.Tags.AddTagsTo(plane, parsedPlane.tags);
  41061. }
  41062. scene.pushGeometry(plane, true);
  41063. return plane;
  41064. };
  41065. return PlaneGeometry;
  41066. }(_PrimitiveGeometry));
  41067. BABYLON.PlaneGeometry = PlaneGeometry;
  41068. /**
  41069. * Creates a torus knot geometry
  41070. * @description see http://doc.babylonjs.com/how_to/set_shapes#torus-knot
  41071. */
  41072. var TorusKnotGeometry = /** @class */ (function (_super) {
  41073. __extends(TorusKnotGeometry, _super);
  41074. /**
  41075. * Creates a torus knot geometry
  41076. * @param id defines the unique ID of the geometry
  41077. * @param scene defines the hosting scene
  41078. * @param radius defines the radius of the torus knot
  41079. * @param tube defines the thickness of the torus knot tube
  41080. * @param radialSegments defines the number of radial segments
  41081. * @param tubularSegments defines the number of tubular segments
  41082. * @param p defines the first number of windings
  41083. * @param q defines the second number of windings
  41084. * @param canBeRegenerated defines if the geometry supports being regenerated with new parameters (false by default)
  41085. * @param mesh defines the hosting mesh (can be null)
  41086. * @param side defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41087. */
  41088. function TorusKnotGeometry(id, scene,
  41089. /**
  41090. * Defines the radius of the torus knot
  41091. */
  41092. radius,
  41093. /**
  41094. * Defines the thickness of the torus knot tube
  41095. */
  41096. tube,
  41097. /**
  41098. * Defines the number of radial segments
  41099. */
  41100. radialSegments,
  41101. /**
  41102. * Defines the number of tubular segments
  41103. */
  41104. tubularSegments,
  41105. /**
  41106. * Defines the first number of windings
  41107. */
  41108. p,
  41109. /**
  41110. * Defines the second number of windings
  41111. */
  41112. q, canBeRegenerated, mesh,
  41113. /**
  41114. * Defines if the created geometry is double sided or not (default is BABYLON.Mesh.DEFAULTSIDE)
  41115. */
  41116. side) {
  41117. if (mesh === void 0) { mesh = null; }
  41118. if (side === void 0) { side = BABYLON.Mesh.DEFAULTSIDE; }
  41119. var _this = _super.call(this, id, scene, canBeRegenerated, mesh) || this;
  41120. _this.radius = radius;
  41121. _this.tube = tube;
  41122. _this.radialSegments = radialSegments;
  41123. _this.tubularSegments = tubularSegments;
  41124. _this.p = p;
  41125. _this.q = q;
  41126. _this.side = side;
  41127. return _this;
  41128. }
  41129. TorusKnotGeometry.prototype._regenerateVertexData = function () {
  41130. 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 });
  41131. };
  41132. TorusKnotGeometry.prototype.copy = function (id) {
  41133. return new TorusKnotGeometry(id, this.getScene(), this.radius, this.tube, this.radialSegments, this.tubularSegments, this.p, this.q, this.canBeRegenerated(), null, this.side);
  41134. };
  41135. TorusKnotGeometry.prototype.serialize = function () {
  41136. var serializationObject = _super.prototype.serialize.call(this);
  41137. serializationObject.radius = this.radius;
  41138. serializationObject.tube = this.tube;
  41139. serializationObject.radialSegments = this.radialSegments;
  41140. serializationObject.tubularSegments = this.tubularSegments;
  41141. serializationObject.p = this.p;
  41142. serializationObject.q = this.q;
  41143. return serializationObject;
  41144. };
  41145. ;
  41146. TorusKnotGeometry.Parse = function (parsedTorusKnot, scene) {
  41147. if (scene.getGeometryByID(parsedTorusKnot.id)) {
  41148. return null; // null since geometry could be something else than a ground...
  41149. }
  41150. var torusKnot = new TorusKnotGeometry(parsedTorusKnot.id, scene, parsedTorusKnot.radius, parsedTorusKnot.tube, parsedTorusKnot.radialSegments, parsedTorusKnot.tubularSegments, parsedTorusKnot.p, parsedTorusKnot.q, parsedTorusKnot.canBeRegenerated, null);
  41151. if (BABYLON.Tags) {
  41152. BABYLON.Tags.AddTagsTo(torusKnot, parsedTorusKnot.tags);
  41153. }
  41154. scene.pushGeometry(torusKnot, true);
  41155. return torusKnot;
  41156. };
  41157. return TorusKnotGeometry;
  41158. }(_PrimitiveGeometry));
  41159. BABYLON.TorusKnotGeometry = TorusKnotGeometry;
  41160. //}
  41161. })(BABYLON || (BABYLON = {}));
  41162. //# sourceMappingURL=babylon.geometry.js.map
  41163. var BABYLON;
  41164. (function (BABYLON) {
  41165. /**
  41166. * Performance monitor tracks rolling average frame-time and frame-time variance over a user defined sliding-window
  41167. */
  41168. var PerformanceMonitor = /** @class */ (function () {
  41169. /**
  41170. * constructor
  41171. * @param frameSampleSize The number of samples required to saturate the sliding window
  41172. */
  41173. function PerformanceMonitor(frameSampleSize) {
  41174. if (frameSampleSize === void 0) { frameSampleSize = 30; }
  41175. this._enabled = true;
  41176. this._rollingFrameTime = new RollingAverage(frameSampleSize);
  41177. }
  41178. /**
  41179. * Samples current frame
  41180. * @param timeMs A timestamp in milliseconds of the current frame to compare with other frames
  41181. */
  41182. PerformanceMonitor.prototype.sampleFrame = function (timeMs) {
  41183. if (timeMs === void 0) { timeMs = BABYLON.Tools.Now; }
  41184. if (!this._enabled)
  41185. return;
  41186. if (this._lastFrameTimeMs != null) {
  41187. var dt = timeMs - this._lastFrameTimeMs;
  41188. this._rollingFrameTime.add(dt);
  41189. }
  41190. this._lastFrameTimeMs = timeMs;
  41191. };
  41192. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTime", {
  41193. /**
  41194. * Returns the average frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41195. * @return Average frame time in milliseconds
  41196. */
  41197. get: function () {
  41198. return this._rollingFrameTime.average;
  41199. },
  41200. enumerable: true,
  41201. configurable: true
  41202. });
  41203. Object.defineProperty(PerformanceMonitor.prototype, "averageFrameTimeVariance", {
  41204. /**
  41205. * Returns the variance frame time in milliseconds over the sliding window (or the subset of frames sampled so far)
  41206. * @return Frame time variance in milliseconds squared
  41207. */
  41208. get: function () {
  41209. return this._rollingFrameTime.variance;
  41210. },
  41211. enumerable: true,
  41212. configurable: true
  41213. });
  41214. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFrameTime", {
  41215. /**
  41216. * Returns the frame time of the most recent frame
  41217. * @return Frame time in milliseconds
  41218. */
  41219. get: function () {
  41220. return this._rollingFrameTime.history(0);
  41221. },
  41222. enumerable: true,
  41223. configurable: true
  41224. });
  41225. Object.defineProperty(PerformanceMonitor.prototype, "averageFPS", {
  41226. /**
  41227. * Returns the average framerate in frames per second over the sliding window (or the subset of frames sampled so far)
  41228. * @return Framerate in frames per second
  41229. */
  41230. get: function () {
  41231. return 1000.0 / this._rollingFrameTime.average;
  41232. },
  41233. enumerable: true,
  41234. configurable: true
  41235. });
  41236. Object.defineProperty(PerformanceMonitor.prototype, "instantaneousFPS", {
  41237. /**
  41238. * Returns the average framerate in frames per second using the most recent frame time
  41239. * @return Framerate in frames per second
  41240. */
  41241. get: function () {
  41242. var history = this._rollingFrameTime.history(0);
  41243. if (history === 0) {
  41244. return 0;
  41245. }
  41246. return 1000.0 / history;
  41247. },
  41248. enumerable: true,
  41249. configurable: true
  41250. });
  41251. Object.defineProperty(PerformanceMonitor.prototype, "isSaturated", {
  41252. /**
  41253. * Returns true if enough samples have been taken to completely fill the sliding window
  41254. * @return true if saturated
  41255. */
  41256. get: function () {
  41257. return this._rollingFrameTime.isSaturated();
  41258. },
  41259. enumerable: true,
  41260. configurable: true
  41261. });
  41262. /**
  41263. * Enables contributions to the sliding window sample set
  41264. */
  41265. PerformanceMonitor.prototype.enable = function () {
  41266. this._enabled = true;
  41267. };
  41268. /**
  41269. * Disables contributions to the sliding window sample set
  41270. * Samples will not be interpolated over the disabled period
  41271. */
  41272. PerformanceMonitor.prototype.disable = function () {
  41273. this._enabled = false;
  41274. //clear last sample to avoid interpolating over the disabled period when next enabled
  41275. this._lastFrameTimeMs = null;
  41276. };
  41277. Object.defineProperty(PerformanceMonitor.prototype, "isEnabled", {
  41278. /**
  41279. * Returns true if sampling is enabled
  41280. * @return true if enabled
  41281. */
  41282. get: function () {
  41283. return this._enabled;
  41284. },
  41285. enumerable: true,
  41286. configurable: true
  41287. });
  41288. /**
  41289. * Resets performance monitor
  41290. */
  41291. PerformanceMonitor.prototype.reset = function () {
  41292. //clear last sample to avoid interpolating over the disabled period when next enabled
  41293. this._lastFrameTimeMs = null;
  41294. //wipe record
  41295. this._rollingFrameTime.reset();
  41296. };
  41297. return PerformanceMonitor;
  41298. }());
  41299. BABYLON.PerformanceMonitor = PerformanceMonitor;
  41300. /**
  41301. * RollingAverage
  41302. *
  41303. * Utility to efficiently compute the rolling average and variance over a sliding window of samples
  41304. */
  41305. var RollingAverage = /** @class */ (function () {
  41306. /**
  41307. * constructor
  41308. * @param length The number of samples required to saturate the sliding window
  41309. */
  41310. function RollingAverage(length) {
  41311. this._samples = new Array(length);
  41312. this.reset();
  41313. }
  41314. /**
  41315. * Adds a sample to the sample set
  41316. * @param v The sample value
  41317. */
  41318. RollingAverage.prototype.add = function (v) {
  41319. //http://en.wikipedia.org/wiki/Algorithms_for_calculating_variance
  41320. var delta;
  41321. //we need to check if we've already wrapped round
  41322. if (this.isSaturated()) {
  41323. //remove bottom of stack from mean
  41324. var bottomValue = this._samples[this._pos];
  41325. delta = bottomValue - this.average;
  41326. this.average -= delta / (this._sampleCount - 1);
  41327. this._m2 -= delta * (bottomValue - this.average);
  41328. }
  41329. else {
  41330. this._sampleCount++;
  41331. }
  41332. //add new value to mean
  41333. delta = v - this.average;
  41334. this.average += delta / (this._sampleCount);
  41335. this._m2 += delta * (v - this.average);
  41336. //set the new variance
  41337. this.variance = this._m2 / (this._sampleCount - 1);
  41338. this._samples[this._pos] = v;
  41339. this._pos++;
  41340. this._pos %= this._samples.length; //positive wrap around
  41341. };
  41342. /**
  41343. * Returns previously added values or null if outside of history or outside the sliding window domain
  41344. * @param i Index in history. For example, pass 0 for the most recent value and 1 for the value before that
  41345. * @return Value previously recorded with add() or null if outside of range
  41346. */
  41347. RollingAverage.prototype.history = function (i) {
  41348. if ((i >= this._sampleCount) || (i >= this._samples.length)) {
  41349. return 0;
  41350. }
  41351. var i0 = this._wrapPosition(this._pos - 1.0);
  41352. return this._samples[this._wrapPosition(i0 - i)];
  41353. };
  41354. /**
  41355. * Returns true if enough samples have been taken to completely fill the sliding window
  41356. * @return true if sample-set saturated
  41357. */
  41358. RollingAverage.prototype.isSaturated = function () {
  41359. return this._sampleCount >= this._samples.length;
  41360. };
  41361. /**
  41362. * Resets the rolling average (equivalent to 0 samples taken so far)
  41363. */
  41364. RollingAverage.prototype.reset = function () {
  41365. this.average = 0;
  41366. this.variance = 0;
  41367. this._sampleCount = 0;
  41368. this._pos = 0;
  41369. this._m2 = 0;
  41370. };
  41371. /**
  41372. * Wraps a value around the sample range boundaries
  41373. * @param i Position in sample range, for example if the sample length is 5, and i is -3, then 2 will be returned.
  41374. * @return Wrapped position in sample range
  41375. */
  41376. RollingAverage.prototype._wrapPosition = function (i) {
  41377. var max = this._samples.length;
  41378. return ((i % max) + max) % max;
  41379. };
  41380. return RollingAverage;
  41381. }());
  41382. BABYLON.RollingAverage = RollingAverage;
  41383. })(BABYLON || (BABYLON = {}));
  41384. //# sourceMappingURL=babylon.performanceMonitor.js.map
  41385. var BABYLON;
  41386. (function (BABYLON) {
  41387. /**
  41388. * "Static Class" containing the most commonly used helper while dealing with material for
  41389. * rendering purpose.
  41390. *
  41391. * It contains the basic tools to help defining defines, binding uniform for the common part of the materials.
  41392. *
  41393. * This works by convention in BabylonJS but is meant to be use only with shader following the in place naming rules and conventions.
  41394. */
  41395. var MaterialHelper = /** @class */ (function () {
  41396. function MaterialHelper() {
  41397. }
  41398. /**
  41399. * Bind the current view position to an effect.
  41400. * @param effect The effect to be bound
  41401. * @param scene The scene the eyes position is used from
  41402. */
  41403. MaterialHelper.BindEyePosition = function (effect, scene) {
  41404. if (scene._forcedViewPosition) {
  41405. effect.setVector3("vEyePosition", scene._forcedViewPosition);
  41406. return;
  41407. }
  41408. effect.setVector3("vEyePosition", scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  41409. };
  41410. /**
  41411. * Helps preparing the defines values about the UVs in used in the effect.
  41412. * UVs are shared as much as we can accross chanels in the shaders.
  41413. * @param texture The texture we are preparing the UVs for
  41414. * @param defines The defines to update
  41415. * @param key The chanel key "diffuse", "specular"... used in the shader
  41416. */
  41417. MaterialHelper.PrepareDefinesForMergedUV = function (texture, defines, key) {
  41418. defines._needUVs = true;
  41419. defines[key] = true;
  41420. if (texture.getTextureMatrix().isIdentity(true)) {
  41421. defines[key + "DIRECTUV"] = texture.coordinatesIndex + 1;
  41422. if (texture.coordinatesIndex === 0) {
  41423. defines["MAINUV1"] = true;
  41424. }
  41425. else {
  41426. defines["MAINUV2"] = true;
  41427. }
  41428. }
  41429. else {
  41430. defines[key + "DIRECTUV"] = 0;
  41431. }
  41432. };
  41433. /**
  41434. * Binds a texture matrix value to its corrsponding uniform
  41435. * @param texture The texture to bind the matrix for
  41436. * @param uniformBuffer The uniform buffer receivin the data
  41437. * @param key The chanel key "diffuse", "specular"... used in the shader
  41438. */
  41439. MaterialHelper.BindTextureMatrix = function (texture, uniformBuffer, key) {
  41440. var matrix = texture.getTextureMatrix();
  41441. if (!matrix.isIdentity(true)) {
  41442. uniformBuffer.updateMatrix(key + "Matrix", matrix);
  41443. }
  41444. };
  41445. /**
  41446. * Helper used to prepare the list of defines associated with misc. values for shader compilation
  41447. * @param mesh defines the current mesh
  41448. * @param scene defines the current scene
  41449. * @param useLogarithmicDepth defines if logarithmic depth has to be turned on
  41450. * @param pointsCloud defines if point cloud rendering has to be turned on
  41451. * @param fogEnabled defines if fog has to be turned on
  41452. * @param alphaTest defines if alpha testing has to be turned on
  41453. * @param defines defines the current list of defines
  41454. */
  41455. MaterialHelper.PrepareDefinesForMisc = function (mesh, scene, useLogarithmicDepth, pointsCloud, fogEnabled, alphaTest, defines) {
  41456. if (defines._areMiscDirty) {
  41457. defines["LOGARITHMICDEPTH"] = useLogarithmicDepth;
  41458. defines["POINTSIZE"] = pointsCloud;
  41459. defines["FOG"] = (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && fogEnabled);
  41460. defines["NONUNIFORMSCALING"] = mesh.nonUniformScaling;
  41461. defines["ALPHATEST"] = alphaTest;
  41462. }
  41463. };
  41464. /**
  41465. * Helper used to prepare the list of defines associated with frame values for shader compilation
  41466. * @param scene defines the current scene
  41467. * @param engine defines the current engine
  41468. * @param defines specifies the list of active defines
  41469. * @param useInstances defines if instances have to be turned on
  41470. * @param useClipPlane defines if clip plane have to be turned on
  41471. */
  41472. MaterialHelper.PrepareDefinesForFrameBoundValues = function (scene, engine, defines, useInstances, useClipPlane) {
  41473. if (useClipPlane === void 0) { useClipPlane = null; }
  41474. var changed = false;
  41475. if (useClipPlane == null) {
  41476. useClipPlane = (scene.clipPlane !== undefined && scene.clipPlane !== null);
  41477. }
  41478. if (defines["CLIPPLANE"] !== useClipPlane) {
  41479. defines["CLIPPLANE"] = useClipPlane;
  41480. changed = true;
  41481. }
  41482. if (defines["DEPTHPREPASS"] !== !engine.getColorWrite()) {
  41483. defines["DEPTHPREPASS"] = !defines["DEPTHPREPASS"];
  41484. changed = true;
  41485. }
  41486. if (defines["INSTANCES"] !== useInstances) {
  41487. defines["INSTANCES"] = useInstances;
  41488. changed = true;
  41489. }
  41490. if (changed) {
  41491. defines.markAsUnprocessed();
  41492. }
  41493. };
  41494. /**
  41495. * Prepares the defines used in the shader depending on the attributes data available in the mesh
  41496. * @param mesh The mesh containing the geometry data we will draw
  41497. * @param defines The defines to update
  41498. * @param useVertexColor Precise whether vertex colors should be used or not (override mesh info)
  41499. * @param useBones Precise whether bones should be used or not (override mesh info)
  41500. * @param useMorphTargets Precise whether morph targets should be used or not (override mesh info)
  41501. * @param useVertexAlpha Precise whether vertex alpha should be used or not (override mesh info)
  41502. * @returns false if defines are considered not dirty and have not been checked
  41503. */
  41504. MaterialHelper.PrepareDefinesForAttributes = function (mesh, defines, useVertexColor, useBones, useMorphTargets, useVertexAlpha) {
  41505. if (useMorphTargets === void 0) { useMorphTargets = false; }
  41506. if (useVertexAlpha === void 0) { useVertexAlpha = true; }
  41507. if (!defines._areAttributesDirty && defines._needNormals === defines._normals && defines._needUVs === defines._uvs) {
  41508. return false;
  41509. }
  41510. defines._normals = defines._needNormals;
  41511. defines._uvs = defines._needUVs;
  41512. defines["NORMAL"] = (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  41513. if (defines._needNormals && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  41514. defines["TANGENT"] = true;
  41515. }
  41516. if (defines._needUVs) {
  41517. defines["UV1"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind);
  41518. defines["UV2"] = mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind);
  41519. }
  41520. else {
  41521. defines["UV1"] = false;
  41522. defines["UV2"] = false;
  41523. }
  41524. if (useVertexColor) {
  41525. var hasVertexColors = mesh.useVertexColors && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind);
  41526. defines["VERTEXCOLOR"] = hasVertexColors;
  41527. defines["VERTEXALPHA"] = mesh.hasVertexAlpha && hasVertexColors && useVertexAlpha;
  41528. }
  41529. if (useBones) {
  41530. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41531. defines["NUM_BONE_INFLUENCERS"] = mesh.numBoneInfluencers;
  41532. defines["BonesPerMesh"] = (mesh.skeleton.bones.length + 1);
  41533. }
  41534. else {
  41535. defines["NUM_BONE_INFLUENCERS"] = 0;
  41536. defines["BonesPerMesh"] = 0;
  41537. }
  41538. }
  41539. if (useMorphTargets) {
  41540. var manager = mesh.morphTargetManager;
  41541. if (manager) {
  41542. defines["MORPHTARGETS_TANGENT"] = manager.supportsTangents && defines["TANGENT"];
  41543. defines["MORPHTARGETS_NORMAL"] = manager.supportsNormals && defines["NORMAL"];
  41544. defines["MORPHTARGETS"] = (manager.numInfluencers > 0);
  41545. defines["NUM_MORPH_INFLUENCERS"] = manager.numInfluencers;
  41546. }
  41547. else {
  41548. defines["MORPHTARGETS_TANGENT"] = false;
  41549. defines["MORPHTARGETS_NORMAL"] = false;
  41550. defines["MORPHTARGETS"] = false;
  41551. defines["NUM_MORPH_INFLUENCERS"] = 0;
  41552. }
  41553. }
  41554. return true;
  41555. };
  41556. /**
  41557. * Prepares the defines related to the light information passed in parameter
  41558. * @param scene The scene we are intending to draw
  41559. * @param mesh The mesh the effect is compiling for
  41560. * @param defines The defines to update
  41561. * @param specularSupported Specifies whether specular is supported or not (override lights data)
  41562. * @param maxSimultaneousLights Specfies how manuy lights can be added to the effect at max
  41563. * @param disableLighting Specifies whether the lighting is disabled (override scene and light)
  41564. * @returns true if normals will be required for the rest of the effect
  41565. */
  41566. MaterialHelper.PrepareDefinesForLights = function (scene, mesh, defines, specularSupported, maxSimultaneousLights, disableLighting) {
  41567. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41568. if (disableLighting === void 0) { disableLighting = false; }
  41569. if (!defines._areLightsDirty) {
  41570. return defines._needNormals;
  41571. }
  41572. var lightIndex = 0;
  41573. var needNormals = false;
  41574. var needRebuild = false;
  41575. var lightmapMode = false;
  41576. var shadowEnabled = false;
  41577. var specularEnabled = false;
  41578. if (scene.lightsEnabled && !disableLighting) {
  41579. for (var _i = 0, _a = mesh._lightSources; _i < _a.length; _i++) {
  41580. var light = _a[_i];
  41581. needNormals = true;
  41582. if (defines["LIGHT" + lightIndex] === undefined) {
  41583. needRebuild = true;
  41584. }
  41585. defines["LIGHT" + lightIndex] = true;
  41586. defines["SPOTLIGHT" + lightIndex] = false;
  41587. defines["HEMILIGHT" + lightIndex] = false;
  41588. defines["POINTLIGHT" + lightIndex] = false;
  41589. defines["DIRLIGHT" + lightIndex] = false;
  41590. var type;
  41591. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  41592. type = "SPOTLIGHT" + lightIndex;
  41593. var spotLight = light;
  41594. defines["PROJECTEDLIGHTTEXTURE" + lightIndex] = spotLight.projectionTexture ? true : false;
  41595. }
  41596. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT) {
  41597. type = "HEMILIGHT" + lightIndex;
  41598. }
  41599. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  41600. type = "POINTLIGHT" + lightIndex;
  41601. }
  41602. else {
  41603. type = "DIRLIGHT" + lightIndex;
  41604. }
  41605. defines[type] = true;
  41606. // Specular
  41607. if (specularSupported && !light.specular.equalsFloats(0, 0, 0)) {
  41608. specularEnabled = true;
  41609. }
  41610. // Shadows
  41611. defines["SHADOW" + lightIndex] = false;
  41612. defines["SHADOWPCF" + lightIndex] = false;
  41613. defines["SHADOWPCSS" + lightIndex] = false;
  41614. defines["SHADOWPOISSON" + lightIndex] = false;
  41615. defines["SHADOWESM" + lightIndex] = false;
  41616. defines["SHADOWCUBE" + lightIndex] = false;
  41617. defines["SHADOWLOWQUALITY" + lightIndex] = false;
  41618. defines["SHADOWMEDIUMQUALITY" + lightIndex] = false;
  41619. if (mesh && mesh.receiveShadows && scene.shadowsEnabled && light.shadowEnabled) {
  41620. var shadowGenerator = light.getShadowGenerator();
  41621. if (shadowGenerator) {
  41622. shadowEnabled = true;
  41623. shadowGenerator.prepareDefines(defines, lightIndex);
  41624. }
  41625. }
  41626. if (light.lightmapMode != BABYLON.Light.LIGHTMAP_DEFAULT) {
  41627. lightmapMode = true;
  41628. defines["LIGHTMAPEXCLUDED" + lightIndex] = true;
  41629. defines["LIGHTMAPNOSPECULAR" + lightIndex] = (light.lightmapMode == BABYLON.Light.LIGHTMAP_SHADOWSONLY);
  41630. }
  41631. else {
  41632. defines["LIGHTMAPEXCLUDED" + lightIndex] = false;
  41633. defines["LIGHTMAPNOSPECULAR" + lightIndex] = false;
  41634. }
  41635. lightIndex++;
  41636. if (lightIndex === maxSimultaneousLights)
  41637. break;
  41638. }
  41639. }
  41640. defines["SPECULARTERM"] = specularEnabled;
  41641. defines["SHADOWS"] = shadowEnabled;
  41642. // Resetting all other lights if any
  41643. for (var index = lightIndex; index < maxSimultaneousLights; index++) {
  41644. if (defines["LIGHT" + index] !== undefined) {
  41645. defines["LIGHT" + index] = false;
  41646. defines["HEMILIGHT" + lightIndex] = false;
  41647. defines["POINTLIGHT" + lightIndex] = false;
  41648. defines["DIRLIGHT" + lightIndex] = false;
  41649. defines["SPOTLIGHT" + lightIndex] = false;
  41650. defines["SHADOW" + lightIndex] = false;
  41651. }
  41652. }
  41653. var caps = scene.getEngine().getCaps();
  41654. if (defines["SHADOWFLOAT"] === undefined) {
  41655. needRebuild = true;
  41656. }
  41657. defines["SHADOWFLOAT"] = shadowEnabled &&
  41658. ((caps.textureFloatRender && caps.textureFloatLinearFiltering) ||
  41659. (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering));
  41660. defines["LIGHTMAPEXCLUDED"] = lightmapMode;
  41661. if (needRebuild) {
  41662. defines.rebuild();
  41663. }
  41664. return needNormals;
  41665. };
  41666. /**
  41667. * Prepares the uniforms and samplers list to be used in the effect. This can automatically remove from the list uniforms
  41668. * that won t be acctive due to defines being turned off.
  41669. * @param uniformsListOrOptions The uniform names to prepare or an EffectCreationOptions containing the liist and extra information
  41670. * @param samplersList The samplers list
  41671. * @param defines The defines helping in the list generation
  41672. * @param maxSimultaneousLights The maximum number of simultanous light allowed in the effect
  41673. */
  41674. MaterialHelper.PrepareUniformsAndSamplersList = function (uniformsListOrOptions, samplersList, defines, maxSimultaneousLights) {
  41675. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41676. var uniformsList;
  41677. var uniformBuffersList = null;
  41678. if (uniformsListOrOptions.uniformsNames) {
  41679. var options = uniformsListOrOptions;
  41680. uniformsList = options.uniformsNames;
  41681. uniformBuffersList = options.uniformBuffersNames;
  41682. samplersList = options.samplers;
  41683. defines = options.defines;
  41684. maxSimultaneousLights = options.maxSimultaneousLights;
  41685. }
  41686. else {
  41687. uniformsList = uniformsListOrOptions;
  41688. if (!samplersList) {
  41689. samplersList = [];
  41690. }
  41691. }
  41692. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41693. if (!defines["LIGHT" + lightIndex]) {
  41694. break;
  41695. }
  41696. uniformsList.push("vLightData" + lightIndex, "vLightDiffuse" + lightIndex, "vLightSpecular" + lightIndex, "vLightDirection" + lightIndex, "vLightGround" + lightIndex, "lightMatrix" + lightIndex, "shadowsInfo" + lightIndex, "depthValues" + lightIndex);
  41697. if (uniformBuffersList) {
  41698. uniformBuffersList.push("Light" + lightIndex);
  41699. }
  41700. samplersList.push("shadowSampler" + lightIndex);
  41701. samplersList.push("depthSampler" + lightIndex);
  41702. if (defines["PROJECTEDLIGHTTEXTURE" + lightIndex]) {
  41703. samplersList.push("projectionLightSampler" + lightIndex);
  41704. uniformsList.push("textureProjectionMatrix" + lightIndex);
  41705. }
  41706. }
  41707. if (defines["NUM_MORPH_INFLUENCERS"]) {
  41708. uniformsList.push("morphTargetInfluences");
  41709. }
  41710. };
  41711. /**
  41712. * This helps decreasing rank by rank the shadow quality (0 being the highest rank and quality)
  41713. * @param defines The defines to update while falling back
  41714. * @param fallbacks The authorized effect fallbacks
  41715. * @param maxSimultaneousLights The maximum number of lights allowed
  41716. * @param rank the current rank of the Effect
  41717. * @returns The newly affected rank
  41718. */
  41719. MaterialHelper.HandleFallbacksForShadows = function (defines, fallbacks, maxSimultaneousLights, rank) {
  41720. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41721. if (rank === void 0) { rank = 0; }
  41722. var lightFallbackRank = 0;
  41723. for (var lightIndex = 0; lightIndex < maxSimultaneousLights; lightIndex++) {
  41724. if (!defines["LIGHT" + lightIndex]) {
  41725. break;
  41726. }
  41727. if (lightIndex > 0) {
  41728. lightFallbackRank = rank + lightIndex;
  41729. fallbacks.addFallback(lightFallbackRank, "LIGHT" + lightIndex);
  41730. }
  41731. if (!defines["SHADOWS"]) {
  41732. if (defines["SHADOW" + lightIndex]) {
  41733. fallbacks.addFallback(rank, "SHADOW" + lightIndex);
  41734. }
  41735. if (defines["SHADOWPCF" + lightIndex]) {
  41736. fallbacks.addFallback(rank, "SHADOWPCF" + lightIndex);
  41737. }
  41738. if (defines["SHADOWPCSS" + lightIndex]) {
  41739. fallbacks.addFallback(rank, "SHADOWPCSS" + lightIndex);
  41740. }
  41741. if (defines["SHADOWPOISSON" + lightIndex]) {
  41742. fallbacks.addFallback(rank, "SHADOWPOISSON" + lightIndex);
  41743. }
  41744. if (defines["SHADOWESM" + lightIndex]) {
  41745. fallbacks.addFallback(rank, "SHADOWESM" + lightIndex);
  41746. }
  41747. }
  41748. }
  41749. return lightFallbackRank++;
  41750. };
  41751. /**
  41752. * Prepares the list of attributes required for morph targets according to the effect defines.
  41753. * @param attribs The current list of supported attribs
  41754. * @param mesh The mesh to prepare the morph targets attributes for
  41755. * @param defines The current Defines of the effect
  41756. */
  41757. MaterialHelper.PrepareAttributesForMorphTargets = function (attribs, mesh, defines) {
  41758. var influencers = defines["NUM_MORPH_INFLUENCERS"];
  41759. if (influencers > 0 && BABYLON.Engine.LastCreatedEngine) {
  41760. var maxAttributesCount = BABYLON.Engine.LastCreatedEngine.getCaps().maxVertexAttribs;
  41761. var manager = mesh.morphTargetManager;
  41762. var normal = manager && manager.supportsNormals && defines["NORMAL"];
  41763. var tangent = manager && manager.supportsTangents && defines["TANGENT"];
  41764. for (var index = 0; index < influencers; index++) {
  41765. attribs.push(BABYLON.VertexBuffer.PositionKind + index);
  41766. if (normal) {
  41767. attribs.push(BABYLON.VertexBuffer.NormalKind + index);
  41768. }
  41769. if (tangent) {
  41770. attribs.push(BABYLON.VertexBuffer.TangentKind + index);
  41771. }
  41772. if (attribs.length > maxAttributesCount) {
  41773. BABYLON.Tools.Error("Cannot add more vertex attributes for mesh " + mesh.name);
  41774. }
  41775. }
  41776. }
  41777. };
  41778. /**
  41779. * Prepares the list of attributes required for bones according to the effect defines.
  41780. * @param attribs The current list of supported attribs
  41781. * @param mesh The mesh to prepare the bones attributes for
  41782. * @param defines The current Defines of the effect
  41783. * @param fallbacks The current efffect fallback strategy
  41784. */
  41785. MaterialHelper.PrepareAttributesForBones = function (attribs, mesh, defines, fallbacks) {
  41786. if (defines["NUM_BONE_INFLUENCERS"] > 0) {
  41787. fallbacks.addCPUSkinningFallback(0, mesh);
  41788. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  41789. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  41790. if (defines["NUM_BONE_INFLUENCERS"] > 4) {
  41791. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  41792. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  41793. }
  41794. }
  41795. };
  41796. /**
  41797. * Prepares the list of attributes required for instances according to the effect defines.
  41798. * @param attribs The current list of supported attribs
  41799. * @param defines The current Defines of the effect
  41800. */
  41801. MaterialHelper.PrepareAttributesForInstances = function (attribs, defines) {
  41802. if (defines["INSTANCES"]) {
  41803. attribs.push("world0");
  41804. attribs.push("world1");
  41805. attribs.push("world2");
  41806. attribs.push("world3");
  41807. }
  41808. };
  41809. /**
  41810. * Binds the light shadow information to the effect for the given mesh.
  41811. * @param light The light containing the generator
  41812. * @param scene The scene the lights belongs to
  41813. * @param mesh The mesh we are binding the information to render
  41814. * @param lightIndex The light index in the effect used to render the mesh
  41815. * @param effect The effect we are binding the data to
  41816. */
  41817. MaterialHelper.BindLightShadow = function (light, scene, mesh, lightIndex, effect) {
  41818. if (light.shadowEnabled && mesh.receiveShadows) {
  41819. var shadowGenerator = light.getShadowGenerator();
  41820. if (shadowGenerator) {
  41821. shadowGenerator.bindShadowLight(lightIndex, effect);
  41822. }
  41823. }
  41824. };
  41825. /**
  41826. * Binds the light information to the effect.
  41827. * @param light The light containing the generator
  41828. * @param effect The effect we are binding the data to
  41829. * @param lightIndex The light index in the effect used to render
  41830. */
  41831. MaterialHelper.BindLightProperties = function (light, effect, lightIndex) {
  41832. light.transferToEffect(effect, lightIndex + "");
  41833. };
  41834. /**
  41835. * Binds the lights information from the scene to the effect for the given mesh.
  41836. * @param scene The scene the lights belongs to
  41837. * @param mesh The mesh we are binding the information to render
  41838. * @param effect The effect we are binding the data to
  41839. * @param defines The generated defines for the effect
  41840. * @param maxSimultaneousLights The maximum number of light that can be bound to the effect
  41841. * @param usePhysicalLightFalloff Specifies whether the light falloff is defined physically or not
  41842. */
  41843. MaterialHelper.BindLights = function (scene, mesh, effect, defines, maxSimultaneousLights, usePhysicalLightFalloff) {
  41844. if (maxSimultaneousLights === void 0) { maxSimultaneousLights = 4; }
  41845. if (usePhysicalLightFalloff === void 0) { usePhysicalLightFalloff = false; }
  41846. var len = Math.min(mesh._lightSources.length, maxSimultaneousLights);
  41847. for (var i = 0; i < len; i++) {
  41848. var light = mesh._lightSources[i];
  41849. var iAsString = i.toString();
  41850. var scaledIntensity = light.getScaledIntensity();
  41851. light._uniformBuffer.bindToEffect(effect, "Light" + i);
  41852. MaterialHelper.BindLightProperties(light, effect, i);
  41853. light.diffuse.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[0]);
  41854. light._uniformBuffer.updateColor4("vLightDiffuse", BABYLON.Tmp.Color3[0], usePhysicalLightFalloff ? light.radius : light.range, iAsString);
  41855. if (defines["SPECULARTERM"]) {
  41856. light.specular.scaleToRef(scaledIntensity, BABYLON.Tmp.Color3[1]);
  41857. light._uniformBuffer.updateColor3("vLightSpecular", BABYLON.Tmp.Color3[1], iAsString);
  41858. }
  41859. // Shadows
  41860. if (scene.shadowsEnabled) {
  41861. this.BindLightShadow(light, scene, mesh, iAsString, effect);
  41862. }
  41863. light._uniformBuffer.update();
  41864. }
  41865. };
  41866. /**
  41867. * Binds the fog information from the scene to the effect for the given mesh.
  41868. * @param scene The scene the lights belongs to
  41869. * @param mesh The mesh we are binding the information to render
  41870. * @param effect The effect we are binding the data to
  41871. */
  41872. MaterialHelper.BindFogParameters = function (scene, mesh, effect) {
  41873. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE) {
  41874. effect.setFloat4("vFogInfos", scene.fogMode, scene.fogStart, scene.fogEnd, scene.fogDensity);
  41875. effect.setColor3("vFogColor", scene.fogColor);
  41876. }
  41877. };
  41878. /**
  41879. * Binds the bones information from the mesh to the effect.
  41880. * @param mesh The mesh we are binding the information to render
  41881. * @param effect The effect we are binding the data to
  41882. */
  41883. MaterialHelper.BindBonesParameters = function (mesh, effect) {
  41884. if (!effect || !mesh) {
  41885. return;
  41886. }
  41887. if (mesh.computeBonesUsingShaders && effect._bonesComputationForcedToCPU) {
  41888. mesh.computeBonesUsingShaders = false;
  41889. }
  41890. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  41891. var matrices = mesh.skeleton.getTransformMatrices(mesh);
  41892. if (matrices) {
  41893. effect.setMatrices("mBones", matrices);
  41894. }
  41895. }
  41896. };
  41897. /**
  41898. * Binds the morph targets information from the mesh to the effect.
  41899. * @param abstractMesh The mesh we are binding the information to render
  41900. * @param effect The effect we are binding the data to
  41901. */
  41902. MaterialHelper.BindMorphTargetParameters = function (abstractMesh, effect) {
  41903. var manager = abstractMesh.morphTargetManager;
  41904. if (!abstractMesh || !manager) {
  41905. return;
  41906. }
  41907. effect.setFloatArray("morphTargetInfluences", manager.influences);
  41908. };
  41909. /**
  41910. * Binds the logarithmic depth information from the scene to the effect for the given defines.
  41911. * @param defines The generated defines used in the effect
  41912. * @param effect The effect we are binding the data to
  41913. * @param scene The scene we are willing to render with logarithmic scale for
  41914. */
  41915. MaterialHelper.BindLogDepth = function (defines, effect, scene) {
  41916. if (defines["LOGARITHMICDEPTH"]) {
  41917. effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  41918. }
  41919. };
  41920. /**
  41921. * Binds the clip plane information from the scene to the effect.
  41922. * @param scene The scene the clip plane information are extracted from
  41923. * @param effect The effect we are binding the data to
  41924. */
  41925. MaterialHelper.BindClipPlane = function (effect, scene) {
  41926. if (scene.clipPlane) {
  41927. var clipPlane = scene.clipPlane;
  41928. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  41929. }
  41930. };
  41931. return MaterialHelper;
  41932. }());
  41933. BABYLON.MaterialHelper = MaterialHelper;
  41934. })(BABYLON || (BABYLON = {}));
  41935. //# sourceMappingURL=babylon.materialHelper.js.map
  41936. var BABYLON;
  41937. (function (BABYLON) {
  41938. var PushMaterial = /** @class */ (function (_super) {
  41939. __extends(PushMaterial, _super);
  41940. function PushMaterial(name, scene) {
  41941. var _this = _super.call(this, name, scene) || this;
  41942. _this._normalMatrix = new BABYLON.Matrix();
  41943. _this.storeEffectOnSubMeshes = true;
  41944. return _this;
  41945. }
  41946. PushMaterial.prototype.getEffect = function () {
  41947. return this._activeEffect;
  41948. };
  41949. PushMaterial.prototype.isReady = function (mesh, useInstances) {
  41950. if (!mesh) {
  41951. return false;
  41952. }
  41953. if (!mesh.subMeshes || mesh.subMeshes.length === 0) {
  41954. return true;
  41955. }
  41956. return this.isReadyForSubMesh(mesh, mesh.subMeshes[0], useInstances);
  41957. };
  41958. /**
  41959. * Binds the given world matrix to the active effect
  41960. *
  41961. * @param world the matrix to bind
  41962. */
  41963. PushMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  41964. this._activeEffect.setMatrix("world", world);
  41965. };
  41966. /**
  41967. * Binds the given normal matrix to the active effect
  41968. *
  41969. * @param normalMatrix the matrix to bind
  41970. */
  41971. PushMaterial.prototype.bindOnlyNormalMatrix = function (normalMatrix) {
  41972. this._activeEffect.setMatrix("normalMatrix", normalMatrix);
  41973. };
  41974. PushMaterial.prototype.bind = function (world, mesh) {
  41975. if (!mesh) {
  41976. return;
  41977. }
  41978. this.bindForSubMesh(world, mesh, mesh.subMeshes[0]);
  41979. };
  41980. PushMaterial.prototype._afterBind = function (mesh, effect) {
  41981. if (effect === void 0) { effect = null; }
  41982. _super.prototype._afterBind.call(this, mesh);
  41983. this.getScene()._cachedEffect = effect;
  41984. };
  41985. PushMaterial.prototype._mustRebind = function (scene, effect, visibility) {
  41986. if (visibility === void 0) { visibility = 1; }
  41987. return scene.isCachedMaterialInvalid(this, effect, visibility);
  41988. };
  41989. return PushMaterial;
  41990. }(BABYLON.Material));
  41991. BABYLON.PushMaterial = PushMaterial;
  41992. })(BABYLON || (BABYLON = {}));
  41993. //# sourceMappingURL=babylon.pushMaterial.js.map
  41994. var BABYLON;
  41995. (function (BABYLON) {
  41996. /** @hidden */
  41997. var StandardMaterialDefines = /** @class */ (function (_super) {
  41998. __extends(StandardMaterialDefines, _super);
  41999. function StandardMaterialDefines() {
  42000. var _this = _super.call(this) || this;
  42001. _this.MAINUV1 = false;
  42002. _this.MAINUV2 = false;
  42003. _this.DIFFUSE = false;
  42004. _this.DIFFUSEDIRECTUV = 0;
  42005. _this.AMBIENT = false;
  42006. _this.AMBIENTDIRECTUV = 0;
  42007. _this.OPACITY = false;
  42008. _this.OPACITYDIRECTUV = 0;
  42009. _this.OPACITYRGB = false;
  42010. _this.REFLECTION = false;
  42011. _this.EMISSIVE = false;
  42012. _this.EMISSIVEDIRECTUV = 0;
  42013. _this.SPECULAR = false;
  42014. _this.SPECULARDIRECTUV = 0;
  42015. _this.BUMP = false;
  42016. _this.BUMPDIRECTUV = 0;
  42017. _this.PARALLAX = false;
  42018. _this.PARALLAXOCCLUSION = false;
  42019. _this.SPECULAROVERALPHA = false;
  42020. _this.CLIPPLANE = false;
  42021. _this.ALPHATEST = false;
  42022. _this.DEPTHPREPASS = false;
  42023. _this.ALPHAFROMDIFFUSE = false;
  42024. _this.POINTSIZE = false;
  42025. _this.FOG = false;
  42026. _this.SPECULARTERM = false;
  42027. _this.DIFFUSEFRESNEL = false;
  42028. _this.OPACITYFRESNEL = false;
  42029. _this.REFLECTIONFRESNEL = false;
  42030. _this.REFRACTIONFRESNEL = false;
  42031. _this.EMISSIVEFRESNEL = false;
  42032. _this.FRESNEL = false;
  42033. _this.NORMAL = false;
  42034. _this.UV1 = false;
  42035. _this.UV2 = false;
  42036. _this.VERTEXCOLOR = false;
  42037. _this.VERTEXALPHA = false;
  42038. _this.NUM_BONE_INFLUENCERS = 0;
  42039. _this.BonesPerMesh = 0;
  42040. _this.INSTANCES = false;
  42041. _this.GLOSSINESS = false;
  42042. _this.ROUGHNESS = false;
  42043. _this.EMISSIVEASILLUMINATION = false;
  42044. _this.LINKEMISSIVEWITHDIFFUSE = false;
  42045. _this.REFLECTIONFRESNELFROMSPECULAR = false;
  42046. _this.LIGHTMAP = false;
  42047. _this.LIGHTMAPDIRECTUV = 0;
  42048. _this.OBJECTSPACE_NORMALMAP = false;
  42049. _this.USELIGHTMAPASSHADOWMAP = false;
  42050. _this.REFLECTIONMAP_3D = false;
  42051. _this.REFLECTIONMAP_SPHERICAL = false;
  42052. _this.REFLECTIONMAP_PLANAR = false;
  42053. _this.REFLECTIONMAP_CUBIC = false;
  42054. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  42055. _this.REFLECTIONMAP_PROJECTION = false;
  42056. _this.REFLECTIONMAP_SKYBOX = false;
  42057. _this.REFLECTIONMAP_EXPLICIT = false;
  42058. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  42059. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  42060. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  42061. _this.INVERTCUBICMAP = false;
  42062. _this.LOGARITHMICDEPTH = false;
  42063. _this.REFRACTION = false;
  42064. _this.REFRACTIONMAP_3D = false;
  42065. _this.REFLECTIONOVERALPHA = false;
  42066. _this.TWOSIDEDLIGHTING = false;
  42067. _this.SHADOWFLOAT = false;
  42068. _this.MORPHTARGETS = false;
  42069. _this.MORPHTARGETS_NORMAL = false;
  42070. _this.MORPHTARGETS_TANGENT = false;
  42071. _this.NUM_MORPH_INFLUENCERS = 0;
  42072. _this.NONUNIFORMSCALING = false; // https://playground.babylonjs.com#V6DWIH
  42073. _this.PREMULTIPLYALPHA = false; // https://playground.babylonjs.com#LNVJJ7
  42074. _this.IMAGEPROCESSING = false;
  42075. _this.VIGNETTE = false;
  42076. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  42077. _this.VIGNETTEBLENDMODEOPAQUE = false;
  42078. _this.TONEMAPPING = false;
  42079. _this.CONTRAST = false;
  42080. _this.COLORCURVES = false;
  42081. _this.COLORGRADING = false;
  42082. _this.COLORGRADING3D = false;
  42083. _this.SAMPLER3DGREENDEPTH = false;
  42084. _this.SAMPLER3DBGRMAP = false;
  42085. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  42086. /**
  42087. * If the reflection texture on this material is in linear color space
  42088. * @hidden
  42089. */
  42090. _this.IS_REFLECTION_LINEAR = false;
  42091. /**
  42092. * If the refraction texture on this material is in linear color space
  42093. * @hidden
  42094. */
  42095. _this.IS_REFRACTION_LINEAR = false;
  42096. _this.EXPOSURE = false;
  42097. _this.rebuild();
  42098. return _this;
  42099. }
  42100. StandardMaterialDefines.prototype.setReflectionMode = function (modeToEnable) {
  42101. var modes = [
  42102. "REFLECTIONMAP_CUBIC", "REFLECTIONMAP_EXPLICIT", "REFLECTIONMAP_PLANAR",
  42103. "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_PROJECTION", "REFLECTIONMAP_SKYBOX",
  42104. "REFLECTIONMAP_SPHERICAL", "REFLECTIONMAP_EQUIRECTANGULAR", "REFLECTIONMAP_EQUIRECTANGULAR_FIXED",
  42105. "REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED"
  42106. ];
  42107. for (var _i = 0, modes_1 = modes; _i < modes_1.length; _i++) {
  42108. var mode = modes_1[_i];
  42109. this[mode] = (mode === modeToEnable);
  42110. }
  42111. };
  42112. return StandardMaterialDefines;
  42113. }(BABYLON.MaterialDefines));
  42114. BABYLON.StandardMaterialDefines = StandardMaterialDefines;
  42115. var StandardMaterial = /** @class */ (function (_super) {
  42116. __extends(StandardMaterial, _super);
  42117. function StandardMaterial(name, scene) {
  42118. var _this = _super.call(this, name, scene) || this;
  42119. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  42120. _this.diffuseColor = new BABYLON.Color3(1, 1, 1);
  42121. _this.specularColor = new BABYLON.Color3(1, 1, 1);
  42122. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  42123. _this.specularPower = 64;
  42124. _this._useAlphaFromDiffuseTexture = false;
  42125. _this._useEmissiveAsIllumination = false;
  42126. _this._linkEmissiveWithDiffuse = false;
  42127. _this._useSpecularOverAlpha = false;
  42128. _this._useReflectionOverAlpha = false;
  42129. _this._disableLighting = false;
  42130. _this._useObjectSpaceNormalMap = false;
  42131. _this._useParallax = false;
  42132. _this._useParallaxOcclusion = false;
  42133. _this.parallaxScaleBias = 0.05;
  42134. _this._roughness = 0;
  42135. _this.indexOfRefraction = 0.98;
  42136. _this.invertRefractionY = true;
  42137. /**
  42138. * Defines the alpha limits in alpha test mode
  42139. */
  42140. _this.alphaCutOff = 0.4;
  42141. _this._useLightmapAsShadowmap = false;
  42142. _this._useReflectionFresnelFromSpecular = false;
  42143. _this._useGlossinessFromSpecularMapAlpha = false;
  42144. _this._maxSimultaneousLights = 4;
  42145. /**
  42146. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  42147. */
  42148. _this._invertNormalMapX = false;
  42149. /**
  42150. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  42151. */
  42152. _this._invertNormalMapY = false;
  42153. /**
  42154. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  42155. */
  42156. _this._twoSidedLighting = false;
  42157. _this._renderTargets = new BABYLON.SmartArray(16);
  42158. _this._worldViewProjectionMatrix = BABYLON.Matrix.Zero();
  42159. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  42160. // Setup the default processing configuration to the scene.
  42161. _this._attachImageProcessingConfiguration(null);
  42162. _this.getRenderTargetTextures = function () {
  42163. _this._renderTargets.reset();
  42164. if (StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  42165. _this._renderTargets.push(_this._reflectionTexture);
  42166. }
  42167. if (StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  42168. _this._renderTargets.push(_this._refractionTexture);
  42169. }
  42170. return _this._renderTargets;
  42171. };
  42172. return _this;
  42173. }
  42174. Object.defineProperty(StandardMaterial.prototype, "imageProcessingConfiguration", {
  42175. /**
  42176. * Gets the image processing configuration used either in this material.
  42177. */
  42178. get: function () {
  42179. return this._imageProcessingConfiguration;
  42180. },
  42181. /**
  42182. * Sets the Default image processing configuration used either in the this material.
  42183. *
  42184. * If sets to null, the scene one is in use.
  42185. */
  42186. set: function (value) {
  42187. this._attachImageProcessingConfiguration(value);
  42188. // Ensure the effect will be rebuilt.
  42189. this._markAllSubMeshesAsTexturesDirty();
  42190. },
  42191. enumerable: true,
  42192. configurable: true
  42193. });
  42194. /**
  42195. * Attaches a new image processing configuration to the Standard Material.
  42196. * @param configuration
  42197. */
  42198. StandardMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  42199. var _this = this;
  42200. if (configuration === this._imageProcessingConfiguration) {
  42201. return;
  42202. }
  42203. // Detaches observer.
  42204. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  42205. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  42206. }
  42207. // Pick the scene configuration if needed.
  42208. if (!configuration) {
  42209. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  42210. }
  42211. else {
  42212. this._imageProcessingConfiguration = configuration;
  42213. }
  42214. // Attaches observer.
  42215. if (this._imageProcessingConfiguration) {
  42216. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  42217. _this._markAllSubMeshesAsImageProcessingDirty();
  42218. });
  42219. }
  42220. };
  42221. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurvesEnabled", {
  42222. /**
  42223. * Gets wether the color curves effect is enabled.
  42224. */
  42225. get: function () {
  42226. return this.imageProcessingConfiguration.colorCurvesEnabled;
  42227. },
  42228. /**
  42229. * Sets wether the color curves effect is enabled.
  42230. */
  42231. set: function (value) {
  42232. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  42233. },
  42234. enumerable: true,
  42235. configurable: true
  42236. });
  42237. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingEnabled", {
  42238. /**
  42239. * Gets wether the color grading effect is enabled.
  42240. */
  42241. get: function () {
  42242. return this.imageProcessingConfiguration.colorGradingEnabled;
  42243. },
  42244. /**
  42245. * Gets wether the color grading effect is enabled.
  42246. */
  42247. set: function (value) {
  42248. this.imageProcessingConfiguration.colorGradingEnabled = value;
  42249. },
  42250. enumerable: true,
  42251. configurable: true
  42252. });
  42253. Object.defineProperty(StandardMaterial.prototype, "cameraToneMappingEnabled", {
  42254. /**
  42255. * Gets wether tonemapping is enabled or not.
  42256. */
  42257. get: function () {
  42258. return this._imageProcessingConfiguration.toneMappingEnabled;
  42259. },
  42260. /**
  42261. * Sets wether tonemapping is enabled or not
  42262. */
  42263. set: function (value) {
  42264. this._imageProcessingConfiguration.toneMappingEnabled = value;
  42265. },
  42266. enumerable: true,
  42267. configurable: true
  42268. });
  42269. ;
  42270. ;
  42271. Object.defineProperty(StandardMaterial.prototype, "cameraExposure", {
  42272. /**
  42273. * The camera exposure used on this material.
  42274. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42275. * This corresponds to a photographic exposure.
  42276. */
  42277. get: function () {
  42278. return this._imageProcessingConfiguration.exposure;
  42279. },
  42280. /**
  42281. * The camera exposure used on this material.
  42282. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  42283. * This corresponds to a photographic exposure.
  42284. */
  42285. set: function (value) {
  42286. this._imageProcessingConfiguration.exposure = value;
  42287. },
  42288. enumerable: true,
  42289. configurable: true
  42290. });
  42291. ;
  42292. ;
  42293. Object.defineProperty(StandardMaterial.prototype, "cameraContrast", {
  42294. /**
  42295. * Gets The camera contrast used on this material.
  42296. */
  42297. get: function () {
  42298. return this._imageProcessingConfiguration.contrast;
  42299. },
  42300. /**
  42301. * Sets The camera contrast used on this material.
  42302. */
  42303. set: function (value) {
  42304. this._imageProcessingConfiguration.contrast = value;
  42305. },
  42306. enumerable: true,
  42307. configurable: true
  42308. });
  42309. Object.defineProperty(StandardMaterial.prototype, "cameraColorGradingTexture", {
  42310. /**
  42311. * Gets the Color Grading 2D Lookup Texture.
  42312. */
  42313. get: function () {
  42314. return this._imageProcessingConfiguration.colorGradingTexture;
  42315. },
  42316. /**
  42317. * Sets the Color Grading 2D Lookup Texture.
  42318. */
  42319. set: function (value) {
  42320. this._imageProcessingConfiguration.colorGradingTexture = value;
  42321. },
  42322. enumerable: true,
  42323. configurable: true
  42324. });
  42325. Object.defineProperty(StandardMaterial.prototype, "cameraColorCurves", {
  42326. /**
  42327. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42328. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42329. * 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;
  42330. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42331. */
  42332. get: function () {
  42333. return this._imageProcessingConfiguration.colorCurves;
  42334. },
  42335. /**
  42336. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  42337. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  42338. * 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;
  42339. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  42340. */
  42341. set: function (value) {
  42342. this._imageProcessingConfiguration.colorCurves = value;
  42343. },
  42344. enumerable: true,
  42345. configurable: true
  42346. });
  42347. StandardMaterial.prototype.getClassName = function () {
  42348. return "StandardMaterial";
  42349. };
  42350. Object.defineProperty(StandardMaterial.prototype, "useLogarithmicDepth", {
  42351. get: function () {
  42352. return this._useLogarithmicDepth;
  42353. },
  42354. set: function (value) {
  42355. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  42356. this._markAllSubMeshesAsMiscDirty();
  42357. },
  42358. enumerable: true,
  42359. configurable: true
  42360. });
  42361. StandardMaterial.prototype.needAlphaBlending = function () {
  42362. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromDiffuseTexture() || this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled;
  42363. };
  42364. StandardMaterial.prototype.needAlphaTesting = function () {
  42365. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha;
  42366. };
  42367. StandardMaterial.prototype._shouldUseAlphaFromDiffuseTexture = function () {
  42368. return this._diffuseTexture != null && this._diffuseTexture.hasAlpha && this._useAlphaFromDiffuseTexture;
  42369. };
  42370. StandardMaterial.prototype.getAlphaTestTexture = function () {
  42371. return this._diffuseTexture;
  42372. };
  42373. /**
  42374. * Child classes can use it to update shaders
  42375. */
  42376. StandardMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  42377. if (useInstances === void 0) { useInstances = false; }
  42378. if (subMesh.effect && this.isFrozen) {
  42379. if (this._wasPreviouslyReady && subMesh.effect) {
  42380. return true;
  42381. }
  42382. }
  42383. if (!subMesh._materialDefines) {
  42384. subMesh._materialDefines = new StandardMaterialDefines();
  42385. }
  42386. var scene = this.getScene();
  42387. var defines = subMesh._materialDefines;
  42388. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  42389. if (defines._renderId === scene.getRenderId()) {
  42390. return true;
  42391. }
  42392. }
  42393. var engine = scene.getEngine();
  42394. // Lights
  42395. defines._needNormals = BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  42396. // Textures
  42397. if (defines._areTexturesDirty) {
  42398. defines._needUVs = false;
  42399. defines.MAINUV1 = false;
  42400. defines.MAINUV2 = false;
  42401. if (scene.texturesEnabled) {
  42402. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42403. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  42404. return false;
  42405. }
  42406. else {
  42407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  42408. }
  42409. }
  42410. else {
  42411. defines.DIFFUSE = false;
  42412. }
  42413. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42414. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  42415. return false;
  42416. }
  42417. else {
  42418. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  42419. }
  42420. }
  42421. else {
  42422. defines.AMBIENT = false;
  42423. }
  42424. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42425. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  42426. return false;
  42427. }
  42428. else {
  42429. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  42430. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  42431. }
  42432. }
  42433. else {
  42434. defines.OPACITY = false;
  42435. }
  42436. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42437. if (!this._reflectionTexture.isReadyOrNotBlocking()) {
  42438. return false;
  42439. }
  42440. else {
  42441. defines._needNormals = true;
  42442. defines.REFLECTION = true;
  42443. defines.ROUGHNESS = (this._roughness > 0);
  42444. defines.REFLECTIONOVERALPHA = this._useReflectionOverAlpha;
  42445. defines.INVERTCUBICMAP = (this._reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE);
  42446. defines.REFLECTIONMAP_3D = this._reflectionTexture.isCube;
  42447. switch (this._reflectionTexture.coordinatesMode) {
  42448. case BABYLON.Texture.EXPLICIT_MODE:
  42449. defines.setReflectionMode("REFLECTIONMAP_EXPLICIT");
  42450. break;
  42451. case BABYLON.Texture.PLANAR_MODE:
  42452. defines.setReflectionMode("REFLECTIONMAP_PLANAR");
  42453. break;
  42454. case BABYLON.Texture.PROJECTION_MODE:
  42455. defines.setReflectionMode("REFLECTIONMAP_PROJECTION");
  42456. break;
  42457. case BABYLON.Texture.SKYBOX_MODE:
  42458. defines.setReflectionMode("REFLECTIONMAP_SKYBOX");
  42459. break;
  42460. case BABYLON.Texture.SPHERICAL_MODE:
  42461. defines.setReflectionMode("REFLECTIONMAP_SPHERICAL");
  42462. break;
  42463. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  42464. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR");
  42465. break;
  42466. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  42467. defines.setReflectionMode("REFLECTIONMAP_EQUIRECTANGULAR_FIXED");
  42468. break;
  42469. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  42470. defines.setReflectionMode("REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED");
  42471. break;
  42472. case BABYLON.Texture.CUBIC_MODE:
  42473. case BABYLON.Texture.INVCUBIC_MODE:
  42474. default:
  42475. defines.setReflectionMode("REFLECTIONMAP_CUBIC");
  42476. break;
  42477. }
  42478. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = this._reflectionTexture.boundingBoxSize ? true : false;
  42479. }
  42480. }
  42481. else {
  42482. defines.REFLECTION = false;
  42483. }
  42484. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42485. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  42486. return false;
  42487. }
  42488. else {
  42489. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  42490. }
  42491. }
  42492. else {
  42493. defines.EMISSIVE = false;
  42494. }
  42495. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42496. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  42497. return false;
  42498. }
  42499. else {
  42500. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  42501. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  42502. }
  42503. }
  42504. else {
  42505. defines.LIGHTMAP = false;
  42506. }
  42507. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42508. if (!this._specularTexture.isReadyOrNotBlocking()) {
  42509. return false;
  42510. }
  42511. else {
  42512. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._specularTexture, defines, "SPECULAR");
  42513. defines.GLOSSINESS = this._useGlossinessFromSpecularMapAlpha;
  42514. }
  42515. }
  42516. else {
  42517. defines.SPECULAR = false;
  42518. }
  42519. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && StandardMaterial.BumpTextureEnabled) {
  42520. // Bump texure can not be not blocking.
  42521. if (!this._bumpTexture.isReady()) {
  42522. return false;
  42523. }
  42524. else {
  42525. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  42526. defines.PARALLAX = this._useParallax;
  42527. defines.PARALLAXOCCLUSION = this._useParallaxOcclusion;
  42528. }
  42529. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  42530. }
  42531. else {
  42532. defines.BUMP = false;
  42533. }
  42534. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42535. if (!this._refractionTexture.isReadyOrNotBlocking()) {
  42536. return false;
  42537. }
  42538. else {
  42539. defines._needUVs = true;
  42540. defines.REFRACTION = true;
  42541. defines.REFRACTIONMAP_3D = this._refractionTexture.isCube;
  42542. }
  42543. }
  42544. else {
  42545. defines.REFRACTION = false;
  42546. }
  42547. defines.TWOSIDEDLIGHTING = !this._backFaceCulling && this._twoSidedLighting;
  42548. }
  42549. else {
  42550. defines.DIFFUSE = false;
  42551. defines.AMBIENT = false;
  42552. defines.OPACITY = false;
  42553. defines.REFLECTION = false;
  42554. defines.EMISSIVE = false;
  42555. defines.LIGHTMAP = false;
  42556. defines.BUMP = false;
  42557. defines.REFRACTION = false;
  42558. }
  42559. defines.ALPHAFROMDIFFUSE = this._shouldUseAlphaFromDiffuseTexture();
  42560. defines.EMISSIVEASILLUMINATION = this._useEmissiveAsIllumination;
  42561. defines.LINKEMISSIVEWITHDIFFUSE = this._linkEmissiveWithDiffuse;
  42562. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  42563. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  42564. }
  42565. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  42566. if (!this._imageProcessingConfiguration.isReady()) {
  42567. return false;
  42568. }
  42569. this._imageProcessingConfiguration.prepareDefines(defines);
  42570. defines.IS_REFLECTION_LINEAR = (this.reflectionTexture != null && !this.reflectionTexture.gammaSpace);
  42571. defines.IS_REFRACTION_LINEAR = (this.refractionTexture != null && !this.refractionTexture.gammaSpace);
  42572. }
  42573. if (defines._areFresnelDirty) {
  42574. if (StandardMaterial.FresnelEnabled) {
  42575. // Fresnel
  42576. if (this._diffuseFresnelParameters || this._opacityFresnelParameters ||
  42577. this._emissiveFresnelParameters || this._refractionFresnelParameters ||
  42578. this._reflectionFresnelParameters) {
  42579. defines.DIFFUSEFRESNEL = (this._diffuseFresnelParameters && this._diffuseFresnelParameters.isEnabled);
  42580. defines.OPACITYFRESNEL = (this._opacityFresnelParameters && this._opacityFresnelParameters.isEnabled);
  42581. defines.REFLECTIONFRESNEL = (this._reflectionFresnelParameters && this._reflectionFresnelParameters.isEnabled);
  42582. defines.REFLECTIONFRESNELFROMSPECULAR = this._useReflectionFresnelFromSpecular;
  42583. defines.REFRACTIONFRESNEL = (this._refractionFresnelParameters && this._refractionFresnelParameters.isEnabled);
  42584. defines.EMISSIVEFRESNEL = (this._emissiveFresnelParameters && this._emissiveFresnelParameters.isEnabled);
  42585. defines._needNormals = true;
  42586. defines.FRESNEL = true;
  42587. }
  42588. }
  42589. else {
  42590. defines.FRESNEL = false;
  42591. }
  42592. }
  42593. // Misc.
  42594. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  42595. // Attribs
  42596. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true);
  42597. // Values that need to be evaluated on every frame
  42598. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  42599. // Get correct effect
  42600. if (defines.isDirty) {
  42601. defines.markAsProcessed();
  42602. scene.resetCachedMaterial();
  42603. // Fallbacks
  42604. var fallbacks = new BABYLON.EffectFallbacks();
  42605. if (defines.REFLECTION) {
  42606. fallbacks.addFallback(0, "REFLECTION");
  42607. }
  42608. if (defines.SPECULAR) {
  42609. fallbacks.addFallback(0, "SPECULAR");
  42610. }
  42611. if (defines.BUMP) {
  42612. fallbacks.addFallback(0, "BUMP");
  42613. }
  42614. if (defines.PARALLAX) {
  42615. fallbacks.addFallback(1, "PARALLAX");
  42616. }
  42617. if (defines.PARALLAXOCCLUSION) {
  42618. fallbacks.addFallback(0, "PARALLAXOCCLUSION");
  42619. }
  42620. if (defines.SPECULAROVERALPHA) {
  42621. fallbacks.addFallback(0, "SPECULAROVERALPHA");
  42622. }
  42623. if (defines.FOG) {
  42624. fallbacks.addFallback(1, "FOG");
  42625. }
  42626. if (defines.POINTSIZE) {
  42627. fallbacks.addFallback(0, "POINTSIZE");
  42628. }
  42629. if (defines.LOGARITHMICDEPTH) {
  42630. fallbacks.addFallback(0, "LOGARITHMICDEPTH");
  42631. }
  42632. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  42633. if (defines.SPECULARTERM) {
  42634. fallbacks.addFallback(0, "SPECULARTERM");
  42635. }
  42636. if (defines.DIFFUSEFRESNEL) {
  42637. fallbacks.addFallback(1, "DIFFUSEFRESNEL");
  42638. }
  42639. if (defines.OPACITYFRESNEL) {
  42640. fallbacks.addFallback(2, "OPACITYFRESNEL");
  42641. }
  42642. if (defines.REFLECTIONFRESNEL) {
  42643. fallbacks.addFallback(3, "REFLECTIONFRESNEL");
  42644. }
  42645. if (defines.EMISSIVEFRESNEL) {
  42646. fallbacks.addFallback(4, "EMISSIVEFRESNEL");
  42647. }
  42648. if (defines.FRESNEL) {
  42649. fallbacks.addFallback(4, "FRESNEL");
  42650. }
  42651. //Attributes
  42652. var attribs = [BABYLON.VertexBuffer.PositionKind];
  42653. if (defines.NORMAL) {
  42654. attribs.push(BABYLON.VertexBuffer.NormalKind);
  42655. }
  42656. if (defines.UV1) {
  42657. attribs.push(BABYLON.VertexBuffer.UVKind);
  42658. }
  42659. if (defines.UV2) {
  42660. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  42661. }
  42662. if (defines.VERTEXCOLOR) {
  42663. attribs.push(BABYLON.VertexBuffer.ColorKind);
  42664. }
  42665. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  42666. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  42667. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  42668. var shaderName = "default";
  42669. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vDiffuseColor", "vSpecularColor", "vEmissiveColor",
  42670. "vFogInfos", "vFogColor", "pointSize",
  42671. "vDiffuseInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vEmissiveInfos", "vSpecularInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  42672. "mBones",
  42673. "vClipPlane", "diffuseMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "specularMatrix", "bumpMatrix", "normalMatrix", "lightmapMatrix", "refractionMatrix",
  42674. "diffuseLeftColor", "diffuseRightColor", "opacityParts", "reflectionLeftColor", "reflectionRightColor", "emissiveLeftColor", "emissiveRightColor", "refractionLeftColor", "refractionRightColor",
  42675. "vReflectionPosition", "vReflectionSize",
  42676. "logarithmicDepthConstant", "vTangentSpaceParams", "alphaCutOff"
  42677. ];
  42678. var samplers = ["diffuseSampler", "ambientSampler", "opacitySampler", "reflectionCubeSampler", "reflection2DSampler", "emissiveSampler", "specularSampler", "bumpSampler", "lightmapSampler", "refractionCubeSampler", "refraction2DSampler"];
  42679. var uniformBuffers = ["Material", "Scene"];
  42680. if (BABYLON.ImageProcessingConfiguration) {
  42681. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  42682. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  42683. }
  42684. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  42685. uniformsNames: uniforms,
  42686. uniformBuffersNames: uniformBuffers,
  42687. samplers: samplers,
  42688. defines: defines,
  42689. maxSimultaneousLights: this._maxSimultaneousLights
  42690. });
  42691. if (this.customShaderNameResolve) {
  42692. shaderName = this.customShaderNameResolve(shaderName, uniforms, uniformBuffers, samplers, defines);
  42693. }
  42694. var join = defines.toString();
  42695. subMesh.setEffect(scene.getEngine().createEffect(shaderName, {
  42696. attributes: attribs,
  42697. uniformsNames: uniforms,
  42698. uniformBuffersNames: uniformBuffers,
  42699. samplers: samplers,
  42700. defines: join,
  42701. fallbacks: fallbacks,
  42702. onCompiled: this.onCompiled,
  42703. onError: this.onError,
  42704. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  42705. }, engine), defines);
  42706. this.buildUniformLayout();
  42707. }
  42708. if (!subMesh.effect || !subMesh.effect.isReady()) {
  42709. return false;
  42710. }
  42711. defines._renderId = scene.getRenderId();
  42712. this._wasPreviouslyReady = true;
  42713. return true;
  42714. };
  42715. StandardMaterial.prototype.buildUniformLayout = function () {
  42716. // Order is important !
  42717. this._uniformBuffer.addUniform("diffuseLeftColor", 4);
  42718. this._uniformBuffer.addUniform("diffuseRightColor", 4);
  42719. this._uniformBuffer.addUniform("opacityParts", 4);
  42720. this._uniformBuffer.addUniform("reflectionLeftColor", 4);
  42721. this._uniformBuffer.addUniform("reflectionRightColor", 4);
  42722. this._uniformBuffer.addUniform("refractionLeftColor", 4);
  42723. this._uniformBuffer.addUniform("refractionRightColor", 4);
  42724. this._uniformBuffer.addUniform("emissiveLeftColor", 4);
  42725. this._uniformBuffer.addUniform("emissiveRightColor", 4);
  42726. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  42727. this._uniformBuffer.addUniform("vAmbientInfos", 2);
  42728. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  42729. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  42730. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  42731. this._uniformBuffer.addUniform("vReflectionSize", 3);
  42732. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  42733. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  42734. this._uniformBuffer.addUniform("vSpecularInfos", 2);
  42735. this._uniformBuffer.addUniform("vBumpInfos", 3);
  42736. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  42737. this._uniformBuffer.addUniform("ambientMatrix", 16);
  42738. this._uniformBuffer.addUniform("opacityMatrix", 16);
  42739. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  42740. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  42741. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  42742. this._uniformBuffer.addUniform("specularMatrix", 16);
  42743. this._uniformBuffer.addUniform("bumpMatrix", 16);
  42744. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  42745. this._uniformBuffer.addUniform("refractionMatrix", 16);
  42746. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  42747. this._uniformBuffer.addUniform("vSpecularColor", 4);
  42748. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  42749. this._uniformBuffer.addUniform("vDiffuseColor", 4);
  42750. this._uniformBuffer.addUniform("pointSize", 1);
  42751. this._uniformBuffer.create();
  42752. };
  42753. StandardMaterial.prototype.unbind = function () {
  42754. if (this._activeEffect) {
  42755. var needFlag = false;
  42756. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  42757. this._activeEffect.setTexture("reflection2DSampler", null);
  42758. needFlag = true;
  42759. }
  42760. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  42761. this._activeEffect.setTexture("refraction2DSampler", null);
  42762. needFlag = true;
  42763. }
  42764. if (needFlag) {
  42765. this._markAllSubMeshesAsTexturesDirty();
  42766. }
  42767. }
  42768. _super.prototype.unbind.call(this);
  42769. };
  42770. StandardMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  42771. var scene = this.getScene();
  42772. var defines = subMesh._materialDefines;
  42773. if (!defines) {
  42774. return;
  42775. }
  42776. var effect = subMesh.effect;
  42777. if (!effect) {
  42778. return;
  42779. }
  42780. this._activeEffect = effect;
  42781. // Matrices
  42782. this.bindOnlyWorldMatrix(world);
  42783. // Normal Matrix
  42784. if (defines.OBJECTSPACE_NORMALMAP) {
  42785. world.toNormalMatrix(this._normalMatrix);
  42786. this.bindOnlyNormalMatrix(this._normalMatrix);
  42787. }
  42788. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  42789. // Bones
  42790. BABYLON.MaterialHelper.BindBonesParameters(mesh, effect);
  42791. if (mustRebind) {
  42792. this._uniformBuffer.bindToEffect(effect, "Material");
  42793. this.bindViewProjection(effect);
  42794. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  42795. if (StandardMaterial.FresnelEnabled && defines.FRESNEL) {
  42796. // Fresnel
  42797. if (this.diffuseFresnelParameters && this.diffuseFresnelParameters.isEnabled) {
  42798. this._uniformBuffer.updateColor4("diffuseLeftColor", this.diffuseFresnelParameters.leftColor, this.diffuseFresnelParameters.power);
  42799. this._uniformBuffer.updateColor4("diffuseRightColor", this.diffuseFresnelParameters.rightColor, this.diffuseFresnelParameters.bias);
  42800. }
  42801. if (this.opacityFresnelParameters && this.opacityFresnelParameters.isEnabled) {
  42802. this._uniformBuffer.updateColor4("opacityParts", new BABYLON.Color3(this.opacityFresnelParameters.leftColor.toLuminance(), this.opacityFresnelParameters.rightColor.toLuminance(), this.opacityFresnelParameters.bias), this.opacityFresnelParameters.power);
  42803. }
  42804. if (this.reflectionFresnelParameters && this.reflectionFresnelParameters.isEnabled) {
  42805. this._uniformBuffer.updateColor4("reflectionLeftColor", this.reflectionFresnelParameters.leftColor, this.reflectionFresnelParameters.power);
  42806. this._uniformBuffer.updateColor4("reflectionRightColor", this.reflectionFresnelParameters.rightColor, this.reflectionFresnelParameters.bias);
  42807. }
  42808. if (this.refractionFresnelParameters && this.refractionFresnelParameters.isEnabled) {
  42809. this._uniformBuffer.updateColor4("refractionLeftColor", this.refractionFresnelParameters.leftColor, this.refractionFresnelParameters.power);
  42810. this._uniformBuffer.updateColor4("refractionRightColor", this.refractionFresnelParameters.rightColor, this.refractionFresnelParameters.bias);
  42811. }
  42812. if (this.emissiveFresnelParameters && this.emissiveFresnelParameters.isEnabled) {
  42813. this._uniformBuffer.updateColor4("emissiveLeftColor", this.emissiveFresnelParameters.leftColor, this.emissiveFresnelParameters.power);
  42814. this._uniformBuffer.updateColor4("emissiveRightColor", this.emissiveFresnelParameters.rightColor, this.emissiveFresnelParameters.bias);
  42815. }
  42816. }
  42817. // Textures
  42818. if (scene.texturesEnabled) {
  42819. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42820. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  42821. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  42822. if (this._diffuseTexture.hasAlpha) {
  42823. effect.setFloat("alphaCutOff", this.alphaCutOff);
  42824. }
  42825. }
  42826. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42827. this._uniformBuffer.updateFloat2("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level);
  42828. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  42829. }
  42830. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42831. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  42832. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  42833. }
  42834. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42835. this._uniformBuffer.updateFloat2("vReflectionInfos", this._reflectionTexture.level, this.roughness);
  42836. this._uniformBuffer.updateMatrix("reflectionMatrix", this._reflectionTexture.getReflectionTextureMatrix());
  42837. if (this._reflectionTexture.boundingBoxSize) {
  42838. var cubeTexture = this._reflectionTexture;
  42839. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  42840. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  42841. }
  42842. }
  42843. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42844. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  42845. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  42846. }
  42847. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42848. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  42849. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  42850. }
  42851. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42852. this._uniformBuffer.updateFloat2("vSpecularInfos", this._specularTexture.coordinatesIndex, this._specularTexture.level);
  42853. BABYLON.MaterialHelper.BindTextureMatrix(this._specularTexture, this._uniformBuffer, "specular");
  42854. }
  42855. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42856. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, 1.0 / this._bumpTexture.level, this.parallaxScaleBias);
  42857. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  42858. if (scene._mirroredCameraPosition) {
  42859. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  42860. }
  42861. else {
  42862. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  42863. }
  42864. }
  42865. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42866. var depth = 1.0;
  42867. if (!this._refractionTexture.isCube) {
  42868. this._uniformBuffer.updateMatrix("refractionMatrix", this._refractionTexture.getReflectionTextureMatrix());
  42869. if (this._refractionTexture.depth) {
  42870. depth = this._refractionTexture.depth;
  42871. }
  42872. }
  42873. this._uniformBuffer.updateFloat4("vRefractionInfos", this._refractionTexture.level, this.indexOfRefraction, depth, this.invertRefractionY ? -1 : 1);
  42874. }
  42875. }
  42876. // Point size
  42877. if (this.pointsCloud) {
  42878. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  42879. }
  42880. if (defines.SPECULARTERM) {
  42881. this._uniformBuffer.updateColor4("vSpecularColor", this.specularColor, this.specularPower);
  42882. }
  42883. this._uniformBuffer.updateColor3("vEmissiveColor", this.emissiveColor);
  42884. // Diffuse
  42885. this._uniformBuffer.updateColor4("vDiffuseColor", this.diffuseColor, this.alpha * mesh.visibility);
  42886. }
  42887. // Textures
  42888. if (scene.texturesEnabled) {
  42889. if (this._diffuseTexture && StandardMaterial.DiffuseTextureEnabled) {
  42890. effect.setTexture("diffuseSampler", this._diffuseTexture);
  42891. }
  42892. if (this._ambientTexture && StandardMaterial.AmbientTextureEnabled) {
  42893. effect.setTexture("ambientSampler", this._ambientTexture);
  42894. }
  42895. if (this._opacityTexture && StandardMaterial.OpacityTextureEnabled) {
  42896. effect.setTexture("opacitySampler", this._opacityTexture);
  42897. }
  42898. if (this._reflectionTexture && StandardMaterial.ReflectionTextureEnabled) {
  42899. if (this._reflectionTexture.isCube) {
  42900. effect.setTexture("reflectionCubeSampler", this._reflectionTexture);
  42901. }
  42902. else {
  42903. effect.setTexture("reflection2DSampler", this._reflectionTexture);
  42904. }
  42905. }
  42906. if (this._emissiveTexture && StandardMaterial.EmissiveTextureEnabled) {
  42907. effect.setTexture("emissiveSampler", this._emissiveTexture);
  42908. }
  42909. if (this._lightmapTexture && StandardMaterial.LightmapTextureEnabled) {
  42910. effect.setTexture("lightmapSampler", this._lightmapTexture);
  42911. }
  42912. if (this._specularTexture && StandardMaterial.SpecularTextureEnabled) {
  42913. effect.setTexture("specularSampler", this._specularTexture);
  42914. }
  42915. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && StandardMaterial.BumpTextureEnabled) {
  42916. effect.setTexture("bumpSampler", this._bumpTexture);
  42917. }
  42918. if (this._refractionTexture && StandardMaterial.RefractionTextureEnabled) {
  42919. var depth = 1.0;
  42920. if (this._refractionTexture.isCube) {
  42921. effect.setTexture("refractionCubeSampler", this._refractionTexture);
  42922. }
  42923. else {
  42924. effect.setTexture("refraction2DSampler", this._refractionTexture);
  42925. }
  42926. }
  42927. }
  42928. // Clip plane
  42929. BABYLON.MaterialHelper.BindClipPlane(effect, scene);
  42930. // Colors
  42931. scene.ambientColor.multiplyToRef(this.ambientColor, this._globalAmbientColor);
  42932. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  42933. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  42934. }
  42935. if (mustRebind || !this.isFrozen) {
  42936. // Lights
  42937. if (scene.lightsEnabled && !this._disableLighting) {
  42938. BABYLON.MaterialHelper.BindLights(scene, mesh, effect, defines, this._maxSimultaneousLights);
  42939. }
  42940. // View
  42941. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || this._reflectionTexture || this._refractionTexture) {
  42942. this.bindView(effect);
  42943. }
  42944. // Fog
  42945. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, effect);
  42946. // Morph targets
  42947. if (defines.NUM_MORPH_INFLUENCERS) {
  42948. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, effect);
  42949. }
  42950. // Log. depth
  42951. BABYLON.MaterialHelper.BindLogDepth(defines, effect, scene);
  42952. // image processing
  42953. if (this._imageProcessingConfiguration && !this._imageProcessingConfiguration.applyByPostProcess) {
  42954. this._imageProcessingConfiguration.bind(this._activeEffect);
  42955. }
  42956. }
  42957. this._uniformBuffer.update();
  42958. this._afterBind(mesh, this._activeEffect);
  42959. };
  42960. StandardMaterial.prototype.getAnimatables = function () {
  42961. var results = [];
  42962. if (this._diffuseTexture && this._diffuseTexture.animations && this._diffuseTexture.animations.length > 0) {
  42963. results.push(this._diffuseTexture);
  42964. }
  42965. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  42966. results.push(this._ambientTexture);
  42967. }
  42968. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  42969. results.push(this._opacityTexture);
  42970. }
  42971. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  42972. results.push(this._reflectionTexture);
  42973. }
  42974. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  42975. results.push(this._emissiveTexture);
  42976. }
  42977. if (this._specularTexture && this._specularTexture.animations && this._specularTexture.animations.length > 0) {
  42978. results.push(this._specularTexture);
  42979. }
  42980. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  42981. results.push(this._bumpTexture);
  42982. }
  42983. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  42984. results.push(this._lightmapTexture);
  42985. }
  42986. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  42987. results.push(this._refractionTexture);
  42988. }
  42989. return results;
  42990. };
  42991. StandardMaterial.prototype.getActiveTextures = function () {
  42992. var activeTextures = _super.prototype.getActiveTextures.call(this);
  42993. if (this._diffuseTexture) {
  42994. activeTextures.push(this._diffuseTexture);
  42995. }
  42996. if (this._ambientTexture) {
  42997. activeTextures.push(this._ambientTexture);
  42998. }
  42999. if (this._opacityTexture) {
  43000. activeTextures.push(this._opacityTexture);
  43001. }
  43002. if (this._reflectionTexture) {
  43003. activeTextures.push(this._reflectionTexture);
  43004. }
  43005. if (this._emissiveTexture) {
  43006. activeTextures.push(this._emissiveTexture);
  43007. }
  43008. if (this._specularTexture) {
  43009. activeTextures.push(this._specularTexture);
  43010. }
  43011. if (this._bumpTexture) {
  43012. activeTextures.push(this._bumpTexture);
  43013. }
  43014. if (this._lightmapTexture) {
  43015. activeTextures.push(this._lightmapTexture);
  43016. }
  43017. if (this._refractionTexture) {
  43018. activeTextures.push(this._refractionTexture);
  43019. }
  43020. return activeTextures;
  43021. };
  43022. StandardMaterial.prototype.hasTexture = function (texture) {
  43023. if (_super.prototype.hasTexture.call(this, texture)) {
  43024. return true;
  43025. }
  43026. if (this._diffuseTexture === texture) {
  43027. return true;
  43028. }
  43029. if (this._ambientTexture === texture) {
  43030. return true;
  43031. }
  43032. if (this._opacityTexture === texture) {
  43033. return true;
  43034. }
  43035. if (this._reflectionTexture === texture) {
  43036. return true;
  43037. }
  43038. if (this._emissiveTexture === texture) {
  43039. return true;
  43040. }
  43041. if (this._specularTexture === texture) {
  43042. return true;
  43043. }
  43044. if (this._bumpTexture === texture) {
  43045. return true;
  43046. }
  43047. if (this._lightmapTexture === texture) {
  43048. return true;
  43049. }
  43050. if (this._refractionTexture === texture) {
  43051. return true;
  43052. }
  43053. return false;
  43054. };
  43055. StandardMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  43056. if (forceDisposeTextures) {
  43057. if (this._diffuseTexture) {
  43058. this._diffuseTexture.dispose();
  43059. }
  43060. if (this._ambientTexture) {
  43061. this._ambientTexture.dispose();
  43062. }
  43063. if (this._opacityTexture) {
  43064. this._opacityTexture.dispose();
  43065. }
  43066. if (this._reflectionTexture) {
  43067. this._reflectionTexture.dispose();
  43068. }
  43069. if (this._emissiveTexture) {
  43070. this._emissiveTexture.dispose();
  43071. }
  43072. if (this._specularTexture) {
  43073. this._specularTexture.dispose();
  43074. }
  43075. if (this._bumpTexture) {
  43076. this._bumpTexture.dispose();
  43077. }
  43078. if (this._lightmapTexture) {
  43079. this._lightmapTexture.dispose();
  43080. }
  43081. if (this._refractionTexture) {
  43082. this._refractionTexture.dispose();
  43083. }
  43084. }
  43085. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43086. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43087. }
  43088. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  43089. };
  43090. StandardMaterial.prototype.clone = function (name) {
  43091. var _this = this;
  43092. var result = BABYLON.SerializationHelper.Clone(function () { return new StandardMaterial(name, _this.getScene()); }, this);
  43093. result.name = name;
  43094. result.id = name;
  43095. return result;
  43096. };
  43097. StandardMaterial.prototype.serialize = function () {
  43098. return BABYLON.SerializationHelper.Serialize(this);
  43099. };
  43100. // Statics
  43101. StandardMaterial.Parse = function (source, scene, rootUrl) {
  43102. return BABYLON.SerializationHelper.Parse(function () { return new StandardMaterial(source.name, scene); }, source, scene, rootUrl);
  43103. };
  43104. Object.defineProperty(StandardMaterial, "DiffuseTextureEnabled", {
  43105. get: function () {
  43106. return StandardMaterial._DiffuseTextureEnabled;
  43107. },
  43108. set: function (value) {
  43109. if (StandardMaterial._DiffuseTextureEnabled === value) {
  43110. return;
  43111. }
  43112. StandardMaterial._DiffuseTextureEnabled = value;
  43113. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43114. },
  43115. enumerable: true,
  43116. configurable: true
  43117. });
  43118. Object.defineProperty(StandardMaterial, "AmbientTextureEnabled", {
  43119. get: function () {
  43120. return StandardMaterial._AmbientTextureEnabled;
  43121. },
  43122. set: function (value) {
  43123. if (StandardMaterial._AmbientTextureEnabled === value) {
  43124. return;
  43125. }
  43126. StandardMaterial._AmbientTextureEnabled = value;
  43127. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43128. },
  43129. enumerable: true,
  43130. configurable: true
  43131. });
  43132. Object.defineProperty(StandardMaterial, "OpacityTextureEnabled", {
  43133. get: function () {
  43134. return StandardMaterial._OpacityTextureEnabled;
  43135. },
  43136. set: function (value) {
  43137. if (StandardMaterial._OpacityTextureEnabled === value) {
  43138. return;
  43139. }
  43140. StandardMaterial._OpacityTextureEnabled = value;
  43141. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43142. },
  43143. enumerable: true,
  43144. configurable: true
  43145. });
  43146. Object.defineProperty(StandardMaterial, "ReflectionTextureEnabled", {
  43147. get: function () {
  43148. return StandardMaterial._ReflectionTextureEnabled;
  43149. },
  43150. set: function (value) {
  43151. if (StandardMaterial._ReflectionTextureEnabled === value) {
  43152. return;
  43153. }
  43154. StandardMaterial._ReflectionTextureEnabled = value;
  43155. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43156. },
  43157. enumerable: true,
  43158. configurable: true
  43159. });
  43160. Object.defineProperty(StandardMaterial, "EmissiveTextureEnabled", {
  43161. get: function () {
  43162. return StandardMaterial._EmissiveTextureEnabled;
  43163. },
  43164. set: function (value) {
  43165. if (StandardMaterial._EmissiveTextureEnabled === value) {
  43166. return;
  43167. }
  43168. StandardMaterial._EmissiveTextureEnabled = value;
  43169. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43170. },
  43171. enumerable: true,
  43172. configurable: true
  43173. });
  43174. Object.defineProperty(StandardMaterial, "SpecularTextureEnabled", {
  43175. get: function () {
  43176. return StandardMaterial._SpecularTextureEnabled;
  43177. },
  43178. set: function (value) {
  43179. if (StandardMaterial._SpecularTextureEnabled === value) {
  43180. return;
  43181. }
  43182. StandardMaterial._SpecularTextureEnabled = value;
  43183. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43184. },
  43185. enumerable: true,
  43186. configurable: true
  43187. });
  43188. Object.defineProperty(StandardMaterial, "BumpTextureEnabled", {
  43189. get: function () {
  43190. return StandardMaterial._BumpTextureEnabled;
  43191. },
  43192. set: function (value) {
  43193. if (StandardMaterial._BumpTextureEnabled === value) {
  43194. return;
  43195. }
  43196. StandardMaterial._BumpTextureEnabled = value;
  43197. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43198. },
  43199. enumerable: true,
  43200. configurable: true
  43201. });
  43202. Object.defineProperty(StandardMaterial, "LightmapTextureEnabled", {
  43203. get: function () {
  43204. return StandardMaterial._LightmapTextureEnabled;
  43205. },
  43206. set: function (value) {
  43207. if (StandardMaterial._LightmapTextureEnabled === value) {
  43208. return;
  43209. }
  43210. StandardMaterial._LightmapTextureEnabled = value;
  43211. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43212. },
  43213. enumerable: true,
  43214. configurable: true
  43215. });
  43216. Object.defineProperty(StandardMaterial, "RefractionTextureEnabled", {
  43217. get: function () {
  43218. return StandardMaterial._RefractionTextureEnabled;
  43219. },
  43220. set: function (value) {
  43221. if (StandardMaterial._RefractionTextureEnabled === value) {
  43222. return;
  43223. }
  43224. StandardMaterial._RefractionTextureEnabled = value;
  43225. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43226. },
  43227. enumerable: true,
  43228. configurable: true
  43229. });
  43230. Object.defineProperty(StandardMaterial, "ColorGradingTextureEnabled", {
  43231. get: function () {
  43232. return StandardMaterial._ColorGradingTextureEnabled;
  43233. },
  43234. set: function (value) {
  43235. if (StandardMaterial._ColorGradingTextureEnabled === value) {
  43236. return;
  43237. }
  43238. StandardMaterial._ColorGradingTextureEnabled = value;
  43239. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  43240. },
  43241. enumerable: true,
  43242. configurable: true
  43243. });
  43244. Object.defineProperty(StandardMaterial, "FresnelEnabled", {
  43245. get: function () {
  43246. return StandardMaterial._FresnelEnabled;
  43247. },
  43248. set: function (value) {
  43249. if (StandardMaterial._FresnelEnabled === value) {
  43250. return;
  43251. }
  43252. StandardMaterial._FresnelEnabled = value;
  43253. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag);
  43254. },
  43255. enumerable: true,
  43256. configurable: true
  43257. });
  43258. // Flags used to enable or disable a type of texture for all Standard Materials
  43259. StandardMaterial._DiffuseTextureEnabled = true;
  43260. StandardMaterial._AmbientTextureEnabled = true;
  43261. StandardMaterial._OpacityTextureEnabled = true;
  43262. StandardMaterial._ReflectionTextureEnabled = true;
  43263. StandardMaterial._EmissiveTextureEnabled = true;
  43264. StandardMaterial._SpecularTextureEnabled = true;
  43265. StandardMaterial._BumpTextureEnabled = true;
  43266. StandardMaterial._LightmapTextureEnabled = true;
  43267. StandardMaterial._RefractionTextureEnabled = true;
  43268. StandardMaterial._ColorGradingTextureEnabled = true;
  43269. StandardMaterial._FresnelEnabled = true;
  43270. __decorate([
  43271. BABYLON.serializeAsTexture("diffuseTexture")
  43272. ], StandardMaterial.prototype, "_diffuseTexture", void 0);
  43273. __decorate([
  43274. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43275. ], StandardMaterial.prototype, "diffuseTexture", void 0);
  43276. __decorate([
  43277. BABYLON.serializeAsTexture("ambientTexture")
  43278. ], StandardMaterial.prototype, "_ambientTexture", void 0);
  43279. __decorate([
  43280. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43281. ], StandardMaterial.prototype, "ambientTexture", void 0);
  43282. __decorate([
  43283. BABYLON.serializeAsTexture("opacityTexture")
  43284. ], StandardMaterial.prototype, "_opacityTexture", void 0);
  43285. __decorate([
  43286. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  43287. ], StandardMaterial.prototype, "opacityTexture", void 0);
  43288. __decorate([
  43289. BABYLON.serializeAsTexture("reflectionTexture")
  43290. ], StandardMaterial.prototype, "_reflectionTexture", void 0);
  43291. __decorate([
  43292. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43293. ], StandardMaterial.prototype, "reflectionTexture", void 0);
  43294. __decorate([
  43295. BABYLON.serializeAsTexture("emissiveTexture")
  43296. ], StandardMaterial.prototype, "_emissiveTexture", void 0);
  43297. __decorate([
  43298. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43299. ], StandardMaterial.prototype, "emissiveTexture", void 0);
  43300. __decorate([
  43301. BABYLON.serializeAsTexture("specularTexture")
  43302. ], StandardMaterial.prototype, "_specularTexture", void 0);
  43303. __decorate([
  43304. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43305. ], StandardMaterial.prototype, "specularTexture", void 0);
  43306. __decorate([
  43307. BABYLON.serializeAsTexture("bumpTexture")
  43308. ], StandardMaterial.prototype, "_bumpTexture", void 0);
  43309. __decorate([
  43310. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43311. ], StandardMaterial.prototype, "bumpTexture", void 0);
  43312. __decorate([
  43313. BABYLON.serializeAsTexture("lightmapTexture")
  43314. ], StandardMaterial.prototype, "_lightmapTexture", void 0);
  43315. __decorate([
  43316. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43317. ], StandardMaterial.prototype, "lightmapTexture", void 0);
  43318. __decorate([
  43319. BABYLON.serializeAsTexture("refractionTexture")
  43320. ], StandardMaterial.prototype, "_refractionTexture", void 0);
  43321. __decorate([
  43322. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43323. ], StandardMaterial.prototype, "refractionTexture", void 0);
  43324. __decorate([
  43325. BABYLON.serializeAsColor3("ambient")
  43326. ], StandardMaterial.prototype, "ambientColor", void 0);
  43327. __decorate([
  43328. BABYLON.serializeAsColor3("diffuse")
  43329. ], StandardMaterial.prototype, "diffuseColor", void 0);
  43330. __decorate([
  43331. BABYLON.serializeAsColor3("specular")
  43332. ], StandardMaterial.prototype, "specularColor", void 0);
  43333. __decorate([
  43334. BABYLON.serializeAsColor3("emissive")
  43335. ], StandardMaterial.prototype, "emissiveColor", void 0);
  43336. __decorate([
  43337. BABYLON.serialize()
  43338. ], StandardMaterial.prototype, "specularPower", void 0);
  43339. __decorate([
  43340. BABYLON.serialize("useAlphaFromDiffuseTexture")
  43341. ], StandardMaterial.prototype, "_useAlphaFromDiffuseTexture", void 0);
  43342. __decorate([
  43343. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43344. ], StandardMaterial.prototype, "useAlphaFromDiffuseTexture", void 0);
  43345. __decorate([
  43346. BABYLON.serialize("useEmissiveAsIllumination")
  43347. ], StandardMaterial.prototype, "_useEmissiveAsIllumination", void 0);
  43348. __decorate([
  43349. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43350. ], StandardMaterial.prototype, "useEmissiveAsIllumination", void 0);
  43351. __decorate([
  43352. BABYLON.serialize("linkEmissiveWithDiffuse")
  43353. ], StandardMaterial.prototype, "_linkEmissiveWithDiffuse", void 0);
  43354. __decorate([
  43355. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43356. ], StandardMaterial.prototype, "linkEmissiveWithDiffuse", void 0);
  43357. __decorate([
  43358. BABYLON.serialize("useSpecularOverAlpha")
  43359. ], StandardMaterial.prototype, "_useSpecularOverAlpha", void 0);
  43360. __decorate([
  43361. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43362. ], StandardMaterial.prototype, "useSpecularOverAlpha", void 0);
  43363. __decorate([
  43364. BABYLON.serialize("useReflectionOverAlpha")
  43365. ], StandardMaterial.prototype, "_useReflectionOverAlpha", void 0);
  43366. __decorate([
  43367. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43368. ], StandardMaterial.prototype, "useReflectionOverAlpha", void 0);
  43369. __decorate([
  43370. BABYLON.serialize("disableLighting")
  43371. ], StandardMaterial.prototype, "_disableLighting", void 0);
  43372. __decorate([
  43373. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43374. ], StandardMaterial.prototype, "disableLighting", void 0);
  43375. __decorate([
  43376. BABYLON.serialize("useObjectSpaceNormalMap")
  43377. ], StandardMaterial.prototype, "_useObjectSpaceNormalMap", void 0);
  43378. __decorate([
  43379. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43380. ], StandardMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  43381. __decorate([
  43382. BABYLON.serialize("useParallax")
  43383. ], StandardMaterial.prototype, "_useParallax", void 0);
  43384. __decorate([
  43385. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43386. ], StandardMaterial.prototype, "useParallax", void 0);
  43387. __decorate([
  43388. BABYLON.serialize("useParallaxOcclusion")
  43389. ], StandardMaterial.prototype, "_useParallaxOcclusion", void 0);
  43390. __decorate([
  43391. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43392. ], StandardMaterial.prototype, "useParallaxOcclusion", void 0);
  43393. __decorate([
  43394. BABYLON.serialize()
  43395. ], StandardMaterial.prototype, "parallaxScaleBias", void 0);
  43396. __decorate([
  43397. BABYLON.serialize("roughness")
  43398. ], StandardMaterial.prototype, "_roughness", void 0);
  43399. __decorate([
  43400. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43401. ], StandardMaterial.prototype, "roughness", void 0);
  43402. __decorate([
  43403. BABYLON.serialize()
  43404. ], StandardMaterial.prototype, "indexOfRefraction", void 0);
  43405. __decorate([
  43406. BABYLON.serialize()
  43407. ], StandardMaterial.prototype, "invertRefractionY", void 0);
  43408. __decorate([
  43409. BABYLON.serialize()
  43410. ], StandardMaterial.prototype, "alphaCutOff", void 0);
  43411. __decorate([
  43412. BABYLON.serialize("useLightmapAsShadowmap")
  43413. ], StandardMaterial.prototype, "_useLightmapAsShadowmap", void 0);
  43414. __decorate([
  43415. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43416. ], StandardMaterial.prototype, "useLightmapAsShadowmap", void 0);
  43417. __decorate([
  43418. BABYLON.serializeAsFresnelParameters("diffuseFresnelParameters")
  43419. ], StandardMaterial.prototype, "_diffuseFresnelParameters", void 0);
  43420. __decorate([
  43421. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43422. ], StandardMaterial.prototype, "diffuseFresnelParameters", void 0);
  43423. __decorate([
  43424. BABYLON.serializeAsFresnelParameters("opacityFresnelParameters")
  43425. ], StandardMaterial.prototype, "_opacityFresnelParameters", void 0);
  43426. __decorate([
  43427. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelAndMiscDirty")
  43428. ], StandardMaterial.prototype, "opacityFresnelParameters", void 0);
  43429. __decorate([
  43430. BABYLON.serializeAsFresnelParameters("reflectionFresnelParameters")
  43431. ], StandardMaterial.prototype, "_reflectionFresnelParameters", void 0);
  43432. __decorate([
  43433. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43434. ], StandardMaterial.prototype, "reflectionFresnelParameters", void 0);
  43435. __decorate([
  43436. BABYLON.serializeAsFresnelParameters("refractionFresnelParameters")
  43437. ], StandardMaterial.prototype, "_refractionFresnelParameters", void 0);
  43438. __decorate([
  43439. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43440. ], StandardMaterial.prototype, "refractionFresnelParameters", void 0);
  43441. __decorate([
  43442. BABYLON.serializeAsFresnelParameters("emissiveFresnelParameters")
  43443. ], StandardMaterial.prototype, "_emissiveFresnelParameters", void 0);
  43444. __decorate([
  43445. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43446. ], StandardMaterial.prototype, "emissiveFresnelParameters", void 0);
  43447. __decorate([
  43448. BABYLON.serialize("useReflectionFresnelFromSpecular")
  43449. ], StandardMaterial.prototype, "_useReflectionFresnelFromSpecular", void 0);
  43450. __decorate([
  43451. BABYLON.expandToProperty("_markAllSubMeshesAsFresnelDirty")
  43452. ], StandardMaterial.prototype, "useReflectionFresnelFromSpecular", void 0);
  43453. __decorate([
  43454. BABYLON.serialize("useGlossinessFromSpecularMapAlpha")
  43455. ], StandardMaterial.prototype, "_useGlossinessFromSpecularMapAlpha", void 0);
  43456. __decorate([
  43457. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43458. ], StandardMaterial.prototype, "useGlossinessFromSpecularMapAlpha", void 0);
  43459. __decorate([
  43460. BABYLON.serialize("maxSimultaneousLights")
  43461. ], StandardMaterial.prototype, "_maxSimultaneousLights", void 0);
  43462. __decorate([
  43463. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  43464. ], StandardMaterial.prototype, "maxSimultaneousLights", void 0);
  43465. __decorate([
  43466. BABYLON.serialize("invertNormalMapX")
  43467. ], StandardMaterial.prototype, "_invertNormalMapX", void 0);
  43468. __decorate([
  43469. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43470. ], StandardMaterial.prototype, "invertNormalMapX", void 0);
  43471. __decorate([
  43472. BABYLON.serialize("invertNormalMapY")
  43473. ], StandardMaterial.prototype, "_invertNormalMapY", void 0);
  43474. __decorate([
  43475. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43476. ], StandardMaterial.prototype, "invertNormalMapY", void 0);
  43477. __decorate([
  43478. BABYLON.serialize("twoSidedLighting")
  43479. ], StandardMaterial.prototype, "_twoSidedLighting", void 0);
  43480. __decorate([
  43481. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  43482. ], StandardMaterial.prototype, "twoSidedLighting", void 0);
  43483. __decorate([
  43484. BABYLON.serialize()
  43485. ], StandardMaterial.prototype, "useLogarithmicDepth", null);
  43486. return StandardMaterial;
  43487. }(BABYLON.PushMaterial));
  43488. BABYLON.StandardMaterial = StandardMaterial;
  43489. })(BABYLON || (BABYLON = {}));
  43490. //# sourceMappingURL=babylon.standardMaterial.js.map
  43491. var BABYLON;
  43492. (function (BABYLON) {
  43493. /**
  43494. * Manages the defines for the PBR Material.
  43495. * @hiddenChildren
  43496. */
  43497. var PBRMaterialDefines = /** @class */ (function (_super) {
  43498. __extends(PBRMaterialDefines, _super);
  43499. /**
  43500. * Initializes the PBR Material defines.
  43501. */
  43502. function PBRMaterialDefines() {
  43503. var _this = _super.call(this) || this;
  43504. _this.PBR = true;
  43505. _this.MAINUV1 = false;
  43506. _this.MAINUV2 = false;
  43507. _this.UV1 = false;
  43508. _this.UV2 = false;
  43509. _this.ALBEDO = false;
  43510. _this.ALBEDODIRECTUV = 0;
  43511. _this.VERTEXCOLOR = false;
  43512. _this.AMBIENT = false;
  43513. _this.AMBIENTDIRECTUV = 0;
  43514. _this.AMBIENTINGRAYSCALE = false;
  43515. _this.OPACITY = false;
  43516. _this.VERTEXALPHA = false;
  43517. _this.OPACITYDIRECTUV = 0;
  43518. _this.OPACITYRGB = false;
  43519. _this.ALPHATEST = false;
  43520. _this.DEPTHPREPASS = false;
  43521. _this.ALPHABLEND = false;
  43522. _this.ALPHAFROMALBEDO = false;
  43523. _this.ALPHATESTVALUE = "0.5";
  43524. _this.SPECULAROVERALPHA = false;
  43525. _this.RADIANCEOVERALPHA = false;
  43526. _this.ALPHAFRESNEL = false;
  43527. _this.LINEARALPHAFRESNEL = false;
  43528. _this.PREMULTIPLYALPHA = false;
  43529. _this.EMISSIVE = false;
  43530. _this.EMISSIVEDIRECTUV = 0;
  43531. _this.REFLECTIVITY = false;
  43532. _this.REFLECTIVITYDIRECTUV = 0;
  43533. _this.SPECULARTERM = false;
  43534. _this.MICROSURFACEFROMREFLECTIVITYMAP = false;
  43535. _this.MICROSURFACEAUTOMATIC = false;
  43536. _this.LODBASEDMICROSFURACE = false;
  43537. _this.MICROSURFACEMAP = false;
  43538. _this.MICROSURFACEMAPDIRECTUV = 0;
  43539. _this.METALLICWORKFLOW = false;
  43540. _this.ROUGHNESSSTOREINMETALMAPALPHA = false;
  43541. _this.ROUGHNESSSTOREINMETALMAPGREEN = false;
  43542. _this.METALLNESSSTOREINMETALMAPBLUE = false;
  43543. _this.AOSTOREINMETALMAPRED = false;
  43544. _this.ENVIRONMENTBRDF = false;
  43545. _this.NORMAL = false;
  43546. _this.TANGENT = false;
  43547. _this.BUMP = false;
  43548. _this.BUMPDIRECTUV = 0;
  43549. _this.OBJECTSPACE_NORMALMAP = false;
  43550. _this.PARALLAX = false;
  43551. _this.PARALLAXOCCLUSION = false;
  43552. _this.NORMALXYSCALE = true;
  43553. _this.LIGHTMAP = false;
  43554. _this.LIGHTMAPDIRECTUV = 0;
  43555. _this.USELIGHTMAPASSHADOWMAP = false;
  43556. _this.GAMMALIGHTMAP = false;
  43557. _this.REFLECTION = false;
  43558. _this.REFLECTIONMAP_3D = false;
  43559. _this.REFLECTIONMAP_SPHERICAL = false;
  43560. _this.REFLECTIONMAP_PLANAR = false;
  43561. _this.REFLECTIONMAP_CUBIC = false;
  43562. _this.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  43563. _this.REFLECTIONMAP_PROJECTION = false;
  43564. _this.REFLECTIONMAP_SKYBOX = false;
  43565. _this.REFLECTIONMAP_EXPLICIT = false;
  43566. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  43567. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  43568. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  43569. _this.INVERTCUBICMAP = false;
  43570. _this.USESPHERICALFROMREFLECTIONMAP = false;
  43571. _this.USESPHERICALINVERTEX = false;
  43572. _this.REFLECTIONMAP_OPPOSITEZ = false;
  43573. _this.LODINREFLECTIONALPHA = false;
  43574. _this.GAMMAREFLECTION = false;
  43575. _this.RGBDREFLECTION = false;
  43576. _this.RADIANCEOCCLUSION = false;
  43577. _this.HORIZONOCCLUSION = false;
  43578. _this.REFRACTION = false;
  43579. _this.REFRACTIONMAP_3D = false;
  43580. _this.REFRACTIONMAP_OPPOSITEZ = false;
  43581. _this.LODINREFRACTIONALPHA = false;
  43582. _this.GAMMAREFRACTION = false;
  43583. _this.RGBDREFRACTION = false;
  43584. _this.LINKREFRACTIONTOTRANSPARENCY = false;
  43585. _this.INSTANCES = false;
  43586. _this.NUM_BONE_INFLUENCERS = 0;
  43587. _this.BonesPerMesh = 0;
  43588. _this.NONUNIFORMSCALING = false;
  43589. _this.MORPHTARGETS = false;
  43590. _this.MORPHTARGETS_NORMAL = false;
  43591. _this.MORPHTARGETS_TANGENT = false;
  43592. _this.NUM_MORPH_INFLUENCERS = 0;
  43593. _this.IMAGEPROCESSING = false;
  43594. _this.VIGNETTE = false;
  43595. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  43596. _this.VIGNETTEBLENDMODEOPAQUE = false;
  43597. _this.TONEMAPPING = false;
  43598. _this.CONTRAST = false;
  43599. _this.COLORCURVES = false;
  43600. _this.COLORGRADING = false;
  43601. _this.COLORGRADING3D = false;
  43602. _this.SAMPLER3DGREENDEPTH = false;
  43603. _this.SAMPLER3DBGRMAP = false;
  43604. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  43605. _this.EXPOSURE = false;
  43606. _this.USEPHYSICALLIGHTFALLOFF = false;
  43607. _this.TWOSIDEDLIGHTING = false;
  43608. _this.SHADOWFLOAT = false;
  43609. _this.CLIPPLANE = false;
  43610. _this.POINTSIZE = false;
  43611. _this.FOG = false;
  43612. _this.LOGARITHMICDEPTH = false;
  43613. _this.FORCENORMALFORWARD = false;
  43614. _this.SPECULARAA = false;
  43615. _this.UNLIT = false;
  43616. _this.rebuild();
  43617. return _this;
  43618. }
  43619. /**
  43620. * Resets the PBR Material defines.
  43621. */
  43622. PBRMaterialDefines.prototype.reset = function () {
  43623. _super.prototype.reset.call(this);
  43624. this.ALPHATESTVALUE = "0.5";
  43625. this.PBR = true;
  43626. };
  43627. return PBRMaterialDefines;
  43628. }(BABYLON.MaterialDefines));
  43629. /**
  43630. * The Physically based material base class of BJS.
  43631. *
  43632. * This offers the main features of a standard PBR material.
  43633. * For more information, please refer to the documentation :
  43634. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  43635. */
  43636. var PBRBaseMaterial = /** @class */ (function (_super) {
  43637. __extends(PBRBaseMaterial, _super);
  43638. /**
  43639. * Instantiates a new PBRMaterial instance.
  43640. *
  43641. * @param name The material name
  43642. * @param scene The scene the material will be use in.
  43643. */
  43644. function PBRBaseMaterial(name, scene) {
  43645. var _this = _super.call(this, name, scene) || this;
  43646. /**
  43647. * Intensity of the direct lights e.g. the four lights available in your scene.
  43648. * This impacts both the direct diffuse and specular highlights.
  43649. */
  43650. _this._directIntensity = 1.0;
  43651. /**
  43652. * Intensity of the emissive part of the material.
  43653. * This helps controlling the emissive effect without modifying the emissive color.
  43654. */
  43655. _this._emissiveIntensity = 1.0;
  43656. /**
  43657. * Intensity of the environment e.g. how much the environment will light the object
  43658. * either through harmonics for rough material or through the refelction for shiny ones.
  43659. */
  43660. _this._environmentIntensity = 1.0;
  43661. /**
  43662. * This is a special control allowing the reduction of the specular highlights coming from the
  43663. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  43664. */
  43665. _this._specularIntensity = 1.0;
  43666. /**
  43667. * This stores the direct, emissive, environment, and specular light intensities into a Vector4.
  43668. */
  43669. _this._lightingInfos = new BABYLON.Vector4(_this._directIntensity, _this._emissiveIntensity, _this._environmentIntensity, _this._specularIntensity);
  43670. /**
  43671. * Debug Control allowing disabling the bump map on this material.
  43672. */
  43673. _this._disableBumpMap = false;
  43674. /**
  43675. * AKA Occlusion Texture Intensity in other nomenclature.
  43676. */
  43677. _this._ambientTextureStrength = 1.0;
  43678. /**
  43679. * The color of a material in ambient lighting.
  43680. */
  43681. _this._ambientColor = new BABYLON.Color3(0, 0, 0);
  43682. /**
  43683. * AKA Diffuse Color in other nomenclature.
  43684. */
  43685. _this._albedoColor = new BABYLON.Color3(1, 1, 1);
  43686. /**
  43687. * AKA Specular Color in other nomenclature.
  43688. */
  43689. _this._reflectivityColor = new BABYLON.Color3(1, 1, 1);
  43690. /**
  43691. * The color applied when light is reflected from a material.
  43692. */
  43693. _this._reflectionColor = new BABYLON.Color3(1, 1, 1);
  43694. /**
  43695. * The color applied when light is emitted from a material.
  43696. */
  43697. _this._emissiveColor = new BABYLON.Color3(0, 0, 0);
  43698. /**
  43699. * AKA Glossiness in other nomenclature.
  43700. */
  43701. _this._microSurface = 0.9;
  43702. /**
  43703. * source material index of refraction (IOR)' / 'destination material IOR.
  43704. */
  43705. _this._indexOfRefraction = 0.66;
  43706. /**
  43707. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  43708. */
  43709. _this._invertRefractionY = false;
  43710. /**
  43711. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  43712. * Materials half opaque for instance using refraction could benefit from this control.
  43713. */
  43714. _this._linkRefractionWithTransparency = false;
  43715. /**
  43716. * Specifies that the material will use the light map as a show map.
  43717. */
  43718. _this._useLightmapAsShadowmap = false;
  43719. /**
  43720. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  43721. * makes the reflect vector face the model (under horizon).
  43722. */
  43723. _this._useHorizonOcclusion = true;
  43724. /**
  43725. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  43726. * too much the area relying on ambient texture to define their ambient occlusion.
  43727. */
  43728. _this._useRadianceOcclusion = true;
  43729. /**
  43730. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  43731. */
  43732. _this._useAlphaFromAlbedoTexture = false;
  43733. /**
  43734. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  43735. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  43736. */
  43737. _this._useSpecularOverAlpha = true;
  43738. /**
  43739. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  43740. */
  43741. _this._useMicroSurfaceFromReflectivityMapAlpha = false;
  43742. /**
  43743. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  43744. */
  43745. _this._useRoughnessFromMetallicTextureAlpha = true;
  43746. /**
  43747. * Specifies if the metallic texture contains the roughness information in its green channel.
  43748. */
  43749. _this._useRoughnessFromMetallicTextureGreen = false;
  43750. /**
  43751. * Specifies if the metallic texture contains the metallness information in its blue channel.
  43752. */
  43753. _this._useMetallnessFromMetallicTextureBlue = false;
  43754. /**
  43755. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  43756. */
  43757. _this._useAmbientOcclusionFromMetallicTextureRed = false;
  43758. /**
  43759. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  43760. */
  43761. _this._useAmbientInGrayScale = false;
  43762. /**
  43763. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  43764. * The material will try to infer what glossiness each pixel should be.
  43765. */
  43766. _this._useAutoMicroSurfaceFromReflectivityMap = false;
  43767. /**
  43768. * BJS is using an harcoded light falloff based on a manually sets up range.
  43769. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  43770. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  43771. */
  43772. _this._usePhysicalLightFalloff = true;
  43773. /**
  43774. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  43775. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  43776. */
  43777. _this._useRadianceOverAlpha = true;
  43778. /**
  43779. * Allows using an object space normal map (instead of tangent space).
  43780. */
  43781. _this._useObjectSpaceNormalMap = false;
  43782. /**
  43783. * Allows using the bump map in parallax mode.
  43784. */
  43785. _this._useParallax = false;
  43786. /**
  43787. * Allows using the bump map in parallax occlusion mode.
  43788. */
  43789. _this._useParallaxOcclusion = false;
  43790. /**
  43791. * Controls the scale bias of the parallax mode.
  43792. */
  43793. _this._parallaxScaleBias = 0.05;
  43794. /**
  43795. * If sets to true, disables all the lights affecting the material.
  43796. */
  43797. _this._disableLighting = false;
  43798. /**
  43799. * Number of Simultaneous lights allowed on the material.
  43800. */
  43801. _this._maxSimultaneousLights = 4;
  43802. /**
  43803. * If sets to true, x component of normal map value will be inverted (x = 1.0 - x).
  43804. */
  43805. _this._invertNormalMapX = false;
  43806. /**
  43807. * If sets to true, y component of normal map value will be inverted (y = 1.0 - y).
  43808. */
  43809. _this._invertNormalMapY = false;
  43810. /**
  43811. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  43812. */
  43813. _this._twoSidedLighting = false;
  43814. /**
  43815. * Defines the alpha limits in alpha test mode.
  43816. */
  43817. _this._alphaCutOff = 0.4;
  43818. /**
  43819. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  43820. */
  43821. _this._forceAlphaTest = false;
  43822. /**
  43823. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43824. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  43825. */
  43826. _this._useAlphaFresnel = false;
  43827. /**
  43828. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  43829. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  43830. */
  43831. _this._useLinearAlphaFresnel = false;
  43832. /**
  43833. * The transparency mode of the material.
  43834. */
  43835. _this._transparencyMode = null;
  43836. /**
  43837. * Specifies the environment BRDF texture used to comput the scale and offset roughness values
  43838. * from cos thetav and roughness:
  43839. * http://blog.selfshadow.com/publications/s2013-shading-course/karis/s2013_pbs_epic_notes_v2.pdf
  43840. */
  43841. _this._environmentBRDFTexture = null;
  43842. /**
  43843. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  43844. */
  43845. _this._forceIrradianceInFragment = false;
  43846. /**
  43847. * Force normal to face away from face.
  43848. */
  43849. _this._forceNormalForward = false;
  43850. /**
  43851. * Enables specular anti aliasing in the PBR shader.
  43852. * It will both interacts on the Geometry for analytical and IBL lighting.
  43853. * It also prefilter the roughness map based on the bump values.
  43854. */
  43855. _this._enableSpecularAntiAliasing = false;
  43856. /**
  43857. * Stores the available render targets.
  43858. */
  43859. _this._renderTargets = new BABYLON.SmartArray(16);
  43860. /**
  43861. * Sets the global ambient color for the material used in lighting calculations.
  43862. */
  43863. _this._globalAmbientColor = new BABYLON.Color3(0, 0, 0);
  43864. /**
  43865. * If set to true, no lighting calculations will be applied.
  43866. */
  43867. _this._unlit = false;
  43868. // Setup the default processing configuration to the scene.
  43869. _this._attachImageProcessingConfiguration(null);
  43870. _this.getRenderTargetTextures = function () {
  43871. _this._renderTargets.reset();
  43872. if (BABYLON.StandardMaterial.ReflectionTextureEnabled && _this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  43873. _this._renderTargets.push(_this._reflectionTexture);
  43874. }
  43875. if (BABYLON.StandardMaterial.RefractionTextureEnabled && _this._refractionTexture && _this._refractionTexture.isRenderTarget) {
  43876. _this._renderTargets.push(_this._refractionTexture);
  43877. }
  43878. return _this._renderTargets;
  43879. };
  43880. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  43881. return _this;
  43882. }
  43883. /**
  43884. * Attaches a new image processing configuration to the PBR Material.
  43885. * @param configuration
  43886. */
  43887. PBRBaseMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  43888. var _this = this;
  43889. if (configuration === this._imageProcessingConfiguration) {
  43890. return;
  43891. }
  43892. // Detaches observer.
  43893. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  43894. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  43895. }
  43896. // Pick the scene configuration if needed.
  43897. if (!configuration) {
  43898. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  43899. }
  43900. else {
  43901. this._imageProcessingConfiguration = configuration;
  43902. }
  43903. // Attaches observer.
  43904. if (this._imageProcessingConfiguration) {
  43905. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  43906. _this._markAllSubMeshesAsImageProcessingDirty();
  43907. });
  43908. }
  43909. };
  43910. /**
  43911. * Gets the name of the material class.
  43912. */
  43913. PBRBaseMaterial.prototype.getClassName = function () {
  43914. return "PBRBaseMaterial";
  43915. };
  43916. Object.defineProperty(PBRBaseMaterial.prototype, "useLogarithmicDepth", {
  43917. /**
  43918. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43919. */
  43920. get: function () {
  43921. return this._useLogarithmicDepth;
  43922. },
  43923. /**
  43924. * Enabled the use of logarithmic depth buffers, which is good for wide depth buffers.
  43925. */
  43926. set: function (value) {
  43927. this._useLogarithmicDepth = value && this.getScene().getEngine().getCaps().fragmentDepthSupported;
  43928. },
  43929. enumerable: true,
  43930. configurable: true
  43931. });
  43932. Object.defineProperty(PBRBaseMaterial.prototype, "transparencyMode", {
  43933. /**
  43934. * Gets the current transparency mode.
  43935. */
  43936. get: function () {
  43937. return this._transparencyMode;
  43938. },
  43939. /**
  43940. * Sets the transparency mode of the material.
  43941. *
  43942. * | Value | Type | Description |
  43943. * | ----- | ----------------------------------- | ----------- |
  43944. * | 0 | OPAQUE | |
  43945. * | 1 | ALPHATEST | |
  43946. * | 2 | ALPHABLEND | |
  43947. * | 3 | ALPHATESTANDBLEND | |
  43948. *
  43949. */
  43950. set: function (value) {
  43951. if (this._transparencyMode === value) {
  43952. return;
  43953. }
  43954. this._transparencyMode = value;
  43955. this._forceAlphaTest = (value === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATESTANDBLEND);
  43956. this._markAllSubMeshesAsTexturesAndMiscDirty();
  43957. },
  43958. enumerable: true,
  43959. configurable: true
  43960. });
  43961. Object.defineProperty(PBRBaseMaterial.prototype, "_disableAlphaBlending", {
  43962. /**
  43963. * Returns true if alpha blending should be disabled.
  43964. */
  43965. get: function () {
  43966. return (this._linkRefractionWithTransparency ||
  43967. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE ||
  43968. this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  43969. },
  43970. enumerable: true,
  43971. configurable: true
  43972. });
  43973. /**
  43974. * Specifies whether or not this material should be rendered in alpha blend mode.
  43975. */
  43976. PBRBaseMaterial.prototype.needAlphaBlending = function () {
  43977. if (this._disableAlphaBlending) {
  43978. return false;
  43979. }
  43980. return (this.alpha < 1.0) || (this._opacityTexture != null) || this._shouldUseAlphaFromAlbedoTexture();
  43981. };
  43982. /**
  43983. * Specifies if the mesh will require alpha blending.
  43984. * @param mesh - BJS mesh.
  43985. */
  43986. PBRBaseMaterial.prototype.needAlphaBlendingForMesh = function (mesh) {
  43987. if (this._disableAlphaBlending) {
  43988. return false;
  43989. }
  43990. return _super.prototype.needAlphaBlendingForMesh.call(this, mesh);
  43991. };
  43992. /**
  43993. * Specifies whether or not this material should be rendered in alpha test mode.
  43994. */
  43995. PBRBaseMaterial.prototype.needAlphaTesting = function () {
  43996. if (this._forceAlphaTest) {
  43997. return true;
  43998. }
  43999. if (this._linkRefractionWithTransparency) {
  44000. return false;
  44001. }
  44002. return this._albedoTexture != null && this._albedoTexture.hasAlpha && (this._transparencyMode == null || this._transparencyMode === BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST);
  44003. };
  44004. /**
  44005. * Specifies whether or not the alpha value of the albedo texture should be used for alpha blending.
  44006. */
  44007. PBRBaseMaterial.prototype._shouldUseAlphaFromAlbedoTexture = function () {
  44008. return this._albedoTexture != null && this._albedoTexture.hasAlpha && this._useAlphaFromAlbedoTexture && this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  44009. };
  44010. /**
  44011. * Gets the texture used for the alpha test.
  44012. */
  44013. PBRBaseMaterial.prototype.getAlphaTestTexture = function () {
  44014. return this._albedoTexture;
  44015. };
  44016. /**
  44017. * Specifies that the submesh is ready to be used.
  44018. * @param mesh - BJS mesh.
  44019. * @param subMesh - A submesh of the BJS mesh. Used to check if it is ready.
  44020. * @param useInstances - Specifies that instances should be used.
  44021. * @returns - boolean indicating that the submesh is ready or not.
  44022. */
  44023. PBRBaseMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  44024. if (subMesh.effect && this.isFrozen) {
  44025. if (this._wasPreviouslyReady) {
  44026. return true;
  44027. }
  44028. }
  44029. if (!subMesh._materialDefines) {
  44030. subMesh._materialDefines = new PBRMaterialDefines();
  44031. }
  44032. var defines = subMesh._materialDefines;
  44033. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  44034. if (defines._renderId === this.getScene().getRenderId()) {
  44035. return true;
  44036. }
  44037. }
  44038. var scene = this.getScene();
  44039. var engine = scene.getEngine();
  44040. if (defines._areTexturesDirty) {
  44041. if (scene.texturesEnabled) {
  44042. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44043. if (!this._albedoTexture.isReadyOrNotBlocking()) {
  44044. return false;
  44045. }
  44046. }
  44047. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44048. if (!this._ambientTexture.isReadyOrNotBlocking()) {
  44049. return false;
  44050. }
  44051. }
  44052. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44053. if (!this._opacityTexture.isReadyOrNotBlocking()) {
  44054. return false;
  44055. }
  44056. }
  44057. var reflectionTexture = this._getReflectionTexture();
  44058. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44059. if (!reflectionTexture.isReadyOrNotBlocking()) {
  44060. return false;
  44061. }
  44062. }
  44063. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44064. if (!this._lightmapTexture.isReadyOrNotBlocking()) {
  44065. return false;
  44066. }
  44067. }
  44068. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44069. if (!this._emissiveTexture.isReadyOrNotBlocking()) {
  44070. return false;
  44071. }
  44072. }
  44073. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44074. if (this._metallicTexture) {
  44075. if (!this._metallicTexture.isReadyOrNotBlocking()) {
  44076. return false;
  44077. }
  44078. }
  44079. else if (this._reflectivityTexture) {
  44080. if (!this._reflectivityTexture.isReadyOrNotBlocking()) {
  44081. return false;
  44082. }
  44083. }
  44084. if (this._microSurfaceTexture) {
  44085. if (!this._microSurfaceTexture.isReadyOrNotBlocking()) {
  44086. return false;
  44087. }
  44088. }
  44089. }
  44090. if (engine.getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44091. // Bump texture cannot be not blocking.
  44092. if (!this._bumpTexture.isReady()) {
  44093. return false;
  44094. }
  44095. }
  44096. var refractionTexture = this._getRefractionTexture();
  44097. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44098. if (!refractionTexture.isReadyOrNotBlocking()) {
  44099. return false;
  44100. }
  44101. }
  44102. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44103. // This is blocking.
  44104. if (!this._environmentBRDFTexture.isReady()) {
  44105. return false;
  44106. }
  44107. }
  44108. }
  44109. }
  44110. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44111. if (!this._imageProcessingConfiguration.isReady()) {
  44112. return false;
  44113. }
  44114. }
  44115. if (!engine.getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  44116. mesh.createNormals(true);
  44117. BABYLON.Tools.Warn("PBRMaterial: Normals have been created for the mesh: " + mesh.name);
  44118. }
  44119. var effect = this._prepareEffect(mesh, defines, this.onCompiled, this.onError, useInstances);
  44120. if (effect) {
  44121. scene.resetCachedMaterial();
  44122. subMesh.setEffect(effect, defines);
  44123. this.buildUniformLayout();
  44124. }
  44125. if (!subMesh.effect || !subMesh.effect.isReady()) {
  44126. return false;
  44127. }
  44128. defines._renderId = scene.getRenderId();
  44129. this._wasPreviouslyReady = true;
  44130. return true;
  44131. };
  44132. /**
  44133. * Specifies if the material uses metallic roughness workflow.
  44134. * @returns boolean specifiying if the material uses metallic roughness workflow.
  44135. */
  44136. PBRBaseMaterial.prototype.isMetallicWorkflow = function () {
  44137. if (this._metallic != null || this._roughness != null || this._metallicTexture) {
  44138. return true;
  44139. }
  44140. return false;
  44141. };
  44142. PBRBaseMaterial.prototype._prepareEffect = function (mesh, defines, onCompiled, onError, useInstances, useClipPlane) {
  44143. if (onCompiled === void 0) { onCompiled = null; }
  44144. if (onError === void 0) { onError = null; }
  44145. if (useInstances === void 0) { useInstances = null; }
  44146. if (useClipPlane === void 0) { useClipPlane = null; }
  44147. this._prepareDefines(mesh, defines, useInstances, useClipPlane);
  44148. if (!defines.isDirty) {
  44149. return null;
  44150. }
  44151. defines.markAsProcessed();
  44152. var scene = this.getScene();
  44153. var engine = scene.getEngine();
  44154. // Fallbacks
  44155. var fallbacks = new BABYLON.EffectFallbacks();
  44156. var fallbackRank = 0;
  44157. if (defines.USESPHERICALINVERTEX) {
  44158. fallbacks.addFallback(fallbackRank++, "USESPHERICALINVERTEX");
  44159. }
  44160. if (defines.FOG) {
  44161. fallbacks.addFallback(fallbackRank, "FOG");
  44162. }
  44163. if (defines.SPECULARAA) {
  44164. fallbacks.addFallback(fallbackRank, "SPECULARAA");
  44165. }
  44166. if (defines.POINTSIZE) {
  44167. fallbacks.addFallback(fallbackRank, "POINTSIZE");
  44168. }
  44169. if (defines.LOGARITHMICDEPTH) {
  44170. fallbacks.addFallback(fallbackRank, "LOGARITHMICDEPTH");
  44171. }
  44172. if (defines.PARALLAX) {
  44173. fallbacks.addFallback(fallbackRank, "PARALLAX");
  44174. }
  44175. if (defines.PARALLAXOCCLUSION) {
  44176. fallbacks.addFallback(fallbackRank++, "PARALLAXOCCLUSION");
  44177. }
  44178. if (defines.ENVIRONMENTBRDF) {
  44179. fallbacks.addFallback(fallbackRank++, "ENVIRONMENTBRDF");
  44180. }
  44181. if (defines.TANGENT) {
  44182. fallbacks.addFallback(fallbackRank++, "TANGENT");
  44183. }
  44184. if (defines.BUMP) {
  44185. fallbacks.addFallback(fallbackRank++, "BUMP");
  44186. }
  44187. fallbackRank = BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights, fallbackRank++);
  44188. if (defines.SPECULARTERM) {
  44189. fallbacks.addFallback(fallbackRank++, "SPECULARTERM");
  44190. }
  44191. if (defines.USESPHERICALFROMREFLECTIONMAP) {
  44192. fallbacks.addFallback(fallbackRank++, "USESPHERICALFROMREFLECTIONMAP");
  44193. }
  44194. if (defines.LIGHTMAP) {
  44195. fallbacks.addFallback(fallbackRank++, "LIGHTMAP");
  44196. }
  44197. if (defines.NORMAL) {
  44198. fallbacks.addFallback(fallbackRank++, "NORMAL");
  44199. }
  44200. if (defines.AMBIENT) {
  44201. fallbacks.addFallback(fallbackRank++, "AMBIENT");
  44202. }
  44203. if (defines.EMISSIVE) {
  44204. fallbacks.addFallback(fallbackRank++, "EMISSIVE");
  44205. }
  44206. if (defines.VERTEXCOLOR) {
  44207. fallbacks.addFallback(fallbackRank++, "VERTEXCOLOR");
  44208. }
  44209. if (defines.NUM_BONE_INFLUENCERS > 0) {
  44210. fallbacks.addCPUSkinningFallback(fallbackRank++, mesh);
  44211. }
  44212. if (defines.MORPHTARGETS) {
  44213. fallbacks.addFallback(fallbackRank++, "MORPHTARGETS");
  44214. }
  44215. //Attributes
  44216. var attribs = [BABYLON.VertexBuffer.PositionKind];
  44217. if (defines.NORMAL) {
  44218. attribs.push(BABYLON.VertexBuffer.NormalKind);
  44219. }
  44220. if (defines.TANGENT) {
  44221. attribs.push(BABYLON.VertexBuffer.TangentKind);
  44222. }
  44223. if (defines.UV1) {
  44224. attribs.push(BABYLON.VertexBuffer.UVKind);
  44225. }
  44226. if (defines.UV2) {
  44227. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  44228. }
  44229. if (defines.VERTEXCOLOR) {
  44230. attribs.push(BABYLON.VertexBuffer.ColorKind);
  44231. }
  44232. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  44233. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  44234. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, defines);
  44235. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType", "vAmbientColor", "vAlbedoColor", "vReflectivityColor", "vEmissiveColor", "vReflectionColor",
  44236. "vFogInfos", "vFogColor", "pointSize",
  44237. "vAlbedoInfos", "vAmbientInfos", "vOpacityInfos", "vReflectionInfos", "vReflectionPosition", "vReflectionSize", "vEmissiveInfos", "vReflectivityInfos",
  44238. "vMicroSurfaceSamplerInfos", "vBumpInfos", "vLightmapInfos", "vRefractionInfos",
  44239. "mBones",
  44240. "vClipPlane", "albedoMatrix", "ambientMatrix", "opacityMatrix", "reflectionMatrix", "emissiveMatrix", "reflectivityMatrix", "normalMatrix", "microSurfaceSamplerMatrix", "bumpMatrix", "lightmapMatrix", "refractionMatrix",
  44241. "vLightingIntensity",
  44242. "logarithmicDepthConstant",
  44243. "vSphericalX", "vSphericalY", "vSphericalZ",
  44244. "vSphericalXX", "vSphericalYY", "vSphericalZZ",
  44245. "vSphericalXY", "vSphericalYZ", "vSphericalZX",
  44246. "vReflectionMicrosurfaceInfos", "vRefractionMicrosurfaceInfos",
  44247. "vTangentSpaceParams"
  44248. ];
  44249. var samplers = ["albedoSampler", "reflectivitySampler", "ambientSampler", "emissiveSampler",
  44250. "bumpSampler", "lightmapSampler", "opacitySampler",
  44251. "refractionSampler", "refractionSamplerLow", "refractionSamplerHigh",
  44252. "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh",
  44253. "microSurfaceSampler", "environmentBrdfSampler"];
  44254. var uniformBuffers = ["Material", "Scene"];
  44255. if (BABYLON.ImageProcessingConfiguration) {
  44256. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  44257. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  44258. }
  44259. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  44260. uniformsNames: uniforms,
  44261. uniformBuffersNames: uniformBuffers,
  44262. samplers: samplers,
  44263. defines: defines,
  44264. maxSimultaneousLights: this._maxSimultaneousLights
  44265. });
  44266. var join = defines.toString();
  44267. return engine.createEffect("pbr", {
  44268. attributes: attribs,
  44269. uniformsNames: uniforms,
  44270. uniformBuffersNames: uniformBuffers,
  44271. samplers: samplers,
  44272. defines: join,
  44273. fallbacks: fallbacks,
  44274. onCompiled: onCompiled,
  44275. onError: onError,
  44276. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights, maxSimultaneousMorphTargets: defines.NUM_MORPH_INFLUENCERS }
  44277. }, engine);
  44278. };
  44279. PBRBaseMaterial.prototype._prepareDefines = function (mesh, defines, useInstances, useClipPlane) {
  44280. if (useInstances === void 0) { useInstances = null; }
  44281. if (useClipPlane === void 0) { useClipPlane = null; }
  44282. var scene = this.getScene();
  44283. var engine = scene.getEngine();
  44284. // Lights
  44285. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, true, this._maxSimultaneousLights, this._disableLighting);
  44286. defines._needNormals = true;
  44287. // Textures
  44288. defines.METALLICWORKFLOW = this.isMetallicWorkflow();
  44289. if (defines._areTexturesDirty) {
  44290. defines._needUVs = false;
  44291. if (scene.texturesEnabled) {
  44292. if (scene.getEngine().getCaps().textureLOD) {
  44293. defines.LODBASEDMICROSFURACE = true;
  44294. }
  44295. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44296. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._albedoTexture, defines, "ALBEDO");
  44297. }
  44298. else {
  44299. defines.ALBEDO = false;
  44300. }
  44301. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44302. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._ambientTexture, defines, "AMBIENT");
  44303. defines.AMBIENTINGRAYSCALE = this._useAmbientInGrayScale;
  44304. }
  44305. else {
  44306. defines.AMBIENT = false;
  44307. }
  44308. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44309. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._opacityTexture, defines, "OPACITY");
  44310. defines.OPACITYRGB = this._opacityTexture.getAlphaFromRGB;
  44311. }
  44312. else {
  44313. defines.OPACITY = false;
  44314. }
  44315. var reflectionTexture = this._getReflectionTexture();
  44316. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44317. defines.REFLECTION = true;
  44318. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  44319. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  44320. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  44321. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  44322. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  44323. defines.INVERTCUBICMAP = true;
  44324. }
  44325. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  44326. switch (reflectionTexture.coordinatesMode) {
  44327. case BABYLON.Texture.EXPLICIT_MODE:
  44328. defines.REFLECTIONMAP_EXPLICIT = true;
  44329. break;
  44330. case BABYLON.Texture.PLANAR_MODE:
  44331. defines.REFLECTIONMAP_PLANAR = true;
  44332. break;
  44333. case BABYLON.Texture.PROJECTION_MODE:
  44334. defines.REFLECTIONMAP_PROJECTION = true;
  44335. break;
  44336. case BABYLON.Texture.SKYBOX_MODE:
  44337. defines.REFLECTIONMAP_SKYBOX = true;
  44338. break;
  44339. case BABYLON.Texture.SPHERICAL_MODE:
  44340. defines.REFLECTIONMAP_SPHERICAL = true;
  44341. break;
  44342. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  44343. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  44344. break;
  44345. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  44346. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  44347. break;
  44348. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  44349. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  44350. break;
  44351. case BABYLON.Texture.CUBIC_MODE:
  44352. case BABYLON.Texture.INVCUBIC_MODE:
  44353. default:
  44354. defines.REFLECTIONMAP_CUBIC = true;
  44355. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = reflectionTexture.boundingBoxSize ? true : false;
  44356. break;
  44357. }
  44358. if (reflectionTexture.coordinatesMode !== BABYLON.Texture.SKYBOX_MODE) {
  44359. if (reflectionTexture.sphericalPolynomial) {
  44360. defines.USESPHERICALFROMREFLECTIONMAP = true;
  44361. if (this._forceIrradianceInFragment || scene.getEngine().getCaps().maxVaryingVectors <= 8) {
  44362. defines.USESPHERICALINVERTEX = false;
  44363. }
  44364. else {
  44365. defines.USESPHERICALINVERTEX = true;
  44366. }
  44367. }
  44368. }
  44369. }
  44370. else {
  44371. defines.REFLECTION = false;
  44372. defines.REFLECTIONMAP_3D = false;
  44373. defines.REFLECTIONMAP_SPHERICAL = false;
  44374. defines.REFLECTIONMAP_PLANAR = false;
  44375. defines.REFLECTIONMAP_CUBIC = false;
  44376. defines.USE_LOCAL_REFLECTIONMAP_CUBIC = false;
  44377. defines.REFLECTIONMAP_PROJECTION = false;
  44378. defines.REFLECTIONMAP_SKYBOX = false;
  44379. defines.REFLECTIONMAP_EXPLICIT = false;
  44380. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  44381. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  44382. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  44383. defines.INVERTCUBICMAP = false;
  44384. defines.USESPHERICALFROMREFLECTIONMAP = false;
  44385. defines.USESPHERICALINVERTEX = false;
  44386. defines.REFLECTIONMAP_OPPOSITEZ = false;
  44387. defines.LODINREFLECTIONALPHA = false;
  44388. defines.GAMMAREFLECTION = false;
  44389. defines.RGBDREFLECTION = false;
  44390. }
  44391. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44392. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._lightmapTexture, defines, "LIGHTMAP");
  44393. defines.USELIGHTMAPASSHADOWMAP = this._useLightmapAsShadowmap;
  44394. defines.GAMMALIGHTMAP = this._lightmapTexture.gammaSpace;
  44395. }
  44396. else {
  44397. defines.LIGHTMAP = false;
  44398. }
  44399. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44400. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._emissiveTexture, defines, "EMISSIVE");
  44401. }
  44402. else {
  44403. defines.EMISSIVE = false;
  44404. }
  44405. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44406. if (this._metallicTexture) {
  44407. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._metallicTexture, defines, "REFLECTIVITY");
  44408. defines.ROUGHNESSSTOREINMETALMAPALPHA = this._useRoughnessFromMetallicTextureAlpha;
  44409. defines.ROUGHNESSSTOREINMETALMAPGREEN = !this._useRoughnessFromMetallicTextureAlpha && this._useRoughnessFromMetallicTextureGreen;
  44410. defines.METALLNESSSTOREINMETALMAPBLUE = this._useMetallnessFromMetallicTextureBlue;
  44411. defines.AOSTOREINMETALMAPRED = this._useAmbientOcclusionFromMetallicTextureRed;
  44412. }
  44413. else if (this._reflectivityTexture) {
  44414. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._reflectivityTexture, defines, "REFLECTIVITY");
  44415. defines.MICROSURFACEFROMREFLECTIVITYMAP = this._useMicroSurfaceFromReflectivityMapAlpha;
  44416. defines.MICROSURFACEAUTOMATIC = this._useAutoMicroSurfaceFromReflectivityMap;
  44417. }
  44418. else {
  44419. defines.REFLECTIVITY = false;
  44420. }
  44421. if (this._microSurfaceTexture) {
  44422. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._microSurfaceTexture, defines, "MICROSURFACEMAP");
  44423. }
  44424. else {
  44425. defines.MICROSURFACEMAP = false;
  44426. }
  44427. }
  44428. else {
  44429. defines.REFLECTIVITY = false;
  44430. defines.MICROSURFACEMAP = false;
  44431. }
  44432. if (scene.getEngine().getCaps().standardDerivatives && this._bumpTexture && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44433. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._bumpTexture, defines, "BUMP");
  44434. if (this._useParallax && this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44435. defines.PARALLAX = true;
  44436. defines.PARALLAXOCCLUSION = !!this._useParallaxOcclusion;
  44437. }
  44438. else {
  44439. defines.PARALLAX = false;
  44440. }
  44441. defines.OBJECTSPACE_NORMALMAP = this._useObjectSpaceNormalMap;
  44442. }
  44443. else {
  44444. defines.BUMP = false;
  44445. }
  44446. var refractionTexture = this._getRefractionTexture();
  44447. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44448. defines.REFRACTION = true;
  44449. defines.REFRACTIONMAP_3D = refractionTexture.isCube;
  44450. defines.GAMMAREFRACTION = refractionTexture.gammaSpace;
  44451. defines.RGBDREFRACTION = refractionTexture.isRGBD;
  44452. defines.REFRACTIONMAP_OPPOSITEZ = refractionTexture.invertZ;
  44453. defines.LODINREFRACTIONALPHA = refractionTexture.lodLevelInAlpha;
  44454. if (this._linkRefractionWithTransparency) {
  44455. defines.LINKREFRACTIONTOTRANSPARENCY = true;
  44456. }
  44457. }
  44458. else {
  44459. defines.REFRACTION = false;
  44460. }
  44461. if (this._environmentBRDFTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44462. defines.ENVIRONMENTBRDF = true;
  44463. }
  44464. else {
  44465. defines.ENVIRONMENTBRDF = false;
  44466. }
  44467. if (this._shouldUseAlphaFromAlbedoTexture()) {
  44468. defines.ALPHAFROMALBEDO = true;
  44469. }
  44470. else {
  44471. defines.ALPHAFROMALBEDO = false;
  44472. }
  44473. }
  44474. defines.SPECULAROVERALPHA = this._useSpecularOverAlpha;
  44475. defines.USEPHYSICALLIGHTFALLOFF = this._usePhysicalLightFalloff;
  44476. defines.RADIANCEOVERALPHA = this._useRadianceOverAlpha;
  44477. if (!this.backFaceCulling && this._twoSidedLighting) {
  44478. defines.TWOSIDEDLIGHTING = true;
  44479. }
  44480. else {
  44481. defines.TWOSIDEDLIGHTING = false;
  44482. }
  44483. defines.ALPHATESTVALUE = "" + this._alphaCutOff + (this._alphaCutOff % 1 === 0 ? "." : "");
  44484. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  44485. defines.ALPHABLEND = this.needAlphaBlendingForMesh(mesh);
  44486. defines.ALPHAFRESNEL = this._useAlphaFresnel || this._useLinearAlphaFresnel;
  44487. defines.LINEARALPHAFRESNEL = this._useLinearAlphaFresnel;
  44488. defines.SPECULARAA = scene.getEngine().getCaps().standardDerivatives && this._enableSpecularAntiAliasing;
  44489. }
  44490. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  44491. this._imageProcessingConfiguration.prepareDefines(defines);
  44492. }
  44493. defines.FORCENORMALFORWARD = this._forceNormalForward;
  44494. defines.RADIANCEOCCLUSION = this._useRadianceOcclusion;
  44495. defines.HORIZONOCCLUSION = this._useHorizonOcclusion;
  44496. // Misc.
  44497. if (defines._areMiscDirty) {
  44498. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, this._useLogarithmicDepth, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh) || this._forceAlphaTest, defines);
  44499. defines.UNLIT = this._unlit || ((this.pointsCloud || this.wireframe) && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind));
  44500. }
  44501. // Values that need to be evaluated on every frame
  44502. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances ? true : false, useClipPlane);
  44503. // Attribs
  44504. BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, true, true, true, this._transparencyMode !== BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE);
  44505. };
  44506. /**
  44507. * Force shader compilation
  44508. */
  44509. PBRBaseMaterial.prototype.forceCompilation = function (mesh, onCompiled, options) {
  44510. var _this = this;
  44511. var localOptions = __assign({ clipPlane: false }, options);
  44512. var defines = new PBRMaterialDefines();
  44513. var effect = this._prepareEffect(mesh, defines, undefined, undefined, undefined, localOptions.clipPlane);
  44514. if (effect.isReady()) {
  44515. if (onCompiled) {
  44516. onCompiled(this);
  44517. }
  44518. }
  44519. else {
  44520. effect.onCompileObservable.add(function () {
  44521. if (onCompiled) {
  44522. onCompiled(_this);
  44523. }
  44524. });
  44525. }
  44526. };
  44527. /**
  44528. * Initializes the uniform buffer layout for the shader.
  44529. */
  44530. PBRBaseMaterial.prototype.buildUniformLayout = function () {
  44531. // Order is important !
  44532. this._uniformBuffer.addUniform("vAlbedoInfos", 2);
  44533. this._uniformBuffer.addUniform("vAmbientInfos", 3);
  44534. this._uniformBuffer.addUniform("vOpacityInfos", 2);
  44535. this._uniformBuffer.addUniform("vEmissiveInfos", 2);
  44536. this._uniformBuffer.addUniform("vLightmapInfos", 2);
  44537. this._uniformBuffer.addUniform("vReflectivityInfos", 3);
  44538. this._uniformBuffer.addUniform("vMicroSurfaceSamplerInfos", 2);
  44539. this._uniformBuffer.addUniform("vRefractionInfos", 4);
  44540. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  44541. this._uniformBuffer.addUniform("vReflectionPosition", 3);
  44542. this._uniformBuffer.addUniform("vReflectionSize", 3);
  44543. this._uniformBuffer.addUniform("vBumpInfos", 3);
  44544. this._uniformBuffer.addUniform("albedoMatrix", 16);
  44545. this._uniformBuffer.addUniform("ambientMatrix", 16);
  44546. this._uniformBuffer.addUniform("opacityMatrix", 16);
  44547. this._uniformBuffer.addUniform("emissiveMatrix", 16);
  44548. this._uniformBuffer.addUniform("lightmapMatrix", 16);
  44549. this._uniformBuffer.addUniform("reflectivityMatrix", 16);
  44550. this._uniformBuffer.addUniform("microSurfaceSamplerMatrix", 16);
  44551. this._uniformBuffer.addUniform("bumpMatrix", 16);
  44552. this._uniformBuffer.addUniform("vTangentSpaceParams", 2);
  44553. this._uniformBuffer.addUniform("refractionMatrix", 16);
  44554. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  44555. this._uniformBuffer.addUniform("vReflectionColor", 3);
  44556. this._uniformBuffer.addUniform("vAlbedoColor", 4);
  44557. this._uniformBuffer.addUniform("vLightingIntensity", 4);
  44558. this._uniformBuffer.addUniform("vRefractionMicrosurfaceInfos", 3);
  44559. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  44560. this._uniformBuffer.addUniform("vReflectivityColor", 4);
  44561. this._uniformBuffer.addUniform("vEmissiveColor", 3);
  44562. this._uniformBuffer.addUniform("pointSize", 1);
  44563. this._uniformBuffer.create();
  44564. };
  44565. /**
  44566. * Unbinds the textures.
  44567. */
  44568. PBRBaseMaterial.prototype.unbind = function () {
  44569. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  44570. this._uniformBuffer.setTexture("reflectionSampler", null);
  44571. }
  44572. if (this._refractionTexture && this._refractionTexture.isRenderTarget) {
  44573. this._uniformBuffer.setTexture("refractionSampler", null);
  44574. }
  44575. _super.prototype.unbind.call(this);
  44576. };
  44577. /**
  44578. * Binds the submesh data.
  44579. * @param world - The world matrix.
  44580. * @param mesh - The BJS mesh.
  44581. * @param subMesh - A submesh of the BJS mesh.
  44582. */
  44583. PBRBaseMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  44584. var scene = this.getScene();
  44585. var defines = subMesh._materialDefines;
  44586. if (!defines) {
  44587. return;
  44588. }
  44589. var effect = subMesh.effect;
  44590. if (!effect) {
  44591. return;
  44592. }
  44593. this._activeEffect = effect;
  44594. // Matrices
  44595. this.bindOnlyWorldMatrix(world);
  44596. // Normal Matrix
  44597. if (defines.OBJECTSPACE_NORMALMAP) {
  44598. world.toNormalMatrix(this._normalMatrix);
  44599. this.bindOnlyNormalMatrix(this._normalMatrix);
  44600. }
  44601. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  44602. // Bones
  44603. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  44604. var reflectionTexture = null;
  44605. if (mustRebind) {
  44606. this._uniformBuffer.bindToEffect(effect, "Material");
  44607. this.bindViewProjection(effect);
  44608. reflectionTexture = this._getReflectionTexture();
  44609. var refractionTexture = this._getRefractionTexture();
  44610. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  44611. // Texture uniforms
  44612. if (scene.texturesEnabled) {
  44613. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44614. this._uniformBuffer.updateFloat2("vAlbedoInfos", this._albedoTexture.coordinatesIndex, this._albedoTexture.level);
  44615. BABYLON.MaterialHelper.BindTextureMatrix(this._albedoTexture, this._uniformBuffer, "albedo");
  44616. }
  44617. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44618. this._uniformBuffer.updateFloat3("vAmbientInfos", this._ambientTexture.coordinatesIndex, this._ambientTexture.level, this._ambientTextureStrength);
  44619. BABYLON.MaterialHelper.BindTextureMatrix(this._ambientTexture, this._uniformBuffer, "ambient");
  44620. }
  44621. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44622. this._uniformBuffer.updateFloat2("vOpacityInfos", this._opacityTexture.coordinatesIndex, this._opacityTexture.level);
  44623. BABYLON.MaterialHelper.BindTextureMatrix(this._opacityTexture, this._uniformBuffer, "opacity");
  44624. }
  44625. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44626. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  44627. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, 0);
  44628. if (reflectionTexture.boundingBoxSize) {
  44629. var cubeTexture = reflectionTexture;
  44630. this._uniformBuffer.updateVector3("vReflectionPosition", cubeTexture.boundingBoxPosition);
  44631. this._uniformBuffer.updateVector3("vReflectionSize", cubeTexture.boundingBoxSize);
  44632. }
  44633. var polynomials = reflectionTexture.sphericalPolynomial;
  44634. if (defines.USESPHERICALFROMREFLECTIONMAP && polynomials) {
  44635. this._activeEffect.setFloat3("vSphericalX", polynomials.x.x, polynomials.x.y, polynomials.x.z);
  44636. this._activeEffect.setFloat3("vSphericalY", polynomials.y.x, polynomials.y.y, polynomials.y.z);
  44637. this._activeEffect.setFloat3("vSphericalZ", polynomials.z.x, polynomials.z.y, polynomials.z.z);
  44638. this._activeEffect.setFloat3("vSphericalXX_ZZ", polynomials.xx.x - polynomials.zz.x, polynomials.xx.y - polynomials.zz.y, polynomials.xx.z - polynomials.zz.z);
  44639. this._activeEffect.setFloat3("vSphericalYY_ZZ", polynomials.yy.x - polynomials.zz.x, polynomials.yy.y - polynomials.zz.y, polynomials.yy.z - polynomials.zz.z);
  44640. this._activeEffect.setFloat3("vSphericalZZ", polynomials.zz.x, polynomials.zz.y, polynomials.zz.z);
  44641. this._activeEffect.setFloat3("vSphericalXY", polynomials.xy.x, polynomials.xy.y, polynomials.xy.z);
  44642. this._activeEffect.setFloat3("vSphericalYZ", polynomials.yz.x, polynomials.yz.y, polynomials.yz.z);
  44643. this._activeEffect.setFloat3("vSphericalZX", polynomials.zx.x, polynomials.zx.y, polynomials.zx.z);
  44644. }
  44645. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  44646. }
  44647. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44648. this._uniformBuffer.updateFloat2("vEmissiveInfos", this._emissiveTexture.coordinatesIndex, this._emissiveTexture.level);
  44649. BABYLON.MaterialHelper.BindTextureMatrix(this._emissiveTexture, this._uniformBuffer, "emissive");
  44650. }
  44651. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44652. this._uniformBuffer.updateFloat2("vLightmapInfos", this._lightmapTexture.coordinatesIndex, this._lightmapTexture.level);
  44653. BABYLON.MaterialHelper.BindTextureMatrix(this._lightmapTexture, this._uniformBuffer, "lightmap");
  44654. }
  44655. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44656. if (this._metallicTexture) {
  44657. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._metallicTexture.coordinatesIndex, this._metallicTexture.level, this._ambientTextureStrength);
  44658. BABYLON.MaterialHelper.BindTextureMatrix(this._metallicTexture, this._uniformBuffer, "reflectivity");
  44659. }
  44660. else if (this._reflectivityTexture) {
  44661. this._uniformBuffer.updateFloat3("vReflectivityInfos", this._reflectivityTexture.coordinatesIndex, this._reflectivityTexture.level, 1.0);
  44662. BABYLON.MaterialHelper.BindTextureMatrix(this._reflectivityTexture, this._uniformBuffer, "reflectivity");
  44663. }
  44664. if (this._microSurfaceTexture) {
  44665. this._uniformBuffer.updateFloat2("vMicroSurfaceSamplerInfos", this._microSurfaceTexture.coordinatesIndex, this._microSurfaceTexture.level);
  44666. BABYLON.MaterialHelper.BindTextureMatrix(this._microSurfaceTexture, this._uniformBuffer, "microSurfaceSampler");
  44667. }
  44668. }
  44669. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44670. this._uniformBuffer.updateFloat3("vBumpInfos", this._bumpTexture.coordinatesIndex, this._bumpTexture.level, this._parallaxScaleBias);
  44671. BABYLON.MaterialHelper.BindTextureMatrix(this._bumpTexture, this._uniformBuffer, "bump");
  44672. if (scene._mirroredCameraPosition) {
  44673. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? 1.0 : -1.0, this._invertNormalMapY ? 1.0 : -1.0);
  44674. }
  44675. else {
  44676. this._uniformBuffer.updateFloat2("vTangentSpaceParams", this._invertNormalMapX ? -1.0 : 1.0, this._invertNormalMapY ? -1.0 : 1.0);
  44677. }
  44678. }
  44679. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44680. this._uniformBuffer.updateMatrix("refractionMatrix", refractionTexture.getReflectionTextureMatrix());
  44681. var depth = 1.0;
  44682. if (!refractionTexture.isCube) {
  44683. if (refractionTexture.depth) {
  44684. depth = refractionTexture.depth;
  44685. }
  44686. }
  44687. this._uniformBuffer.updateFloat4("vRefractionInfos", refractionTexture.level, this._indexOfRefraction, depth, this._invertRefractionY ? -1 : 1);
  44688. this._uniformBuffer.updateFloat3("vRefractionMicrosurfaceInfos", refractionTexture.getSize().width, refractionTexture.lodGenerationScale, refractionTexture.lodGenerationOffset);
  44689. }
  44690. }
  44691. // Point size
  44692. if (this.pointsCloud) {
  44693. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  44694. }
  44695. // Colors
  44696. if (defines.METALLICWORKFLOW) {
  44697. BABYLON.PBRMaterial._scaledReflectivity.r = (this._metallic === undefined || this._metallic === null) ? 1 : this._metallic;
  44698. BABYLON.PBRMaterial._scaledReflectivity.g = (this._roughness === undefined || this._roughness === null) ? 1 : this._roughness;
  44699. this._uniformBuffer.updateColor4("vReflectivityColor", BABYLON.PBRMaterial._scaledReflectivity, 0);
  44700. }
  44701. else {
  44702. this._uniformBuffer.updateColor4("vReflectivityColor", this._reflectivityColor, this._microSurface);
  44703. }
  44704. this._uniformBuffer.updateColor3("vEmissiveColor", this._emissiveColor);
  44705. this._uniformBuffer.updateColor3("vReflectionColor", this._reflectionColor);
  44706. this._uniformBuffer.updateColor4("vAlbedoColor", this._albedoColor, this.alpha * mesh.visibility);
  44707. // Misc
  44708. this._lightingInfos.x = this._directIntensity;
  44709. this._lightingInfos.y = this._emissiveIntensity;
  44710. this._lightingInfos.z = this._environmentIntensity;
  44711. this._lightingInfos.w = this._specularIntensity;
  44712. this._uniformBuffer.updateVector4("vLightingIntensity", this._lightingInfos);
  44713. }
  44714. // Textures
  44715. if (scene.texturesEnabled) {
  44716. if (this._albedoTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  44717. this._uniformBuffer.setTexture("albedoSampler", this._albedoTexture);
  44718. }
  44719. if (this._ambientTexture && BABYLON.StandardMaterial.AmbientTextureEnabled) {
  44720. this._uniformBuffer.setTexture("ambientSampler", this._ambientTexture);
  44721. }
  44722. if (this._opacityTexture && BABYLON.StandardMaterial.OpacityTextureEnabled) {
  44723. this._uniformBuffer.setTexture("opacitySampler", this._opacityTexture);
  44724. }
  44725. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  44726. if (defines.LODBASEDMICROSFURACE) {
  44727. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  44728. }
  44729. else {
  44730. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  44731. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  44732. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  44733. }
  44734. }
  44735. if (defines.ENVIRONMENTBRDF) {
  44736. this._uniformBuffer.setTexture("environmentBrdfSampler", this._environmentBRDFTexture);
  44737. }
  44738. if (refractionTexture && BABYLON.StandardMaterial.RefractionTextureEnabled) {
  44739. if (defines.LODBASEDMICROSFURACE) {
  44740. this._uniformBuffer.setTexture("refractionSampler", refractionTexture);
  44741. }
  44742. else {
  44743. this._uniformBuffer.setTexture("refractionSampler", refractionTexture._lodTextureMid || refractionTexture);
  44744. this._uniformBuffer.setTexture("refractionSamplerLow", refractionTexture._lodTextureLow || refractionTexture);
  44745. this._uniformBuffer.setTexture("refractionSamplerHigh", refractionTexture._lodTextureHigh || refractionTexture);
  44746. }
  44747. }
  44748. if (this._emissiveTexture && BABYLON.StandardMaterial.EmissiveTextureEnabled) {
  44749. this._uniformBuffer.setTexture("emissiveSampler", this._emissiveTexture);
  44750. }
  44751. if (this._lightmapTexture && BABYLON.StandardMaterial.LightmapTextureEnabled) {
  44752. this._uniformBuffer.setTexture("lightmapSampler", this._lightmapTexture);
  44753. }
  44754. if (BABYLON.StandardMaterial.SpecularTextureEnabled) {
  44755. if (this._metallicTexture) {
  44756. this._uniformBuffer.setTexture("reflectivitySampler", this._metallicTexture);
  44757. }
  44758. else if (this._reflectivityTexture) {
  44759. this._uniformBuffer.setTexture("reflectivitySampler", this._reflectivityTexture);
  44760. }
  44761. if (this._microSurfaceTexture) {
  44762. this._uniformBuffer.setTexture("microSurfaceSampler", this._microSurfaceTexture);
  44763. }
  44764. }
  44765. if (this._bumpTexture && scene.getEngine().getCaps().standardDerivatives && BABYLON.StandardMaterial.BumpTextureEnabled && !this._disableBumpMap) {
  44766. this._uniformBuffer.setTexture("bumpSampler", this._bumpTexture);
  44767. }
  44768. }
  44769. // Clip plane
  44770. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  44771. // Colors
  44772. scene.ambientColor.multiplyToRef(this._ambientColor, this._globalAmbientColor);
  44773. var eyePosition = scene._forcedViewPosition ? scene._forcedViewPosition : (scene._mirroredCameraPosition ? scene._mirroredCameraPosition : scene.activeCamera.globalPosition);
  44774. var invertNormal = (scene.useRightHandedSystem === (scene._mirroredCameraPosition != null));
  44775. effect.setFloat4("vEyePosition", eyePosition.x, eyePosition.y, eyePosition.z, invertNormal ? -1 : 1);
  44776. effect.setColor3("vAmbientColor", this._globalAmbientColor);
  44777. }
  44778. if (mustRebind || !this.isFrozen) {
  44779. // Lights
  44780. if (scene.lightsEnabled && !this._disableLighting) {
  44781. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, this._usePhysicalLightFalloff);
  44782. }
  44783. // View
  44784. if (scene.fogEnabled && mesh.applyFog && scene.fogMode !== BABYLON.Scene.FOGMODE_NONE || reflectionTexture) {
  44785. this.bindView(effect);
  44786. }
  44787. // Fog
  44788. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  44789. // Morph targets
  44790. if (defines.NUM_MORPH_INFLUENCERS) {
  44791. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._activeEffect);
  44792. }
  44793. // image processing
  44794. this._imageProcessingConfiguration.bind(this._activeEffect);
  44795. // Log. depth
  44796. BABYLON.MaterialHelper.BindLogDepth(defines, this._activeEffect, scene);
  44797. }
  44798. this._uniformBuffer.update();
  44799. this._afterBind(mesh, this._activeEffect);
  44800. };
  44801. /**
  44802. * Returns the animatable textures.
  44803. * @returns - Array of animatable textures.
  44804. */
  44805. PBRBaseMaterial.prototype.getAnimatables = function () {
  44806. var results = [];
  44807. if (this._albedoTexture && this._albedoTexture.animations && this._albedoTexture.animations.length > 0) {
  44808. results.push(this._albedoTexture);
  44809. }
  44810. if (this._ambientTexture && this._ambientTexture.animations && this._ambientTexture.animations.length > 0) {
  44811. results.push(this._ambientTexture);
  44812. }
  44813. if (this._opacityTexture && this._opacityTexture.animations && this._opacityTexture.animations.length > 0) {
  44814. results.push(this._opacityTexture);
  44815. }
  44816. if (this._reflectionTexture && this._reflectionTexture.animations && this._reflectionTexture.animations.length > 0) {
  44817. results.push(this._reflectionTexture);
  44818. }
  44819. if (this._emissiveTexture && this._emissiveTexture.animations && this._emissiveTexture.animations.length > 0) {
  44820. results.push(this._emissiveTexture);
  44821. }
  44822. if (this._metallicTexture && this._metallicTexture.animations && this._metallicTexture.animations.length > 0) {
  44823. results.push(this._metallicTexture);
  44824. }
  44825. else if (this._reflectivityTexture && this._reflectivityTexture.animations && this._reflectivityTexture.animations.length > 0) {
  44826. results.push(this._reflectivityTexture);
  44827. }
  44828. if (this._bumpTexture && this._bumpTexture.animations && this._bumpTexture.animations.length > 0) {
  44829. results.push(this._bumpTexture);
  44830. }
  44831. if (this._lightmapTexture && this._lightmapTexture.animations && this._lightmapTexture.animations.length > 0) {
  44832. results.push(this._lightmapTexture);
  44833. }
  44834. if (this._refractionTexture && this._refractionTexture.animations && this._refractionTexture.animations.length > 0) {
  44835. results.push(this._refractionTexture);
  44836. }
  44837. return results;
  44838. };
  44839. /**
  44840. * Returns the texture used for reflections.
  44841. * @returns - Reflection texture if present. Otherwise, returns the environment texture.
  44842. */
  44843. PBRBaseMaterial.prototype._getReflectionTexture = function () {
  44844. if (this._reflectionTexture) {
  44845. return this._reflectionTexture;
  44846. }
  44847. return this.getScene().environmentTexture;
  44848. };
  44849. /**
  44850. * Returns the texture used for refraction or null if none is used.
  44851. * @returns - Refection texture if present. If no refraction texture and refraction
  44852. * is linked with transparency, returns environment texture. Otherwise, returns null.
  44853. */
  44854. PBRBaseMaterial.prototype._getRefractionTexture = function () {
  44855. if (this._refractionTexture) {
  44856. return this._refractionTexture;
  44857. }
  44858. if (this._linkRefractionWithTransparency) {
  44859. return this.getScene().environmentTexture;
  44860. }
  44861. return null;
  44862. };
  44863. /**
  44864. * Disposes the resources of the material.
  44865. * @param forceDisposeEffect - Forces the disposal of effects.
  44866. * @param forceDisposeTextures - Forces the disposal of all textures.
  44867. */
  44868. PBRBaseMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  44869. if (forceDisposeTextures) {
  44870. if (this._albedoTexture) {
  44871. this._albedoTexture.dispose();
  44872. }
  44873. if (this._ambientTexture) {
  44874. this._ambientTexture.dispose();
  44875. }
  44876. if (this._opacityTexture) {
  44877. this._opacityTexture.dispose();
  44878. }
  44879. if (this._reflectionTexture) {
  44880. this._reflectionTexture.dispose();
  44881. }
  44882. if (this._environmentBRDFTexture && this.getScene()._environmentBRDFTexture !== this._environmentBRDFTexture) {
  44883. this._environmentBRDFTexture.dispose();
  44884. }
  44885. if (this._emissiveTexture) {
  44886. this._emissiveTexture.dispose();
  44887. }
  44888. if (this._metallicTexture) {
  44889. this._metallicTexture.dispose();
  44890. }
  44891. if (this._reflectivityTexture) {
  44892. this._reflectivityTexture.dispose();
  44893. }
  44894. if (this._bumpTexture) {
  44895. this._bumpTexture.dispose();
  44896. }
  44897. if (this._lightmapTexture) {
  44898. this._lightmapTexture.dispose();
  44899. }
  44900. if (this._refractionTexture) {
  44901. this._refractionTexture.dispose();
  44902. }
  44903. }
  44904. this._renderTargets.dispose();
  44905. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  44906. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  44907. }
  44908. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  44909. };
  44910. /**
  44911. * Stores the reflectivity values based on metallic roughness workflow.
  44912. */
  44913. PBRBaseMaterial._scaledReflectivity = new BABYLON.Color3();
  44914. __decorate([
  44915. BABYLON.serializeAsImageProcessingConfiguration()
  44916. ], PBRBaseMaterial.prototype, "_imageProcessingConfiguration", void 0);
  44917. __decorate([
  44918. BABYLON.serialize()
  44919. ], PBRBaseMaterial.prototype, "useLogarithmicDepth", null);
  44920. __decorate([
  44921. BABYLON.serialize()
  44922. ], PBRBaseMaterial.prototype, "transparencyMode", null);
  44923. return PBRBaseMaterial;
  44924. }(BABYLON.PushMaterial));
  44925. BABYLON.PBRBaseMaterial = PBRBaseMaterial;
  44926. })(BABYLON || (BABYLON = {}));
  44927. //# sourceMappingURL=babylon.pbrBaseMaterial.js.map
  44928. var BABYLON;
  44929. (function (BABYLON) {
  44930. /**
  44931. * The Physically based simple base material of BJS.
  44932. *
  44933. * This enables better naming and convention enforcements on top of the pbrMaterial.
  44934. * It is used as the base class for both the specGloss and metalRough conventions.
  44935. */
  44936. var PBRBaseSimpleMaterial = /** @class */ (function (_super) {
  44937. __extends(PBRBaseSimpleMaterial, _super);
  44938. /**
  44939. * Instantiates a new PBRMaterial instance.
  44940. *
  44941. * @param name The material name
  44942. * @param scene The scene the material will be use in.
  44943. */
  44944. function PBRBaseSimpleMaterial(name, scene) {
  44945. var _this = _super.call(this, name, scene) || this;
  44946. /**
  44947. * Number of Simultaneous lights allowed on the material.
  44948. */
  44949. _this.maxSimultaneousLights = 4;
  44950. /**
  44951. * If sets to true, disables all the lights affecting the material.
  44952. */
  44953. _this.disableLighting = false;
  44954. /**
  44955. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  44956. */
  44957. _this.invertNormalMapX = false;
  44958. /**
  44959. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  44960. */
  44961. _this.invertNormalMapY = false;
  44962. /**
  44963. * Emissivie color used to self-illuminate the model.
  44964. */
  44965. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  44966. /**
  44967. * Occlusion Channel Strenght.
  44968. */
  44969. _this.occlusionStrength = 1.0;
  44970. _this.useLightmapAsShadowmap = false;
  44971. _this._useAlphaFromAlbedoTexture = true;
  44972. _this._useAmbientInGrayScale = true;
  44973. return _this;
  44974. }
  44975. Object.defineProperty(PBRBaseSimpleMaterial.prototype, "doubleSided", {
  44976. /**
  44977. * Gets the current double sided mode.
  44978. */
  44979. get: function () {
  44980. return this._twoSidedLighting;
  44981. },
  44982. /**
  44983. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  44984. */
  44985. set: function (value) {
  44986. if (this._twoSidedLighting === value) {
  44987. return;
  44988. }
  44989. this._twoSidedLighting = value;
  44990. this.backFaceCulling = !value;
  44991. this._markAllSubMeshesAsTexturesDirty();
  44992. },
  44993. enumerable: true,
  44994. configurable: true
  44995. });
  44996. /**
  44997. * Return the active textures of the material.
  44998. */
  44999. PBRBaseSimpleMaterial.prototype.getActiveTextures = function () {
  45000. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45001. if (this.environmentTexture) {
  45002. activeTextures.push(this.environmentTexture);
  45003. }
  45004. if (this.normalTexture) {
  45005. activeTextures.push(this.normalTexture);
  45006. }
  45007. if (this.emissiveTexture) {
  45008. activeTextures.push(this.emissiveTexture);
  45009. }
  45010. if (this.occlusionTexture) {
  45011. activeTextures.push(this.occlusionTexture);
  45012. }
  45013. if (this.lightmapTexture) {
  45014. activeTextures.push(this.lightmapTexture);
  45015. }
  45016. return activeTextures;
  45017. };
  45018. PBRBaseSimpleMaterial.prototype.hasTexture = function (texture) {
  45019. if (_super.prototype.hasTexture.call(this, texture)) {
  45020. return true;
  45021. }
  45022. if (this.lightmapTexture === texture) {
  45023. return true;
  45024. }
  45025. return false;
  45026. };
  45027. PBRBaseSimpleMaterial.prototype.getClassName = function () {
  45028. return "PBRBaseSimpleMaterial";
  45029. };
  45030. __decorate([
  45031. BABYLON.serialize(),
  45032. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45033. ], PBRBaseSimpleMaterial.prototype, "maxSimultaneousLights", void 0);
  45034. __decorate([
  45035. BABYLON.serialize(),
  45036. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45037. ], PBRBaseSimpleMaterial.prototype, "disableLighting", void 0);
  45038. __decorate([
  45039. BABYLON.serializeAsTexture(),
  45040. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectionTexture")
  45041. ], PBRBaseSimpleMaterial.prototype, "environmentTexture", void 0);
  45042. __decorate([
  45043. BABYLON.serialize(),
  45044. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45045. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapX", void 0);
  45046. __decorate([
  45047. BABYLON.serialize(),
  45048. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45049. ], PBRBaseSimpleMaterial.prototype, "invertNormalMapY", void 0);
  45050. __decorate([
  45051. BABYLON.serializeAsTexture(),
  45052. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_bumpTexture")
  45053. ], PBRBaseSimpleMaterial.prototype, "normalTexture", void 0);
  45054. __decorate([
  45055. BABYLON.serializeAsColor3("emissive"),
  45056. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45057. ], PBRBaseSimpleMaterial.prototype, "emissiveColor", void 0);
  45058. __decorate([
  45059. BABYLON.serializeAsTexture(),
  45060. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45061. ], PBRBaseSimpleMaterial.prototype, "emissiveTexture", void 0);
  45062. __decorate([
  45063. BABYLON.serialize(),
  45064. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTextureStrength")
  45065. ], PBRBaseSimpleMaterial.prototype, "occlusionStrength", void 0);
  45066. __decorate([
  45067. BABYLON.serializeAsTexture(),
  45068. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_ambientTexture")
  45069. ], PBRBaseSimpleMaterial.prototype, "occlusionTexture", void 0);
  45070. __decorate([
  45071. BABYLON.serialize(),
  45072. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_alphaCutOff")
  45073. ], PBRBaseSimpleMaterial.prototype, "alphaCutOff", void 0);
  45074. __decorate([
  45075. BABYLON.serialize()
  45076. ], PBRBaseSimpleMaterial.prototype, "doubleSided", null);
  45077. __decorate([
  45078. BABYLON.serializeAsTexture(),
  45079. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45080. ], PBRBaseSimpleMaterial.prototype, "lightmapTexture", void 0);
  45081. __decorate([
  45082. BABYLON.serialize(),
  45083. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45084. ], PBRBaseSimpleMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45085. return PBRBaseSimpleMaterial;
  45086. }(BABYLON.PBRBaseMaterial));
  45087. BABYLON.PBRBaseSimpleMaterial = PBRBaseSimpleMaterial;
  45088. })(BABYLON || (BABYLON = {}));
  45089. //# sourceMappingURL=babylon.pbrBaseSimpleMaterial.js.map
  45090. var BABYLON;
  45091. (function (BABYLON) {
  45092. /**
  45093. * The Physically based material of BJS.
  45094. *
  45095. * This offers the main features of a standard PBR material.
  45096. * For more information, please refer to the documentation :
  45097. * http://doc.babylonjs.com/extensions/Physically_Based_Rendering
  45098. */
  45099. var PBRMaterial = /** @class */ (function (_super) {
  45100. __extends(PBRMaterial, _super);
  45101. /**
  45102. * Instantiates a new PBRMaterial instance.
  45103. *
  45104. * @param name The material name
  45105. * @param scene The scene the material will be use in.
  45106. */
  45107. function PBRMaterial(name, scene) {
  45108. var _this = _super.call(this, name, scene) || this;
  45109. /**
  45110. * Intensity of the direct lights e.g. the four lights available in your scene.
  45111. * This impacts both the direct diffuse and specular highlights.
  45112. */
  45113. _this.directIntensity = 1.0;
  45114. /**
  45115. * Intensity of the emissive part of the material.
  45116. * This helps controlling the emissive effect without modifying the emissive color.
  45117. */
  45118. _this.emissiveIntensity = 1.0;
  45119. /**
  45120. * Intensity of the environment e.g. how much the environment will light the object
  45121. * either through harmonics for rough material or through the refelction for shiny ones.
  45122. */
  45123. _this.environmentIntensity = 1.0;
  45124. /**
  45125. * This is a special control allowing the reduction of the specular highlights coming from the
  45126. * four lights of the scene. Those highlights may not be needed in full environment lighting.
  45127. */
  45128. _this.specularIntensity = 1.0;
  45129. /**
  45130. * Debug Control allowing disabling the bump map on this material.
  45131. */
  45132. _this.disableBumpMap = false;
  45133. /**
  45134. * AKA Occlusion Texture Intensity in other nomenclature.
  45135. */
  45136. _this.ambientTextureStrength = 1.0;
  45137. /**
  45138. * The color of a material in ambient lighting.
  45139. */
  45140. _this.ambientColor = new BABYLON.Color3(0, 0, 0);
  45141. /**
  45142. * AKA Diffuse Color in other nomenclature.
  45143. */
  45144. _this.albedoColor = new BABYLON.Color3(1, 1, 1);
  45145. /**
  45146. * AKA Specular Color in other nomenclature.
  45147. */
  45148. _this.reflectivityColor = new BABYLON.Color3(1, 1, 1);
  45149. /**
  45150. * The color reflected from the material.
  45151. */
  45152. _this.reflectionColor = new BABYLON.Color3(1.0, 1.0, 1.0);
  45153. /**
  45154. * The color emitted from the material.
  45155. */
  45156. _this.emissiveColor = new BABYLON.Color3(0, 0, 0);
  45157. /**
  45158. * AKA Glossiness in other nomenclature.
  45159. */
  45160. _this.microSurface = 1.0;
  45161. /**
  45162. * source material index of refraction (IOR)' / 'destination material IOR.
  45163. */
  45164. _this.indexOfRefraction = 0.66;
  45165. /**
  45166. * Controls if refraction needs to be inverted on Y. This could be usefull for procedural texture.
  45167. */
  45168. _this.invertRefractionY = false;
  45169. /**
  45170. * This parameters will make the material used its opacity to control how much it is refracting aginst not.
  45171. * Materials half opaque for instance using refraction could benefit from this control.
  45172. */
  45173. _this.linkRefractionWithTransparency = false;
  45174. _this.useLightmapAsShadowmap = false;
  45175. /**
  45176. * Specifies that the alpha is coming form the albedo channel alpha channel for alpha blending.
  45177. */
  45178. _this.useAlphaFromAlbedoTexture = false;
  45179. /**
  45180. * Enforces alpha test in opaque or blend mode in order to improve the performances of some situations.
  45181. */
  45182. _this.forceAlphaTest = false;
  45183. /**
  45184. * Defines the alpha limits in alpha test mode.
  45185. */
  45186. _this.alphaCutOff = 0.4;
  45187. /**
  45188. * Specifies that the material will keeps the specular highlights over a transparent surface (only the most limunous ones).
  45189. * A car glass is a good exemple of that. When sun reflects on it you can not see what is behind.
  45190. */
  45191. _this.useSpecularOverAlpha = true;
  45192. /**
  45193. * Specifies if the reflectivity texture contains the glossiness information in its alpha channel.
  45194. */
  45195. _this.useMicroSurfaceFromReflectivityMapAlpha = false;
  45196. /**
  45197. * Specifies if the metallic texture contains the roughness information in its alpha channel.
  45198. */
  45199. _this.useRoughnessFromMetallicTextureAlpha = true;
  45200. /**
  45201. * Specifies if the metallic texture contains the roughness information in its green channel.
  45202. */
  45203. _this.useRoughnessFromMetallicTextureGreen = false;
  45204. /**
  45205. * Specifies if the metallic texture contains the metallness information in its blue channel.
  45206. */
  45207. _this.useMetallnessFromMetallicTextureBlue = false;
  45208. /**
  45209. * Specifies if the metallic texture contains the ambient occlusion information in its red channel.
  45210. */
  45211. _this.useAmbientOcclusionFromMetallicTextureRed = false;
  45212. /**
  45213. * Specifies if the ambient texture contains the ambient occlusion information in its red channel only.
  45214. */
  45215. _this.useAmbientInGrayScale = false;
  45216. /**
  45217. * In case the reflectivity map does not contain the microsurface information in its alpha channel,
  45218. * The material will try to infer what glossiness each pixel should be.
  45219. */
  45220. _this.useAutoMicroSurfaceFromReflectivityMap = false;
  45221. /**
  45222. * BJS is using an harcoded light falloff based on a manually sets up range.
  45223. * In PBR, one way to represents the fallof is to use the inverse squared root algorythm.
  45224. * This parameter can help you switch back to the BJS mode in order to create scenes using both materials.
  45225. */
  45226. _this.usePhysicalLightFalloff = true;
  45227. /**
  45228. * Specifies that the material will keeps the reflection highlights over a transparent surface (only the most limunous ones).
  45229. * A car glass is a good exemple of that. When the street lights reflects on it you can not see what is behind.
  45230. */
  45231. _this.useRadianceOverAlpha = true;
  45232. /**
  45233. * Allows using an object space normal map (instead of tangent space).
  45234. */
  45235. _this.useObjectSpaceNormalMap = false;
  45236. /**
  45237. * Allows using the bump map in parallax mode.
  45238. */
  45239. _this.useParallax = false;
  45240. /**
  45241. * Allows using the bump map in parallax occlusion mode.
  45242. */
  45243. _this.useParallaxOcclusion = false;
  45244. /**
  45245. * Controls the scale bias of the parallax mode.
  45246. */
  45247. _this.parallaxScaleBias = 0.05;
  45248. /**
  45249. * If sets to true, disables all the lights affecting the material.
  45250. */
  45251. _this.disableLighting = false;
  45252. /**
  45253. * Force the shader to compute irradiance in the fragment shader in order to take bump in account.
  45254. */
  45255. _this.forceIrradianceInFragment = false;
  45256. /**
  45257. * Number of Simultaneous lights allowed on the material.
  45258. */
  45259. _this.maxSimultaneousLights = 4;
  45260. /**
  45261. * If sets to true, x component of normal map value will invert (x = 1.0 - x).
  45262. */
  45263. _this.invertNormalMapX = false;
  45264. /**
  45265. * If sets to true, y component of normal map value will invert (y = 1.0 - y).
  45266. */
  45267. _this.invertNormalMapY = false;
  45268. /**
  45269. * If sets to true and backfaceCulling is false, normals will be flipped on the backside.
  45270. */
  45271. _this.twoSidedLighting = false;
  45272. /**
  45273. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45274. * And/Or occlude the blended part. (alpha is converted to gamma to compute the fresnel)
  45275. */
  45276. _this.useAlphaFresnel = false;
  45277. /**
  45278. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45279. * And/Or occlude the blended part. (alpha stays linear to compute the fresnel)
  45280. */
  45281. _this.useLinearAlphaFresnel = false;
  45282. /**
  45283. * A fresnel is applied to the alpha of the model to ensure grazing angles edges are not alpha tested.
  45284. * And/Or occlude the blended part.
  45285. */
  45286. _this.environmentBRDFTexture = null;
  45287. /**
  45288. * Force normal to face away from face.
  45289. */
  45290. _this.forceNormalForward = false;
  45291. /**
  45292. * Enables specular anti aliasing in the PBR shader.
  45293. * It will both interacts on the Geometry for analytical and IBL lighting.
  45294. * It also prefilter the roughness map based on the bump values.
  45295. */
  45296. _this.enableSpecularAntiAliasing = false;
  45297. /**
  45298. * This parameters will enable/disable Horizon occlusion to prevent normal maps to look shiny when the normal
  45299. * makes the reflect vector face the model (under horizon).
  45300. */
  45301. _this.useHorizonOcclusion = true;
  45302. /**
  45303. * This parameters will enable/disable radiance occlusion by preventing the radiance to lit
  45304. * too much the area relying on ambient texture to define their ambient occlusion.
  45305. */
  45306. _this.useRadianceOcclusion = true;
  45307. /**
  45308. * If set to true, no lighting calculations will be applied.
  45309. */
  45310. _this.unlit = false;
  45311. _this._environmentBRDFTexture = BABYLON.TextureTools.GetEnvironmentBRDFTexture(scene);
  45312. return _this;
  45313. }
  45314. Object.defineProperty(PBRMaterial, "PBRMATERIAL_OPAQUE", {
  45315. /**
  45316. * PBRMaterialTransparencyMode: No transparency mode, Alpha channel is not use.
  45317. */
  45318. get: function () {
  45319. return this._PBRMATERIAL_OPAQUE;
  45320. },
  45321. enumerable: true,
  45322. configurable: true
  45323. });
  45324. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATEST", {
  45325. /**
  45326. * PBRMaterialTransparencyMode: Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45327. */
  45328. get: function () {
  45329. return this._PBRMATERIAL_ALPHATEST;
  45330. },
  45331. enumerable: true,
  45332. configurable: true
  45333. });
  45334. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHABLEND", {
  45335. /**
  45336. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45337. */
  45338. get: function () {
  45339. return this._PBRMATERIAL_ALPHABLEND;
  45340. },
  45341. enumerable: true,
  45342. configurable: true
  45343. });
  45344. Object.defineProperty(PBRMaterial, "PBRMATERIAL_ALPHATESTANDBLEND", {
  45345. /**
  45346. * PBRMaterialTransparencyMode: Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45347. * They are also discarded below the alpha cutoff threshold to improve performances.
  45348. */
  45349. get: function () {
  45350. return this._PBRMATERIAL_ALPHATESTANDBLEND;
  45351. },
  45352. enumerable: true,
  45353. configurable: true
  45354. });
  45355. Object.defineProperty(PBRMaterial.prototype, "imageProcessingConfiguration", {
  45356. /**
  45357. * Gets the image processing configuration used either in this material.
  45358. */
  45359. get: function () {
  45360. return this._imageProcessingConfiguration;
  45361. },
  45362. /**
  45363. * Sets the Default image processing configuration used either in the this material.
  45364. *
  45365. * If sets to null, the scene one is in use.
  45366. */
  45367. set: function (value) {
  45368. this._attachImageProcessingConfiguration(value);
  45369. // Ensure the effect will be rebuilt.
  45370. this._markAllSubMeshesAsTexturesDirty();
  45371. },
  45372. enumerable: true,
  45373. configurable: true
  45374. });
  45375. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurvesEnabled", {
  45376. /**
  45377. * Gets wether the color curves effect is enabled.
  45378. */
  45379. get: function () {
  45380. return this.imageProcessingConfiguration.colorCurvesEnabled;
  45381. },
  45382. /**
  45383. * Sets wether the color curves effect is enabled.
  45384. */
  45385. set: function (value) {
  45386. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  45387. },
  45388. enumerable: true,
  45389. configurable: true
  45390. });
  45391. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingEnabled", {
  45392. /**
  45393. * Gets wether the color grading effect is enabled.
  45394. */
  45395. get: function () {
  45396. return this.imageProcessingConfiguration.colorGradingEnabled;
  45397. },
  45398. /**
  45399. * Gets wether the color grading effect is enabled.
  45400. */
  45401. set: function (value) {
  45402. this.imageProcessingConfiguration.colorGradingEnabled = value;
  45403. },
  45404. enumerable: true,
  45405. configurable: true
  45406. });
  45407. Object.defineProperty(PBRMaterial.prototype, "cameraToneMappingEnabled", {
  45408. /**
  45409. * Gets wether tonemapping is enabled or not.
  45410. */
  45411. get: function () {
  45412. return this._imageProcessingConfiguration.toneMappingEnabled;
  45413. },
  45414. /**
  45415. * Sets wether tonemapping is enabled or not
  45416. */
  45417. set: function (value) {
  45418. this._imageProcessingConfiguration.toneMappingEnabled = value;
  45419. },
  45420. enumerable: true,
  45421. configurable: true
  45422. });
  45423. ;
  45424. ;
  45425. Object.defineProperty(PBRMaterial.prototype, "cameraExposure", {
  45426. /**
  45427. * The camera exposure used on this material.
  45428. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45429. * This corresponds to a photographic exposure.
  45430. */
  45431. get: function () {
  45432. return this._imageProcessingConfiguration.exposure;
  45433. },
  45434. /**
  45435. * The camera exposure used on this material.
  45436. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  45437. * This corresponds to a photographic exposure.
  45438. */
  45439. set: function (value) {
  45440. this._imageProcessingConfiguration.exposure = value;
  45441. },
  45442. enumerable: true,
  45443. configurable: true
  45444. });
  45445. ;
  45446. ;
  45447. Object.defineProperty(PBRMaterial.prototype, "cameraContrast", {
  45448. /**
  45449. * Gets The camera contrast used on this material.
  45450. */
  45451. get: function () {
  45452. return this._imageProcessingConfiguration.contrast;
  45453. },
  45454. /**
  45455. * Sets The camera contrast used on this material.
  45456. */
  45457. set: function (value) {
  45458. this._imageProcessingConfiguration.contrast = value;
  45459. },
  45460. enumerable: true,
  45461. configurable: true
  45462. });
  45463. Object.defineProperty(PBRMaterial.prototype, "cameraColorGradingTexture", {
  45464. /**
  45465. * Gets the Color Grading 2D Lookup Texture.
  45466. */
  45467. get: function () {
  45468. return this._imageProcessingConfiguration.colorGradingTexture;
  45469. },
  45470. /**
  45471. * Sets the Color Grading 2D Lookup Texture.
  45472. */
  45473. set: function (value) {
  45474. this._imageProcessingConfiguration.colorGradingTexture = value;
  45475. },
  45476. enumerable: true,
  45477. configurable: true
  45478. });
  45479. Object.defineProperty(PBRMaterial.prototype, "cameraColorCurves", {
  45480. /**
  45481. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45482. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45483. * 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;
  45484. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45485. */
  45486. get: function () {
  45487. return this._imageProcessingConfiguration.colorCurves;
  45488. },
  45489. /**
  45490. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  45491. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  45492. * 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;
  45493. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  45494. */
  45495. set: function (value) {
  45496. this._imageProcessingConfiguration.colorCurves = value;
  45497. },
  45498. enumerable: true,
  45499. configurable: true
  45500. });
  45501. /**
  45502. * Returns the name of this material class.
  45503. */
  45504. PBRMaterial.prototype.getClassName = function () {
  45505. return "PBRMaterial";
  45506. };
  45507. /**
  45508. * Returns an array of the actively used textures.
  45509. * @returns - Array of BaseTextures
  45510. */
  45511. PBRMaterial.prototype.getActiveTextures = function () {
  45512. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45513. if (this._albedoTexture) {
  45514. activeTextures.push(this._albedoTexture);
  45515. }
  45516. if (this._ambientTexture) {
  45517. activeTextures.push(this._ambientTexture);
  45518. }
  45519. if (this._opacityTexture) {
  45520. activeTextures.push(this._opacityTexture);
  45521. }
  45522. if (this._reflectionTexture) {
  45523. activeTextures.push(this._reflectionTexture);
  45524. }
  45525. if (this._emissiveTexture) {
  45526. activeTextures.push(this._emissiveTexture);
  45527. }
  45528. if (this._reflectivityTexture) {
  45529. activeTextures.push(this._reflectivityTexture);
  45530. }
  45531. if (this._metallicTexture) {
  45532. activeTextures.push(this._metallicTexture);
  45533. }
  45534. if (this._microSurfaceTexture) {
  45535. activeTextures.push(this._microSurfaceTexture);
  45536. }
  45537. if (this._bumpTexture) {
  45538. activeTextures.push(this._bumpTexture);
  45539. }
  45540. if (this._lightmapTexture) {
  45541. activeTextures.push(this._lightmapTexture);
  45542. }
  45543. if (this._refractionTexture) {
  45544. activeTextures.push(this._refractionTexture);
  45545. }
  45546. return activeTextures;
  45547. };
  45548. /**
  45549. * Checks to see if a texture is used in the material.
  45550. * @param texture - Base texture to use.
  45551. * @returns - Boolean specifying if a texture is used in the material.
  45552. */
  45553. PBRMaterial.prototype.hasTexture = function (texture) {
  45554. if (_super.prototype.hasTexture.call(this, texture)) {
  45555. return true;
  45556. }
  45557. if (this._albedoTexture === texture) {
  45558. return true;
  45559. }
  45560. if (this._ambientTexture === texture) {
  45561. return true;
  45562. }
  45563. if (this._opacityTexture === texture) {
  45564. return true;
  45565. }
  45566. if (this._reflectionTexture === texture) {
  45567. return true;
  45568. }
  45569. if (this._reflectivityTexture === texture) {
  45570. return true;
  45571. }
  45572. if (this._metallicTexture === texture) {
  45573. return true;
  45574. }
  45575. if (this._microSurfaceTexture === texture) {
  45576. return true;
  45577. }
  45578. if (this._bumpTexture === texture) {
  45579. return true;
  45580. }
  45581. if (this._lightmapTexture === texture) {
  45582. return true;
  45583. }
  45584. if (this._refractionTexture === texture) {
  45585. return true;
  45586. }
  45587. return false;
  45588. };
  45589. /**
  45590. * Makes a duplicate of the current material.
  45591. * @param name - name to use for the new material.
  45592. */
  45593. PBRMaterial.prototype.clone = function (name) {
  45594. var _this = this;
  45595. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMaterial(name, _this.getScene()); }, this);
  45596. clone.id = name;
  45597. clone.name = name;
  45598. return clone;
  45599. };
  45600. /**
  45601. * Serializes this PBR Material.
  45602. * @returns - An object with the serialized material.
  45603. */
  45604. PBRMaterial.prototype.serialize = function () {
  45605. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45606. serializationObject.customType = "BABYLON.PBRMaterial";
  45607. return serializationObject;
  45608. };
  45609. // Statics
  45610. /**
  45611. * Parses a PBR Material from a serialized object.
  45612. * @param source - Serialized object.
  45613. * @param scene - BJS scene instance.
  45614. * @param rootUrl - url for the scene object
  45615. * @returns - PBRMaterial
  45616. */
  45617. PBRMaterial.Parse = function (source, scene, rootUrl) {
  45618. return BABYLON.SerializationHelper.Parse(function () { return new PBRMaterial(source.name, scene); }, source, scene, rootUrl);
  45619. };
  45620. PBRMaterial._PBRMATERIAL_OPAQUE = 0;
  45621. /**
  45622. * Alpha Test mode, pixel are discarded below a certain threshold defined by the alpha cutoff value.
  45623. */
  45624. PBRMaterial._PBRMATERIAL_ALPHATEST = 1;
  45625. /**
  45626. * Represents the value for Alpha Blend. Pixels are blended (according to the alpha mode) with the already drawn pixels in the current frame buffer.
  45627. */
  45628. PBRMaterial._PBRMATERIAL_ALPHABLEND = 2;
  45629. /**
  45630. * 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.
  45631. * They are also discarded below the alpha cutoff threshold to improve performances.
  45632. */
  45633. PBRMaterial._PBRMATERIAL_ALPHATESTANDBLEND = 3;
  45634. __decorate([
  45635. BABYLON.serialize(),
  45636. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45637. ], PBRMaterial.prototype, "directIntensity", void 0);
  45638. __decorate([
  45639. BABYLON.serialize(),
  45640. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45641. ], PBRMaterial.prototype, "emissiveIntensity", void 0);
  45642. __decorate([
  45643. BABYLON.serialize(),
  45644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45645. ], PBRMaterial.prototype, "environmentIntensity", void 0);
  45646. __decorate([
  45647. BABYLON.serialize(),
  45648. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45649. ], PBRMaterial.prototype, "specularIntensity", void 0);
  45650. __decorate([
  45651. BABYLON.serialize(),
  45652. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45653. ], PBRMaterial.prototype, "disableBumpMap", void 0);
  45654. __decorate([
  45655. BABYLON.serializeAsTexture(),
  45656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45657. ], PBRMaterial.prototype, "albedoTexture", void 0);
  45658. __decorate([
  45659. BABYLON.serializeAsTexture(),
  45660. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45661. ], PBRMaterial.prototype, "ambientTexture", void 0);
  45662. __decorate([
  45663. BABYLON.serialize(),
  45664. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45665. ], PBRMaterial.prototype, "ambientTextureStrength", void 0);
  45666. __decorate([
  45667. BABYLON.serializeAsTexture(),
  45668. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45669. ], PBRMaterial.prototype, "opacityTexture", void 0);
  45670. __decorate([
  45671. BABYLON.serializeAsTexture(),
  45672. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45673. ], PBRMaterial.prototype, "reflectionTexture", void 0);
  45674. __decorate([
  45675. BABYLON.serializeAsTexture(),
  45676. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45677. ], PBRMaterial.prototype, "emissiveTexture", void 0);
  45678. __decorate([
  45679. BABYLON.serializeAsTexture(),
  45680. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45681. ], PBRMaterial.prototype, "reflectivityTexture", void 0);
  45682. __decorate([
  45683. BABYLON.serializeAsTexture(),
  45684. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45685. ], PBRMaterial.prototype, "metallicTexture", void 0);
  45686. __decorate([
  45687. BABYLON.serialize(),
  45688. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45689. ], PBRMaterial.prototype, "metallic", void 0);
  45690. __decorate([
  45691. BABYLON.serialize(),
  45692. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45693. ], PBRMaterial.prototype, "roughness", void 0);
  45694. __decorate([
  45695. BABYLON.serializeAsTexture(),
  45696. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45697. ], PBRMaterial.prototype, "microSurfaceTexture", void 0);
  45698. __decorate([
  45699. BABYLON.serializeAsTexture(),
  45700. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45701. ], PBRMaterial.prototype, "bumpTexture", void 0);
  45702. __decorate([
  45703. BABYLON.serializeAsTexture(),
  45704. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", null)
  45705. ], PBRMaterial.prototype, "lightmapTexture", void 0);
  45706. __decorate([
  45707. BABYLON.serializeAsTexture(),
  45708. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45709. ], PBRMaterial.prototype, "refractionTexture", void 0);
  45710. __decorate([
  45711. BABYLON.serializeAsColor3("ambient"),
  45712. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45713. ], PBRMaterial.prototype, "ambientColor", void 0);
  45714. __decorate([
  45715. BABYLON.serializeAsColor3("albedo"),
  45716. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45717. ], PBRMaterial.prototype, "albedoColor", void 0);
  45718. __decorate([
  45719. BABYLON.serializeAsColor3("reflectivity"),
  45720. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45721. ], PBRMaterial.prototype, "reflectivityColor", void 0);
  45722. __decorate([
  45723. BABYLON.serializeAsColor3("reflection"),
  45724. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45725. ], PBRMaterial.prototype, "reflectionColor", void 0);
  45726. __decorate([
  45727. BABYLON.serializeAsColor3("emissive"),
  45728. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45729. ], PBRMaterial.prototype, "emissiveColor", void 0);
  45730. __decorate([
  45731. BABYLON.serialize(),
  45732. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45733. ], PBRMaterial.prototype, "microSurface", void 0);
  45734. __decorate([
  45735. BABYLON.serialize(),
  45736. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45737. ], PBRMaterial.prototype, "indexOfRefraction", void 0);
  45738. __decorate([
  45739. BABYLON.serialize(),
  45740. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45741. ], PBRMaterial.prototype, "invertRefractionY", void 0);
  45742. __decorate([
  45743. BABYLON.serialize(),
  45744. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45745. ], PBRMaterial.prototype, "linkRefractionWithTransparency", void 0);
  45746. __decorate([
  45747. BABYLON.serialize(),
  45748. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45749. ], PBRMaterial.prototype, "useLightmapAsShadowmap", void 0);
  45750. __decorate([
  45751. BABYLON.serialize(),
  45752. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45753. ], PBRMaterial.prototype, "useAlphaFromAlbedoTexture", void 0);
  45754. __decorate([
  45755. BABYLON.serialize(),
  45756. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45757. ], PBRMaterial.prototype, "forceAlphaTest", void 0);
  45758. __decorate([
  45759. BABYLON.serialize(),
  45760. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesAndMiscDirty")
  45761. ], PBRMaterial.prototype, "alphaCutOff", void 0);
  45762. __decorate([
  45763. BABYLON.serialize(),
  45764. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45765. ], PBRMaterial.prototype, "useSpecularOverAlpha", void 0);
  45766. __decorate([
  45767. BABYLON.serialize(),
  45768. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45769. ], PBRMaterial.prototype, "useMicroSurfaceFromReflectivityMapAlpha", void 0);
  45770. __decorate([
  45771. BABYLON.serialize(),
  45772. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45773. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureAlpha", void 0);
  45774. __decorate([
  45775. BABYLON.serialize(),
  45776. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45777. ], PBRMaterial.prototype, "useRoughnessFromMetallicTextureGreen", void 0);
  45778. __decorate([
  45779. BABYLON.serialize(),
  45780. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45781. ], PBRMaterial.prototype, "useMetallnessFromMetallicTextureBlue", void 0);
  45782. __decorate([
  45783. BABYLON.serialize(),
  45784. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45785. ], PBRMaterial.prototype, "useAmbientOcclusionFromMetallicTextureRed", void 0);
  45786. __decorate([
  45787. BABYLON.serialize(),
  45788. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45789. ], PBRMaterial.prototype, "useAmbientInGrayScale", void 0);
  45790. __decorate([
  45791. BABYLON.serialize(),
  45792. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45793. ], PBRMaterial.prototype, "useAutoMicroSurfaceFromReflectivityMap", void 0);
  45794. __decorate([
  45795. BABYLON.serialize(),
  45796. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45797. ], PBRMaterial.prototype, "usePhysicalLightFalloff", void 0);
  45798. __decorate([
  45799. BABYLON.serialize(),
  45800. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45801. ], PBRMaterial.prototype, "useRadianceOverAlpha", void 0);
  45802. __decorate([
  45803. BABYLON.serialize(),
  45804. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45805. ], PBRMaterial.prototype, "useObjectSpaceNormalMap", void 0);
  45806. __decorate([
  45807. BABYLON.serialize(),
  45808. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45809. ], PBRMaterial.prototype, "useParallax", void 0);
  45810. __decorate([
  45811. BABYLON.serialize(),
  45812. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45813. ], PBRMaterial.prototype, "useParallaxOcclusion", void 0);
  45814. __decorate([
  45815. BABYLON.serialize(),
  45816. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45817. ], PBRMaterial.prototype, "parallaxScaleBias", void 0);
  45818. __decorate([
  45819. BABYLON.serialize(),
  45820. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45821. ], PBRMaterial.prototype, "disableLighting", void 0);
  45822. __decorate([
  45823. BABYLON.serialize(),
  45824. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45825. ], PBRMaterial.prototype, "forceIrradianceInFragment", void 0);
  45826. __decorate([
  45827. BABYLON.serialize(),
  45828. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  45829. ], PBRMaterial.prototype, "maxSimultaneousLights", void 0);
  45830. __decorate([
  45831. BABYLON.serialize(),
  45832. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45833. ], PBRMaterial.prototype, "invertNormalMapX", void 0);
  45834. __decorate([
  45835. BABYLON.serialize(),
  45836. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45837. ], PBRMaterial.prototype, "invertNormalMapY", void 0);
  45838. __decorate([
  45839. BABYLON.serialize(),
  45840. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45841. ], PBRMaterial.prototype, "twoSidedLighting", void 0);
  45842. __decorate([
  45843. BABYLON.serialize(),
  45844. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45845. ], PBRMaterial.prototype, "useAlphaFresnel", void 0);
  45846. __decorate([
  45847. BABYLON.serialize(),
  45848. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45849. ], PBRMaterial.prototype, "useLinearAlphaFresnel", void 0);
  45850. __decorate([
  45851. BABYLON.serializeAsTexture(),
  45852. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45853. ], PBRMaterial.prototype, "environmentBRDFTexture", void 0);
  45854. __decorate([
  45855. BABYLON.serialize(),
  45856. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45857. ], PBRMaterial.prototype, "forceNormalForward", void 0);
  45858. __decorate([
  45859. BABYLON.serialize(),
  45860. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45861. ], PBRMaterial.prototype, "enableSpecularAntiAliasing", void 0);
  45862. __decorate([
  45863. BABYLON.serialize(),
  45864. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45865. ], PBRMaterial.prototype, "useHorizonOcclusion", void 0);
  45866. __decorate([
  45867. BABYLON.serialize(),
  45868. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45869. ], PBRMaterial.prototype, "useRadianceOcclusion", void 0);
  45870. __decorate([
  45871. BABYLON.serialize(),
  45872. BABYLON.expandToProperty("_markAllSubMeshesAsMiscDirty")
  45873. ], PBRMaterial.prototype, "unlit", void 0);
  45874. return PBRMaterial;
  45875. }(BABYLON.PBRBaseMaterial));
  45876. BABYLON.PBRMaterial = PBRMaterial;
  45877. })(BABYLON || (BABYLON = {}));
  45878. //# sourceMappingURL=babylon.pbrMaterial.js.map
  45879. var BABYLON;
  45880. (function (BABYLON) {
  45881. /**
  45882. * The PBR material of BJS following the metal roughness convention.
  45883. *
  45884. * This fits to the PBR convention in the GLTF definition:
  45885. * https://github.com/KhronosGroup/glTF/tree/2.0/specification/2.0
  45886. */
  45887. var PBRMetallicRoughnessMaterial = /** @class */ (function (_super) {
  45888. __extends(PBRMetallicRoughnessMaterial, _super);
  45889. /**
  45890. * Instantiates a new PBRMetalRoughnessMaterial instance.
  45891. *
  45892. * @param name The material name
  45893. * @param scene The scene the material will be use in.
  45894. */
  45895. function PBRMetallicRoughnessMaterial(name, scene) {
  45896. var _this = _super.call(this, name, scene) || this;
  45897. _this._useRoughnessFromMetallicTextureAlpha = false;
  45898. _this._useRoughnessFromMetallicTextureGreen = true;
  45899. _this._useMetallnessFromMetallicTextureBlue = true;
  45900. _this.metallic = 1.0;
  45901. _this.roughness = 1.0;
  45902. return _this;
  45903. }
  45904. /**
  45905. * Return the currrent class name of the material.
  45906. */
  45907. PBRMetallicRoughnessMaterial.prototype.getClassName = function () {
  45908. return "PBRMetallicRoughnessMaterial";
  45909. };
  45910. /**
  45911. * Return the active textures of the material.
  45912. */
  45913. PBRMetallicRoughnessMaterial.prototype.getActiveTextures = function () {
  45914. var activeTextures = _super.prototype.getActiveTextures.call(this);
  45915. if (this.baseTexture) {
  45916. activeTextures.push(this.baseTexture);
  45917. }
  45918. if (this.metallicRoughnessTexture) {
  45919. activeTextures.push(this.metallicRoughnessTexture);
  45920. }
  45921. return activeTextures;
  45922. };
  45923. /**
  45924. * Checks to see if a texture is used in the material.
  45925. * @param texture - Base texture to use.
  45926. * @returns - Boolean specifying if a texture is used in the material.
  45927. */
  45928. PBRMetallicRoughnessMaterial.prototype.hasTexture = function (texture) {
  45929. if (_super.prototype.hasTexture.call(this, texture)) {
  45930. return true;
  45931. }
  45932. if (this.baseTexture === texture) {
  45933. return true;
  45934. }
  45935. if (this.metallicRoughnessTexture === texture) {
  45936. return true;
  45937. }
  45938. return false;
  45939. };
  45940. /**
  45941. * Makes a duplicate of the current material.
  45942. * @param name - name to use for the new material.
  45943. */
  45944. PBRMetallicRoughnessMaterial.prototype.clone = function (name) {
  45945. var _this = this;
  45946. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRMetallicRoughnessMaterial(name, _this.getScene()); }, this);
  45947. clone.id = name;
  45948. clone.name = name;
  45949. return clone;
  45950. };
  45951. /**
  45952. * Serialize the material to a parsable JSON object.
  45953. */
  45954. PBRMetallicRoughnessMaterial.prototype.serialize = function () {
  45955. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  45956. serializationObject.customType = "BABYLON.PBRMetallicRoughnessMaterial";
  45957. return serializationObject;
  45958. };
  45959. /**
  45960. * Parses a JSON object correponding to the serialize function.
  45961. */
  45962. PBRMetallicRoughnessMaterial.Parse = function (source, scene, rootUrl) {
  45963. return BABYLON.SerializationHelper.Parse(function () { return new PBRMetallicRoughnessMaterial(source.name, scene); }, source, scene, rootUrl);
  45964. };
  45965. __decorate([
  45966. BABYLON.serializeAsColor3(),
  45967. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  45968. ], PBRMetallicRoughnessMaterial.prototype, "baseColor", void 0);
  45969. __decorate([
  45970. BABYLON.serializeAsTexture(),
  45971. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  45972. ], PBRMetallicRoughnessMaterial.prototype, "baseTexture", void 0);
  45973. __decorate([
  45974. BABYLON.serialize(),
  45975. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45976. ], PBRMetallicRoughnessMaterial.prototype, "metallic", void 0);
  45977. __decorate([
  45978. BABYLON.serialize(),
  45979. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  45980. ], PBRMetallicRoughnessMaterial.prototype, "roughness", void 0);
  45981. __decorate([
  45982. BABYLON.serializeAsTexture(),
  45983. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_metallicTexture")
  45984. ], PBRMetallicRoughnessMaterial.prototype, "metallicRoughnessTexture", void 0);
  45985. return PBRMetallicRoughnessMaterial;
  45986. }(BABYLON.PBRBaseSimpleMaterial));
  45987. BABYLON.PBRMetallicRoughnessMaterial = PBRMetallicRoughnessMaterial;
  45988. })(BABYLON || (BABYLON = {}));
  45989. //# sourceMappingURL=babylon.pbrMetallicRoughnessMaterial.js.map
  45990. var BABYLON;
  45991. (function (BABYLON) {
  45992. /**
  45993. * The PBR material of BJS following the specular glossiness convention.
  45994. *
  45995. * This fits to the PBR convention in the GLTF definition:
  45996. * https://github.com/KhronosGroup/glTF/tree/2.0/extensions/Khronos/KHR_materials_pbrSpecularGlossiness
  45997. */
  45998. var PBRSpecularGlossinessMaterial = /** @class */ (function (_super) {
  45999. __extends(PBRSpecularGlossinessMaterial, _super);
  46000. /**
  46001. * Instantiates a new PBRSpecularGlossinessMaterial instance.
  46002. *
  46003. * @param name The material name
  46004. * @param scene The scene the material will be use in.
  46005. */
  46006. function PBRSpecularGlossinessMaterial(name, scene) {
  46007. var _this = _super.call(this, name, scene) || this;
  46008. _this._useMicroSurfaceFromReflectivityMapAlpha = true;
  46009. return _this;
  46010. }
  46011. /**
  46012. * Return the currrent class name of the material.
  46013. */
  46014. PBRSpecularGlossinessMaterial.prototype.getClassName = function () {
  46015. return "PBRSpecularGlossinessMaterial";
  46016. };
  46017. /**
  46018. * Return the active textures of the material.
  46019. */
  46020. PBRSpecularGlossinessMaterial.prototype.getActiveTextures = function () {
  46021. var activeTextures = _super.prototype.getActiveTextures.call(this);
  46022. if (this.diffuseTexture) {
  46023. activeTextures.push(this.diffuseTexture);
  46024. }
  46025. if (this.specularGlossinessTexture) {
  46026. activeTextures.push(this.specularGlossinessTexture);
  46027. }
  46028. return activeTextures;
  46029. };
  46030. /**
  46031. * Checks to see if a texture is used in the material.
  46032. * @param texture - Base texture to use.
  46033. * @returns - Boolean specifying if a texture is used in the material.
  46034. */
  46035. PBRSpecularGlossinessMaterial.prototype.hasTexture = function (texture) {
  46036. if (_super.prototype.hasTexture.call(this, texture)) {
  46037. return true;
  46038. }
  46039. if (this.diffuseTexture === texture) {
  46040. return true;
  46041. }
  46042. if (this.specularGlossinessTexture === texture) {
  46043. return true;
  46044. }
  46045. return false;
  46046. };
  46047. /**
  46048. * Makes a duplicate of the current material.
  46049. * @param name - name to use for the new material.
  46050. */
  46051. PBRSpecularGlossinessMaterial.prototype.clone = function (name) {
  46052. var _this = this;
  46053. var clone = BABYLON.SerializationHelper.Clone(function () { return new PBRSpecularGlossinessMaterial(name, _this.getScene()); }, this);
  46054. clone.id = name;
  46055. clone.name = name;
  46056. return clone;
  46057. };
  46058. /**
  46059. * Serialize the material to a parsable JSON object.
  46060. */
  46061. PBRSpecularGlossinessMaterial.prototype.serialize = function () {
  46062. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  46063. serializationObject.customType = "BABYLON.PBRSpecularGlossinessMaterial";
  46064. return serializationObject;
  46065. };
  46066. /**
  46067. * Parses a JSON object correponding to the serialize function.
  46068. */
  46069. PBRSpecularGlossinessMaterial.Parse = function (source, scene, rootUrl) {
  46070. return BABYLON.SerializationHelper.Parse(function () { return new PBRSpecularGlossinessMaterial(source.name, scene); }, source, scene, rootUrl);
  46071. };
  46072. __decorate([
  46073. BABYLON.serializeAsColor3("diffuse"),
  46074. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoColor")
  46075. ], PBRSpecularGlossinessMaterial.prototype, "diffuseColor", void 0);
  46076. __decorate([
  46077. BABYLON.serializeAsTexture(),
  46078. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_albedoTexture")
  46079. ], PBRSpecularGlossinessMaterial.prototype, "diffuseTexture", void 0);
  46080. __decorate([
  46081. BABYLON.serializeAsColor3("specular"),
  46082. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityColor")
  46083. ], PBRSpecularGlossinessMaterial.prototype, "specularColor", void 0);
  46084. __decorate([
  46085. BABYLON.serialize(),
  46086. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_microSurface")
  46087. ], PBRSpecularGlossinessMaterial.prototype, "glossiness", void 0);
  46088. __decorate([
  46089. BABYLON.serializeAsTexture(),
  46090. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty", "_reflectivityTexture")
  46091. ], PBRSpecularGlossinessMaterial.prototype, "specularGlossinessTexture", void 0);
  46092. return PBRSpecularGlossinessMaterial;
  46093. }(BABYLON.PBRBaseSimpleMaterial));
  46094. BABYLON.PBRSpecularGlossinessMaterial = PBRSpecularGlossinessMaterial;
  46095. })(BABYLON || (BABYLON = {}));
  46096. //# sourceMappingURL=babylon.pbrSpecularGlossinessMaterial.js.map
  46097. var BABYLON;
  46098. (function (BABYLON) {
  46099. BABYLON.CameraInputTypes = {};
  46100. var CameraInputsManager = /** @class */ (function () {
  46101. function CameraInputsManager(camera) {
  46102. this.attached = {};
  46103. this.camera = camera;
  46104. this.checkInputs = function () { };
  46105. }
  46106. /**
  46107. * Add an input method to a camera.
  46108. * builtin inputs example: camera.inputs.addGamepad();
  46109. * custom inputs example: camera.inputs.add(new BABYLON.FreeCameraGamepadInput());
  46110. * @param input camera input method
  46111. */
  46112. CameraInputsManager.prototype.add = function (input) {
  46113. var type = input.getSimpleName();
  46114. if (this.attached[type]) {
  46115. BABYLON.Tools.Warn("camera input of type " + type + " already exists on camera");
  46116. return;
  46117. }
  46118. this.attached[type] = input;
  46119. input.camera = this.camera;
  46120. //for checkInputs, we are dynamically creating a function
  46121. //the goal is to avoid the performance penalty of looping for inputs in the render loop
  46122. if (input.checkInputs) {
  46123. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46124. }
  46125. if (this.attachedElement) {
  46126. input.attachControl(this.attachedElement);
  46127. }
  46128. };
  46129. /**
  46130. * Remove a specific input method from a camera
  46131. * example: camera.inputs.remove(camera.inputs.attached.mouse);
  46132. * @param inputToRemove camera input method
  46133. */
  46134. CameraInputsManager.prototype.remove = function (inputToRemove) {
  46135. for (var cam in this.attached) {
  46136. var input = this.attached[cam];
  46137. if (input === inputToRemove) {
  46138. input.detachControl(this.attachedElement);
  46139. input.camera = null;
  46140. delete this.attached[cam];
  46141. this.rebuildInputCheck();
  46142. }
  46143. }
  46144. };
  46145. CameraInputsManager.prototype.removeByType = function (inputType) {
  46146. for (var cam in this.attached) {
  46147. var input = this.attached[cam];
  46148. if (input.getClassName() === inputType) {
  46149. input.detachControl(this.attachedElement);
  46150. input.camera = null;
  46151. delete this.attached[cam];
  46152. this.rebuildInputCheck();
  46153. }
  46154. }
  46155. };
  46156. CameraInputsManager.prototype._addCheckInputs = function (fn) {
  46157. var current = this.checkInputs;
  46158. return function () {
  46159. current();
  46160. fn();
  46161. };
  46162. };
  46163. CameraInputsManager.prototype.attachInput = function (input) {
  46164. if (this.attachedElement) {
  46165. input.attachControl(this.attachedElement, this.noPreventDefault);
  46166. }
  46167. };
  46168. CameraInputsManager.prototype.attachElement = function (element, noPreventDefault) {
  46169. if (noPreventDefault === void 0) { noPreventDefault = false; }
  46170. if (this.attachedElement) {
  46171. return;
  46172. }
  46173. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  46174. this.attachedElement = element;
  46175. this.noPreventDefault = noPreventDefault;
  46176. for (var cam in this.attached) {
  46177. this.attached[cam].attachControl(element, noPreventDefault);
  46178. }
  46179. };
  46180. CameraInputsManager.prototype.detachElement = function (element, disconnect) {
  46181. if (disconnect === void 0) { disconnect = false; }
  46182. if (this.attachedElement !== element) {
  46183. return;
  46184. }
  46185. for (var cam in this.attached) {
  46186. this.attached[cam].detachControl(element);
  46187. if (disconnect) {
  46188. this.attached[cam].camera = null;
  46189. }
  46190. }
  46191. this.attachedElement = null;
  46192. };
  46193. CameraInputsManager.prototype.rebuildInputCheck = function () {
  46194. this.checkInputs = function () { };
  46195. for (var cam in this.attached) {
  46196. var input = this.attached[cam];
  46197. if (input.checkInputs) {
  46198. this.checkInputs = this._addCheckInputs(input.checkInputs.bind(input));
  46199. }
  46200. }
  46201. };
  46202. /**
  46203. * Remove all attached input methods from a camera
  46204. */
  46205. CameraInputsManager.prototype.clear = function () {
  46206. if (this.attachedElement) {
  46207. this.detachElement(this.attachedElement, true);
  46208. }
  46209. this.attached = {};
  46210. this.attachedElement = null;
  46211. this.checkInputs = function () { };
  46212. };
  46213. CameraInputsManager.prototype.serialize = function (serializedCamera) {
  46214. var inputs = {};
  46215. for (var cam in this.attached) {
  46216. var input = this.attached[cam];
  46217. var res = BABYLON.SerializationHelper.Serialize(input);
  46218. inputs[input.getClassName()] = res;
  46219. }
  46220. serializedCamera.inputsmgr = inputs;
  46221. };
  46222. CameraInputsManager.prototype.parse = function (parsedCamera) {
  46223. var parsedInputs = parsedCamera.inputsmgr;
  46224. if (parsedInputs) {
  46225. this.clear();
  46226. for (var n in parsedInputs) {
  46227. var construct = BABYLON.CameraInputTypes[n];
  46228. if (construct) {
  46229. var parsedinput = parsedInputs[n];
  46230. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedinput, null);
  46231. this.add(input);
  46232. }
  46233. }
  46234. }
  46235. else {
  46236. //2016-03-08 this part is for managing backward compatibility
  46237. for (var n in this.attached) {
  46238. var construct = BABYLON.CameraInputTypes[this.attached[n].getClassName()];
  46239. if (construct) {
  46240. var input = BABYLON.SerializationHelper.Parse(function () { return new construct(); }, parsedCamera, null);
  46241. this.remove(this.attached[n]);
  46242. this.add(input);
  46243. }
  46244. }
  46245. }
  46246. };
  46247. return CameraInputsManager;
  46248. }());
  46249. BABYLON.CameraInputsManager = CameraInputsManager;
  46250. })(BABYLON || (BABYLON = {}));
  46251. //# sourceMappingURL=babylon.cameraInputsManager.js.map
  46252. var BABYLON;
  46253. (function (BABYLON) {
  46254. var TargetCamera = /** @class */ (function (_super) {
  46255. __extends(TargetCamera, _super);
  46256. function TargetCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46257. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46258. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46259. _this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46260. _this.cameraRotation = new BABYLON.Vector2(0, 0);
  46261. _this.rotation = new BABYLON.Vector3(0, 0, 0);
  46262. _this.speed = 2.0;
  46263. _this.noRotationConstraint = false;
  46264. _this.lockedTarget = null;
  46265. _this._currentTarget = BABYLON.Vector3.Zero();
  46266. _this._viewMatrix = BABYLON.Matrix.Zero();
  46267. _this._camMatrix = BABYLON.Matrix.Zero();
  46268. _this._cameraTransformMatrix = BABYLON.Matrix.Zero();
  46269. _this._cameraRotationMatrix = BABYLON.Matrix.Zero();
  46270. _this._referencePoint = new BABYLON.Vector3(0, 0, 1);
  46271. _this._currentUpVector = new BABYLON.Vector3(0, 1, 0);
  46272. _this._transformedReferencePoint = BABYLON.Vector3.Zero();
  46273. _this._globalCurrentTarget = BABYLON.Vector3.Zero();
  46274. _this._globalCurrentUpVector = BABYLON.Vector3.Zero();
  46275. return _this;
  46276. }
  46277. TargetCamera.prototype.getFrontPosition = function (distance) {
  46278. this.getWorldMatrix();
  46279. var direction = this.getTarget().subtract(this.position);
  46280. direction.normalize();
  46281. direction.scaleInPlace(distance);
  46282. return this.globalPosition.add(direction);
  46283. };
  46284. TargetCamera.prototype._getLockedTargetPosition = function () {
  46285. if (!this.lockedTarget) {
  46286. return null;
  46287. }
  46288. if (this.lockedTarget.absolutePosition) {
  46289. this.lockedTarget.computeWorldMatrix();
  46290. }
  46291. return this.lockedTarget.absolutePosition || this.lockedTarget;
  46292. };
  46293. TargetCamera.prototype.storeState = function () {
  46294. this._storedPosition = this.position.clone();
  46295. this._storedRotation = this.rotation.clone();
  46296. if (this.rotationQuaternion) {
  46297. this._storedRotationQuaternion = this.rotationQuaternion.clone();
  46298. }
  46299. return _super.prototype.storeState.call(this);
  46300. };
  46301. /**
  46302. * Restored camera state. You must call storeState() first
  46303. */
  46304. TargetCamera.prototype._restoreStateValues = function () {
  46305. if (!_super.prototype._restoreStateValues.call(this)) {
  46306. return false;
  46307. }
  46308. this.position = this._storedPosition.clone();
  46309. this.rotation = this._storedRotation.clone();
  46310. if (this.rotationQuaternion) {
  46311. this.rotationQuaternion = this._storedRotationQuaternion.clone();
  46312. }
  46313. this.cameraDirection.copyFromFloats(0, 0, 0);
  46314. this.cameraRotation.copyFromFloats(0, 0);
  46315. return true;
  46316. };
  46317. // Cache
  46318. TargetCamera.prototype._initCache = function () {
  46319. _super.prototype._initCache.call(this);
  46320. this._cache.lockedTarget = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46321. this._cache.rotation = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46322. this._cache.rotationQuaternion = new BABYLON.Quaternion(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  46323. };
  46324. TargetCamera.prototype._updateCache = function (ignoreParentClass) {
  46325. if (!ignoreParentClass) {
  46326. _super.prototype._updateCache.call(this);
  46327. }
  46328. var lockedTargetPosition = this._getLockedTargetPosition();
  46329. if (!lockedTargetPosition) {
  46330. this._cache.lockedTarget = null;
  46331. }
  46332. else {
  46333. if (!this._cache.lockedTarget) {
  46334. this._cache.lockedTarget = lockedTargetPosition.clone();
  46335. }
  46336. else {
  46337. this._cache.lockedTarget.copyFrom(lockedTargetPosition);
  46338. }
  46339. }
  46340. this._cache.rotation.copyFrom(this.rotation);
  46341. if (this.rotationQuaternion)
  46342. this._cache.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46343. };
  46344. // Synchronized
  46345. TargetCamera.prototype._isSynchronizedViewMatrix = function () {
  46346. if (!_super.prototype._isSynchronizedViewMatrix.call(this)) {
  46347. return false;
  46348. }
  46349. var lockedTargetPosition = this._getLockedTargetPosition();
  46350. return (this._cache.lockedTarget ? this._cache.lockedTarget.equals(lockedTargetPosition) : !lockedTargetPosition)
  46351. && (this.rotationQuaternion ? this.rotationQuaternion.equals(this._cache.rotationQuaternion) : this._cache.rotation.equals(this.rotation));
  46352. };
  46353. // Methods
  46354. TargetCamera.prototype._computeLocalCameraSpeed = function () {
  46355. var engine = this.getEngine();
  46356. return this.speed * Math.sqrt((engine.getDeltaTime() / (engine.getFps() * 100.0)));
  46357. };
  46358. // Target
  46359. TargetCamera.prototype.setTarget = function (target) {
  46360. this.upVector.normalize();
  46361. BABYLON.Matrix.LookAtLHToRef(this.position, target, this.upVector, this._camMatrix);
  46362. this._camMatrix.invert();
  46363. this.rotation.x = Math.atan(this._camMatrix.m[6] / this._camMatrix.m[10]);
  46364. var vDir = target.subtract(this.position);
  46365. if (vDir.x >= 0.0) {
  46366. this.rotation.y = (-Math.atan(vDir.z / vDir.x) + Math.PI / 2.0);
  46367. }
  46368. else {
  46369. this.rotation.y = (-Math.atan(vDir.z / vDir.x) - Math.PI / 2.0);
  46370. }
  46371. this.rotation.z = 0;
  46372. if (isNaN(this.rotation.x)) {
  46373. this.rotation.x = 0;
  46374. }
  46375. if (isNaN(this.rotation.y)) {
  46376. this.rotation.y = 0;
  46377. }
  46378. if (isNaN(this.rotation.z)) {
  46379. this.rotation.z = 0;
  46380. }
  46381. if (this.rotationQuaternion) {
  46382. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46383. }
  46384. };
  46385. /**
  46386. * Return the current target position of the camera. This value is expressed in local space.
  46387. */
  46388. TargetCamera.prototype.getTarget = function () {
  46389. return this._currentTarget;
  46390. };
  46391. TargetCamera.prototype._decideIfNeedsToMove = function () {
  46392. return Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  46393. };
  46394. TargetCamera.prototype._updatePosition = function () {
  46395. if (this.parent) {
  46396. this.parent.getWorldMatrix().invertToRef(BABYLON.Tmp.Matrix[0]);
  46397. BABYLON.Vector3.TransformNormalToRef(this.cameraDirection, BABYLON.Tmp.Matrix[0], BABYLON.Tmp.Vector3[0]);
  46398. this.position.addInPlace(BABYLON.Tmp.Vector3[0]);
  46399. return;
  46400. }
  46401. this.position.addInPlace(this.cameraDirection);
  46402. };
  46403. TargetCamera.prototype._checkInputs = function () {
  46404. var needToMove = this._decideIfNeedsToMove();
  46405. var needToRotate = Math.abs(this.cameraRotation.x) > 0 || Math.abs(this.cameraRotation.y) > 0;
  46406. // Move
  46407. if (needToMove) {
  46408. this._updatePosition();
  46409. }
  46410. // Rotate
  46411. if (needToRotate) {
  46412. this.rotation.x += this.cameraRotation.x;
  46413. this.rotation.y += this.cameraRotation.y;
  46414. //rotate, if quaternion is set and rotation was used
  46415. if (this.rotationQuaternion) {
  46416. var len = this.rotation.lengthSquared();
  46417. if (len) {
  46418. BABYLON.Quaternion.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this.rotationQuaternion);
  46419. }
  46420. }
  46421. if (!this.noRotationConstraint) {
  46422. var limit = (Math.PI / 2) * 0.95;
  46423. if (this.rotation.x > limit)
  46424. this.rotation.x = limit;
  46425. if (this.rotation.x < -limit)
  46426. this.rotation.x = -limit;
  46427. }
  46428. }
  46429. // Inertia
  46430. if (needToMove) {
  46431. if (Math.abs(this.cameraDirection.x) < this.speed * BABYLON.Epsilon) {
  46432. this.cameraDirection.x = 0;
  46433. }
  46434. if (Math.abs(this.cameraDirection.y) < this.speed * BABYLON.Epsilon) {
  46435. this.cameraDirection.y = 0;
  46436. }
  46437. if (Math.abs(this.cameraDirection.z) < this.speed * BABYLON.Epsilon) {
  46438. this.cameraDirection.z = 0;
  46439. }
  46440. this.cameraDirection.scaleInPlace(this.inertia);
  46441. }
  46442. if (needToRotate) {
  46443. if (Math.abs(this.cameraRotation.x) < this.speed * BABYLON.Epsilon) {
  46444. this.cameraRotation.x = 0;
  46445. }
  46446. if (Math.abs(this.cameraRotation.y) < this.speed * BABYLON.Epsilon) {
  46447. this.cameraRotation.y = 0;
  46448. }
  46449. this.cameraRotation.scaleInPlace(this.inertia);
  46450. }
  46451. _super.prototype._checkInputs.call(this);
  46452. };
  46453. TargetCamera.prototype._updateCameraRotationMatrix = function () {
  46454. if (this.rotationQuaternion) {
  46455. this.rotationQuaternion.toRotationMatrix(this._cameraRotationMatrix);
  46456. }
  46457. else {
  46458. BABYLON.Matrix.RotationYawPitchRollToRef(this.rotation.y, this.rotation.x, this.rotation.z, this._cameraRotationMatrix);
  46459. }
  46460. //update the up vector!
  46461. BABYLON.Vector3.TransformNormalToRef(this.upVector, this._cameraRotationMatrix, this._currentUpVector);
  46462. };
  46463. TargetCamera.prototype._getViewMatrix = function () {
  46464. if (this.lockedTarget) {
  46465. this.setTarget(this._getLockedTargetPosition());
  46466. }
  46467. // Compute
  46468. this._updateCameraRotationMatrix();
  46469. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  46470. // Computing target and final matrix
  46471. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  46472. this._computeViewMatrix(this.position, this._currentTarget, this._currentUpVector);
  46473. return this._viewMatrix;
  46474. };
  46475. TargetCamera.prototype._computeViewMatrix = function (position, target, up) {
  46476. if (this.parent) {
  46477. var parentWorldMatrix = this.parent.getWorldMatrix();
  46478. BABYLON.Vector3.TransformCoordinatesToRef(this.position, parentWorldMatrix, this._globalPosition);
  46479. BABYLON.Vector3.TransformCoordinatesToRef(target, parentWorldMatrix, this._globalCurrentTarget);
  46480. BABYLON.Vector3.TransformNormalToRef(up, parentWorldMatrix, this._globalCurrentUpVector);
  46481. this._markSyncedWithParent();
  46482. }
  46483. else {
  46484. this._globalPosition.copyFrom(this.position);
  46485. this._globalCurrentTarget.copyFrom(target);
  46486. this._globalCurrentUpVector.copyFrom(up);
  46487. }
  46488. if (this.getScene().useRightHandedSystem) {
  46489. BABYLON.Matrix.LookAtRHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46490. }
  46491. else {
  46492. BABYLON.Matrix.LookAtLHToRef(this._globalPosition, this._globalCurrentTarget, this._globalCurrentUpVector, this._viewMatrix);
  46493. }
  46494. };
  46495. /**
  46496. * @override
  46497. * Override Camera.createRigCamera
  46498. */
  46499. TargetCamera.prototype.createRigCamera = function (name, cameraIndex) {
  46500. if (this.cameraRigMode !== BABYLON.Camera.RIG_MODE_NONE) {
  46501. var rigCamera = new TargetCamera(name, this.position.clone(), this.getScene());
  46502. if (this.cameraRigMode === BABYLON.Camera.RIG_MODE_VR || this.cameraRigMode === BABYLON.Camera.RIG_MODE_WEBVR) {
  46503. if (!this.rotationQuaternion) {
  46504. this.rotationQuaternion = new BABYLON.Quaternion();
  46505. }
  46506. rigCamera._cameraRigParams = {};
  46507. rigCamera.rotationQuaternion = new BABYLON.Quaternion();
  46508. }
  46509. return rigCamera;
  46510. }
  46511. return null;
  46512. };
  46513. /**
  46514. * @override
  46515. * Override Camera._updateRigCameras
  46516. */
  46517. TargetCamera.prototype._updateRigCameras = function () {
  46518. var camLeft = this._rigCameras[0];
  46519. var camRight = this._rigCameras[1];
  46520. switch (this.cameraRigMode) {
  46521. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  46522. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  46523. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  46524. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  46525. //provisionnaly using _cameraRigParams.stereoHalfAngle instead of calculations based on _cameraRigParams.interaxialDistance:
  46526. var leftSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? 1 : -1;
  46527. var rightSign = (this.cameraRigMode === BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED) ? -1 : 1;
  46528. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * leftSign, camLeft.position);
  46529. this._getRigCamPosition(this._cameraRigParams.stereoHalfAngle * rightSign, camRight.position);
  46530. camLeft.setTarget(this.getTarget());
  46531. camRight.setTarget(this.getTarget());
  46532. break;
  46533. case BABYLON.Camera.RIG_MODE_VR:
  46534. if (camLeft.rotationQuaternion) {
  46535. camLeft.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46536. camRight.rotationQuaternion.copyFrom(this.rotationQuaternion);
  46537. }
  46538. else {
  46539. camLeft.rotation.copyFrom(this.rotation);
  46540. camRight.rotation.copyFrom(this.rotation);
  46541. }
  46542. camLeft.position.copyFrom(this.position);
  46543. camRight.position.copyFrom(this.position);
  46544. break;
  46545. }
  46546. _super.prototype._updateRigCameras.call(this);
  46547. };
  46548. TargetCamera.prototype._getRigCamPosition = function (halfSpace, result) {
  46549. if (!this._rigCamTransformMatrix) {
  46550. this._rigCamTransformMatrix = new BABYLON.Matrix();
  46551. }
  46552. var target = this.getTarget();
  46553. BABYLON.Matrix.Translation(-target.x, -target.y, -target.z).multiplyToRef(BABYLON.Matrix.RotationY(halfSpace), this._rigCamTransformMatrix);
  46554. this._rigCamTransformMatrix = this._rigCamTransformMatrix.multiply(BABYLON.Matrix.Translation(target.x, target.y, target.z));
  46555. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this._rigCamTransformMatrix, result);
  46556. };
  46557. TargetCamera.prototype.getClassName = function () {
  46558. return "TargetCamera";
  46559. };
  46560. __decorate([
  46561. BABYLON.serializeAsVector3()
  46562. ], TargetCamera.prototype, "rotation", void 0);
  46563. __decorate([
  46564. BABYLON.serialize()
  46565. ], TargetCamera.prototype, "speed", void 0);
  46566. __decorate([
  46567. BABYLON.serializeAsMeshReference("lockedTargetId")
  46568. ], TargetCamera.prototype, "lockedTarget", void 0);
  46569. return TargetCamera;
  46570. }(BABYLON.Camera));
  46571. BABYLON.TargetCamera = TargetCamera;
  46572. })(BABYLON || (BABYLON = {}));
  46573. //# sourceMappingURL=babylon.targetCamera.js.map
  46574. var BABYLON;
  46575. (function (BABYLON) {
  46576. var FreeCameraMouseInput = /** @class */ (function () {
  46577. function FreeCameraMouseInput(touchEnabled) {
  46578. if (touchEnabled === void 0) { touchEnabled = true; }
  46579. this.touchEnabled = touchEnabled;
  46580. this.buttons = [0, 1, 2];
  46581. this.angularSensibility = 2000.0;
  46582. this.previousPosition = null;
  46583. }
  46584. FreeCameraMouseInput.prototype.attachControl = function (element, noPreventDefault) {
  46585. var _this = this;
  46586. var engine = this.camera.getEngine();
  46587. if (!this._pointerInput) {
  46588. this._pointerInput = function (p, s) {
  46589. var evt = p.event;
  46590. if (engine.isInVRExclusivePointerMode) {
  46591. return;
  46592. }
  46593. if (!_this.touchEnabled && evt.pointerType === "touch") {
  46594. return;
  46595. }
  46596. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  46597. return;
  46598. }
  46599. var srcElement = (evt.srcElement || evt.target);
  46600. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  46601. try {
  46602. srcElement.setPointerCapture(evt.pointerId);
  46603. }
  46604. catch (e) {
  46605. //Nothing to do with the error. Execution will continue.
  46606. }
  46607. _this.previousPosition = {
  46608. x: evt.clientX,
  46609. y: evt.clientY
  46610. };
  46611. if (!noPreventDefault) {
  46612. evt.preventDefault();
  46613. element.focus();
  46614. }
  46615. }
  46616. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  46617. try {
  46618. srcElement.releasePointerCapture(evt.pointerId);
  46619. }
  46620. catch (e) {
  46621. //Nothing to do with the error.
  46622. }
  46623. _this.previousPosition = null;
  46624. if (!noPreventDefault) {
  46625. evt.preventDefault();
  46626. }
  46627. }
  46628. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  46629. if (!_this.previousPosition || engine.isPointerLock) {
  46630. return;
  46631. }
  46632. var offsetX = evt.clientX - _this.previousPosition.x;
  46633. if (_this.camera.getScene().useRightHandedSystem)
  46634. offsetX *= -1;
  46635. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46636. offsetX *= -1;
  46637. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46638. var offsetY = evt.clientY - _this.previousPosition.y;
  46639. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46640. _this.previousPosition = {
  46641. x: evt.clientX,
  46642. y: evt.clientY
  46643. };
  46644. if (!noPreventDefault) {
  46645. evt.preventDefault();
  46646. }
  46647. }
  46648. };
  46649. }
  46650. this._onMouseMove = function (evt) {
  46651. if (!engine.isPointerLock) {
  46652. return;
  46653. }
  46654. if (engine.isInVRExclusivePointerMode) {
  46655. return;
  46656. }
  46657. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  46658. if (_this.camera.getScene().useRightHandedSystem)
  46659. offsetX *= -1;
  46660. if (_this.camera.parent && _this.camera.parent._getWorldMatrixDeterminant() < 0)
  46661. offsetX *= -1;
  46662. _this.camera.cameraRotation.y += offsetX / _this.angularSensibility;
  46663. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  46664. _this.camera.cameraRotation.x += offsetY / _this.angularSensibility;
  46665. _this.previousPosition = null;
  46666. if (!noPreventDefault) {
  46667. evt.preventDefault();
  46668. }
  46669. };
  46670. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  46671. element.addEventListener("mousemove", this._onMouseMove, false);
  46672. };
  46673. FreeCameraMouseInput.prototype.detachControl = function (element) {
  46674. if (this._observer && element) {
  46675. this.camera.getScene().onPointerObservable.remove(this._observer);
  46676. if (this._onMouseMove) {
  46677. element.removeEventListener("mousemove", this._onMouseMove);
  46678. }
  46679. this._observer = null;
  46680. this._onMouseMove = null;
  46681. this.previousPosition = null;
  46682. }
  46683. };
  46684. FreeCameraMouseInput.prototype.getClassName = function () {
  46685. return "FreeCameraMouseInput";
  46686. };
  46687. FreeCameraMouseInput.prototype.getSimpleName = function () {
  46688. return "mouse";
  46689. };
  46690. __decorate([
  46691. BABYLON.serialize()
  46692. ], FreeCameraMouseInput.prototype, "buttons", void 0);
  46693. __decorate([
  46694. BABYLON.serialize()
  46695. ], FreeCameraMouseInput.prototype, "angularSensibility", void 0);
  46696. return FreeCameraMouseInput;
  46697. }());
  46698. BABYLON.FreeCameraMouseInput = FreeCameraMouseInput;
  46699. BABYLON.CameraInputTypes["FreeCameraMouseInput"] = FreeCameraMouseInput;
  46700. })(BABYLON || (BABYLON = {}));
  46701. //# sourceMappingURL=babylon.freeCameraMouseInput.js.map
  46702. var BABYLON;
  46703. (function (BABYLON) {
  46704. var FreeCameraKeyboardMoveInput = /** @class */ (function () {
  46705. function FreeCameraKeyboardMoveInput() {
  46706. this._keys = new Array();
  46707. this.keysUp = [38];
  46708. this.keysDown = [40];
  46709. this.keysLeft = [37];
  46710. this.keysRight = [39];
  46711. }
  46712. FreeCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  46713. var _this = this;
  46714. if (this._onCanvasBlurObserver) {
  46715. return;
  46716. }
  46717. this._scene = this.camera.getScene();
  46718. this._engine = this._scene.getEngine();
  46719. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  46720. _this._keys = [];
  46721. });
  46722. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  46723. var evt = info.event;
  46724. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  46725. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46726. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46727. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46728. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46729. var index = _this._keys.indexOf(evt.keyCode);
  46730. if (index === -1) {
  46731. _this._keys.push(evt.keyCode);
  46732. }
  46733. if (!noPreventDefault) {
  46734. evt.preventDefault();
  46735. }
  46736. }
  46737. }
  46738. else {
  46739. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  46740. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  46741. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  46742. _this.keysRight.indexOf(evt.keyCode) !== -1) {
  46743. var index = _this._keys.indexOf(evt.keyCode);
  46744. if (index >= 0) {
  46745. _this._keys.splice(index, 1);
  46746. }
  46747. if (!noPreventDefault) {
  46748. evt.preventDefault();
  46749. }
  46750. }
  46751. }
  46752. });
  46753. };
  46754. FreeCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  46755. if (this._scene) {
  46756. if (this._onKeyboardObserver) {
  46757. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  46758. }
  46759. if (this._onCanvasBlurObserver) {
  46760. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  46761. }
  46762. this._onKeyboardObserver = null;
  46763. this._onCanvasBlurObserver = null;
  46764. }
  46765. this._keys = [];
  46766. };
  46767. FreeCameraKeyboardMoveInput.prototype.checkInputs = function () {
  46768. if (this._onKeyboardObserver) {
  46769. var camera = this.camera;
  46770. // Keyboard
  46771. for (var index = 0; index < this._keys.length; index++) {
  46772. var keyCode = this._keys[index];
  46773. var speed = camera._computeLocalCameraSpeed();
  46774. if (this.keysLeft.indexOf(keyCode) !== -1) {
  46775. camera._localDirection.copyFromFloats(-speed, 0, 0);
  46776. }
  46777. else if (this.keysUp.indexOf(keyCode) !== -1) {
  46778. camera._localDirection.copyFromFloats(0, 0, speed);
  46779. }
  46780. else if (this.keysRight.indexOf(keyCode) !== -1) {
  46781. camera._localDirection.copyFromFloats(speed, 0, 0);
  46782. }
  46783. else if (this.keysDown.indexOf(keyCode) !== -1) {
  46784. camera._localDirection.copyFromFloats(0, 0, -speed);
  46785. }
  46786. if (camera.getScene().useRightHandedSystem) {
  46787. camera._localDirection.z *= -1;
  46788. }
  46789. camera.getViewMatrix().invertToRef(camera._cameraTransformMatrix);
  46790. BABYLON.Vector3.TransformNormalToRef(camera._localDirection, camera._cameraTransformMatrix, camera._transformedDirection);
  46791. camera.cameraDirection.addInPlace(camera._transformedDirection);
  46792. }
  46793. }
  46794. };
  46795. FreeCameraKeyboardMoveInput.prototype.getClassName = function () {
  46796. return "FreeCameraKeyboardMoveInput";
  46797. };
  46798. FreeCameraKeyboardMoveInput.prototype._onLostFocus = function (e) {
  46799. this._keys = [];
  46800. };
  46801. FreeCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  46802. return "keyboard";
  46803. };
  46804. __decorate([
  46805. BABYLON.serialize()
  46806. ], FreeCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  46807. __decorate([
  46808. BABYLON.serialize()
  46809. ], FreeCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  46810. __decorate([
  46811. BABYLON.serialize()
  46812. ], FreeCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  46813. __decorate([
  46814. BABYLON.serialize()
  46815. ], FreeCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  46816. return FreeCameraKeyboardMoveInput;
  46817. }());
  46818. BABYLON.FreeCameraKeyboardMoveInput = FreeCameraKeyboardMoveInput;
  46819. BABYLON.CameraInputTypes["FreeCameraKeyboardMoveInput"] = FreeCameraKeyboardMoveInput;
  46820. })(BABYLON || (BABYLON = {}));
  46821. //# sourceMappingURL=babylon.freeCameraKeyboardMoveInput.js.map
  46822. var BABYLON;
  46823. (function (BABYLON) {
  46824. var FreeCameraInputsManager = /** @class */ (function (_super) {
  46825. __extends(FreeCameraInputsManager, _super);
  46826. function FreeCameraInputsManager(camera) {
  46827. return _super.call(this, camera) || this;
  46828. }
  46829. FreeCameraInputsManager.prototype.addKeyboard = function () {
  46830. this.add(new BABYLON.FreeCameraKeyboardMoveInput());
  46831. return this;
  46832. };
  46833. FreeCameraInputsManager.prototype.addMouse = function (touchEnabled) {
  46834. if (touchEnabled === void 0) { touchEnabled = true; }
  46835. this.add(new BABYLON.FreeCameraMouseInput(touchEnabled));
  46836. return this;
  46837. };
  46838. FreeCameraInputsManager.prototype.addGamepad = function () {
  46839. this.add(new BABYLON.FreeCameraGamepadInput());
  46840. return this;
  46841. };
  46842. FreeCameraInputsManager.prototype.addDeviceOrientation = function () {
  46843. this.add(new BABYLON.FreeCameraDeviceOrientationInput());
  46844. return this;
  46845. };
  46846. FreeCameraInputsManager.prototype.addTouch = function () {
  46847. this.add(new BABYLON.FreeCameraTouchInput());
  46848. return this;
  46849. };
  46850. FreeCameraInputsManager.prototype.addVirtualJoystick = function () {
  46851. this.add(new BABYLON.FreeCameraVirtualJoystickInput());
  46852. return this;
  46853. };
  46854. return FreeCameraInputsManager;
  46855. }(BABYLON.CameraInputsManager));
  46856. BABYLON.FreeCameraInputsManager = FreeCameraInputsManager;
  46857. })(BABYLON || (BABYLON = {}));
  46858. //# sourceMappingURL=babylon.freeCameraInputsManager.js.map
  46859. var BABYLON;
  46860. (function (BABYLON) {
  46861. var FreeCamera = /** @class */ (function (_super) {
  46862. __extends(FreeCamera, _super);
  46863. function FreeCamera(name, position, scene, setActiveOnSceneIfNoneActive) {
  46864. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  46865. var _this = _super.call(this, name, position, scene, setActiveOnSceneIfNoneActive) || this;
  46866. _this.ellipsoid = new BABYLON.Vector3(0.5, 1, 0.5);
  46867. _this.ellipsoidOffset = new BABYLON.Vector3(0, 0, 0);
  46868. _this.checkCollisions = false;
  46869. _this.applyGravity = false;
  46870. _this._needMoveForGravity = false;
  46871. _this._oldPosition = BABYLON.Vector3.Zero();
  46872. _this._diffPosition = BABYLON.Vector3.Zero();
  46873. _this._newPosition = BABYLON.Vector3.Zero();
  46874. // Collisions
  46875. _this._collisionMask = -1;
  46876. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  46877. if (collidedMesh === void 0) { collidedMesh = null; }
  46878. //TODO move this to the collision coordinator!
  46879. if (_this.getScene().workerCollisions)
  46880. newPosition.multiplyInPlace(_this._collider._radius);
  46881. var updatePosition = function (newPos) {
  46882. _this._newPosition.copyFrom(newPos);
  46883. _this._newPosition.subtractToRef(_this._oldPosition, _this._diffPosition);
  46884. if (_this._diffPosition.length() > BABYLON.Engine.CollisionsEpsilon) {
  46885. _this.position.addInPlace(_this._diffPosition);
  46886. if (_this.onCollide && collidedMesh) {
  46887. _this.onCollide(collidedMesh);
  46888. }
  46889. }
  46890. };
  46891. updatePosition(newPosition);
  46892. };
  46893. _this.inputs = new BABYLON.FreeCameraInputsManager(_this);
  46894. _this.inputs.addKeyboard().addMouse();
  46895. return _this;
  46896. }
  46897. Object.defineProperty(FreeCamera.prototype, "angularSensibility", {
  46898. //-- begin properties for backward compatibility for inputs
  46899. /**
  46900. * Gets the input sensibility for a mouse input. (default is 2000.0)
  46901. * Higher values reduce sensitivity.
  46902. */
  46903. get: function () {
  46904. var mouse = this.inputs.attached["mouse"];
  46905. if (mouse)
  46906. return mouse.angularSensibility;
  46907. return 0;
  46908. },
  46909. /**
  46910. * Sets the input sensibility for a mouse input. (default is 2000.0)
  46911. * Higher values reduce sensitivity.
  46912. */
  46913. set: function (value) {
  46914. var mouse = this.inputs.attached["mouse"];
  46915. if (mouse)
  46916. mouse.angularSensibility = value;
  46917. },
  46918. enumerable: true,
  46919. configurable: true
  46920. });
  46921. Object.defineProperty(FreeCamera.prototype, "keysUp", {
  46922. get: function () {
  46923. var keyboard = this.inputs.attached["keyboard"];
  46924. if (keyboard)
  46925. return keyboard.keysUp;
  46926. return [];
  46927. },
  46928. set: function (value) {
  46929. var keyboard = this.inputs.attached["keyboard"];
  46930. if (keyboard)
  46931. keyboard.keysUp = value;
  46932. },
  46933. enumerable: true,
  46934. configurable: true
  46935. });
  46936. Object.defineProperty(FreeCamera.prototype, "keysDown", {
  46937. get: function () {
  46938. var keyboard = this.inputs.attached["keyboard"];
  46939. if (keyboard)
  46940. return keyboard.keysDown;
  46941. return [];
  46942. },
  46943. set: function (value) {
  46944. var keyboard = this.inputs.attached["keyboard"];
  46945. if (keyboard)
  46946. keyboard.keysDown = value;
  46947. },
  46948. enumerable: true,
  46949. configurable: true
  46950. });
  46951. Object.defineProperty(FreeCamera.prototype, "keysLeft", {
  46952. get: function () {
  46953. var keyboard = this.inputs.attached["keyboard"];
  46954. if (keyboard)
  46955. return keyboard.keysLeft;
  46956. return [];
  46957. },
  46958. set: function (value) {
  46959. var keyboard = this.inputs.attached["keyboard"];
  46960. if (keyboard)
  46961. keyboard.keysLeft = value;
  46962. },
  46963. enumerable: true,
  46964. configurable: true
  46965. });
  46966. Object.defineProperty(FreeCamera.prototype, "keysRight", {
  46967. get: function () {
  46968. var keyboard = this.inputs.attached["keyboard"];
  46969. if (keyboard)
  46970. return keyboard.keysRight;
  46971. return [];
  46972. },
  46973. set: function (value) {
  46974. var keyboard = this.inputs.attached["keyboard"];
  46975. if (keyboard)
  46976. keyboard.keysRight = value;
  46977. },
  46978. enumerable: true,
  46979. configurable: true
  46980. });
  46981. // Controls
  46982. FreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  46983. this.inputs.attachElement(element, noPreventDefault);
  46984. };
  46985. FreeCamera.prototype.detachControl = function (element) {
  46986. this.inputs.detachElement(element);
  46987. this.cameraDirection = new BABYLON.Vector3(0, 0, 0);
  46988. this.cameraRotation = new BABYLON.Vector2(0, 0);
  46989. };
  46990. Object.defineProperty(FreeCamera.prototype, "collisionMask", {
  46991. get: function () {
  46992. return this._collisionMask;
  46993. },
  46994. set: function (mask) {
  46995. this._collisionMask = !isNaN(mask) ? mask : -1;
  46996. },
  46997. enumerable: true,
  46998. configurable: true
  46999. });
  47000. FreeCamera.prototype._collideWithWorld = function (displacement) {
  47001. var globalPosition;
  47002. if (this.parent) {
  47003. globalPosition = BABYLON.Vector3.TransformCoordinates(this.position, this.parent.getWorldMatrix());
  47004. }
  47005. else {
  47006. globalPosition = this.position;
  47007. }
  47008. globalPosition.subtractFromFloatsToRef(0, this.ellipsoid.y, 0, this._oldPosition);
  47009. this._oldPosition.addInPlace(this.ellipsoidOffset);
  47010. if (!this._collider) {
  47011. this._collider = new BABYLON.Collider();
  47012. }
  47013. this._collider._radius = this.ellipsoid;
  47014. this._collider.collisionMask = this._collisionMask;
  47015. //no need for clone, as long as gravity is not on.
  47016. var actualDisplacement = displacement;
  47017. //add gravity to the direction to prevent the dual-collision checking
  47018. if (this.applyGravity) {
  47019. //this prevents mending with cameraDirection, a global variable of the free camera class.
  47020. actualDisplacement = displacement.add(this.getScene().gravity);
  47021. }
  47022. this.getScene().collisionCoordinator.getNewPosition(this._oldPosition, actualDisplacement, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  47023. };
  47024. FreeCamera.prototype._checkInputs = function () {
  47025. if (!this._localDirection) {
  47026. this._localDirection = BABYLON.Vector3.Zero();
  47027. this._transformedDirection = BABYLON.Vector3.Zero();
  47028. }
  47029. this.inputs.checkInputs();
  47030. _super.prototype._checkInputs.call(this);
  47031. };
  47032. FreeCamera.prototype._decideIfNeedsToMove = function () {
  47033. return this._needMoveForGravity || Math.abs(this.cameraDirection.x) > 0 || Math.abs(this.cameraDirection.y) > 0 || Math.abs(this.cameraDirection.z) > 0;
  47034. };
  47035. FreeCamera.prototype._updatePosition = function () {
  47036. if (this.checkCollisions && this.getScene().collisionsEnabled) {
  47037. this._collideWithWorld(this.cameraDirection);
  47038. }
  47039. else {
  47040. _super.prototype._updatePosition.call(this);
  47041. }
  47042. };
  47043. FreeCamera.prototype.dispose = function () {
  47044. this.inputs.clear();
  47045. _super.prototype.dispose.call(this);
  47046. };
  47047. FreeCamera.prototype.getClassName = function () {
  47048. return "FreeCamera";
  47049. };
  47050. __decorate([
  47051. BABYLON.serializeAsVector3()
  47052. ], FreeCamera.prototype, "ellipsoid", void 0);
  47053. __decorate([
  47054. BABYLON.serializeAsVector3()
  47055. ], FreeCamera.prototype, "ellipsoidOffset", void 0);
  47056. __decorate([
  47057. BABYLON.serialize()
  47058. ], FreeCamera.prototype, "checkCollisions", void 0);
  47059. __decorate([
  47060. BABYLON.serialize()
  47061. ], FreeCamera.prototype, "applyGravity", void 0);
  47062. return FreeCamera;
  47063. }(BABYLON.TargetCamera));
  47064. BABYLON.FreeCamera = FreeCamera;
  47065. })(BABYLON || (BABYLON = {}));
  47066. //# sourceMappingURL=babylon.freeCamera.js.map
  47067. var BABYLON;
  47068. (function (BABYLON) {
  47069. var ArcRotateCameraKeyboardMoveInput = /** @class */ (function () {
  47070. function ArcRotateCameraKeyboardMoveInput() {
  47071. this._keys = new Array();
  47072. this.keysUp = [38];
  47073. this.keysDown = [40];
  47074. this.keysLeft = [37];
  47075. this.keysRight = [39];
  47076. this.keysReset = [220];
  47077. this.panningSensibility = 50.0;
  47078. this.zoomingSensibility = 25.0;
  47079. this.useAltToZoom = true;
  47080. }
  47081. ArcRotateCameraKeyboardMoveInput.prototype.attachControl = function (element, noPreventDefault) {
  47082. var _this = this;
  47083. if (this._onCanvasBlurObserver) {
  47084. return;
  47085. }
  47086. this._scene = this.camera.getScene();
  47087. this._engine = this._scene.getEngine();
  47088. this._onCanvasBlurObserver = this._engine.onCanvasBlurObservable.add(function () {
  47089. _this._keys = [];
  47090. });
  47091. this._onKeyboardObserver = this._scene.onKeyboardObservable.add(function (info) {
  47092. var evt = info.event;
  47093. if (info.type === BABYLON.KeyboardEventTypes.KEYDOWN) {
  47094. _this._ctrlPressed = evt.ctrlKey;
  47095. _this._altPressed = evt.altKey;
  47096. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47097. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47098. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47099. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47100. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47101. var index = _this._keys.indexOf(evt.keyCode);
  47102. if (index === -1) {
  47103. _this._keys.push(evt.keyCode);
  47104. }
  47105. if (evt.preventDefault) {
  47106. if (!noPreventDefault) {
  47107. evt.preventDefault();
  47108. }
  47109. }
  47110. }
  47111. }
  47112. else {
  47113. if (_this.keysUp.indexOf(evt.keyCode) !== -1 ||
  47114. _this.keysDown.indexOf(evt.keyCode) !== -1 ||
  47115. _this.keysLeft.indexOf(evt.keyCode) !== -1 ||
  47116. _this.keysRight.indexOf(evt.keyCode) !== -1 ||
  47117. _this.keysReset.indexOf(evt.keyCode) !== -1) {
  47118. var index = _this._keys.indexOf(evt.keyCode);
  47119. if (index >= 0) {
  47120. _this._keys.splice(index, 1);
  47121. }
  47122. if (evt.preventDefault) {
  47123. if (!noPreventDefault) {
  47124. evt.preventDefault();
  47125. }
  47126. }
  47127. }
  47128. }
  47129. });
  47130. };
  47131. ArcRotateCameraKeyboardMoveInput.prototype.detachControl = function (element) {
  47132. if (this._scene) {
  47133. if (this._onKeyboardObserver) {
  47134. this._scene.onKeyboardObservable.remove(this._onKeyboardObserver);
  47135. }
  47136. if (this._onCanvasBlurObserver) {
  47137. this._engine.onCanvasBlurObservable.remove(this._onCanvasBlurObserver);
  47138. }
  47139. this._onKeyboardObserver = null;
  47140. this._onCanvasBlurObserver = null;
  47141. }
  47142. this._keys = [];
  47143. };
  47144. ArcRotateCameraKeyboardMoveInput.prototype.checkInputs = function () {
  47145. if (this._onKeyboardObserver) {
  47146. var camera = this.camera;
  47147. for (var index = 0; index < this._keys.length; index++) {
  47148. var keyCode = this._keys[index];
  47149. if (this.keysLeft.indexOf(keyCode) !== -1) {
  47150. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47151. camera.inertialPanningX -= 1 / this.panningSensibility;
  47152. }
  47153. else {
  47154. camera.inertialAlphaOffset -= 0.01;
  47155. }
  47156. }
  47157. else if (this.keysUp.indexOf(keyCode) !== -1) {
  47158. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47159. camera.inertialPanningY += 1 / this.panningSensibility;
  47160. }
  47161. else if (this._altPressed && this.useAltToZoom) {
  47162. camera.inertialRadiusOffset += 1 / this.zoomingSensibility;
  47163. }
  47164. else {
  47165. camera.inertialBetaOffset -= 0.01;
  47166. }
  47167. }
  47168. else if (this.keysRight.indexOf(keyCode) !== -1) {
  47169. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47170. camera.inertialPanningX += 1 / this.panningSensibility;
  47171. }
  47172. else {
  47173. camera.inertialAlphaOffset += 0.01;
  47174. }
  47175. }
  47176. else if (this.keysDown.indexOf(keyCode) !== -1) {
  47177. if (this._ctrlPressed && this.camera._useCtrlForPanning) {
  47178. camera.inertialPanningY -= 1 / this.panningSensibility;
  47179. }
  47180. else if (this._altPressed && this.useAltToZoom) {
  47181. camera.inertialRadiusOffset -= 1 / this.zoomingSensibility;
  47182. }
  47183. else {
  47184. camera.inertialBetaOffset += 0.01;
  47185. }
  47186. }
  47187. else if (this.keysReset.indexOf(keyCode) !== -1) {
  47188. camera.restoreState();
  47189. }
  47190. }
  47191. }
  47192. };
  47193. ArcRotateCameraKeyboardMoveInput.prototype.getClassName = function () {
  47194. return "ArcRotateCameraKeyboardMoveInput";
  47195. };
  47196. ArcRotateCameraKeyboardMoveInput.prototype.getSimpleName = function () {
  47197. return "keyboard";
  47198. };
  47199. __decorate([
  47200. BABYLON.serialize()
  47201. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysUp", void 0);
  47202. __decorate([
  47203. BABYLON.serialize()
  47204. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysDown", void 0);
  47205. __decorate([
  47206. BABYLON.serialize()
  47207. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysLeft", void 0);
  47208. __decorate([
  47209. BABYLON.serialize()
  47210. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysRight", void 0);
  47211. __decorate([
  47212. BABYLON.serialize()
  47213. ], ArcRotateCameraKeyboardMoveInput.prototype, "keysReset", void 0);
  47214. __decorate([
  47215. BABYLON.serialize()
  47216. ], ArcRotateCameraKeyboardMoveInput.prototype, "panningSensibility", void 0);
  47217. __decorate([
  47218. BABYLON.serialize()
  47219. ], ArcRotateCameraKeyboardMoveInput.prototype, "zoomingSensibility", void 0);
  47220. __decorate([
  47221. BABYLON.serialize()
  47222. ], ArcRotateCameraKeyboardMoveInput.prototype, "useAltToZoom", void 0);
  47223. return ArcRotateCameraKeyboardMoveInput;
  47224. }());
  47225. BABYLON.ArcRotateCameraKeyboardMoveInput = ArcRotateCameraKeyboardMoveInput;
  47226. BABYLON.CameraInputTypes["ArcRotateCameraKeyboardMoveInput"] = ArcRotateCameraKeyboardMoveInput;
  47227. })(BABYLON || (BABYLON = {}));
  47228. //# sourceMappingURL=babylon.arcRotateCameraKeyboardMoveInput.js.map
  47229. var BABYLON;
  47230. (function (BABYLON) {
  47231. var ArcRotateCameraMouseWheelInput = /** @class */ (function () {
  47232. function ArcRotateCameraMouseWheelInput() {
  47233. this.wheelPrecision = 3.0;
  47234. /**
  47235. * wheelDeltaPercentage will be used instead of wheelPrecision if different from 0.
  47236. * It defines the percentage of current camera.radius to use as delta when wheel is used.
  47237. */
  47238. this.wheelDeltaPercentage = 0;
  47239. }
  47240. ArcRotateCameraMouseWheelInput.prototype.attachControl = function (element, noPreventDefault) {
  47241. var _this = this;
  47242. this._wheel = function (p, s) {
  47243. //sanity check - this should be a PointerWheel event.
  47244. if (p.type !== BABYLON.PointerEventTypes.POINTERWHEEL)
  47245. return;
  47246. var event = p.event;
  47247. var delta = 0;
  47248. if (event.wheelDelta) {
  47249. if (_this.wheelDeltaPercentage) {
  47250. var wheelDelta = (event.wheelDelta * 0.01 * _this.wheelDeltaPercentage) * _this.camera.radius;
  47251. if (event.wheelDelta > 0) {
  47252. delta = wheelDelta / (1.0 + _this.wheelDeltaPercentage);
  47253. }
  47254. else {
  47255. delta = wheelDelta * (1.0 + _this.wheelDeltaPercentage);
  47256. }
  47257. }
  47258. else {
  47259. delta = event.wheelDelta / (_this.wheelPrecision * 40);
  47260. }
  47261. }
  47262. else if (event.detail) {
  47263. delta = -event.detail / _this.wheelPrecision;
  47264. }
  47265. if (delta)
  47266. _this.camera.inertialRadiusOffset += delta;
  47267. if (event.preventDefault) {
  47268. if (!noPreventDefault) {
  47269. event.preventDefault();
  47270. }
  47271. }
  47272. };
  47273. this._observer = this.camera.getScene().onPointerObservable.add(this._wheel, BABYLON.PointerEventTypes.POINTERWHEEL);
  47274. };
  47275. ArcRotateCameraMouseWheelInput.prototype.detachControl = function (element) {
  47276. if (this._observer && element) {
  47277. this.camera.getScene().onPointerObservable.remove(this._observer);
  47278. this._observer = null;
  47279. this._wheel = null;
  47280. }
  47281. };
  47282. ArcRotateCameraMouseWheelInput.prototype.getClassName = function () {
  47283. return "ArcRotateCameraMouseWheelInput";
  47284. };
  47285. ArcRotateCameraMouseWheelInput.prototype.getSimpleName = function () {
  47286. return "mousewheel";
  47287. };
  47288. __decorate([
  47289. BABYLON.serialize()
  47290. ], ArcRotateCameraMouseWheelInput.prototype, "wheelPrecision", void 0);
  47291. __decorate([
  47292. BABYLON.serialize()
  47293. ], ArcRotateCameraMouseWheelInput.prototype, "wheelDeltaPercentage", void 0);
  47294. return ArcRotateCameraMouseWheelInput;
  47295. }());
  47296. BABYLON.ArcRotateCameraMouseWheelInput = ArcRotateCameraMouseWheelInput;
  47297. BABYLON.CameraInputTypes["ArcRotateCameraMouseWheelInput"] = ArcRotateCameraMouseWheelInput;
  47298. })(BABYLON || (BABYLON = {}));
  47299. //# sourceMappingURL=babylon.arcRotateCameraMouseWheelInput.js.map
  47300. var BABYLON;
  47301. (function (BABYLON) {
  47302. var ArcRotateCameraPointersInput = /** @class */ (function () {
  47303. function ArcRotateCameraPointersInput() {
  47304. this.buttons = [0, 1, 2];
  47305. this.angularSensibilityX = 1000.0;
  47306. this.angularSensibilityY = 1000.0;
  47307. this.pinchPrecision = 12.0;
  47308. /**
  47309. * pinchDeltaPercentage will be used instead of pinchPrecision if different from 0.
  47310. * It defines the percentage of current camera.radius to use as delta when pinch zoom is used.
  47311. */
  47312. this.pinchDeltaPercentage = 0;
  47313. this.panningSensibility = 1000.0;
  47314. this.multiTouchPanning = true;
  47315. this.multiTouchPanAndZoom = true;
  47316. this._isPanClick = false;
  47317. this.pinchInwards = true;
  47318. }
  47319. ArcRotateCameraPointersInput.prototype.attachControl = function (element, noPreventDefault) {
  47320. var _this = this;
  47321. var engine = this.camera.getEngine();
  47322. var cacheSoloPointer; // cache pointer object for better perf on camera rotation
  47323. var pointA = null;
  47324. var pointB = null;
  47325. var previousPinchSquaredDistance = 0;
  47326. var initialDistance = 0;
  47327. var twoFingerActivityCount = 0;
  47328. var previousMultiTouchPanPosition = { x: 0, y: 0, isPaning: false, isPinching: false };
  47329. this._pointerInput = function (p, s) {
  47330. var evt = p.event;
  47331. var isTouch = p.event.pointerType === "touch";
  47332. if (engine.isInVRExclusivePointerMode) {
  47333. return;
  47334. }
  47335. if (p.type !== BABYLON.PointerEventTypes.POINTERMOVE && _this.buttons.indexOf(evt.button) === -1) {
  47336. return;
  47337. }
  47338. var srcElement = (evt.srcElement || evt.target);
  47339. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN && srcElement) {
  47340. try {
  47341. srcElement.setPointerCapture(evt.pointerId);
  47342. }
  47343. catch (e) {
  47344. //Nothing to do with the error. Execution will continue.
  47345. }
  47346. // Manage panning with pan button click
  47347. _this._isPanClick = evt.button === _this.camera._panningMouseButton;
  47348. // manage pointers
  47349. cacheSoloPointer = { x: evt.clientX, y: evt.clientY, pointerId: evt.pointerId, type: evt.pointerType };
  47350. if (pointA === null) {
  47351. pointA = cacheSoloPointer;
  47352. }
  47353. else if (pointB === null) {
  47354. pointB = cacheSoloPointer;
  47355. }
  47356. if (!noPreventDefault) {
  47357. evt.preventDefault();
  47358. element.focus();
  47359. }
  47360. }
  47361. else if (p.type === BABYLON.PointerEventTypes.POINTERDOUBLETAP) {
  47362. _this.camera.restoreState();
  47363. }
  47364. else if (p.type === BABYLON.PointerEventTypes.POINTERUP && srcElement) {
  47365. try {
  47366. srcElement.releasePointerCapture(evt.pointerId);
  47367. }
  47368. catch (e) {
  47369. //Nothing to do with the error.
  47370. }
  47371. cacheSoloPointer = null;
  47372. previousPinchSquaredDistance = 0;
  47373. previousMultiTouchPanPosition.isPaning = false;
  47374. previousMultiTouchPanPosition.isPinching = false;
  47375. twoFingerActivityCount = 0;
  47376. initialDistance = 0;
  47377. if (!isTouch) {
  47378. pointB = null; // Mouse and pen are mono pointer
  47379. }
  47380. //would be better to use pointers.remove(evt.pointerId) for multitouch gestures,
  47381. //but emptying completly pointers collection is required to fix a bug on iPhone :
  47382. //when changing orientation while pinching camera, one pointer stay pressed forever if we don't release all pointers
  47383. //will be ok to put back pointers.remove(evt.pointerId); when iPhone bug corrected
  47384. if (engine._badOS) {
  47385. pointA = pointB = null;
  47386. }
  47387. else {
  47388. //only remove the impacted pointer in case of multitouch allowing on most
  47389. //platforms switching from rotate to zoom and pan seamlessly.
  47390. if (pointB && pointA && pointA.pointerId == evt.pointerId) {
  47391. pointA = pointB;
  47392. pointB = null;
  47393. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47394. }
  47395. else if (pointA && pointB && pointB.pointerId == evt.pointerId) {
  47396. pointB = null;
  47397. cacheSoloPointer = { x: pointA.x, y: pointA.y, pointerId: pointA.pointerId, type: evt.pointerType };
  47398. }
  47399. else {
  47400. pointA = pointB = null;
  47401. }
  47402. }
  47403. if (!noPreventDefault) {
  47404. evt.preventDefault();
  47405. }
  47406. }
  47407. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  47408. if (!noPreventDefault) {
  47409. evt.preventDefault();
  47410. }
  47411. // One button down
  47412. if (pointA && pointB === null && cacheSoloPointer) {
  47413. if (_this.panningSensibility !== 0 &&
  47414. ((evt.ctrlKey && _this.camera._useCtrlForPanning) || _this._isPanClick)) {
  47415. _this.camera.inertialPanningX += -(evt.clientX - cacheSoloPointer.x) / _this.panningSensibility;
  47416. _this.camera.inertialPanningY += (evt.clientY - cacheSoloPointer.y) / _this.panningSensibility;
  47417. }
  47418. else {
  47419. var offsetX = evt.clientX - cacheSoloPointer.x;
  47420. var offsetY = evt.clientY - cacheSoloPointer.y;
  47421. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47422. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47423. }
  47424. cacheSoloPointer.x = evt.clientX;
  47425. cacheSoloPointer.y = evt.clientY;
  47426. }
  47427. // Two buttons down: pinch/pan
  47428. else if (pointA && pointB) {
  47429. //if (noPreventDefault) { evt.preventDefault(); } //if pinch gesture, could be useful to force preventDefault to avoid html page scroll/zoom in some mobile browsers
  47430. var ed = (pointA.pointerId === evt.pointerId) ? pointA : pointB;
  47431. ed.x = evt.clientX;
  47432. ed.y = evt.clientY;
  47433. var direction = _this.pinchInwards ? 1 : -1;
  47434. var distX = pointA.x - pointB.x;
  47435. var distY = pointA.y - pointB.y;
  47436. var pinchSquaredDistance = (distX * distX) + (distY * distY);
  47437. var pinchDistance = Math.sqrt(pinchSquaredDistance);
  47438. if (previousPinchSquaredDistance === 0) {
  47439. initialDistance = pinchDistance;
  47440. previousPinchSquaredDistance = pinchSquaredDistance;
  47441. previousMultiTouchPanPosition.x = (pointA.x + pointB.x) / 2;
  47442. previousMultiTouchPanPosition.y = (pointA.y + pointB.y) / 2;
  47443. return;
  47444. }
  47445. if (_this.multiTouchPanAndZoom) {
  47446. if (_this.pinchDeltaPercentage) {
  47447. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47448. }
  47449. else {
  47450. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47451. (_this.pinchPrecision *
  47452. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47453. direction);
  47454. }
  47455. if (_this.panningSensibility !== 0) {
  47456. var pointersCenterX = (pointA.x + pointB.x) / 2;
  47457. var pointersCenterY = (pointA.y + pointB.y) / 2;
  47458. var pointersCenterDistX = pointersCenterX - previousMultiTouchPanPosition.x;
  47459. var pointersCenterDistY = pointersCenterY - previousMultiTouchPanPosition.y;
  47460. previousMultiTouchPanPosition.x = pointersCenterX;
  47461. previousMultiTouchPanPosition.y = pointersCenterY;
  47462. _this.camera.inertialPanningX += -(pointersCenterDistX) / (_this.panningSensibility);
  47463. _this.camera.inertialPanningY += (pointersCenterDistY) / (_this.panningSensibility);
  47464. }
  47465. }
  47466. else {
  47467. twoFingerActivityCount++;
  47468. if (previousMultiTouchPanPosition.isPinching || (twoFingerActivityCount < 20 && Math.abs(pinchDistance - initialDistance) > _this.camera.pinchToPanMaxDistance)) {
  47469. if (_this.pinchDeltaPercentage) {
  47470. _this.camera.inertialRadiusOffset += ((pinchSquaredDistance - previousPinchSquaredDistance) * 0.001) * _this.camera.radius * _this.pinchDeltaPercentage;
  47471. }
  47472. else {
  47473. _this.camera.inertialRadiusOffset += (pinchSquaredDistance - previousPinchSquaredDistance) /
  47474. (_this.pinchPrecision *
  47475. ((_this.angularSensibilityX + _this.angularSensibilityY) / 2) *
  47476. direction);
  47477. }
  47478. previousMultiTouchPanPosition.isPaning = false;
  47479. previousMultiTouchPanPosition.isPinching = true;
  47480. }
  47481. else {
  47482. if (cacheSoloPointer && cacheSoloPointer.pointerId === ed.pointerId && _this.panningSensibility !== 0 && _this.multiTouchPanning) {
  47483. if (!previousMultiTouchPanPosition.isPaning) {
  47484. previousMultiTouchPanPosition.isPaning = true;
  47485. previousMultiTouchPanPosition.isPinching = false;
  47486. previousMultiTouchPanPosition.x = ed.x;
  47487. previousMultiTouchPanPosition.y = ed.y;
  47488. return;
  47489. }
  47490. _this.camera.inertialPanningX += -(ed.x - previousMultiTouchPanPosition.x) / (_this.panningSensibility);
  47491. _this.camera.inertialPanningY += (ed.y - previousMultiTouchPanPosition.y) / (_this.panningSensibility);
  47492. }
  47493. }
  47494. if (cacheSoloPointer && cacheSoloPointer.pointerId === evt.pointerId) {
  47495. previousMultiTouchPanPosition.x = ed.x;
  47496. previousMultiTouchPanPosition.y = ed.y;
  47497. }
  47498. }
  47499. previousPinchSquaredDistance = pinchSquaredDistance;
  47500. }
  47501. }
  47502. };
  47503. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE | BABYLON.PointerEventTypes._POINTERDOUBLETAP);
  47504. this._onContextMenu = function (evt) {
  47505. evt.preventDefault();
  47506. };
  47507. if (!this.camera._useCtrlForPanning) {
  47508. element.addEventListener("contextmenu", this._onContextMenu, false);
  47509. }
  47510. this._onLostFocus = function () {
  47511. //this._keys = [];
  47512. pointA = pointB = null;
  47513. previousPinchSquaredDistance = 0;
  47514. previousMultiTouchPanPosition.isPaning = false;
  47515. previousMultiTouchPanPosition.isPinching = false;
  47516. twoFingerActivityCount = 0;
  47517. cacheSoloPointer = null;
  47518. initialDistance = 0;
  47519. };
  47520. this._onMouseMove = function (evt) {
  47521. if (!engine.isPointerLock) {
  47522. return;
  47523. }
  47524. var offsetX = evt.movementX || evt.mozMovementX || evt.webkitMovementX || evt.msMovementX || 0;
  47525. var offsetY = evt.movementY || evt.mozMovementY || evt.webkitMovementY || evt.msMovementY || 0;
  47526. _this.camera.inertialAlphaOffset -= offsetX / _this.angularSensibilityX;
  47527. _this.camera.inertialBetaOffset -= offsetY / _this.angularSensibilityY;
  47528. if (!noPreventDefault) {
  47529. evt.preventDefault();
  47530. }
  47531. };
  47532. this._onGestureStart = function (e) {
  47533. if (window.MSGesture === undefined) {
  47534. return;
  47535. }
  47536. if (!_this._MSGestureHandler) {
  47537. _this._MSGestureHandler = new MSGesture();
  47538. _this._MSGestureHandler.target = element;
  47539. }
  47540. _this._MSGestureHandler.addPointer(e.pointerId);
  47541. };
  47542. this._onGesture = function (e) {
  47543. _this.camera.radius *= e.scale;
  47544. if (e.preventDefault) {
  47545. if (!noPreventDefault) {
  47546. e.stopPropagation();
  47547. e.preventDefault();
  47548. }
  47549. }
  47550. };
  47551. element.addEventListener("mousemove", this._onMouseMove, false);
  47552. element.addEventListener("MSPointerDown", this._onGestureStart, false);
  47553. element.addEventListener("MSGestureChange", this._onGesture, false);
  47554. BABYLON.Tools.RegisterTopRootEvents([
  47555. { name: "blur", handler: this._onLostFocus }
  47556. ]);
  47557. };
  47558. ArcRotateCameraPointersInput.prototype.detachControl = function (element) {
  47559. if (this._onLostFocus) {
  47560. BABYLON.Tools.UnregisterTopRootEvents([
  47561. { name: "blur", handler: this._onLostFocus }
  47562. ]);
  47563. }
  47564. if (element && this._observer) {
  47565. this.camera.getScene().onPointerObservable.remove(this._observer);
  47566. this._observer = null;
  47567. if (this._onContextMenu) {
  47568. element.removeEventListener("contextmenu", this._onContextMenu);
  47569. }
  47570. if (this._onMouseMove) {
  47571. element.removeEventListener("mousemove", this._onMouseMove);
  47572. }
  47573. if (this._onGestureStart) {
  47574. element.removeEventListener("MSPointerDown", this._onGestureStart);
  47575. }
  47576. if (this._onGesture) {
  47577. element.removeEventListener("MSGestureChange", this._onGesture);
  47578. }
  47579. this._isPanClick = false;
  47580. this.pinchInwards = true;
  47581. this._onMouseMove = null;
  47582. this._onGestureStart = null;
  47583. this._onGesture = null;
  47584. this._MSGestureHandler = null;
  47585. this._onLostFocus = null;
  47586. this._onContextMenu = null;
  47587. }
  47588. };
  47589. ArcRotateCameraPointersInput.prototype.getClassName = function () {
  47590. return "ArcRotateCameraPointersInput";
  47591. };
  47592. ArcRotateCameraPointersInput.prototype.getSimpleName = function () {
  47593. return "pointers";
  47594. };
  47595. __decorate([
  47596. BABYLON.serialize()
  47597. ], ArcRotateCameraPointersInput.prototype, "buttons", void 0);
  47598. __decorate([
  47599. BABYLON.serialize()
  47600. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityX", void 0);
  47601. __decorate([
  47602. BABYLON.serialize()
  47603. ], ArcRotateCameraPointersInput.prototype, "angularSensibilityY", void 0);
  47604. __decorate([
  47605. BABYLON.serialize()
  47606. ], ArcRotateCameraPointersInput.prototype, "pinchPrecision", void 0);
  47607. __decorate([
  47608. BABYLON.serialize()
  47609. ], ArcRotateCameraPointersInput.prototype, "pinchDeltaPercentage", void 0);
  47610. __decorate([
  47611. BABYLON.serialize()
  47612. ], ArcRotateCameraPointersInput.prototype, "panningSensibility", void 0);
  47613. __decorate([
  47614. BABYLON.serialize()
  47615. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanning", void 0);
  47616. __decorate([
  47617. BABYLON.serialize()
  47618. ], ArcRotateCameraPointersInput.prototype, "multiTouchPanAndZoom", void 0);
  47619. return ArcRotateCameraPointersInput;
  47620. }());
  47621. BABYLON.ArcRotateCameraPointersInput = ArcRotateCameraPointersInput;
  47622. BABYLON.CameraInputTypes["ArcRotateCameraPointersInput"] = ArcRotateCameraPointersInput;
  47623. })(BABYLON || (BABYLON = {}));
  47624. //# sourceMappingURL=babylon.arcRotateCameraPointersInput.js.map
  47625. var BABYLON;
  47626. (function (BABYLON) {
  47627. var ArcRotateCameraInputsManager = /** @class */ (function (_super) {
  47628. __extends(ArcRotateCameraInputsManager, _super);
  47629. function ArcRotateCameraInputsManager(camera) {
  47630. return _super.call(this, camera) || this;
  47631. }
  47632. ArcRotateCameraInputsManager.prototype.addMouseWheel = function () {
  47633. this.add(new BABYLON.ArcRotateCameraMouseWheelInput());
  47634. return this;
  47635. };
  47636. ArcRotateCameraInputsManager.prototype.addPointers = function () {
  47637. this.add(new BABYLON.ArcRotateCameraPointersInput());
  47638. return this;
  47639. };
  47640. ArcRotateCameraInputsManager.prototype.addKeyboard = function () {
  47641. this.add(new BABYLON.ArcRotateCameraKeyboardMoveInput());
  47642. return this;
  47643. };
  47644. ArcRotateCameraInputsManager.prototype.addGamepad = function () {
  47645. this.add(new BABYLON.ArcRotateCameraGamepadInput());
  47646. return this;
  47647. };
  47648. ArcRotateCameraInputsManager.prototype.addVRDeviceOrientation = function () {
  47649. this.add(new BABYLON.ArcRotateCameraVRDeviceOrientationInput());
  47650. return this;
  47651. };
  47652. return ArcRotateCameraInputsManager;
  47653. }(BABYLON.CameraInputsManager));
  47654. BABYLON.ArcRotateCameraInputsManager = ArcRotateCameraInputsManager;
  47655. })(BABYLON || (BABYLON = {}));
  47656. //# sourceMappingURL=babylon.arcRotateCameraInputsManager.js.map
  47657. var BABYLON;
  47658. (function (BABYLON) {
  47659. var ArcRotateCamera = /** @class */ (function (_super) {
  47660. __extends(ArcRotateCamera, _super);
  47661. function ArcRotateCamera(name, alpha, beta, radius, target, scene, setActiveOnSceneIfNoneActive) {
  47662. if (setActiveOnSceneIfNoneActive === void 0) { setActiveOnSceneIfNoneActive = true; }
  47663. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene, setActiveOnSceneIfNoneActive) || this;
  47664. _this.inertialAlphaOffset = 0;
  47665. _this.inertialBetaOffset = 0;
  47666. _this.inertialRadiusOffset = 0;
  47667. _this.lowerAlphaLimit = null;
  47668. _this.upperAlphaLimit = null;
  47669. _this.lowerBetaLimit = 0.01;
  47670. _this.upperBetaLimit = Math.PI;
  47671. _this.lowerRadiusLimit = null;
  47672. _this.upperRadiusLimit = null;
  47673. _this.inertialPanningX = 0;
  47674. _this.inertialPanningY = 0;
  47675. _this.pinchToPanMaxDistance = 20;
  47676. _this.panningDistanceLimit = null;
  47677. _this.panningOriginTarget = BABYLON.Vector3.Zero();
  47678. _this.panningInertia = 0.9;
  47679. //-- end properties for backward compatibility for inputs
  47680. _this.zoomOnFactor = 1;
  47681. _this.targetScreenOffset = BABYLON.Vector2.Zero();
  47682. _this.allowUpsideDown = true;
  47683. _this._viewMatrix = new BABYLON.Matrix();
  47684. // Panning
  47685. _this.panningAxis = new BABYLON.Vector3(1, 1, 0);
  47686. _this.onMeshTargetChangedObservable = new BABYLON.Observable();
  47687. _this.checkCollisions = false;
  47688. _this.collisionRadius = new BABYLON.Vector3(0.5, 0.5, 0.5);
  47689. _this._previousPosition = BABYLON.Vector3.Zero();
  47690. _this._collisionVelocity = BABYLON.Vector3.Zero();
  47691. _this._newPosition = BABYLON.Vector3.Zero();
  47692. _this._computationVector = BABYLON.Vector3.Zero();
  47693. _this._onCollisionPositionChange = function (collisionId, newPosition, collidedMesh) {
  47694. if (collidedMesh === void 0) { collidedMesh = null; }
  47695. if (_this.getScene().workerCollisions && _this.checkCollisions) {
  47696. newPosition.multiplyInPlace(_this._collider._radius);
  47697. }
  47698. if (!collidedMesh) {
  47699. _this._previousPosition.copyFrom(_this.position);
  47700. }
  47701. else {
  47702. _this.setPosition(newPosition);
  47703. if (_this.onCollide) {
  47704. _this.onCollide(collidedMesh);
  47705. }
  47706. }
  47707. // Recompute because of constraints
  47708. var cosa = Math.cos(_this.alpha);
  47709. var sina = Math.sin(_this.alpha);
  47710. var cosb = Math.cos(_this.beta);
  47711. var sinb = Math.sin(_this.beta);
  47712. if (sinb === 0) {
  47713. sinb = 0.0001;
  47714. }
  47715. var target = _this._getTargetPosition();
  47716. _this._computationVector.copyFromFloats(_this.radius * cosa * sinb, _this.radius * cosb, _this.radius * sina * sinb);
  47717. target.addToRef(_this._computationVector, _this._newPosition);
  47718. _this.position.copyFrom(_this._newPosition);
  47719. var up = _this.upVector;
  47720. if (_this.allowUpsideDown && _this.beta < 0) {
  47721. up = up.clone();
  47722. up = up.negate();
  47723. }
  47724. _this._computeViewMatrix(_this.position, target, up);
  47725. _this._viewMatrix.m[12] += _this.targetScreenOffset.x;
  47726. _this._viewMatrix.m[13] += _this.targetScreenOffset.y;
  47727. _this._collisionTriggered = false;
  47728. };
  47729. _this._target = BABYLON.Vector3.Zero();
  47730. if (target) {
  47731. _this.setTarget(target);
  47732. }
  47733. _this.alpha = alpha;
  47734. _this.beta = beta;
  47735. _this.radius = radius;
  47736. _this.getViewMatrix();
  47737. _this.inputs = new BABYLON.ArcRotateCameraInputsManager(_this);
  47738. _this.inputs.addKeyboard().addMouseWheel().addPointers();
  47739. return _this;
  47740. }
  47741. Object.defineProperty(ArcRotateCamera.prototype, "target", {
  47742. get: function () {
  47743. return this._target;
  47744. },
  47745. set: function (value) {
  47746. this.setTarget(value);
  47747. },
  47748. enumerable: true,
  47749. configurable: true
  47750. });
  47751. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityX", {
  47752. //-- begin properties for backward compatibility for inputs
  47753. get: function () {
  47754. var pointers = this.inputs.attached["pointers"];
  47755. if (pointers)
  47756. return pointers.angularSensibilityX;
  47757. return 0;
  47758. },
  47759. set: function (value) {
  47760. var pointers = this.inputs.attached["pointers"];
  47761. if (pointers) {
  47762. pointers.angularSensibilityX = value;
  47763. }
  47764. },
  47765. enumerable: true,
  47766. configurable: true
  47767. });
  47768. Object.defineProperty(ArcRotateCamera.prototype, "angularSensibilityY", {
  47769. get: function () {
  47770. var pointers = this.inputs.attached["pointers"];
  47771. if (pointers)
  47772. return pointers.angularSensibilityY;
  47773. return 0;
  47774. },
  47775. set: function (value) {
  47776. var pointers = this.inputs.attached["pointers"];
  47777. if (pointers) {
  47778. pointers.angularSensibilityY = value;
  47779. }
  47780. },
  47781. enumerable: true,
  47782. configurable: true
  47783. });
  47784. Object.defineProperty(ArcRotateCamera.prototype, "pinchPrecision", {
  47785. get: function () {
  47786. var pointers = this.inputs.attached["pointers"];
  47787. if (pointers)
  47788. return pointers.pinchPrecision;
  47789. return 0;
  47790. },
  47791. set: function (value) {
  47792. var pointers = this.inputs.attached["pointers"];
  47793. if (pointers) {
  47794. pointers.pinchPrecision = value;
  47795. }
  47796. },
  47797. enumerable: true,
  47798. configurable: true
  47799. });
  47800. Object.defineProperty(ArcRotateCamera.prototype, "pinchDeltaPercentage", {
  47801. get: function () {
  47802. var pointers = this.inputs.attached["pointers"];
  47803. if (pointers)
  47804. return pointers.pinchDeltaPercentage;
  47805. return 0;
  47806. },
  47807. set: function (value) {
  47808. var pointers = this.inputs.attached["pointers"];
  47809. if (pointers) {
  47810. pointers.pinchDeltaPercentage = value;
  47811. }
  47812. },
  47813. enumerable: true,
  47814. configurable: true
  47815. });
  47816. Object.defineProperty(ArcRotateCamera.prototype, "panningSensibility", {
  47817. get: function () {
  47818. var pointers = this.inputs.attached["pointers"];
  47819. if (pointers)
  47820. return pointers.panningSensibility;
  47821. return 0;
  47822. },
  47823. set: function (value) {
  47824. var pointers = this.inputs.attached["pointers"];
  47825. if (pointers) {
  47826. pointers.panningSensibility = value;
  47827. }
  47828. },
  47829. enumerable: true,
  47830. configurable: true
  47831. });
  47832. Object.defineProperty(ArcRotateCamera.prototype, "keysUp", {
  47833. get: function () {
  47834. var keyboard = this.inputs.attached["keyboard"];
  47835. if (keyboard)
  47836. return keyboard.keysUp;
  47837. return [];
  47838. },
  47839. set: function (value) {
  47840. var keyboard = this.inputs.attached["keyboard"];
  47841. if (keyboard)
  47842. keyboard.keysUp = value;
  47843. },
  47844. enumerable: true,
  47845. configurable: true
  47846. });
  47847. Object.defineProperty(ArcRotateCamera.prototype, "keysDown", {
  47848. get: function () {
  47849. var keyboard = this.inputs.attached["keyboard"];
  47850. if (keyboard)
  47851. return keyboard.keysDown;
  47852. return [];
  47853. },
  47854. set: function (value) {
  47855. var keyboard = this.inputs.attached["keyboard"];
  47856. if (keyboard)
  47857. keyboard.keysDown = value;
  47858. },
  47859. enumerable: true,
  47860. configurable: true
  47861. });
  47862. Object.defineProperty(ArcRotateCamera.prototype, "keysLeft", {
  47863. get: function () {
  47864. var keyboard = this.inputs.attached["keyboard"];
  47865. if (keyboard)
  47866. return keyboard.keysLeft;
  47867. return [];
  47868. },
  47869. set: function (value) {
  47870. var keyboard = this.inputs.attached["keyboard"];
  47871. if (keyboard)
  47872. keyboard.keysLeft = value;
  47873. },
  47874. enumerable: true,
  47875. configurable: true
  47876. });
  47877. Object.defineProperty(ArcRotateCamera.prototype, "keysRight", {
  47878. get: function () {
  47879. var keyboard = this.inputs.attached["keyboard"];
  47880. if (keyboard)
  47881. return keyboard.keysRight;
  47882. return [];
  47883. },
  47884. set: function (value) {
  47885. var keyboard = this.inputs.attached["keyboard"];
  47886. if (keyboard)
  47887. keyboard.keysRight = value;
  47888. },
  47889. enumerable: true,
  47890. configurable: true
  47891. });
  47892. Object.defineProperty(ArcRotateCamera.prototype, "wheelPrecision", {
  47893. get: function () {
  47894. var mousewheel = this.inputs.attached["mousewheel"];
  47895. if (mousewheel)
  47896. return mousewheel.wheelPrecision;
  47897. return 0;
  47898. },
  47899. set: function (value) {
  47900. var mousewheel = this.inputs.attached["mousewheel"];
  47901. if (mousewheel)
  47902. mousewheel.wheelPrecision = value;
  47903. },
  47904. enumerable: true,
  47905. configurable: true
  47906. });
  47907. Object.defineProperty(ArcRotateCamera.prototype, "wheelDeltaPercentage", {
  47908. get: function () {
  47909. var mousewheel = this.inputs.attached["mousewheel"];
  47910. if (mousewheel)
  47911. return mousewheel.wheelDeltaPercentage;
  47912. return 0;
  47913. },
  47914. set: function (value) {
  47915. var mousewheel = this.inputs.attached["mousewheel"];
  47916. if (mousewheel)
  47917. mousewheel.wheelDeltaPercentage = value;
  47918. },
  47919. enumerable: true,
  47920. configurable: true
  47921. });
  47922. Object.defineProperty(ArcRotateCamera.prototype, "bouncingBehavior", {
  47923. get: function () {
  47924. return this._bouncingBehavior;
  47925. },
  47926. enumerable: true,
  47927. configurable: true
  47928. });
  47929. Object.defineProperty(ArcRotateCamera.prototype, "useBouncingBehavior", {
  47930. get: function () {
  47931. return this._bouncingBehavior != null;
  47932. },
  47933. set: function (value) {
  47934. if (value === this.useBouncingBehavior) {
  47935. return;
  47936. }
  47937. if (value) {
  47938. this._bouncingBehavior = new BABYLON.BouncingBehavior();
  47939. this.addBehavior(this._bouncingBehavior);
  47940. }
  47941. else if (this._bouncingBehavior) {
  47942. this.removeBehavior(this._bouncingBehavior);
  47943. this._bouncingBehavior = null;
  47944. }
  47945. },
  47946. enumerable: true,
  47947. configurable: true
  47948. });
  47949. Object.defineProperty(ArcRotateCamera.prototype, "framingBehavior", {
  47950. get: function () {
  47951. return this._framingBehavior;
  47952. },
  47953. enumerable: true,
  47954. configurable: true
  47955. });
  47956. Object.defineProperty(ArcRotateCamera.prototype, "useFramingBehavior", {
  47957. get: function () {
  47958. return this._framingBehavior != null;
  47959. },
  47960. set: function (value) {
  47961. if (value === this.useFramingBehavior) {
  47962. return;
  47963. }
  47964. if (value) {
  47965. this._framingBehavior = new BABYLON.FramingBehavior();
  47966. this.addBehavior(this._framingBehavior);
  47967. }
  47968. else if (this._framingBehavior) {
  47969. this.removeBehavior(this._framingBehavior);
  47970. this._framingBehavior = null;
  47971. }
  47972. },
  47973. enumerable: true,
  47974. configurable: true
  47975. });
  47976. Object.defineProperty(ArcRotateCamera.prototype, "autoRotationBehavior", {
  47977. get: function () {
  47978. return this._autoRotationBehavior;
  47979. },
  47980. enumerable: true,
  47981. configurable: true
  47982. });
  47983. Object.defineProperty(ArcRotateCamera.prototype, "useAutoRotationBehavior", {
  47984. get: function () {
  47985. return this._autoRotationBehavior != null;
  47986. },
  47987. set: function (value) {
  47988. if (value === this.useAutoRotationBehavior) {
  47989. return;
  47990. }
  47991. if (value) {
  47992. this._autoRotationBehavior = new BABYLON.AutoRotationBehavior();
  47993. this.addBehavior(this._autoRotationBehavior);
  47994. }
  47995. else if (this._autoRotationBehavior) {
  47996. this.removeBehavior(this._autoRotationBehavior);
  47997. this._autoRotationBehavior = null;
  47998. }
  47999. },
  48000. enumerable: true,
  48001. configurable: true
  48002. });
  48003. // Cache
  48004. ArcRotateCamera.prototype._initCache = function () {
  48005. _super.prototype._initCache.call(this);
  48006. this._cache._target = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  48007. this._cache.alpha = undefined;
  48008. this._cache.beta = undefined;
  48009. this._cache.radius = undefined;
  48010. this._cache.targetScreenOffset = BABYLON.Vector2.Zero();
  48011. };
  48012. ArcRotateCamera.prototype._updateCache = function (ignoreParentClass) {
  48013. if (!ignoreParentClass) {
  48014. _super.prototype._updateCache.call(this);
  48015. }
  48016. this._cache._target.copyFrom(this._getTargetPosition());
  48017. this._cache.alpha = this.alpha;
  48018. this._cache.beta = this.beta;
  48019. this._cache.radius = this.radius;
  48020. this._cache.targetScreenOffset.copyFrom(this.targetScreenOffset);
  48021. };
  48022. ArcRotateCamera.prototype._getTargetPosition = function () {
  48023. if (this._targetHost && this._targetHost.getAbsolutePosition) {
  48024. var pos = this._targetHost.getAbsolutePosition();
  48025. if (this._targetBoundingCenter) {
  48026. pos.addToRef(this._targetBoundingCenter, this._target);
  48027. }
  48028. else {
  48029. this._target.copyFrom(pos);
  48030. }
  48031. }
  48032. var lockedTargetPosition = this._getLockedTargetPosition();
  48033. if (lockedTargetPosition) {
  48034. return lockedTargetPosition;
  48035. }
  48036. return this._target;
  48037. };
  48038. ArcRotateCamera.prototype.storeState = function () {
  48039. this._storedAlpha = this.alpha;
  48040. this._storedBeta = this.beta;
  48041. this._storedRadius = this.radius;
  48042. this._storedTarget = this._getTargetPosition().clone();
  48043. return _super.prototype.storeState.call(this);
  48044. };
  48045. /**
  48046. * Restored camera state. You must call storeState() first
  48047. */
  48048. ArcRotateCamera.prototype._restoreStateValues = function () {
  48049. if (!_super.prototype._restoreStateValues.call(this)) {
  48050. return false;
  48051. }
  48052. this.alpha = this._storedAlpha;
  48053. this.beta = this._storedBeta;
  48054. this.radius = this._storedRadius;
  48055. this.setTarget(this._storedTarget.clone());
  48056. this.inertialAlphaOffset = 0;
  48057. this.inertialBetaOffset = 0;
  48058. this.inertialRadiusOffset = 0;
  48059. this.inertialPanningX = 0;
  48060. this.inertialPanningY = 0;
  48061. return true;
  48062. };
  48063. // Synchronized
  48064. ArcRotateCamera.prototype._isSynchronizedViewMatrix = function () {
  48065. if (!_super.prototype._isSynchronizedViewMatrix.call(this))
  48066. return false;
  48067. return this._cache._target.equals(this._getTargetPosition())
  48068. && this._cache.alpha === this.alpha
  48069. && this._cache.beta === this.beta
  48070. && this._cache.radius === this.radius
  48071. && this._cache.targetScreenOffset.equals(this.targetScreenOffset);
  48072. };
  48073. // Methods
  48074. ArcRotateCamera.prototype.attachControl = function (element, noPreventDefault, useCtrlForPanning, panningMouseButton) {
  48075. var _this = this;
  48076. if (useCtrlForPanning === void 0) { useCtrlForPanning = true; }
  48077. if (panningMouseButton === void 0) { panningMouseButton = 2; }
  48078. this._useCtrlForPanning = useCtrlForPanning;
  48079. this._panningMouseButton = panningMouseButton;
  48080. this.inputs.attachElement(element, noPreventDefault);
  48081. this._reset = function () {
  48082. _this.inertialAlphaOffset = 0;
  48083. _this.inertialBetaOffset = 0;
  48084. _this.inertialRadiusOffset = 0;
  48085. _this.inertialPanningX = 0;
  48086. _this.inertialPanningY = 0;
  48087. };
  48088. };
  48089. ArcRotateCamera.prototype.detachControl = function (element) {
  48090. this.inputs.detachElement(element);
  48091. if (this._reset) {
  48092. this._reset();
  48093. }
  48094. };
  48095. ArcRotateCamera.prototype._checkInputs = function () {
  48096. //if (async) collision inspection was triggered, don't update the camera's position - until the collision callback was called.
  48097. if (this._collisionTriggered) {
  48098. return;
  48099. }
  48100. this.inputs.checkInputs();
  48101. // Inertia
  48102. if (this.inertialAlphaOffset !== 0 || this.inertialBetaOffset !== 0 || this.inertialRadiusOffset !== 0) {
  48103. var inertialAlphaOffset = this.inertialAlphaOffset;
  48104. if (this.beta <= 0)
  48105. inertialAlphaOffset *= -1;
  48106. if (this.getScene().useRightHandedSystem)
  48107. inertialAlphaOffset *= -1;
  48108. if (this.parent && this.parent._getWorldMatrixDeterminant() < 0)
  48109. inertialAlphaOffset *= -1;
  48110. this.alpha += inertialAlphaOffset;
  48111. this.beta += this.inertialBetaOffset;
  48112. this.radius -= this.inertialRadiusOffset;
  48113. this.inertialAlphaOffset *= this.inertia;
  48114. this.inertialBetaOffset *= this.inertia;
  48115. this.inertialRadiusOffset *= this.inertia;
  48116. if (Math.abs(this.inertialAlphaOffset) < BABYLON.Epsilon)
  48117. this.inertialAlphaOffset = 0;
  48118. if (Math.abs(this.inertialBetaOffset) < BABYLON.Epsilon)
  48119. this.inertialBetaOffset = 0;
  48120. if (Math.abs(this.inertialRadiusOffset) < this.speed * BABYLON.Epsilon)
  48121. this.inertialRadiusOffset = 0;
  48122. }
  48123. // Panning inertia
  48124. if (this.inertialPanningX !== 0 || this.inertialPanningY !== 0) {
  48125. if (!this._localDirection) {
  48126. this._localDirection = BABYLON.Vector3.Zero();
  48127. this._transformedDirection = BABYLON.Vector3.Zero();
  48128. }
  48129. this._localDirection.copyFromFloats(this.inertialPanningX, this.inertialPanningY, this.inertialPanningY);
  48130. this._localDirection.multiplyInPlace(this.panningAxis);
  48131. this._viewMatrix.invertToRef(this._cameraTransformMatrix);
  48132. BABYLON.Vector3.TransformNormalToRef(this._localDirection, this._cameraTransformMatrix, this._transformedDirection);
  48133. //Eliminate y if map panning is enabled (panningAxis == 1,0,1)
  48134. if (!this.panningAxis.y) {
  48135. this._transformedDirection.y = 0;
  48136. }
  48137. if (!this._targetHost) {
  48138. if (this.panningDistanceLimit) {
  48139. this._transformedDirection.addInPlace(this._target);
  48140. var distanceSquared = BABYLON.Vector3.DistanceSquared(this._transformedDirection, this.panningOriginTarget);
  48141. if (distanceSquared <= (this.panningDistanceLimit * this.panningDistanceLimit)) {
  48142. this._target.copyFrom(this._transformedDirection);
  48143. }
  48144. }
  48145. else {
  48146. this._target.addInPlace(this._transformedDirection);
  48147. }
  48148. }
  48149. this.inertialPanningX *= this.panningInertia;
  48150. this.inertialPanningY *= this.panningInertia;
  48151. if (Math.abs(this.inertialPanningX) < this.speed * BABYLON.Epsilon)
  48152. this.inertialPanningX = 0;
  48153. if (Math.abs(this.inertialPanningY) < this.speed * BABYLON.Epsilon)
  48154. this.inertialPanningY = 0;
  48155. }
  48156. // Limits
  48157. this._checkLimits();
  48158. _super.prototype._checkInputs.call(this);
  48159. };
  48160. ArcRotateCamera.prototype._checkLimits = function () {
  48161. if (this.lowerBetaLimit === null || this.lowerBetaLimit === undefined) {
  48162. if (this.allowUpsideDown && this.beta > Math.PI) {
  48163. this.beta = this.beta - (2 * Math.PI);
  48164. }
  48165. }
  48166. else {
  48167. if (this.beta < this.lowerBetaLimit) {
  48168. this.beta = this.lowerBetaLimit;
  48169. }
  48170. }
  48171. if (this.upperBetaLimit === null || this.upperBetaLimit === undefined) {
  48172. if (this.allowUpsideDown && this.beta < -Math.PI) {
  48173. this.beta = this.beta + (2 * Math.PI);
  48174. }
  48175. }
  48176. else {
  48177. if (this.beta > this.upperBetaLimit) {
  48178. this.beta = this.upperBetaLimit;
  48179. }
  48180. }
  48181. if (this.lowerAlphaLimit && this.alpha < this.lowerAlphaLimit) {
  48182. this.alpha = this.lowerAlphaLimit;
  48183. }
  48184. if (this.upperAlphaLimit && this.alpha > this.upperAlphaLimit) {
  48185. this.alpha = this.upperAlphaLimit;
  48186. }
  48187. if (this.lowerRadiusLimit && this.radius < this.lowerRadiusLimit) {
  48188. this.radius = this.lowerRadiusLimit;
  48189. }
  48190. if (this.upperRadiusLimit && this.radius > this.upperRadiusLimit) {
  48191. this.radius = this.upperRadiusLimit;
  48192. }
  48193. };
  48194. ArcRotateCamera.prototype.rebuildAnglesAndRadius = function () {
  48195. this.position.subtractToRef(this._getTargetPosition(), this._computationVector);
  48196. this.radius = this._computationVector.length();
  48197. if (this.radius === 0) {
  48198. this.radius = 0.0001; // Just to avoid division by zero
  48199. }
  48200. // Alpha
  48201. this.alpha = Math.acos(this._computationVector.x / Math.sqrt(Math.pow(this._computationVector.x, 2) + Math.pow(this._computationVector.z, 2)));
  48202. if (this._computationVector.z < 0) {
  48203. this.alpha = 2 * Math.PI - this.alpha;
  48204. }
  48205. // Beta
  48206. this.beta = Math.acos(this._computationVector.y / this.radius);
  48207. this._checkLimits();
  48208. };
  48209. ArcRotateCamera.prototype.setPosition = function (position) {
  48210. if (this.position.equals(position)) {
  48211. return;
  48212. }
  48213. this.position.copyFrom(position);
  48214. this.rebuildAnglesAndRadius();
  48215. };
  48216. ArcRotateCamera.prototype.setTarget = function (target, toBoundingCenter, allowSamePosition) {
  48217. if (toBoundingCenter === void 0) { toBoundingCenter = false; }
  48218. if (allowSamePosition === void 0) { allowSamePosition = false; }
  48219. if (target.getBoundingInfo) {
  48220. if (toBoundingCenter) {
  48221. this._targetBoundingCenter = target.getBoundingInfo().boundingBox.centerWorld.clone();
  48222. }
  48223. else {
  48224. this._targetBoundingCenter = null;
  48225. }
  48226. this._targetHost = target;
  48227. this._target = this._getTargetPosition();
  48228. this.onMeshTargetChangedObservable.notifyObservers(this._targetHost);
  48229. }
  48230. else {
  48231. var newTarget = target;
  48232. var currentTarget = this._getTargetPosition();
  48233. if (currentTarget && !allowSamePosition && currentTarget.equals(newTarget)) {
  48234. return;
  48235. }
  48236. this._targetHost = null;
  48237. this._target = newTarget;
  48238. this._targetBoundingCenter = null;
  48239. this.onMeshTargetChangedObservable.notifyObservers(null);
  48240. }
  48241. this.rebuildAnglesAndRadius();
  48242. };
  48243. ArcRotateCamera.prototype._getViewMatrix = function () {
  48244. // Compute
  48245. var cosa = Math.cos(this.alpha);
  48246. var sina = Math.sin(this.alpha);
  48247. var cosb = Math.cos(this.beta);
  48248. var sinb = Math.sin(this.beta);
  48249. if (sinb === 0) {
  48250. sinb = 0.0001;
  48251. }
  48252. var target = this._getTargetPosition();
  48253. this._computationVector.copyFromFloats(this.radius * cosa * sinb, this.radius * cosb, this.radius * sina * sinb);
  48254. target.addToRef(this._computationVector, this._newPosition);
  48255. if (this.getScene().collisionsEnabled && this.checkCollisions) {
  48256. if (!this._collider) {
  48257. this._collider = new BABYLON.Collider();
  48258. }
  48259. this._collider._radius = this.collisionRadius;
  48260. this._newPosition.subtractToRef(this.position, this._collisionVelocity);
  48261. this._collisionTriggered = true;
  48262. this.getScene().collisionCoordinator.getNewPosition(this.position, this._collisionVelocity, this._collider, 3, null, this._onCollisionPositionChange, this.uniqueId);
  48263. }
  48264. else {
  48265. this.position.copyFrom(this._newPosition);
  48266. var up = this.upVector;
  48267. if (this.allowUpsideDown && sinb < 0) {
  48268. up = up.clone();
  48269. up = up.negate();
  48270. }
  48271. this._computeViewMatrix(this.position, target, up);
  48272. this._viewMatrix.m[12] += this.targetScreenOffset.x;
  48273. this._viewMatrix.m[13] += this.targetScreenOffset.y;
  48274. }
  48275. this._currentTarget = target;
  48276. return this._viewMatrix;
  48277. };
  48278. ArcRotateCamera.prototype.zoomOn = function (meshes, doNotUpdateMaxZ) {
  48279. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48280. meshes = meshes || this.getScene().meshes;
  48281. var minMaxVector = BABYLON.Mesh.MinMax(meshes);
  48282. var distance = BABYLON.Vector3.Distance(minMaxVector.min, minMaxVector.max);
  48283. this.radius = distance * this.zoomOnFactor;
  48284. this.focusOn({ min: minMaxVector.min, max: minMaxVector.max, distance: distance }, doNotUpdateMaxZ);
  48285. };
  48286. ArcRotateCamera.prototype.focusOn = function (meshesOrMinMaxVectorAndDistance, doNotUpdateMaxZ) {
  48287. if (doNotUpdateMaxZ === void 0) { doNotUpdateMaxZ = false; }
  48288. var meshesOrMinMaxVector;
  48289. var distance;
  48290. if (meshesOrMinMaxVectorAndDistance.min === undefined) { // meshes
  48291. var meshes = meshesOrMinMaxVectorAndDistance || this.getScene().meshes;
  48292. meshesOrMinMaxVector = BABYLON.Mesh.MinMax(meshes);
  48293. distance = BABYLON.Vector3.Distance(meshesOrMinMaxVector.min, meshesOrMinMaxVector.max);
  48294. }
  48295. else { //minMaxVector and distance
  48296. var minMaxVectorAndDistance = meshesOrMinMaxVectorAndDistance;
  48297. meshesOrMinMaxVector = minMaxVectorAndDistance;
  48298. distance = minMaxVectorAndDistance.distance;
  48299. }
  48300. this._target = BABYLON.Mesh.Center(meshesOrMinMaxVector);
  48301. if (!doNotUpdateMaxZ) {
  48302. this.maxZ = distance * 2;
  48303. }
  48304. };
  48305. /**
  48306. * @override
  48307. * Override Camera.createRigCamera
  48308. */
  48309. ArcRotateCamera.prototype.createRigCamera = function (name, cameraIndex) {
  48310. var alphaShift = 0;
  48311. switch (this.cameraRigMode) {
  48312. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48313. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48314. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48315. case BABYLON.Camera.RIG_MODE_VR:
  48316. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? 1 : -1);
  48317. break;
  48318. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48319. alphaShift = this._cameraRigParams.stereoHalfAngle * (cameraIndex === 0 ? -1 : 1);
  48320. break;
  48321. }
  48322. var rigCam = new ArcRotateCamera(name, this.alpha + alphaShift, this.beta, this.radius, this._target, this.getScene());
  48323. rigCam._cameraRigParams = {};
  48324. return rigCam;
  48325. };
  48326. /**
  48327. * @override
  48328. * Override Camera._updateRigCameras
  48329. */
  48330. ArcRotateCamera.prototype._updateRigCameras = function () {
  48331. var camLeft = this._rigCameras[0];
  48332. var camRight = this._rigCameras[1];
  48333. camLeft.beta = camRight.beta = this.beta;
  48334. camLeft.radius = camRight.radius = this.radius;
  48335. switch (this.cameraRigMode) {
  48336. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH:
  48337. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL:
  48338. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER:
  48339. case BABYLON.Camera.RIG_MODE_VR:
  48340. camLeft.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48341. camRight.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48342. break;
  48343. case BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_CROSSEYED:
  48344. camLeft.alpha = this.alpha + this._cameraRigParams.stereoHalfAngle;
  48345. camRight.alpha = this.alpha - this._cameraRigParams.stereoHalfAngle;
  48346. break;
  48347. }
  48348. _super.prototype._updateRigCameras.call(this);
  48349. };
  48350. ArcRotateCamera.prototype.dispose = function () {
  48351. this.inputs.clear();
  48352. _super.prototype.dispose.call(this);
  48353. };
  48354. ArcRotateCamera.prototype.getClassName = function () {
  48355. return "ArcRotateCamera";
  48356. };
  48357. __decorate([
  48358. BABYLON.serialize()
  48359. ], ArcRotateCamera.prototype, "alpha", void 0);
  48360. __decorate([
  48361. BABYLON.serialize()
  48362. ], ArcRotateCamera.prototype, "beta", void 0);
  48363. __decorate([
  48364. BABYLON.serialize()
  48365. ], ArcRotateCamera.prototype, "radius", void 0);
  48366. __decorate([
  48367. BABYLON.serializeAsVector3("target")
  48368. ], ArcRotateCamera.prototype, "_target", void 0);
  48369. __decorate([
  48370. BABYLON.serialize()
  48371. ], ArcRotateCamera.prototype, "inertialAlphaOffset", void 0);
  48372. __decorate([
  48373. BABYLON.serialize()
  48374. ], ArcRotateCamera.prototype, "inertialBetaOffset", void 0);
  48375. __decorate([
  48376. BABYLON.serialize()
  48377. ], ArcRotateCamera.prototype, "inertialRadiusOffset", void 0);
  48378. __decorate([
  48379. BABYLON.serialize()
  48380. ], ArcRotateCamera.prototype, "lowerAlphaLimit", void 0);
  48381. __decorate([
  48382. BABYLON.serialize()
  48383. ], ArcRotateCamera.prototype, "upperAlphaLimit", void 0);
  48384. __decorate([
  48385. BABYLON.serialize()
  48386. ], ArcRotateCamera.prototype, "lowerBetaLimit", void 0);
  48387. __decorate([
  48388. BABYLON.serialize()
  48389. ], ArcRotateCamera.prototype, "upperBetaLimit", void 0);
  48390. __decorate([
  48391. BABYLON.serialize()
  48392. ], ArcRotateCamera.prototype, "lowerRadiusLimit", void 0);
  48393. __decorate([
  48394. BABYLON.serialize()
  48395. ], ArcRotateCamera.prototype, "upperRadiusLimit", void 0);
  48396. __decorate([
  48397. BABYLON.serialize()
  48398. ], ArcRotateCamera.prototype, "inertialPanningX", void 0);
  48399. __decorate([
  48400. BABYLON.serialize()
  48401. ], ArcRotateCamera.prototype, "inertialPanningY", void 0);
  48402. __decorate([
  48403. BABYLON.serialize()
  48404. ], ArcRotateCamera.prototype, "pinchToPanMaxDistance", void 0);
  48405. __decorate([
  48406. BABYLON.serialize()
  48407. ], ArcRotateCamera.prototype, "panningDistanceLimit", void 0);
  48408. __decorate([
  48409. BABYLON.serializeAsVector3()
  48410. ], ArcRotateCamera.prototype, "panningOriginTarget", void 0);
  48411. __decorate([
  48412. BABYLON.serialize()
  48413. ], ArcRotateCamera.prototype, "panningInertia", void 0);
  48414. __decorate([
  48415. BABYLON.serialize()
  48416. ], ArcRotateCamera.prototype, "zoomOnFactor", void 0);
  48417. __decorate([
  48418. BABYLON.serialize()
  48419. ], ArcRotateCamera.prototype, "allowUpsideDown", void 0);
  48420. return ArcRotateCamera;
  48421. }(BABYLON.TargetCamera));
  48422. BABYLON.ArcRotateCamera = ArcRotateCamera;
  48423. })(BABYLON || (BABYLON = {}));
  48424. //# sourceMappingURL=babylon.arcRotateCamera.js.map
  48425. var BABYLON;
  48426. (function (BABYLON) {
  48427. /**
  48428. * The HemisphericLight simulates the ambient environment light,
  48429. * so the passed direction is the light reflection direction, not the incoming direction.
  48430. */
  48431. var HemisphericLight = /** @class */ (function (_super) {
  48432. __extends(HemisphericLight, _super);
  48433. /**
  48434. * Creates a HemisphericLight object in the scene according to the passed direction (Vector3).
  48435. * The HemisphericLight simulates the ambient environment light, so the passed direction is the light reflection direction, not the incoming direction.
  48436. * The HemisphericLight can't cast shadows.
  48437. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48438. * @param name The friendly name of the light
  48439. * @param direction The direction of the light reflection
  48440. * @param scene The scene the light belongs to
  48441. */
  48442. function HemisphericLight(name, direction, scene) {
  48443. var _this = _super.call(this, name, scene) || this;
  48444. /**
  48445. * The groundColor is the light in the opposite direction to the one specified during creation.
  48446. * 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.
  48447. */
  48448. _this.groundColor = new BABYLON.Color3(0.0, 0.0, 0.0);
  48449. _this.direction = direction || BABYLON.Vector3.Up();
  48450. return _this;
  48451. }
  48452. HemisphericLight.prototype._buildUniformLayout = function () {
  48453. this._uniformBuffer.addUniform("vLightData", 4);
  48454. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48455. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48456. this._uniformBuffer.addUniform("vLightGround", 3);
  48457. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48458. this._uniformBuffer.addUniform("depthValues", 2);
  48459. this._uniformBuffer.create();
  48460. };
  48461. /**
  48462. * Returns the string "HemisphericLight".
  48463. * @return The class name
  48464. */
  48465. HemisphericLight.prototype.getClassName = function () {
  48466. return "HemisphericLight";
  48467. };
  48468. /**
  48469. * Sets the HemisphericLight direction towards the passed target (Vector3).
  48470. * Returns the updated direction.
  48471. * @param target The target the direction should point to
  48472. * @return The computed direction
  48473. */
  48474. HemisphericLight.prototype.setDirectionToTarget = function (target) {
  48475. this.direction = BABYLON.Vector3.Normalize(target.subtract(BABYLON.Vector3.Zero()));
  48476. return this.direction;
  48477. };
  48478. /**
  48479. * Returns the shadow generator associated to the light.
  48480. * @returns Always null for hemispheric lights because it does not support shadows.
  48481. */
  48482. HemisphericLight.prototype.getShadowGenerator = function () {
  48483. return null;
  48484. };
  48485. /**
  48486. * Sets the passed Effect object with the HemisphericLight normalized direction and color and the passed name (string).
  48487. * @param effect The effect to update
  48488. * @param lightIndex The index of the light in the effect to update
  48489. * @returns The hemispheric light
  48490. */
  48491. HemisphericLight.prototype.transferToEffect = function (effect, lightIndex) {
  48492. var normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  48493. this._uniformBuffer.updateFloat4("vLightData", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, 0.0, lightIndex);
  48494. this._uniformBuffer.updateColor3("vLightGround", this.groundColor.scale(this.intensity), lightIndex);
  48495. return this;
  48496. };
  48497. /**
  48498. * @hidden internal use only.
  48499. */
  48500. HemisphericLight.prototype._getWorldMatrix = function () {
  48501. if (!this._worldMatrix) {
  48502. this._worldMatrix = BABYLON.Matrix.Identity();
  48503. }
  48504. return this._worldMatrix;
  48505. };
  48506. /**
  48507. * Returns the integer 3.
  48508. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48509. */
  48510. HemisphericLight.prototype.getTypeID = function () {
  48511. return BABYLON.Light.LIGHTTYPEID_HEMISPHERICLIGHT;
  48512. };
  48513. __decorate([
  48514. BABYLON.serializeAsColor3()
  48515. ], HemisphericLight.prototype, "groundColor", void 0);
  48516. __decorate([
  48517. BABYLON.serializeAsVector3()
  48518. ], HemisphericLight.prototype, "direction", void 0);
  48519. return HemisphericLight;
  48520. }(BABYLON.Light));
  48521. BABYLON.HemisphericLight = HemisphericLight;
  48522. })(BABYLON || (BABYLON = {}));
  48523. //# sourceMappingURL=babylon.hemisphericLight.js.map
  48524. var BABYLON;
  48525. (function (BABYLON) {
  48526. /**
  48527. * Base implementation IShadowLight
  48528. * It groups all the common behaviour in order to reduce dupplication and better follow the DRY pattern.
  48529. */
  48530. var ShadowLight = /** @class */ (function (_super) {
  48531. __extends(ShadowLight, _super);
  48532. function ShadowLight() {
  48533. var _this = _super !== null && _super.apply(this, arguments) || this;
  48534. _this._needProjectionMatrixCompute = true;
  48535. return _this;
  48536. }
  48537. ShadowLight.prototype._setPosition = function (value) {
  48538. this._position = value;
  48539. };
  48540. Object.defineProperty(ShadowLight.prototype, "position", {
  48541. /**
  48542. * Sets the position the shadow will be casted from. Also use as the light position for both
  48543. * point and spot lights.
  48544. */
  48545. get: function () {
  48546. return this._position;
  48547. },
  48548. /**
  48549. * Sets the position the shadow will be casted from. Also use as the light position for both
  48550. * point and spot lights.
  48551. */
  48552. set: function (value) {
  48553. this._setPosition(value);
  48554. },
  48555. enumerable: true,
  48556. configurable: true
  48557. });
  48558. ShadowLight.prototype._setDirection = function (value) {
  48559. this._direction = value;
  48560. };
  48561. Object.defineProperty(ShadowLight.prototype, "direction", {
  48562. /**
  48563. * In 2d mode (needCube being false), gets the direction used to cast the shadow.
  48564. * Also use as the light direction on spot and directional lights.
  48565. */
  48566. get: function () {
  48567. return this._direction;
  48568. },
  48569. /**
  48570. * In 2d mode (needCube being false), sets the direction used to cast the shadow.
  48571. * Also use as the light direction on spot and directional lights.
  48572. */
  48573. set: function (value) {
  48574. this._setDirection(value);
  48575. },
  48576. enumerable: true,
  48577. configurable: true
  48578. });
  48579. Object.defineProperty(ShadowLight.prototype, "shadowMinZ", {
  48580. /**
  48581. * Gets the shadow projection clipping minimum z value.
  48582. */
  48583. get: function () {
  48584. return this._shadowMinZ;
  48585. },
  48586. /**
  48587. * Sets the shadow projection clipping minimum z value.
  48588. */
  48589. set: function (value) {
  48590. this._shadowMinZ = value;
  48591. this.forceProjectionMatrixCompute();
  48592. },
  48593. enumerable: true,
  48594. configurable: true
  48595. });
  48596. Object.defineProperty(ShadowLight.prototype, "shadowMaxZ", {
  48597. /**
  48598. * Sets the shadow projection clipping maximum z value.
  48599. */
  48600. get: function () {
  48601. return this._shadowMaxZ;
  48602. },
  48603. /**
  48604. * Gets the shadow projection clipping maximum z value.
  48605. */
  48606. set: function (value) {
  48607. this._shadowMaxZ = value;
  48608. this.forceProjectionMatrixCompute();
  48609. },
  48610. enumerable: true,
  48611. configurable: true
  48612. });
  48613. /**
  48614. * Computes the transformed information (transformedPosition and transformedDirection in World space) of the current light
  48615. * @returns true if the information has been computed, false if it does not need to (no parenting)
  48616. */
  48617. ShadowLight.prototype.computeTransformedInformation = function () {
  48618. if (this.parent && this.parent.getWorldMatrix) {
  48619. if (!this.transformedPosition) {
  48620. this.transformedPosition = BABYLON.Vector3.Zero();
  48621. }
  48622. BABYLON.Vector3.TransformCoordinatesToRef(this.position, this.parent.getWorldMatrix(), this.transformedPosition);
  48623. // In case the direction is present.
  48624. if (this.direction) {
  48625. if (!this.transformedDirection) {
  48626. this.transformedDirection = BABYLON.Vector3.Zero();
  48627. }
  48628. BABYLON.Vector3.TransformNormalToRef(this.direction, this.parent.getWorldMatrix(), this.transformedDirection);
  48629. }
  48630. return true;
  48631. }
  48632. return false;
  48633. };
  48634. /**
  48635. * Return the depth scale used for the shadow map.
  48636. * @returns the depth scale.
  48637. */
  48638. ShadowLight.prototype.getDepthScale = function () {
  48639. return 50.0;
  48640. };
  48641. /**
  48642. * Get the direction to use to render the shadow map. In case of cube texture, the face index can be passed.
  48643. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48644. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48645. */
  48646. ShadowLight.prototype.getShadowDirection = function (faceIndex) {
  48647. return this.transformedDirection ? this.transformedDirection : this.direction;
  48648. };
  48649. /**
  48650. * Returns the ShadowLight absolute position in the World.
  48651. * @returns the position vector in world space
  48652. */
  48653. ShadowLight.prototype.getAbsolutePosition = function () {
  48654. return this.transformedPosition ? this.transformedPosition : this.position;
  48655. };
  48656. /**
  48657. * Sets the ShadowLight direction toward the passed target.
  48658. * @param target The point tot target in local space
  48659. * @returns the updated ShadowLight direction
  48660. */
  48661. ShadowLight.prototype.setDirectionToTarget = function (target) {
  48662. this.direction = BABYLON.Vector3.Normalize(target.subtract(this.position));
  48663. return this.direction;
  48664. };
  48665. /**
  48666. * Returns the light rotation in euler definition.
  48667. * @returns the x y z rotation in local space.
  48668. */
  48669. ShadowLight.prototype.getRotation = function () {
  48670. this.direction.normalize();
  48671. var xaxis = BABYLON.Vector3.Cross(this.direction, BABYLON.Axis.Y);
  48672. var yaxis = BABYLON.Vector3.Cross(xaxis, this.direction);
  48673. return BABYLON.Vector3.RotationFromAxis(xaxis, yaxis, this.direction);
  48674. };
  48675. /**
  48676. * Returns whether or not the shadow generation require a cube texture or a 2d texture.
  48677. * @returns true if a cube texture needs to be use
  48678. */
  48679. ShadowLight.prototype.needCube = function () {
  48680. return false;
  48681. };
  48682. /**
  48683. * Detects if the projection matrix requires to be recomputed this frame.
  48684. * @returns true if it requires to be recomputed otherwise, false.
  48685. */
  48686. ShadowLight.prototype.needProjectionMatrixCompute = function () {
  48687. return this._needProjectionMatrixCompute;
  48688. };
  48689. /**
  48690. * Forces the shadow generator to recompute the projection matrix even if position and direction did not changed.
  48691. */
  48692. ShadowLight.prototype.forceProjectionMatrixCompute = function () {
  48693. this._needProjectionMatrixCompute = true;
  48694. };
  48695. /**
  48696. * Get the world matrix of the sahdow lights.
  48697. * @hidden Internal Use Only
  48698. */
  48699. ShadowLight.prototype._getWorldMatrix = function () {
  48700. if (!this._worldMatrix) {
  48701. this._worldMatrix = BABYLON.Matrix.Identity();
  48702. }
  48703. BABYLON.Matrix.TranslationToRef(this.position.x, this.position.y, this.position.z, this._worldMatrix);
  48704. return this._worldMatrix;
  48705. };
  48706. /**
  48707. * Gets the minZ used for shadow according to both the scene and the light.
  48708. * @param activeCamera The camera we are returning the min for
  48709. * @returns the depth min z
  48710. */
  48711. ShadowLight.prototype.getDepthMinZ = function (activeCamera) {
  48712. return this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ;
  48713. };
  48714. /**
  48715. * Gets the maxZ used for shadow according to both the scene and the light.
  48716. * @param activeCamera The camera we are returning the max for
  48717. * @returns the depth max z
  48718. */
  48719. ShadowLight.prototype.getDepthMaxZ = function (activeCamera) {
  48720. return this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ;
  48721. };
  48722. /**
  48723. * Sets the shadow projection matrix in parameter to the generated projection matrix.
  48724. * @param matrix The materix to updated with the projection information
  48725. * @param viewMatrix The transform matrix of the light
  48726. * @param renderList The list of mesh to render in the map
  48727. * @returns The current light
  48728. */
  48729. ShadowLight.prototype.setShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48730. if (this.customProjectionMatrixBuilder) {
  48731. this.customProjectionMatrixBuilder(viewMatrix, renderList, matrix);
  48732. }
  48733. else {
  48734. this._setDefaultShadowProjectionMatrix(matrix, viewMatrix, renderList);
  48735. }
  48736. return this;
  48737. };
  48738. __decorate([
  48739. BABYLON.serializeAsVector3()
  48740. ], ShadowLight.prototype, "position", null);
  48741. __decorate([
  48742. BABYLON.serializeAsVector3()
  48743. ], ShadowLight.prototype, "direction", null);
  48744. __decorate([
  48745. BABYLON.serialize()
  48746. ], ShadowLight.prototype, "shadowMinZ", null);
  48747. __decorate([
  48748. BABYLON.serialize()
  48749. ], ShadowLight.prototype, "shadowMaxZ", null);
  48750. return ShadowLight;
  48751. }(BABYLON.Light));
  48752. BABYLON.ShadowLight = ShadowLight;
  48753. })(BABYLON || (BABYLON = {}));
  48754. //# sourceMappingURL=babylon.shadowLight.js.map
  48755. var BABYLON;
  48756. (function (BABYLON) {
  48757. /**
  48758. * A point light is a light defined by an unique point in world space.
  48759. * The light is emitted in every direction from this point.
  48760. * A good example of a point light is a standard light bulb.
  48761. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48762. */
  48763. var PointLight = /** @class */ (function (_super) {
  48764. __extends(PointLight, _super);
  48765. /**
  48766. * Creates a PointLight object from the passed name and position (Vector3) and adds it in the scene.
  48767. * A PointLight emits the light in every direction.
  48768. * It can cast shadows.
  48769. * If the scene camera is already defined and you want to set your PointLight at the camera position, just set it :
  48770. * ```javascript
  48771. * var pointLight = new BABYLON.PointLight("pl", camera.position, scene);
  48772. * ```
  48773. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48774. * @param name The light friendly name
  48775. * @param position The position of the point light in the scene
  48776. * @param scene The scene the lights belongs to
  48777. */
  48778. function PointLight(name, position, scene) {
  48779. var _this = _super.call(this, name, scene) || this;
  48780. _this._shadowAngle = Math.PI / 2;
  48781. _this.position = position;
  48782. return _this;
  48783. }
  48784. Object.defineProperty(PointLight.prototype, "shadowAngle", {
  48785. /**
  48786. * Getter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48787. * This specifies what angle the shadow will use to be created.
  48788. *
  48789. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48790. */
  48791. get: function () {
  48792. return this._shadowAngle;
  48793. },
  48794. /**
  48795. * Setter: In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48796. * This specifies what angle the shadow will use to be created.
  48797. *
  48798. * It default to 90 degrees to work nicely with the cube texture generation for point lights shadow maps.
  48799. */
  48800. set: function (value) {
  48801. this._shadowAngle = value;
  48802. this.forceProjectionMatrixCompute();
  48803. },
  48804. enumerable: true,
  48805. configurable: true
  48806. });
  48807. Object.defineProperty(PointLight.prototype, "direction", {
  48808. /**
  48809. * Gets the direction if it has been set.
  48810. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48811. */
  48812. get: function () {
  48813. return this._direction;
  48814. },
  48815. /**
  48816. * In case of direction provided, the shadow will not use a cube texture but simulate a spot shadow as a fallback
  48817. */
  48818. set: function (value) {
  48819. var previousNeedCube = this.needCube();
  48820. this._direction = value;
  48821. if (this.needCube() !== previousNeedCube && this._shadowGenerator) {
  48822. this._shadowGenerator.recreateShadowMap();
  48823. }
  48824. },
  48825. enumerable: true,
  48826. configurable: true
  48827. });
  48828. /**
  48829. * Returns the string "PointLight"
  48830. * @returns the class name
  48831. */
  48832. PointLight.prototype.getClassName = function () {
  48833. return "PointLight";
  48834. };
  48835. /**
  48836. * Returns the integer 0.
  48837. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  48838. */
  48839. PointLight.prototype.getTypeID = function () {
  48840. return BABYLON.Light.LIGHTTYPEID_POINTLIGHT;
  48841. };
  48842. /**
  48843. * Specifies wether or not the shadowmap should be a cube texture.
  48844. * @returns true if the shadowmap needs to be a cube texture.
  48845. */
  48846. PointLight.prototype.needCube = function () {
  48847. return !this.direction;
  48848. };
  48849. /**
  48850. * Returns a new Vector3 aligned with the PointLight cube system according to the passed cube face index (integer).
  48851. * @param faceIndex The index of the face we are computed the direction to generate shadow
  48852. * @returns The set direction in 2d mode otherwise the direction to the cubemap face if needCube() is true
  48853. */
  48854. PointLight.prototype.getShadowDirection = function (faceIndex) {
  48855. if (this.direction) {
  48856. return _super.prototype.getShadowDirection.call(this, faceIndex);
  48857. }
  48858. else {
  48859. switch (faceIndex) {
  48860. case 0:
  48861. return new BABYLON.Vector3(1.0, 0.0, 0.0);
  48862. case 1:
  48863. return new BABYLON.Vector3(-1.0, 0.0, 0.0);
  48864. case 2:
  48865. return new BABYLON.Vector3(0.0, -1.0, 0.0);
  48866. case 3:
  48867. return new BABYLON.Vector3(0.0, 1.0, 0.0);
  48868. case 4:
  48869. return new BABYLON.Vector3(0.0, 0.0, 1.0);
  48870. case 5:
  48871. return new BABYLON.Vector3(0.0, 0.0, -1.0);
  48872. }
  48873. }
  48874. return BABYLON.Vector3.Zero();
  48875. };
  48876. /**
  48877. * Sets the passed matrix "matrix" as a left-handed perspective projection matrix with the following settings :
  48878. * - fov = PI / 2
  48879. * - aspect ratio : 1.0
  48880. * - z-near and far equal to the active camera minZ and maxZ.
  48881. * Returns the PointLight.
  48882. */
  48883. PointLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  48884. var activeCamera = this.getScene().activeCamera;
  48885. if (!activeCamera) {
  48886. return;
  48887. }
  48888. BABYLON.Matrix.PerspectiveFovLHToRef(this.shadowAngle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  48889. };
  48890. PointLight.prototype._buildUniformLayout = function () {
  48891. this._uniformBuffer.addUniform("vLightData", 4);
  48892. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  48893. this._uniformBuffer.addUniform("vLightSpecular", 3);
  48894. this._uniformBuffer.addUniform("shadowsInfo", 3);
  48895. this._uniformBuffer.addUniform("depthValues", 2);
  48896. this._uniformBuffer.create();
  48897. };
  48898. /**
  48899. * Sets the passed Effect "effect" with the PointLight transformed position (or position, if none) and passed name (string).
  48900. * @param effect The effect to update
  48901. * @param lightIndex The index of the light in the effect to update
  48902. * @returns The point light
  48903. */
  48904. PointLight.prototype.transferToEffect = function (effect, lightIndex) {
  48905. if (this.computeTransformedInformation()) {
  48906. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, 0.0, lightIndex);
  48907. return this;
  48908. }
  48909. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, 0, lightIndex);
  48910. return this;
  48911. };
  48912. __decorate([
  48913. BABYLON.serialize()
  48914. ], PointLight.prototype, "shadowAngle", null);
  48915. return PointLight;
  48916. }(BABYLON.ShadowLight));
  48917. BABYLON.PointLight = PointLight;
  48918. })(BABYLON || (BABYLON = {}));
  48919. //# sourceMappingURL=babylon.pointLight.js.map
  48920. var BABYLON;
  48921. (function (BABYLON) {
  48922. /**
  48923. * A directional light is defined by a direction (what a surprise!).
  48924. * The light is emitted from everywhere in the specified direction, and has an infinite range.
  48925. * 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.
  48926. * Documentation: https://doc.babylonjs.com/babylon101/lights
  48927. */
  48928. var DirectionalLight = /** @class */ (function (_super) {
  48929. __extends(DirectionalLight, _super);
  48930. /**
  48931. * Creates a DirectionalLight object in the scene, oriented towards the passed direction (Vector3).
  48932. * The directional light is emitted from everywhere in the given direction.
  48933. * It can cast shawdows.
  48934. * Documentation : http://doc.babylonjs.com/tutorials/lights
  48935. * @param name The friendly name of the light
  48936. * @param direction The direction of the light
  48937. * @param scene The scene the light belongs to
  48938. */
  48939. function DirectionalLight(name, direction, scene) {
  48940. var _this = _super.call(this, name, scene) || this;
  48941. _this._shadowFrustumSize = 0;
  48942. _this._shadowOrthoScale = 0.1;
  48943. /**
  48944. * Automatically compute the projection matrix to best fit (including all the casters)
  48945. * on each frame.
  48946. */
  48947. _this.autoUpdateExtends = true;
  48948. // Cache
  48949. _this._orthoLeft = Number.MAX_VALUE;
  48950. _this._orthoRight = Number.MIN_VALUE;
  48951. _this._orthoTop = Number.MIN_VALUE;
  48952. _this._orthoBottom = Number.MAX_VALUE;
  48953. _this.position = direction.scale(-1.0);
  48954. _this.direction = direction;
  48955. return _this;
  48956. }
  48957. Object.defineProperty(DirectionalLight.prototype, "shadowFrustumSize", {
  48958. /**
  48959. * Fix frustum size for the shadow generation. This is disabled if the value is 0.
  48960. */
  48961. get: function () {
  48962. return this._shadowFrustumSize;
  48963. },
  48964. /**
  48965. * Specifies a fix frustum size for the shadow generation.
  48966. */
  48967. set: function (value) {
  48968. this._shadowFrustumSize = value;
  48969. this.forceProjectionMatrixCompute();
  48970. },
  48971. enumerable: true,
  48972. configurable: true
  48973. });
  48974. Object.defineProperty(DirectionalLight.prototype, "shadowOrthoScale", {
  48975. /**
  48976. * Gets the shadow projection scale against the optimal computed one.
  48977. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48978. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48979. */
  48980. get: function () {
  48981. return this._shadowOrthoScale;
  48982. },
  48983. /**
  48984. * Sets the shadow projection scale against the optimal computed one.
  48985. * 0.1 by default which means that the projection window is increase by 10% from the optimal size.
  48986. * This does not impact in fixed frustum size (shadowFrustumSize being set)
  48987. */
  48988. set: function (value) {
  48989. this._shadowOrthoScale = value;
  48990. this.forceProjectionMatrixCompute();
  48991. },
  48992. enumerable: true,
  48993. configurable: true
  48994. });
  48995. /**
  48996. * Returns the string "DirectionalLight".
  48997. * @return The class name
  48998. */
  48999. DirectionalLight.prototype.getClassName = function () {
  49000. return "DirectionalLight";
  49001. };
  49002. /**
  49003. * Returns the integer 1.
  49004. * @return The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49005. */
  49006. DirectionalLight.prototype.getTypeID = function () {
  49007. return BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT;
  49008. };
  49009. /**
  49010. * Sets the passed matrix "matrix" as projection matrix for the shadows cast by the light according to the passed view matrix.
  49011. * Returns the DirectionalLight Shadow projection matrix.
  49012. */
  49013. DirectionalLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49014. if (this.shadowFrustumSize > 0) {
  49015. this._setDefaultFixedFrustumShadowProjectionMatrix(matrix, viewMatrix);
  49016. }
  49017. else {
  49018. this._setDefaultAutoExtendShadowProjectionMatrix(matrix, viewMatrix, renderList);
  49019. }
  49020. };
  49021. /**
  49022. * Sets the passed matrix "matrix" as fixed frustum projection matrix for the shadows cast by the light according to the passed view matrix.
  49023. * Returns the DirectionalLight Shadow projection matrix.
  49024. */
  49025. DirectionalLight.prototype._setDefaultFixedFrustumShadowProjectionMatrix = function (matrix, viewMatrix) {
  49026. var activeCamera = this.getScene().activeCamera;
  49027. if (!activeCamera) {
  49028. return;
  49029. }
  49030. BABYLON.Matrix.OrthoLHToRef(this.shadowFrustumSize, this.shadowFrustumSize, this.shadowMinZ !== undefined ? this.shadowMinZ : activeCamera.minZ, this.shadowMaxZ !== undefined ? this.shadowMaxZ : activeCamera.maxZ, matrix);
  49031. };
  49032. /**
  49033. * Sets the passed matrix "matrix" as auto extend projection matrix for the shadows cast by the light according to the passed view matrix.
  49034. * Returns the DirectionalLight Shadow projection matrix.
  49035. */
  49036. DirectionalLight.prototype._setDefaultAutoExtendShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49037. var activeCamera = this.getScene().activeCamera;
  49038. if (!activeCamera) {
  49039. return;
  49040. }
  49041. // Check extends
  49042. if (this.autoUpdateExtends || this._orthoLeft === Number.MAX_VALUE) {
  49043. var tempVector3 = BABYLON.Vector3.Zero();
  49044. this._orthoLeft = Number.MAX_VALUE;
  49045. this._orthoRight = Number.MIN_VALUE;
  49046. this._orthoTop = Number.MIN_VALUE;
  49047. this._orthoBottom = Number.MAX_VALUE;
  49048. for (var meshIndex = 0; meshIndex < renderList.length; meshIndex++) {
  49049. var mesh = renderList[meshIndex];
  49050. if (!mesh) {
  49051. continue;
  49052. }
  49053. var boundingInfo = mesh.getBoundingInfo();
  49054. var boundingBox = boundingInfo.boundingBox;
  49055. for (var index = 0; index < boundingBox.vectorsWorld.length; index++) {
  49056. BABYLON.Vector3.TransformCoordinatesToRef(boundingBox.vectorsWorld[index], viewMatrix, tempVector3);
  49057. if (tempVector3.x < this._orthoLeft)
  49058. this._orthoLeft = tempVector3.x;
  49059. if (tempVector3.y < this._orthoBottom)
  49060. this._orthoBottom = tempVector3.y;
  49061. if (tempVector3.x > this._orthoRight)
  49062. this._orthoRight = tempVector3.x;
  49063. if (tempVector3.y > this._orthoTop)
  49064. this._orthoTop = tempVector3.y;
  49065. }
  49066. }
  49067. }
  49068. var xOffset = this._orthoRight - this._orthoLeft;
  49069. var yOffset = this._orthoTop - this._orthoBottom;
  49070. 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);
  49071. };
  49072. DirectionalLight.prototype._buildUniformLayout = function () {
  49073. this._uniformBuffer.addUniform("vLightData", 4);
  49074. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49075. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49076. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49077. this._uniformBuffer.addUniform("depthValues", 2);
  49078. this._uniformBuffer.create();
  49079. };
  49080. /**
  49081. * Sets the passed Effect object with the DirectionalLight transformed position (or position if not parented) and the passed name.
  49082. * @param effect The effect to update
  49083. * @param lightIndex The index of the light in the effect to update
  49084. * @returns The directional light
  49085. */
  49086. DirectionalLight.prototype.transferToEffect = function (effect, lightIndex) {
  49087. if (this.computeTransformedInformation()) {
  49088. this._uniformBuffer.updateFloat4("vLightData", this.transformedDirection.x, this.transformedDirection.y, this.transformedDirection.z, 1, lightIndex);
  49089. return this;
  49090. }
  49091. this._uniformBuffer.updateFloat4("vLightData", this.direction.x, this.direction.y, this.direction.z, 1, lightIndex);
  49092. return this;
  49093. };
  49094. /**
  49095. * Gets the minZ used for shadow according to both the scene and the light.
  49096. *
  49097. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49098. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49099. * @param activeCamera The camera we are returning the min for
  49100. * @returns the depth min z
  49101. */
  49102. DirectionalLight.prototype.getDepthMinZ = function (activeCamera) {
  49103. return 1;
  49104. };
  49105. /**
  49106. * Gets the maxZ used for shadow according to both the scene and the light.
  49107. *
  49108. * Values are fixed on directional lights as it relies on an ortho projection hence the need to convert being
  49109. * -1 and 1 to 0 and 1 doing (depth + min) / (min + max) -> (depth + 1) / (1 + 1) -> (depth * 0.5) + 0.5.
  49110. * @param activeCamera The camera we are returning the max for
  49111. * @returns the depth max z
  49112. */
  49113. DirectionalLight.prototype.getDepthMaxZ = function (activeCamera) {
  49114. return 1;
  49115. };
  49116. __decorate([
  49117. BABYLON.serialize()
  49118. ], DirectionalLight.prototype, "shadowFrustumSize", null);
  49119. __decorate([
  49120. BABYLON.serialize()
  49121. ], DirectionalLight.prototype, "shadowOrthoScale", null);
  49122. __decorate([
  49123. BABYLON.serialize()
  49124. ], DirectionalLight.prototype, "autoUpdateExtends", void 0);
  49125. return DirectionalLight;
  49126. }(BABYLON.ShadowLight));
  49127. BABYLON.DirectionalLight = DirectionalLight;
  49128. })(BABYLON || (BABYLON = {}));
  49129. //# sourceMappingURL=babylon.directionalLight.js.map
  49130. var BABYLON;
  49131. (function (BABYLON) {
  49132. /**
  49133. * A spot light is defined by a position, a direction, an angle, and an exponent.
  49134. * These values define a cone of light starting from the position, emitting toward the direction.
  49135. * The angle, in radians, defines the size (field of illumination) of the spotlight's conical beam,
  49136. * and the exponent defines the speed of the decay of the light with distance (reach).
  49137. * Documentation: https://doc.babylonjs.com/babylon101/lights
  49138. */
  49139. var SpotLight = /** @class */ (function (_super) {
  49140. __extends(SpotLight, _super);
  49141. /**
  49142. * Creates a SpotLight object in the scene. A spot light is a simply light oriented cone.
  49143. * It can cast shadows.
  49144. * Documentation : http://doc.babylonjs.com/tutorials/lights
  49145. * @param name The light friendly name
  49146. * @param position The position of the spot light in the scene
  49147. * @param direction The direction of the light in the scene
  49148. * @param angle The cone angle of the light in Radians
  49149. * @param exponent The light decay speed with the distance from the emission spot
  49150. * @param scene The scene the lights belongs to
  49151. */
  49152. function SpotLight(name, position, direction, angle, exponent, scene) {
  49153. var _this = _super.call(this, name, scene) || this;
  49154. _this._projectionTextureMatrix = BABYLON.Matrix.Zero();
  49155. _this._projectionTextureLightNear = 1e-6;
  49156. _this._projectionTextureLightFar = 1000.0;
  49157. _this._projectionTextureUpDirection = BABYLON.Vector3.Up();
  49158. _this._projectionTextureViewLightDirty = true;
  49159. _this._projectionTextureProjectionLightDirty = true;
  49160. _this._projectionTextureDirty = true;
  49161. _this._projectionTextureViewTargetVector = BABYLON.Vector3.Zero();
  49162. _this._projectionTextureViewLightMatrix = BABYLON.Matrix.Zero();
  49163. _this._projectionTextureProjectionLightMatrix = BABYLON.Matrix.Zero();
  49164. _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);
  49165. _this.position = position;
  49166. _this.direction = direction;
  49167. _this.angle = angle;
  49168. _this.exponent = exponent;
  49169. return _this;
  49170. }
  49171. Object.defineProperty(SpotLight.prototype, "angle", {
  49172. /**
  49173. * Gets the cone angle of the spot light in Radians.
  49174. */
  49175. get: function () {
  49176. return this._angle;
  49177. },
  49178. /**
  49179. * Sets the cone angle of the spot light in Radians.
  49180. */
  49181. set: function (value) {
  49182. this._angle = value;
  49183. this._projectionTextureProjectionLightDirty = true;
  49184. this.forceProjectionMatrixCompute();
  49185. },
  49186. enumerable: true,
  49187. configurable: true
  49188. });
  49189. Object.defineProperty(SpotLight.prototype, "shadowAngleScale", {
  49190. /**
  49191. * Allows scaling the angle of the light for shadow generation only.
  49192. */
  49193. get: function () {
  49194. return this._shadowAngleScale;
  49195. },
  49196. /**
  49197. * Allows scaling the angle of the light for shadow generation only.
  49198. */
  49199. set: function (value) {
  49200. this._shadowAngleScale = value;
  49201. this.forceProjectionMatrixCompute();
  49202. },
  49203. enumerable: true,
  49204. configurable: true
  49205. });
  49206. Object.defineProperty(SpotLight.prototype, "projectionTextureMatrix", {
  49207. /**
  49208. * Allows reading the projecton texture
  49209. */
  49210. get: function () {
  49211. return this._projectionTextureMatrix;
  49212. },
  49213. enumerable: true,
  49214. configurable: true
  49215. });
  49216. Object.defineProperty(SpotLight.prototype, "projectionTextureLightNear", {
  49217. /**
  49218. * Gets the near clip of the Spotlight for texture projection.
  49219. */
  49220. get: function () {
  49221. return this._projectionTextureLightNear;
  49222. },
  49223. /**
  49224. * Sets the near clip of the Spotlight for texture projection.
  49225. */
  49226. set: function (value) {
  49227. this._projectionTextureLightNear = value;
  49228. this._projectionTextureProjectionLightDirty = true;
  49229. },
  49230. enumerable: true,
  49231. configurable: true
  49232. });
  49233. Object.defineProperty(SpotLight.prototype, "projectionTextureLightFar", {
  49234. /**
  49235. * Gets the far clip of the Spotlight for texture projection.
  49236. */
  49237. get: function () {
  49238. return this._projectionTextureLightFar;
  49239. },
  49240. /**
  49241. * Sets the far clip of the Spotlight for texture projection.
  49242. */
  49243. set: function (value) {
  49244. this._projectionTextureLightFar = value;
  49245. this._projectionTextureProjectionLightDirty = true;
  49246. },
  49247. enumerable: true,
  49248. configurable: true
  49249. });
  49250. Object.defineProperty(SpotLight.prototype, "projectionTextureUpDirection", {
  49251. /**
  49252. * Gets the Up vector of the Spotlight for texture projection.
  49253. */
  49254. get: function () {
  49255. return this._projectionTextureUpDirection;
  49256. },
  49257. /**
  49258. * Sets the Up vector of the Spotlight for texture projection.
  49259. */
  49260. set: function (value) {
  49261. this._projectionTextureUpDirection = value;
  49262. this._projectionTextureProjectionLightDirty = true;
  49263. },
  49264. enumerable: true,
  49265. configurable: true
  49266. });
  49267. Object.defineProperty(SpotLight.prototype, "projectionTexture", {
  49268. /**
  49269. * Gets the projection texture of the light.
  49270. */
  49271. get: function () {
  49272. return this._projectionTexture;
  49273. },
  49274. /**
  49275. * Sets the projection texture of the light.
  49276. */
  49277. set: function (value) {
  49278. this._projectionTexture = value;
  49279. this._projectionTextureDirty = true;
  49280. },
  49281. enumerable: true,
  49282. configurable: true
  49283. });
  49284. /**
  49285. * Returns the string "SpotLight".
  49286. * @returns the class name
  49287. */
  49288. SpotLight.prototype.getClassName = function () {
  49289. return "SpotLight";
  49290. };
  49291. /**
  49292. * Returns the integer 2.
  49293. * @returns The light Type id as a constant defines in Light.LIGHTTYPEID_x
  49294. */
  49295. SpotLight.prototype.getTypeID = function () {
  49296. return BABYLON.Light.LIGHTTYPEID_SPOTLIGHT;
  49297. };
  49298. /**
  49299. * Overrides the direction setter to recompute the projection texture view light Matrix.
  49300. */
  49301. SpotLight.prototype._setDirection = function (value) {
  49302. _super.prototype._setDirection.call(this, value);
  49303. this._projectionTextureViewLightDirty = true;
  49304. };
  49305. /**
  49306. * Overrides the position setter to recompute the projection texture view light Matrix.
  49307. */
  49308. SpotLight.prototype._setPosition = function (value) {
  49309. _super.prototype._setPosition.call(this, value);
  49310. this._projectionTextureViewLightDirty = true;
  49311. };
  49312. /**
  49313. * 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.
  49314. * Returns the SpotLight.
  49315. */
  49316. SpotLight.prototype._setDefaultShadowProjectionMatrix = function (matrix, viewMatrix, renderList) {
  49317. var activeCamera = this.getScene().activeCamera;
  49318. if (!activeCamera) {
  49319. return;
  49320. }
  49321. this._shadowAngleScale = this._shadowAngleScale || 1;
  49322. var angle = this._shadowAngleScale * this._angle;
  49323. BABYLON.Matrix.PerspectiveFovLHToRef(angle, 1.0, this.getDepthMinZ(activeCamera), this.getDepthMaxZ(activeCamera), matrix);
  49324. };
  49325. SpotLight.prototype._computeProjectionTextureViewLightMatrix = function () {
  49326. this._projectionTextureViewLightDirty = false;
  49327. this._projectionTextureDirty = true;
  49328. this.position.addToRef(this.direction, this._projectionTextureViewTargetVector);
  49329. BABYLON.Matrix.LookAtLHToRef(this.position, this._projectionTextureViewTargetVector, this._projectionTextureUpDirection, this._projectionTextureViewLightMatrix);
  49330. };
  49331. SpotLight.prototype._computeProjectionTextureProjectionLightMatrix = function () {
  49332. this._projectionTextureProjectionLightDirty = false;
  49333. this._projectionTextureDirty = true;
  49334. var light_far = this.projectionTextureLightFar;
  49335. var light_near = this.projectionTextureLightNear;
  49336. var P = light_far / (light_far - light_near);
  49337. var Q = -P * light_near;
  49338. var S = 1.0 / Math.tan(this._angle / 2.0);
  49339. var A = 1.0;
  49340. 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);
  49341. };
  49342. /**
  49343. * Main function for light texture projection matrix computing.
  49344. */
  49345. SpotLight.prototype._computeProjectionTextureMatrix = function () {
  49346. this._projectionTextureDirty = false;
  49347. this._projectionTextureViewLightMatrix.multiplyToRef(this._projectionTextureProjectionLightMatrix, this._projectionTextureMatrix);
  49348. this._projectionTextureMatrix.multiplyToRef(this._projectionTextureScalingMatrix, this._projectionTextureMatrix);
  49349. };
  49350. SpotLight.prototype._buildUniformLayout = function () {
  49351. this._uniformBuffer.addUniform("vLightData", 4);
  49352. this._uniformBuffer.addUniform("vLightDiffuse", 4);
  49353. this._uniformBuffer.addUniform("vLightSpecular", 3);
  49354. this._uniformBuffer.addUniform("vLightDirection", 3);
  49355. this._uniformBuffer.addUniform("shadowsInfo", 3);
  49356. this._uniformBuffer.addUniform("depthValues", 2);
  49357. this._uniformBuffer.create();
  49358. };
  49359. /**
  49360. * Sets the passed Effect object with the SpotLight transfomed position (or position if not parented) and normalized direction.
  49361. * @param effect The effect to update
  49362. * @param lightIndex The index of the light in the effect to update
  49363. * @returns The spot light
  49364. */
  49365. SpotLight.prototype.transferToEffect = function (effect, lightIndex) {
  49366. var normalizeDirection;
  49367. if (this.computeTransformedInformation()) {
  49368. this._uniformBuffer.updateFloat4("vLightData", this.transformedPosition.x, this.transformedPosition.y, this.transformedPosition.z, this.exponent, lightIndex);
  49369. normalizeDirection = BABYLON.Vector3.Normalize(this.transformedDirection);
  49370. }
  49371. else {
  49372. this._uniformBuffer.updateFloat4("vLightData", this.position.x, this.position.y, this.position.z, this.exponent, lightIndex);
  49373. normalizeDirection = BABYLON.Vector3.Normalize(this.direction);
  49374. }
  49375. this._uniformBuffer.updateFloat4("vLightDirection", normalizeDirection.x, normalizeDirection.y, normalizeDirection.z, Math.cos(this.angle * 0.5), lightIndex);
  49376. if (this.projectionTexture && this.projectionTexture.isReady()) {
  49377. if (this._projectionTextureViewLightDirty) {
  49378. this._computeProjectionTextureViewLightMatrix();
  49379. }
  49380. if (this._projectionTextureProjectionLightDirty) {
  49381. this._computeProjectionTextureProjectionLightMatrix();
  49382. }
  49383. if (this._projectionTextureDirty) {
  49384. this._computeProjectionTextureMatrix();
  49385. }
  49386. effect.setMatrix("textureProjectionMatrix" + lightIndex, this._projectionTextureMatrix);
  49387. effect.setTexture("projectionLightSampler" + lightIndex, this.projectionTexture);
  49388. }
  49389. return this;
  49390. };
  49391. /**
  49392. * Disposes the light and the associated resources.
  49393. */
  49394. SpotLight.prototype.dispose = function () {
  49395. _super.prototype.dispose.call(this);
  49396. if (this._projectionTexture) {
  49397. this._projectionTexture.dispose();
  49398. }
  49399. };
  49400. __decorate([
  49401. BABYLON.serialize()
  49402. ], SpotLight.prototype, "angle", null);
  49403. __decorate([
  49404. BABYLON.serialize()
  49405. ], SpotLight.prototype, "shadowAngleScale", null);
  49406. __decorate([
  49407. BABYLON.serialize()
  49408. ], SpotLight.prototype, "exponent", void 0);
  49409. __decorate([
  49410. BABYLON.serialize()
  49411. ], SpotLight.prototype, "projectionTextureLightNear", null);
  49412. __decorate([
  49413. BABYLON.serialize()
  49414. ], SpotLight.prototype, "projectionTextureLightFar", null);
  49415. __decorate([
  49416. BABYLON.serialize()
  49417. ], SpotLight.prototype, "projectionTextureUpDirection", null);
  49418. __decorate([
  49419. BABYLON.serializeAsTexture("projectedLightTexture")
  49420. ], SpotLight.prototype, "_projectionTexture", void 0);
  49421. return SpotLight;
  49422. }(BABYLON.ShadowLight));
  49423. BABYLON.SpotLight = SpotLight;
  49424. })(BABYLON || (BABYLON = {}));
  49425. //# sourceMappingURL=babylon.spotLight.js.map
  49426. var BABYLON;
  49427. (function (BABYLON) {
  49428. /**
  49429. * Class used to override all child animations of a given target
  49430. */
  49431. var AnimationPropertiesOverride = /** @class */ (function () {
  49432. function AnimationPropertiesOverride() {
  49433. /**
  49434. * Gets or sets a value indicating if animation blending must be used
  49435. */
  49436. this.enableBlending = false;
  49437. /**
  49438. * Gets or sets the blending speed to use when enableBlending is true
  49439. */
  49440. this.blendingSpeed = 0.01;
  49441. /**
  49442. * Gets or sets the default loop mode to use
  49443. */
  49444. this.loopMode = BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE;
  49445. }
  49446. return AnimationPropertiesOverride;
  49447. }());
  49448. BABYLON.AnimationPropertiesOverride = AnimationPropertiesOverride;
  49449. })(BABYLON || (BABYLON = {}));
  49450. //# sourceMappingURL=babylon.animationPropertiesOverride.js.map
  49451. var BABYLON;
  49452. (function (BABYLON) {
  49453. /**
  49454. * Represents the range of an animation
  49455. */
  49456. var AnimationRange = /** @class */ (function () {
  49457. /**
  49458. * Initializes the range of an animation
  49459. * @param name The name of the animation range
  49460. * @param from The starting frame of the animation
  49461. * @param to The ending frame of the animation
  49462. */
  49463. function AnimationRange(
  49464. /**The name of the animation range**/
  49465. name,
  49466. /**The starting frame of the animation */
  49467. from,
  49468. /**The ending frame of the animation*/
  49469. to) {
  49470. this.name = name;
  49471. this.from = from;
  49472. this.to = to;
  49473. }
  49474. /**
  49475. * Makes a copy of the animation range
  49476. * @returns A copy of the animation range
  49477. */
  49478. AnimationRange.prototype.clone = function () {
  49479. return new AnimationRange(this.name, this.from, this.to);
  49480. };
  49481. return AnimationRange;
  49482. }());
  49483. BABYLON.AnimationRange = AnimationRange;
  49484. /**
  49485. * Composed of a frame, and an action function
  49486. */
  49487. var AnimationEvent = /** @class */ (function () {
  49488. /**
  49489. * Initializes the animation event
  49490. * @param frame The frame for which the event is triggered
  49491. * @param action The event to perform when triggered
  49492. * @param onlyOnce Specifies if the event should be triggered only once
  49493. */
  49494. function AnimationEvent(
  49495. /** The frame for which the event is triggered **/
  49496. frame,
  49497. /** The event to perform when triggered **/
  49498. action,
  49499. /** Specifies if the event should be triggered only once**/
  49500. onlyOnce) {
  49501. this.frame = frame;
  49502. this.action = action;
  49503. this.onlyOnce = onlyOnce;
  49504. /**
  49505. * Specifies if the animation event is done
  49506. */
  49507. this.isDone = false;
  49508. }
  49509. /** @hidden */
  49510. AnimationEvent.prototype._clone = function () {
  49511. return new AnimationEvent(this.frame, this.action, this.onlyOnce);
  49512. };
  49513. return AnimationEvent;
  49514. }());
  49515. BABYLON.AnimationEvent = AnimationEvent;
  49516. /**
  49517. * A cursor which tracks a point on a path
  49518. */
  49519. var PathCursor = /** @class */ (function () {
  49520. /**
  49521. * Initializes the path cursor
  49522. * @param path The path to track
  49523. */
  49524. function PathCursor(path) {
  49525. this.path = path;
  49526. /**
  49527. * Stores path cursor callbacks for when an onchange event is triggered
  49528. */
  49529. this._onchange = new Array();
  49530. /**
  49531. * The value of the path cursor
  49532. */
  49533. this.value = 0;
  49534. /**
  49535. * The animation array of the path cursor
  49536. */
  49537. this.animations = new Array();
  49538. }
  49539. /**
  49540. * Gets the cursor point on the path
  49541. * @returns A point on the path cursor at the cursor location
  49542. */
  49543. PathCursor.prototype.getPoint = function () {
  49544. var point = this.path.getPointAtLengthPosition(this.value);
  49545. return new BABYLON.Vector3(point.x, 0, point.y);
  49546. };
  49547. /**
  49548. * Moves the cursor ahead by the step amount
  49549. * @param step The amount to move the cursor forward
  49550. * @returns This path cursor
  49551. */
  49552. PathCursor.prototype.moveAhead = function (step) {
  49553. if (step === void 0) { step = 0.002; }
  49554. this.move(step);
  49555. return this;
  49556. };
  49557. /**
  49558. * Moves the cursor behind by the step amount
  49559. * @param step The amount to move the cursor back
  49560. * @returns This path cursor
  49561. */
  49562. PathCursor.prototype.moveBack = function (step) {
  49563. if (step === void 0) { step = 0.002; }
  49564. this.move(-step);
  49565. return this;
  49566. };
  49567. /**
  49568. * Moves the cursor by the step amount
  49569. * If the step amount is greater than one, an exception is thrown
  49570. * @param step The amount to move the cursor
  49571. * @returns This path cursor
  49572. */
  49573. PathCursor.prototype.move = function (step) {
  49574. if (Math.abs(step) > 1) {
  49575. throw "step size should be less than 1.";
  49576. }
  49577. this.value += step;
  49578. this.ensureLimits();
  49579. this.raiseOnChange();
  49580. return this;
  49581. };
  49582. /**
  49583. * Ensures that the value is limited between zero and one
  49584. * @returns This path cursor
  49585. */
  49586. PathCursor.prototype.ensureLimits = function () {
  49587. while (this.value > 1) {
  49588. this.value -= 1;
  49589. }
  49590. while (this.value < 0) {
  49591. this.value += 1;
  49592. }
  49593. return this;
  49594. };
  49595. /**
  49596. * Runs onchange callbacks on change (used by the animation engine)
  49597. * @returns This path cursor
  49598. */
  49599. PathCursor.prototype.raiseOnChange = function () {
  49600. var _this = this;
  49601. this._onchange.forEach(function (f) { return f(_this); });
  49602. return this;
  49603. };
  49604. /**
  49605. * Executes a function on change
  49606. * @param f A path cursor onchange callback
  49607. * @returns This path cursor
  49608. */
  49609. PathCursor.prototype.onchange = function (f) {
  49610. this._onchange.push(f);
  49611. return this;
  49612. };
  49613. return PathCursor;
  49614. }());
  49615. BABYLON.PathCursor = PathCursor;
  49616. /**
  49617. * Enum for the animation key frame interpolation type
  49618. */
  49619. var AnimationKeyInterpolation;
  49620. (function (AnimationKeyInterpolation) {
  49621. /**
  49622. * Do not interpolate between keys and use the start key value only. Tangents are ignored
  49623. */
  49624. AnimationKeyInterpolation[AnimationKeyInterpolation["STEP"] = 1] = "STEP";
  49625. })(AnimationKeyInterpolation = BABYLON.AnimationKeyInterpolation || (BABYLON.AnimationKeyInterpolation = {}));
  49626. /**
  49627. * Class used to store any kind of animation
  49628. */
  49629. var Animation = /** @class */ (function () {
  49630. /**
  49631. * Initializes the animation
  49632. * @param name Name of the animation
  49633. * @param targetProperty Property to animate
  49634. * @param framePerSecond The frames per second of the animation
  49635. * @param dataType The data type of the animation
  49636. * @param loopMode The loop mode of the animation
  49637. * @param enableBlendings Specifies if blending should be enabled
  49638. */
  49639. function Animation(
  49640. /**Name of the animation */
  49641. name,
  49642. /**Property to animate */
  49643. targetProperty,
  49644. /**The frames per second of the animation */
  49645. framePerSecond,
  49646. /**The data type of the animation */
  49647. dataType,
  49648. /**The loop mode of the animation */
  49649. loopMode,
  49650. /**Specifies if blending should be enabled */
  49651. enableBlending) {
  49652. this.name = name;
  49653. this.targetProperty = targetProperty;
  49654. this.framePerSecond = framePerSecond;
  49655. this.dataType = dataType;
  49656. this.loopMode = loopMode;
  49657. this.enableBlending = enableBlending;
  49658. /**
  49659. * @hidden Internal use only
  49660. */
  49661. this._runtimeAnimations = new Array();
  49662. /**
  49663. * The set of event that will be linked to this animation
  49664. */
  49665. this._events = new Array();
  49666. /**
  49667. * Stores the blending speed of the animation
  49668. */
  49669. this.blendingSpeed = 0.01;
  49670. /**
  49671. * Stores the animation ranges for the animation
  49672. */
  49673. this._ranges = {};
  49674. this.targetPropertyPath = targetProperty.split(".");
  49675. this.dataType = dataType;
  49676. this.loopMode = loopMode === undefined ? Animation.ANIMATIONLOOPMODE_CYCLE : loopMode;
  49677. }
  49678. /**
  49679. * @hidden Internal use
  49680. */
  49681. Animation._PrepareAnimation = function (name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction) {
  49682. var dataType = undefined;
  49683. if (!isNaN(parseFloat(from)) && isFinite(from)) {
  49684. dataType = Animation.ANIMATIONTYPE_FLOAT;
  49685. }
  49686. else if (from instanceof BABYLON.Quaternion) {
  49687. dataType = Animation.ANIMATIONTYPE_QUATERNION;
  49688. }
  49689. else if (from instanceof BABYLON.Vector3) {
  49690. dataType = Animation.ANIMATIONTYPE_VECTOR3;
  49691. }
  49692. else if (from instanceof BABYLON.Vector2) {
  49693. dataType = Animation.ANIMATIONTYPE_VECTOR2;
  49694. }
  49695. else if (from instanceof BABYLON.Color3) {
  49696. dataType = Animation.ANIMATIONTYPE_COLOR3;
  49697. }
  49698. else if (from instanceof BABYLON.Size) {
  49699. dataType = Animation.ANIMATIONTYPE_SIZE;
  49700. }
  49701. if (dataType == undefined) {
  49702. return null;
  49703. }
  49704. var animation = new Animation(name, targetProperty, framePerSecond, dataType, loopMode);
  49705. var keys = [{ frame: 0, value: from }, { frame: totalFrame, value: to }];
  49706. animation.setKeys(keys);
  49707. if (easingFunction !== undefined) {
  49708. animation.setEasingFunction(easingFunction);
  49709. }
  49710. return animation;
  49711. };
  49712. /**
  49713. * Sets up an animation
  49714. * @param property The property to animate
  49715. * @param animationType The animation type to apply
  49716. * @param framePerSecond The frames per second of the animation
  49717. * @param easingFunction The easing function used in the animation
  49718. * @returns The created animation
  49719. */
  49720. Animation.CreateAnimation = function (property, animationType, framePerSecond, easingFunction) {
  49721. var animation = new Animation(property + "Animation", property, framePerSecond, animationType, Animation.ANIMATIONLOOPMODE_CONSTANT);
  49722. animation.setEasingFunction(easingFunction);
  49723. return animation;
  49724. };
  49725. /**
  49726. * Create and start an animation on a node
  49727. * @param name defines the name of the global animation that will be run on all nodes
  49728. * @param node defines the root node where the animation will take place
  49729. * @param targetProperty defines property to animate
  49730. * @param framePerSecond defines the number of frame per second yo use
  49731. * @param totalFrame defines the number of frames in total
  49732. * @param from defines the initial value
  49733. * @param to defines the final value
  49734. * @param loopMode defines which loop mode you want to use (off by default)
  49735. * @param easingFunction defines the easing function to use (linear by default)
  49736. * @param onAnimationEnd defines the callback to call when animation end
  49737. * @returns the animatable created for this animation
  49738. */
  49739. Animation.CreateAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49740. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49741. if (!animation) {
  49742. return null;
  49743. }
  49744. return node.getScene().beginDirectAnimation(node, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49745. };
  49746. /**
  49747. * Create and start an animation on a node and its descendants
  49748. * @param name defines the name of the global animation that will be run on all nodes
  49749. * @param node defines the root node where the animation will take place
  49750. * @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
  49751. * @param targetProperty defines property to animate
  49752. * @param framePerSecond defines the number of frame per second to use
  49753. * @param totalFrame defines the number of frames in total
  49754. * @param from defines the initial value
  49755. * @param to defines the final value
  49756. * @param loopMode defines which loop mode you want to use (off by default)
  49757. * @param easingFunction defines the easing function to use (linear by default)
  49758. * @param onAnimationEnd defines the callback to call when an animation ends (will be called once per node)
  49759. * @returns the list of animatables created for all nodes
  49760. * @example https://www.babylonjs-playground.com/#MH0VLI
  49761. */
  49762. Animation.CreateAndStartHierarchyAnimation = function (name, node, directDescendantsOnly, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49763. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49764. if (!animation) {
  49765. return null;
  49766. }
  49767. var scene = node.getScene();
  49768. return scene.beginDirectHierarchyAnimation(node, directDescendantsOnly, [animation], 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49769. };
  49770. /**
  49771. * Creates a new animation, merges it with the existing animations and starts it
  49772. * @param name Name of the animation
  49773. * @param node Node which contains the scene that begins the animations
  49774. * @param targetProperty Specifies which property to animate
  49775. * @param framePerSecond The frames per second of the animation
  49776. * @param totalFrame The total number of frames
  49777. * @param from The frame at the beginning of the animation
  49778. * @param to The frame at the end of the animation
  49779. * @param loopMode Specifies the loop mode of the animation
  49780. * @param easingFunction (Optional) The easing function of the animation, which allow custom mathematical formulas for animations
  49781. * @param onAnimationEnd Callback to run once the animation is complete
  49782. * @returns Nullable animation
  49783. */
  49784. Animation.CreateMergeAndStartAnimation = function (name, node, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction, onAnimationEnd) {
  49785. var animation = Animation._PrepareAnimation(name, targetProperty, framePerSecond, totalFrame, from, to, loopMode, easingFunction);
  49786. if (!animation) {
  49787. return null;
  49788. }
  49789. node.animations.push(animation);
  49790. return node.getScene().beginAnimation(node, 0, totalFrame, (animation.loopMode === 1), 1.0, onAnimationEnd);
  49791. };
  49792. /**
  49793. * Transition property of an host to the target Value
  49794. * @param property The property to transition
  49795. * @param targetValue The target Value of the property
  49796. * @param host The object where the property to animate belongs
  49797. * @param scene Scene used to run the animation
  49798. * @param frameRate Framerate (in frame/s) to use
  49799. * @param transition The transition type we want to use
  49800. * @param duration The duration of the animation, in milliseconds
  49801. * @param onAnimationEnd Callback trigger at the end of the animation
  49802. * @returns Nullable animation
  49803. */
  49804. Animation.TransitionTo = function (property, targetValue, host, scene, frameRate, transition, duration, onAnimationEnd) {
  49805. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  49806. if (duration <= 0) {
  49807. host[property] = targetValue;
  49808. if (onAnimationEnd) {
  49809. onAnimationEnd();
  49810. }
  49811. return null;
  49812. }
  49813. var endFrame = frameRate * (duration / 1000);
  49814. transition.setKeys([{
  49815. frame: 0,
  49816. value: host[property].clone ? host[property].clone() : host[property]
  49817. },
  49818. {
  49819. frame: endFrame,
  49820. value: targetValue
  49821. }]);
  49822. if (!host.animations) {
  49823. host.animations = [];
  49824. }
  49825. host.animations.push(transition);
  49826. var animation = scene.beginAnimation(host, 0, endFrame, false);
  49827. animation.onAnimationEnd = onAnimationEnd;
  49828. return animation;
  49829. };
  49830. Object.defineProperty(Animation.prototype, "runtimeAnimations", {
  49831. /**
  49832. * Return the array of runtime animations currently using this animation
  49833. */
  49834. get: function () {
  49835. return this._runtimeAnimations;
  49836. },
  49837. enumerable: true,
  49838. configurable: true
  49839. });
  49840. Object.defineProperty(Animation.prototype, "hasRunningRuntimeAnimations", {
  49841. /**
  49842. * Specifies if any of the runtime animations are currently running
  49843. */
  49844. get: function () {
  49845. for (var _i = 0, _a = this._runtimeAnimations; _i < _a.length; _i++) {
  49846. var runtimeAnimation = _a[_i];
  49847. if (!runtimeAnimation.isStopped) {
  49848. return true;
  49849. }
  49850. }
  49851. return false;
  49852. },
  49853. enumerable: true,
  49854. configurable: true
  49855. });
  49856. // Methods
  49857. /**
  49858. * Converts the animation to a string
  49859. * @param fullDetails support for multiple levels of logging within scene loading
  49860. * @returns String form of the animation
  49861. */
  49862. Animation.prototype.toString = function (fullDetails) {
  49863. var ret = "Name: " + this.name + ", property: " + this.targetProperty;
  49864. ret += ", datatype: " + (["Float", "Vector3", "Quaternion", "Matrix", "Color3", "Vector2"])[this.dataType];
  49865. ret += ", nKeys: " + (this._keys ? this._keys.length : "none");
  49866. ret += ", nRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  49867. if (fullDetails) {
  49868. ret += ", Ranges: {";
  49869. var first = true;
  49870. for (var name in this._ranges) {
  49871. if (first) {
  49872. ret += ", ";
  49873. first = false;
  49874. }
  49875. ret += name;
  49876. }
  49877. ret += "}";
  49878. }
  49879. return ret;
  49880. };
  49881. /**
  49882. * Add an event to this animation
  49883. * @param event Event to add
  49884. */
  49885. Animation.prototype.addEvent = function (event) {
  49886. this._events.push(event);
  49887. };
  49888. /**
  49889. * Remove all events found at the given frame
  49890. * @param frame The frame to remove events from
  49891. */
  49892. Animation.prototype.removeEvents = function (frame) {
  49893. for (var index = 0; index < this._events.length; index++) {
  49894. if (this._events[index].frame === frame) {
  49895. this._events.splice(index, 1);
  49896. index--;
  49897. }
  49898. }
  49899. };
  49900. /**
  49901. * Retrieves all the events from the animation
  49902. * @returns Events from the animation
  49903. */
  49904. Animation.prototype.getEvents = function () {
  49905. return this._events;
  49906. };
  49907. /**
  49908. * Creates an animation range
  49909. * @param name Name of the animation range
  49910. * @param from Starting frame of the animation range
  49911. * @param to Ending frame of the animation
  49912. */
  49913. Animation.prototype.createRange = function (name, from, to) {
  49914. // check name not already in use; could happen for bones after serialized
  49915. if (!this._ranges[name]) {
  49916. this._ranges[name] = new AnimationRange(name, from, to);
  49917. }
  49918. };
  49919. /**
  49920. * Deletes an animation range by name
  49921. * @param name Name of the animation range to delete
  49922. * @param deleteFrames Specifies if the key frames for the range should also be deleted (true) or not (false)
  49923. */
  49924. Animation.prototype.deleteRange = function (name, deleteFrames) {
  49925. if (deleteFrames === void 0) { deleteFrames = true; }
  49926. var range = this._ranges[name];
  49927. if (!range) {
  49928. return;
  49929. }
  49930. if (deleteFrames) {
  49931. var from = range.from;
  49932. var to = range.to;
  49933. // this loop MUST go high to low for multiple splices to work
  49934. for (var key = this._keys.length - 1; key >= 0; key--) {
  49935. if (this._keys[key].frame >= from && this._keys[key].frame <= to) {
  49936. this._keys.splice(key, 1);
  49937. }
  49938. }
  49939. }
  49940. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  49941. };
  49942. /**
  49943. * Gets the animation range by name, or null if not defined
  49944. * @param name Name of the animation range
  49945. * @returns Nullable animation range
  49946. */
  49947. Animation.prototype.getRange = function (name) {
  49948. return this._ranges[name];
  49949. };
  49950. /**
  49951. * Gets the key frames from the animation
  49952. * @returns The key frames of the animation
  49953. */
  49954. Animation.prototype.getKeys = function () {
  49955. return this._keys;
  49956. };
  49957. /**
  49958. * Gets the highest frame rate of the animation
  49959. * @returns Highest frame rate of the animation
  49960. */
  49961. Animation.prototype.getHighestFrame = function () {
  49962. var ret = 0;
  49963. for (var key = 0, nKeys = this._keys.length; key < nKeys; key++) {
  49964. if (ret < this._keys[key].frame) {
  49965. ret = this._keys[key].frame;
  49966. }
  49967. }
  49968. return ret;
  49969. };
  49970. /**
  49971. * Gets the easing function of the animation
  49972. * @returns Easing function of the animation
  49973. */
  49974. Animation.prototype.getEasingFunction = function () {
  49975. return this._easingFunction;
  49976. };
  49977. /**
  49978. * Sets the easing function of the animation
  49979. * @param easingFunction A custom mathematical formula for animation
  49980. */
  49981. Animation.prototype.setEasingFunction = function (easingFunction) {
  49982. this._easingFunction = easingFunction;
  49983. };
  49984. /**
  49985. * Interpolates a scalar linearly
  49986. * @param startValue Start value of the animation curve
  49987. * @param endValue End value of the animation curve
  49988. * @param gradient Scalar amount to interpolate
  49989. * @returns Interpolated scalar value
  49990. */
  49991. Animation.prototype.floatInterpolateFunction = function (startValue, endValue, gradient) {
  49992. return BABYLON.Scalar.Lerp(startValue, endValue, gradient);
  49993. };
  49994. /**
  49995. * Interpolates a scalar cubically
  49996. * @param startValue Start value of the animation curve
  49997. * @param outTangent End tangent of the animation
  49998. * @param endValue End value of the animation curve
  49999. * @param inTangent Start tangent of the animation curve
  50000. * @param gradient Scalar amount to interpolate
  50001. * @returns Interpolated scalar value
  50002. */
  50003. Animation.prototype.floatInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50004. return BABYLON.Scalar.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50005. };
  50006. /**
  50007. * Interpolates a quaternion using a spherical linear interpolation
  50008. * @param startValue Start value of the animation curve
  50009. * @param endValue End value of the animation curve
  50010. * @param gradient Scalar amount to interpolate
  50011. * @returns Interpolated quaternion value
  50012. */
  50013. Animation.prototype.quaternionInterpolateFunction = function (startValue, endValue, gradient) {
  50014. return BABYLON.Quaternion.Slerp(startValue, endValue, gradient);
  50015. };
  50016. /**
  50017. * Interpolates a quaternion cubically
  50018. * @param startValue Start value of the animation curve
  50019. * @param outTangent End tangent of the animation curve
  50020. * @param endValue End value of the animation curve
  50021. * @param inTangent Start tangent of the animation curve
  50022. * @param gradient Scalar amount to interpolate
  50023. * @returns Interpolated quaternion value
  50024. */
  50025. Animation.prototype.quaternionInterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50026. return BABYLON.Quaternion.Hermite(startValue, outTangent, endValue, inTangent, gradient).normalize();
  50027. };
  50028. /**
  50029. * Interpolates a Vector3 linearl
  50030. * @param startValue Start value of the animation curve
  50031. * @param endValue End value of the animation curve
  50032. * @param gradient Scalar amount to interpolate
  50033. * @returns Interpolated scalar value
  50034. */
  50035. Animation.prototype.vector3InterpolateFunction = function (startValue, endValue, gradient) {
  50036. return BABYLON.Vector3.Lerp(startValue, endValue, gradient);
  50037. };
  50038. /**
  50039. * Interpolates a Vector3 cubically
  50040. * @param startValue Start value of the animation curve
  50041. * @param outTangent End tangent of the animation
  50042. * @param endValue End value of the animation curve
  50043. * @param inTangent Start tangent of the animation curve
  50044. * @param gradient Scalar amount to interpolate
  50045. * @returns InterpolatedVector3 value
  50046. */
  50047. Animation.prototype.vector3InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50048. return BABYLON.Vector3.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50049. };
  50050. /**
  50051. * Interpolates a Vector2 linearly
  50052. * @param startValue Start value of the animation curve
  50053. * @param endValue End value of the animation curve
  50054. * @param gradient Scalar amount to interpolate
  50055. * @returns Interpolated Vector2 value
  50056. */
  50057. Animation.prototype.vector2InterpolateFunction = function (startValue, endValue, gradient) {
  50058. return BABYLON.Vector2.Lerp(startValue, endValue, gradient);
  50059. };
  50060. /**
  50061. * Interpolates a Vector2 cubically
  50062. * @param startValue Start value of the animation curve
  50063. * @param outTangent End tangent of the animation
  50064. * @param endValue End value of the animation curve
  50065. * @param inTangent Start tangent of the animation curve
  50066. * @param gradient Scalar amount to interpolate
  50067. * @returns Interpolated Vector2 value
  50068. */
  50069. Animation.prototype.vector2InterpolateFunctionWithTangents = function (startValue, outTangent, endValue, inTangent, gradient) {
  50070. return BABYLON.Vector2.Hermite(startValue, outTangent, endValue, inTangent, gradient);
  50071. };
  50072. /**
  50073. * Interpolates a size linearly
  50074. * @param startValue Start value of the animation curve
  50075. * @param endValue End value of the animation curve
  50076. * @param gradient Scalar amount to interpolate
  50077. * @returns Interpolated Size value
  50078. */
  50079. Animation.prototype.sizeInterpolateFunction = function (startValue, endValue, gradient) {
  50080. return BABYLON.Size.Lerp(startValue, endValue, gradient);
  50081. };
  50082. /**
  50083. * Interpolates a Color3 linearly
  50084. * @param startValue Start value of the animation curve
  50085. * @param endValue End value of the animation curve
  50086. * @param gradient Scalar amount to interpolate
  50087. * @returns Interpolated Color3 value
  50088. */
  50089. Animation.prototype.color3InterpolateFunction = function (startValue, endValue, gradient) {
  50090. return BABYLON.Color3.Lerp(startValue, endValue, gradient);
  50091. };
  50092. /**
  50093. * @hidden Internal use only
  50094. */
  50095. Animation.prototype._getKeyValue = function (value) {
  50096. if (typeof value === "function") {
  50097. return value();
  50098. }
  50099. return value;
  50100. };
  50101. /**
  50102. * @hidden Internal use only
  50103. */
  50104. Animation.prototype._interpolate = function (currentFrame, repeatCount, workValue, loopMode, offsetValue, highLimitValue) {
  50105. if (loopMode === Animation.ANIMATIONLOOPMODE_CONSTANT && repeatCount > 0) {
  50106. return highLimitValue.clone ? highLimitValue.clone() : highLimitValue;
  50107. }
  50108. var keys = this.getKeys();
  50109. // Try to get a hash to find the right key
  50110. 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));
  50111. if (keys[startKeyIndex].frame >= currentFrame) {
  50112. while (startKeyIndex - 1 >= 0 && keys[startKeyIndex].frame >= currentFrame) {
  50113. startKeyIndex--;
  50114. }
  50115. }
  50116. for (var key = startKeyIndex; key < keys.length; key++) {
  50117. var endKey = keys[key + 1];
  50118. if (endKey.frame >= currentFrame) {
  50119. var startKey = keys[key];
  50120. var startValue = this._getKeyValue(startKey.value);
  50121. if (startKey.interpolation === AnimationKeyInterpolation.STEP) {
  50122. return startValue;
  50123. }
  50124. var endValue = this._getKeyValue(endKey.value);
  50125. var useTangent = startKey.outTangent !== undefined && endKey.inTangent !== undefined;
  50126. var frameDelta = endKey.frame - startKey.frame;
  50127. // gradient : percent of currentFrame between the frame inf and the frame sup
  50128. var gradient = (currentFrame - startKey.frame) / frameDelta;
  50129. // check for easingFunction and correction of gradient
  50130. var easingFunction = this.getEasingFunction();
  50131. if (easingFunction != null) {
  50132. gradient = easingFunction.ease(gradient);
  50133. }
  50134. switch (this.dataType) {
  50135. // Float
  50136. case Animation.ANIMATIONTYPE_FLOAT:
  50137. var floatValue = useTangent ? this.floatInterpolateFunctionWithTangents(startValue, startKey.outTangent * frameDelta, endValue, endKey.inTangent * frameDelta, gradient) : this.floatInterpolateFunction(startValue, endValue, gradient);
  50138. switch (loopMode) {
  50139. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50140. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50141. return floatValue;
  50142. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50143. return offsetValue * repeatCount + floatValue;
  50144. }
  50145. break;
  50146. // Quaternion
  50147. case Animation.ANIMATIONTYPE_QUATERNION:
  50148. var quatValue = useTangent ? this.quaternionInterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.quaternionInterpolateFunction(startValue, endValue, gradient);
  50149. switch (loopMode) {
  50150. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50151. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50152. return quatValue;
  50153. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50154. return quatValue.addInPlace(offsetValue.scale(repeatCount));
  50155. }
  50156. return quatValue;
  50157. // Vector3
  50158. case Animation.ANIMATIONTYPE_VECTOR3:
  50159. var vec3Value = useTangent ? this.vector3InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector3InterpolateFunction(startValue, endValue, gradient);
  50160. switch (loopMode) {
  50161. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50162. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50163. return vec3Value;
  50164. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50165. return vec3Value.add(offsetValue.scale(repeatCount));
  50166. }
  50167. // Vector2
  50168. case Animation.ANIMATIONTYPE_VECTOR2:
  50169. var vec2Value = useTangent ? this.vector2InterpolateFunctionWithTangents(startValue, startKey.outTangent.scale(frameDelta), endValue, endKey.inTangent.scale(frameDelta), gradient) : this.vector2InterpolateFunction(startValue, endValue, gradient);
  50170. switch (loopMode) {
  50171. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50172. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50173. return vec2Value;
  50174. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50175. return vec2Value.add(offsetValue.scale(repeatCount));
  50176. }
  50177. // Size
  50178. case Animation.ANIMATIONTYPE_SIZE:
  50179. switch (loopMode) {
  50180. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50181. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50182. return this.sizeInterpolateFunction(startValue, endValue, gradient);
  50183. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50184. return this.sizeInterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50185. }
  50186. // Color3
  50187. case Animation.ANIMATIONTYPE_COLOR3:
  50188. switch (loopMode) {
  50189. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50190. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50191. return this.color3InterpolateFunction(startValue, endValue, gradient);
  50192. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50193. return this.color3InterpolateFunction(startValue, endValue, gradient).add(offsetValue.scale(repeatCount));
  50194. }
  50195. // Matrix
  50196. case Animation.ANIMATIONTYPE_MATRIX:
  50197. switch (loopMode) {
  50198. case Animation.ANIMATIONLOOPMODE_CYCLE:
  50199. case Animation.ANIMATIONLOOPMODE_CONSTANT:
  50200. if (Animation.AllowMatricesInterpolation) {
  50201. return this.matrixInterpolateFunction(startValue, endValue, gradient, workValue);
  50202. }
  50203. case Animation.ANIMATIONLOOPMODE_RELATIVE:
  50204. return startValue;
  50205. }
  50206. default:
  50207. break;
  50208. }
  50209. break;
  50210. }
  50211. }
  50212. return this._getKeyValue(keys[keys.length - 1].value);
  50213. };
  50214. /**
  50215. * Defines the function to use to interpolate matrices
  50216. * @param startValue defines the start matrix
  50217. * @param endValue defines the end matrix
  50218. * @param gradient defines the gradient between both matrices
  50219. * @param result defines an optional target matrix where to store the interpolation
  50220. * @returns the interpolated matrix
  50221. */
  50222. Animation.prototype.matrixInterpolateFunction = function (startValue, endValue, gradient, result) {
  50223. if (Animation.AllowMatrixDecomposeForInterpolation) {
  50224. if (result) {
  50225. BABYLON.Matrix.DecomposeLerpToRef(startValue, endValue, gradient, result);
  50226. return result;
  50227. }
  50228. return BABYLON.Matrix.DecomposeLerp(startValue, endValue, gradient);
  50229. }
  50230. if (result) {
  50231. BABYLON.Matrix.LerpToRef(startValue, endValue, gradient, result);
  50232. return result;
  50233. }
  50234. return BABYLON.Matrix.Lerp(startValue, endValue, gradient);
  50235. };
  50236. /**
  50237. * Makes a copy of the animation
  50238. * @returns Cloned animation
  50239. */
  50240. Animation.prototype.clone = function () {
  50241. var clone = new Animation(this.name, this.targetPropertyPath.join("."), this.framePerSecond, this.dataType, this.loopMode);
  50242. clone.enableBlending = this.enableBlending;
  50243. clone.blendingSpeed = this.blendingSpeed;
  50244. if (this._keys) {
  50245. clone.setKeys(this._keys);
  50246. }
  50247. if (this._ranges) {
  50248. clone._ranges = {};
  50249. for (var name in this._ranges) {
  50250. var range = this._ranges[name];
  50251. if (!range) {
  50252. continue;
  50253. }
  50254. clone._ranges[name] = range.clone();
  50255. }
  50256. }
  50257. return clone;
  50258. };
  50259. /**
  50260. * Sets the key frames of the animation
  50261. * @param values The animation key frames to set
  50262. */
  50263. Animation.prototype.setKeys = function (values) {
  50264. this._keys = values.slice(0);
  50265. };
  50266. /**
  50267. * Serializes the animation to an object
  50268. * @returns Serialized object
  50269. */
  50270. Animation.prototype.serialize = function () {
  50271. var serializationObject = {};
  50272. serializationObject.name = this.name;
  50273. serializationObject.property = this.targetProperty;
  50274. serializationObject.framePerSecond = this.framePerSecond;
  50275. serializationObject.dataType = this.dataType;
  50276. serializationObject.loopBehavior = this.loopMode;
  50277. serializationObject.enableBlending = this.enableBlending;
  50278. serializationObject.blendingSpeed = this.blendingSpeed;
  50279. var dataType = this.dataType;
  50280. serializationObject.keys = [];
  50281. var keys = this.getKeys();
  50282. for (var index = 0; index < keys.length; index++) {
  50283. var animationKey = keys[index];
  50284. var key = {};
  50285. key.frame = animationKey.frame;
  50286. switch (dataType) {
  50287. case Animation.ANIMATIONTYPE_FLOAT:
  50288. key.values = [animationKey.value];
  50289. break;
  50290. case Animation.ANIMATIONTYPE_QUATERNION:
  50291. case Animation.ANIMATIONTYPE_MATRIX:
  50292. case Animation.ANIMATIONTYPE_VECTOR3:
  50293. case Animation.ANIMATIONTYPE_COLOR3:
  50294. key.values = animationKey.value.asArray();
  50295. break;
  50296. }
  50297. serializationObject.keys.push(key);
  50298. }
  50299. serializationObject.ranges = [];
  50300. for (var name in this._ranges) {
  50301. var source = this._ranges[name];
  50302. if (!source) {
  50303. continue;
  50304. }
  50305. var range = {};
  50306. range.name = name;
  50307. range.from = source.from;
  50308. range.to = source.to;
  50309. serializationObject.ranges.push(range);
  50310. }
  50311. return serializationObject;
  50312. };
  50313. Object.defineProperty(Animation, "ANIMATIONTYPE_FLOAT", {
  50314. /**
  50315. * Get the float animation type
  50316. */
  50317. get: function () {
  50318. return Animation._ANIMATIONTYPE_FLOAT;
  50319. },
  50320. enumerable: true,
  50321. configurable: true
  50322. });
  50323. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR3", {
  50324. /**
  50325. * Get the Vector3 animation type
  50326. */
  50327. get: function () {
  50328. return Animation._ANIMATIONTYPE_VECTOR3;
  50329. },
  50330. enumerable: true,
  50331. configurable: true
  50332. });
  50333. Object.defineProperty(Animation, "ANIMATIONTYPE_VECTOR2", {
  50334. /**
  50335. * Get the Vectpr2 animation type
  50336. */
  50337. get: function () {
  50338. return Animation._ANIMATIONTYPE_VECTOR2;
  50339. },
  50340. enumerable: true,
  50341. configurable: true
  50342. });
  50343. Object.defineProperty(Animation, "ANIMATIONTYPE_SIZE", {
  50344. /**
  50345. * Get the Size animation type
  50346. */
  50347. get: function () {
  50348. return Animation._ANIMATIONTYPE_SIZE;
  50349. },
  50350. enumerable: true,
  50351. configurable: true
  50352. });
  50353. Object.defineProperty(Animation, "ANIMATIONTYPE_QUATERNION", {
  50354. /**
  50355. * Get the Quaternion animation type
  50356. */
  50357. get: function () {
  50358. return Animation._ANIMATIONTYPE_QUATERNION;
  50359. },
  50360. enumerable: true,
  50361. configurable: true
  50362. });
  50363. Object.defineProperty(Animation, "ANIMATIONTYPE_MATRIX", {
  50364. /**
  50365. * Get the Matrix animation type
  50366. */
  50367. get: function () {
  50368. return Animation._ANIMATIONTYPE_MATRIX;
  50369. },
  50370. enumerable: true,
  50371. configurable: true
  50372. });
  50373. Object.defineProperty(Animation, "ANIMATIONTYPE_COLOR3", {
  50374. /**
  50375. * Get the Color3 animation type
  50376. */
  50377. get: function () {
  50378. return Animation._ANIMATIONTYPE_COLOR3;
  50379. },
  50380. enumerable: true,
  50381. configurable: true
  50382. });
  50383. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_RELATIVE", {
  50384. /**
  50385. * Get the Relative Loop Mode
  50386. */
  50387. get: function () {
  50388. return Animation._ANIMATIONLOOPMODE_RELATIVE;
  50389. },
  50390. enumerable: true,
  50391. configurable: true
  50392. });
  50393. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CYCLE", {
  50394. /**
  50395. * Get the Cycle Loop Mode
  50396. */
  50397. get: function () {
  50398. return Animation._ANIMATIONLOOPMODE_CYCLE;
  50399. },
  50400. enumerable: true,
  50401. configurable: true
  50402. });
  50403. Object.defineProperty(Animation, "ANIMATIONLOOPMODE_CONSTANT", {
  50404. /**
  50405. * Get the Constant Loop Mode
  50406. */
  50407. get: function () {
  50408. return Animation._ANIMATIONLOOPMODE_CONSTANT;
  50409. },
  50410. enumerable: true,
  50411. configurable: true
  50412. });
  50413. /** @hidden */
  50414. Animation._UniversalLerp = function (left, right, amount) {
  50415. var constructor = left.constructor;
  50416. if (constructor.Lerp) { // Lerp supported
  50417. return constructor.Lerp(left, right, amount);
  50418. }
  50419. else if (constructor.Slerp) { // Slerp supported
  50420. return constructor.Slerp(left, right, amount);
  50421. }
  50422. else if (left.toFixed) { // Number
  50423. return left * (1.0 - amount) + amount * right;
  50424. }
  50425. else { // Blending not supported
  50426. return right;
  50427. }
  50428. };
  50429. /**
  50430. * Parses an animation object and creates an animation
  50431. * @param parsedAnimation Parsed animation object
  50432. * @returns Animation object
  50433. */
  50434. Animation.Parse = function (parsedAnimation) {
  50435. var animation = new Animation(parsedAnimation.name, parsedAnimation.property, parsedAnimation.framePerSecond, parsedAnimation.dataType, parsedAnimation.loopBehavior);
  50436. var dataType = parsedAnimation.dataType;
  50437. var keys = [];
  50438. var data;
  50439. var index;
  50440. if (parsedAnimation.enableBlending) {
  50441. animation.enableBlending = parsedAnimation.enableBlending;
  50442. }
  50443. if (parsedAnimation.blendingSpeed) {
  50444. animation.blendingSpeed = parsedAnimation.blendingSpeed;
  50445. }
  50446. for (index = 0; index < parsedAnimation.keys.length; index++) {
  50447. var key = parsedAnimation.keys[index];
  50448. var inTangent;
  50449. var outTangent;
  50450. switch (dataType) {
  50451. case Animation.ANIMATIONTYPE_FLOAT:
  50452. data = key.values[0];
  50453. if (key.values.length >= 1) {
  50454. inTangent = key.values[1];
  50455. }
  50456. if (key.values.length >= 2) {
  50457. outTangent = key.values[2];
  50458. }
  50459. break;
  50460. case Animation.ANIMATIONTYPE_QUATERNION:
  50461. data = BABYLON.Quaternion.FromArray(key.values);
  50462. if (key.values.length >= 8) {
  50463. var _inTangent = BABYLON.Quaternion.FromArray(key.values.slice(4, 8));
  50464. if (!_inTangent.equals(BABYLON.Quaternion.Zero())) {
  50465. inTangent = _inTangent;
  50466. }
  50467. }
  50468. if (key.values.length >= 12) {
  50469. var _outTangent = BABYLON.Quaternion.FromArray(key.values.slice(8, 12));
  50470. if (!_outTangent.equals(BABYLON.Quaternion.Zero())) {
  50471. outTangent = _outTangent;
  50472. }
  50473. }
  50474. break;
  50475. case Animation.ANIMATIONTYPE_MATRIX:
  50476. data = BABYLON.Matrix.FromArray(key.values);
  50477. break;
  50478. case Animation.ANIMATIONTYPE_COLOR3:
  50479. data = BABYLON.Color3.FromArray(key.values);
  50480. break;
  50481. case Animation.ANIMATIONTYPE_VECTOR3:
  50482. default:
  50483. data = BABYLON.Vector3.FromArray(key.values);
  50484. break;
  50485. }
  50486. var keyData = {};
  50487. keyData.frame = key.frame;
  50488. keyData.value = data;
  50489. if (inTangent != undefined) {
  50490. keyData.inTangent = inTangent;
  50491. }
  50492. if (outTangent != undefined) {
  50493. keyData.outTangent = outTangent;
  50494. }
  50495. keys.push(keyData);
  50496. }
  50497. animation.setKeys(keys);
  50498. if (parsedAnimation.ranges) {
  50499. for (index = 0; index < parsedAnimation.ranges.length; index++) {
  50500. data = parsedAnimation.ranges[index];
  50501. animation.createRange(data.name, data.from, data.to);
  50502. }
  50503. }
  50504. return animation;
  50505. };
  50506. /**
  50507. * Appends the serialized animations from the source animations
  50508. * @param source Source containing the animations
  50509. * @param destination Target to store the animations
  50510. */
  50511. Animation.AppendSerializedAnimations = function (source, destination) {
  50512. if (source.animations) {
  50513. destination.animations = [];
  50514. for (var animationIndex = 0; animationIndex < source.animations.length; animationIndex++) {
  50515. var animation = source.animations[animationIndex];
  50516. destination.animations.push(animation.serialize());
  50517. }
  50518. }
  50519. };
  50520. /**
  50521. * Use matrix interpolation instead of using direct key value when animating matrices
  50522. */
  50523. Animation.AllowMatricesInterpolation = false;
  50524. /**
  50525. * When matrix interpolation is enabled, this boolean forces the system to use Matrix.DecomposeLerp instead of Matrix.Lerp. Interpolation is more precise but slower
  50526. */
  50527. Animation.AllowMatrixDecomposeForInterpolation = true;
  50528. // Statics
  50529. /**
  50530. * Float animation type
  50531. */
  50532. Animation._ANIMATIONTYPE_FLOAT = 0;
  50533. /**
  50534. * Vector3 animation type
  50535. */
  50536. Animation._ANIMATIONTYPE_VECTOR3 = 1;
  50537. /**
  50538. * Quaternion animation type
  50539. */
  50540. Animation._ANIMATIONTYPE_QUATERNION = 2;
  50541. /**
  50542. * Matrix animation type
  50543. */
  50544. Animation._ANIMATIONTYPE_MATRIX = 3;
  50545. /**
  50546. * Color3 animation type
  50547. */
  50548. Animation._ANIMATIONTYPE_COLOR3 = 4;
  50549. /**
  50550. * Vector2 animation type
  50551. */
  50552. Animation._ANIMATIONTYPE_VECTOR2 = 5;
  50553. /**
  50554. * Size animation type
  50555. */
  50556. Animation._ANIMATIONTYPE_SIZE = 6;
  50557. /**
  50558. * Relative Loop Mode
  50559. */
  50560. Animation._ANIMATIONLOOPMODE_RELATIVE = 0;
  50561. /**
  50562. * Cycle Loop Mode
  50563. */
  50564. Animation._ANIMATIONLOOPMODE_CYCLE = 1;
  50565. /**
  50566. * Constant Loop Mode
  50567. */
  50568. Animation._ANIMATIONLOOPMODE_CONSTANT = 2;
  50569. return Animation;
  50570. }());
  50571. BABYLON.Animation = Animation;
  50572. })(BABYLON || (BABYLON = {}));
  50573. //# sourceMappingURL=babylon.animation.js.map
  50574. var BABYLON;
  50575. (function (BABYLON) {
  50576. /**
  50577. * This class defines the direct association between an animation and a target
  50578. */
  50579. var TargetedAnimation = /** @class */ (function () {
  50580. function TargetedAnimation() {
  50581. }
  50582. return TargetedAnimation;
  50583. }());
  50584. BABYLON.TargetedAnimation = TargetedAnimation;
  50585. /**
  50586. * Use this class to create coordinated animations on multiple targets
  50587. */
  50588. var AnimationGroup = /** @class */ (function () {
  50589. function AnimationGroup(name, scene) {
  50590. if (scene === void 0) { scene = null; }
  50591. this.name = name;
  50592. this._targetedAnimations = new Array();
  50593. this._animatables = new Array();
  50594. this._from = Number.MAX_VALUE;
  50595. this._to = -Number.MAX_VALUE;
  50596. this._speedRatio = 1;
  50597. this.onAnimationEndObservable = new BABYLON.Observable();
  50598. /**
  50599. * This observable will notify when all animations have ended.
  50600. */
  50601. this.onAnimationGroupEndObservable = new BABYLON.Observable();
  50602. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  50603. this._scene.animationGroups.push(this);
  50604. }
  50605. Object.defineProperty(AnimationGroup.prototype, "from", {
  50606. /**
  50607. * Gets the first frame
  50608. */
  50609. get: function () {
  50610. return this._from;
  50611. },
  50612. enumerable: true,
  50613. configurable: true
  50614. });
  50615. Object.defineProperty(AnimationGroup.prototype, "to", {
  50616. /**
  50617. * Gets the last frame
  50618. */
  50619. get: function () {
  50620. return this._to;
  50621. },
  50622. enumerable: true,
  50623. configurable: true
  50624. });
  50625. Object.defineProperty(AnimationGroup.prototype, "isStarted", {
  50626. /**
  50627. * Define if the animations are started
  50628. */
  50629. get: function () {
  50630. return this._isStarted;
  50631. },
  50632. enumerable: true,
  50633. configurable: true
  50634. });
  50635. Object.defineProperty(AnimationGroup.prototype, "speedRatio", {
  50636. /**
  50637. * Gets or sets the speed ratio to use for all animations
  50638. */
  50639. get: function () {
  50640. return this._speedRatio;
  50641. },
  50642. /**
  50643. * Gets or sets the speed ratio to use for all animations
  50644. */
  50645. set: function (value) {
  50646. if (this._speedRatio === value) {
  50647. return;
  50648. }
  50649. this._speedRatio = value;
  50650. for (var index = 0; index < this._animatables.length; index++) {
  50651. var animatable = this._animatables[index];
  50652. animatable.speedRatio = this._speedRatio;
  50653. }
  50654. },
  50655. enumerable: true,
  50656. configurable: true
  50657. });
  50658. Object.defineProperty(AnimationGroup.prototype, "targetedAnimations", {
  50659. /**
  50660. * Gets the targeted animations for this animation group
  50661. */
  50662. get: function () {
  50663. return this._targetedAnimations;
  50664. },
  50665. enumerable: true,
  50666. configurable: true
  50667. });
  50668. Object.defineProperty(AnimationGroup.prototype, "animatables", {
  50669. /**
  50670. * returning the list of animatables controlled by this animation group.
  50671. */
  50672. get: function () {
  50673. return this._animatables;
  50674. },
  50675. enumerable: true,
  50676. configurable: true
  50677. });
  50678. /**
  50679. * Add an animation (with its target) in the group
  50680. * @param animation defines the animation we want to add
  50681. * @param target defines the target of the animation
  50682. * @returns the {BABYLON.TargetedAnimation} object
  50683. */
  50684. AnimationGroup.prototype.addTargetedAnimation = function (animation, target) {
  50685. var targetedAnimation = {
  50686. animation: animation,
  50687. target: target
  50688. };
  50689. var keys = animation.getKeys();
  50690. if (this._from > keys[0].frame) {
  50691. this._from = keys[0].frame;
  50692. }
  50693. if (this._to < keys[keys.length - 1].frame) {
  50694. this._to = keys[keys.length - 1].frame;
  50695. }
  50696. this._targetedAnimations.push(targetedAnimation);
  50697. return targetedAnimation;
  50698. };
  50699. /**
  50700. * This function will normalize every animation in the group to make sure they all go from beginFrame to endFrame
  50701. * It can add constant keys at begin or end
  50702. * @param beginFrame defines the new begin frame for all animations or the smallest begin frame of all animations if null (defaults to null)
  50703. * @param endFrame defines the new end frame for all animations or the largest end frame of all animations if null (defaults to null)
  50704. */
  50705. AnimationGroup.prototype.normalize = function (beginFrame, endFrame) {
  50706. if (beginFrame === void 0) { beginFrame = null; }
  50707. if (endFrame === void 0) { endFrame = null; }
  50708. if (beginFrame == null)
  50709. beginFrame = this._from;
  50710. if (endFrame == null)
  50711. endFrame = this._to;
  50712. for (var index = 0; index < this._targetedAnimations.length; index++) {
  50713. var targetedAnimation = this._targetedAnimations[index];
  50714. var keys = targetedAnimation.animation.getKeys();
  50715. var startKey = keys[0];
  50716. var endKey = keys[keys.length - 1];
  50717. if (startKey.frame > beginFrame) {
  50718. var newKey = {
  50719. frame: beginFrame,
  50720. value: startKey.value,
  50721. inTangent: startKey.inTangent,
  50722. outTangent: startKey.outTangent,
  50723. interpolation: startKey.interpolation
  50724. };
  50725. keys.splice(0, 0, newKey);
  50726. }
  50727. if (endKey.frame < endFrame) {
  50728. var newKey = {
  50729. frame: endFrame,
  50730. value: endKey.value,
  50731. inTangent: endKey.outTangent,
  50732. outTangent: endKey.outTangent,
  50733. interpolation: endKey.interpolation
  50734. };
  50735. keys.push(newKey);
  50736. }
  50737. }
  50738. this._from = beginFrame;
  50739. this._to = endFrame;
  50740. return this;
  50741. };
  50742. /**
  50743. * Start all animations on given targets
  50744. * @param loop defines if animations must loop
  50745. * @param speedRatio defines the ratio to apply to animation speed (1 by default)
  50746. * @param from defines the from key (optional)
  50747. * @param to defines the to key (optional)
  50748. * @returns the current animation group
  50749. */
  50750. AnimationGroup.prototype.start = function (loop, speedRatio, from, to) {
  50751. var _this = this;
  50752. if (loop === void 0) { loop = false; }
  50753. if (speedRatio === void 0) { speedRatio = 1; }
  50754. if (this._isStarted || this._targetedAnimations.length === 0) {
  50755. return this;
  50756. }
  50757. var _loop_1 = function (targetedAnimation) {
  50758. var animatable = this_1._scene.beginDirectAnimation(targetedAnimation.target, [targetedAnimation.animation], from !== undefined ? from : this_1._from, to !== undefined ? to : this_1._to, loop, speedRatio);
  50759. animatable.onAnimationEnd = function () {
  50760. _this.onAnimationEndObservable.notifyObservers(targetedAnimation);
  50761. _this._checkAnimationGroupEnded(animatable);
  50762. };
  50763. this_1._animatables.push(animatable);
  50764. };
  50765. var this_1 = this;
  50766. for (var _i = 0, _a = this._targetedAnimations; _i < _a.length; _i++) {
  50767. var targetedAnimation = _a[_i];
  50768. _loop_1(targetedAnimation);
  50769. }
  50770. this._speedRatio = speedRatio;
  50771. this._isStarted = true;
  50772. return this;
  50773. };
  50774. /**
  50775. * Pause all animations
  50776. */
  50777. AnimationGroup.prototype.pause = function () {
  50778. if (!this._isStarted) {
  50779. return this;
  50780. }
  50781. for (var index = 0; index < this._animatables.length; index++) {
  50782. var animatable = this._animatables[index];
  50783. animatable.pause();
  50784. }
  50785. return this;
  50786. };
  50787. /**
  50788. * Play all animations to initial state
  50789. * This function will start() the animations if they were not started or will restart() them if they were paused
  50790. * @param loop defines if animations must loop
  50791. */
  50792. AnimationGroup.prototype.play = function (loop) {
  50793. // only if all animatables are ready and exist
  50794. if (this.isStarted && this._animatables.length === this._targetedAnimations.length) {
  50795. if (loop !== undefined) {
  50796. for (var index = 0; index < this._animatables.length; index++) {
  50797. var animatable = this._animatables[index];
  50798. animatable.loopAnimation = loop;
  50799. }
  50800. }
  50801. this.restart();
  50802. }
  50803. else {
  50804. this.stop();
  50805. this.start(loop, this._speedRatio);
  50806. }
  50807. return this;
  50808. };
  50809. /**
  50810. * Reset all animations to initial state
  50811. */
  50812. AnimationGroup.prototype.reset = function () {
  50813. if (!this._isStarted) {
  50814. return this;
  50815. }
  50816. for (var index = 0; index < this._animatables.length; index++) {
  50817. var animatable = this._animatables[index];
  50818. animatable.reset();
  50819. }
  50820. return this;
  50821. };
  50822. /**
  50823. * Restart animations from key 0
  50824. */
  50825. AnimationGroup.prototype.restart = function () {
  50826. if (!this._isStarted) {
  50827. return this;
  50828. }
  50829. for (var index = 0; index < this._animatables.length; index++) {
  50830. var animatable = this._animatables[index];
  50831. animatable.restart();
  50832. }
  50833. return this;
  50834. };
  50835. /**
  50836. * Stop all animations
  50837. */
  50838. AnimationGroup.prototype.stop = function () {
  50839. if (!this._isStarted) {
  50840. return this;
  50841. }
  50842. var list = this._animatables.slice();
  50843. for (var index = 0; index < list.length; index++) {
  50844. list[index].stop();
  50845. }
  50846. this._isStarted = false;
  50847. return this;
  50848. };
  50849. /**
  50850. * Set animation weight for all animatables
  50851. * @param weight defines the weight to use
  50852. * @return the animationGroup
  50853. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50854. */
  50855. AnimationGroup.prototype.setWeightForAllAnimatables = function (weight) {
  50856. for (var index = 0; index < this._animatables.length; index++) {
  50857. var animatable = this._animatables[index];
  50858. animatable.weight = weight;
  50859. }
  50860. return this;
  50861. };
  50862. /**
  50863. * Synchronize and normalize all animatables with a source animatable
  50864. * @param root defines the root animatable to synchronize with
  50865. * @return the animationGroup
  50866. * @see http://doc.babylonjs.com/babylon101/animations#animation-weights
  50867. */
  50868. AnimationGroup.prototype.syncAllAnimationsWith = function (root) {
  50869. for (var index = 0; index < this._animatables.length; index++) {
  50870. var animatable = this._animatables[index];
  50871. animatable.syncWith(root);
  50872. }
  50873. return this;
  50874. };
  50875. /**
  50876. * Goes to a specific frame in this animation group
  50877. * @param frame the frame number to go to
  50878. * @return the animationGroup
  50879. */
  50880. AnimationGroup.prototype.goToFrame = function (frame) {
  50881. if (!this._isStarted) {
  50882. return this;
  50883. }
  50884. for (var index = 0; index < this._animatables.length; index++) {
  50885. var animatable = this._animatables[index];
  50886. animatable.goToFrame(frame);
  50887. }
  50888. return this;
  50889. };
  50890. /**
  50891. * Dispose all associated resources
  50892. */
  50893. AnimationGroup.prototype.dispose = function () {
  50894. this._targetedAnimations = [];
  50895. this._animatables = [];
  50896. var index = this._scene.animationGroups.indexOf(this);
  50897. if (index > -1) {
  50898. this._scene.animationGroups.splice(index, 1);
  50899. }
  50900. };
  50901. AnimationGroup.prototype._checkAnimationGroupEnded = function (animatable) {
  50902. // animatable should be taken out of the array
  50903. var idx = this._animatables.indexOf(animatable);
  50904. if (idx > -1) {
  50905. this._animatables.splice(idx, 1);
  50906. }
  50907. // all animatables were removed? animation group ended!
  50908. if (this._animatables.length === 0) {
  50909. this._isStarted = false;
  50910. this.onAnimationGroupEndObservable.notifyObservers(this);
  50911. }
  50912. };
  50913. return AnimationGroup;
  50914. }());
  50915. BABYLON.AnimationGroup = AnimationGroup;
  50916. })(BABYLON || (BABYLON = {}));
  50917. //# sourceMappingURL=babylon.animationGroup.js.map
  50918. var BABYLON;
  50919. (function (BABYLON) {
  50920. /**
  50921. * Defines a runtime animation
  50922. */
  50923. var RuntimeAnimation = /** @class */ (function () {
  50924. /**
  50925. * Create a new RuntimeAnimation object
  50926. * @param target defines the target of the animation
  50927. * @param animation defines the source animation object
  50928. * @param scene defines the hosting scene
  50929. * @param host defines the initiating Animatable
  50930. */
  50931. function RuntimeAnimation(target, animation, scene, host) {
  50932. var _this = this;
  50933. this._events = new Array();
  50934. /**
  50935. * The current frame of the runtime animation
  50936. */
  50937. this._currentFrame = 0;
  50938. /**
  50939. * The original value of the runtime animation
  50940. */
  50941. this._originalValue = new Array();
  50942. /**
  50943. * The offsets cache of the runtime animation
  50944. */
  50945. this._offsetsCache = {};
  50946. /**
  50947. * The high limits cache of the runtime animation
  50948. */
  50949. this._highLimitsCache = {};
  50950. /**
  50951. * Specifies if the runtime animation has been stopped
  50952. */
  50953. this._stopped = false;
  50954. /**
  50955. * The blending factor of the runtime animation
  50956. */
  50957. this._blendingFactor = 0;
  50958. /**
  50959. * The target path of the runtime animation
  50960. */
  50961. this._targetPath = "";
  50962. /**
  50963. * The weight of the runtime animation
  50964. */
  50965. this._weight = 1.0;
  50966. /**
  50967. * The ratio offset of the runtime animation
  50968. */
  50969. this._ratioOffset = 0;
  50970. /**
  50971. * The previous delay of the runtime animation
  50972. */
  50973. this._previousDelay = 0;
  50974. /**
  50975. * The previous ratio of the runtime animation
  50976. */
  50977. this._previousRatio = 0;
  50978. this._animation = animation;
  50979. this._target = target;
  50980. this._scene = scene;
  50981. this._host = host;
  50982. animation._runtimeAnimations.push(this);
  50983. // Cloning events locally
  50984. var events = animation.getEvents();
  50985. if (events && events.length > 0) {
  50986. events.forEach(function (e) {
  50987. _this._events.push(e._clone());
  50988. });
  50989. }
  50990. }
  50991. Object.defineProperty(RuntimeAnimation.prototype, "currentFrame", {
  50992. /**
  50993. * Gets the current frame of the runtime animation
  50994. */
  50995. get: function () {
  50996. return this._currentFrame;
  50997. },
  50998. enumerable: true,
  50999. configurable: true
  51000. });
  51001. Object.defineProperty(RuntimeAnimation.prototype, "weight", {
  51002. /**
  51003. * Gets the weight of the runtime animation
  51004. */
  51005. get: function () {
  51006. return this._weight;
  51007. },
  51008. enumerable: true,
  51009. configurable: true
  51010. });
  51011. Object.defineProperty(RuntimeAnimation.prototype, "currentValue", {
  51012. /**
  51013. * Gets the current value of the runtime animation
  51014. */
  51015. get: function () {
  51016. return this._currentValue;
  51017. },
  51018. enumerable: true,
  51019. configurable: true
  51020. });
  51021. Object.defineProperty(RuntimeAnimation.prototype, "targetPath", {
  51022. /**
  51023. * Gets the target path of the runtime animation
  51024. */
  51025. get: function () {
  51026. return this._targetPath;
  51027. },
  51028. enumerable: true,
  51029. configurable: true
  51030. });
  51031. Object.defineProperty(RuntimeAnimation.prototype, "target", {
  51032. /**
  51033. * Gets the actual target of the runtime animation
  51034. */
  51035. get: function () {
  51036. return this._activeTarget;
  51037. },
  51038. enumerable: true,
  51039. configurable: true
  51040. });
  51041. Object.defineProperty(RuntimeAnimation.prototype, "animation", {
  51042. /**
  51043. * Gets the animation from the runtime animation
  51044. */
  51045. get: function () {
  51046. return this._animation;
  51047. },
  51048. enumerable: true,
  51049. configurable: true
  51050. });
  51051. /**
  51052. * Resets the runtime animation to the beginning
  51053. * @param restoreOriginal defines whether to restore the target property to the original value
  51054. */
  51055. RuntimeAnimation.prototype.reset = function (restoreOriginal) {
  51056. if (restoreOriginal === void 0) { restoreOriginal = false; }
  51057. if (restoreOriginal) {
  51058. if (this._target instanceof Array) {
  51059. var index = 0;
  51060. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51061. var target = _a[_i];
  51062. if (this._originalValue[index] !== undefined) {
  51063. this._setValue(target, this._originalValue[index], -1);
  51064. }
  51065. index++;
  51066. }
  51067. }
  51068. else {
  51069. if (this._originalValue[0] !== undefined) {
  51070. this._setValue(this._target, this._originalValue[0], -1);
  51071. }
  51072. }
  51073. }
  51074. this._offsetsCache = {};
  51075. this._highLimitsCache = {};
  51076. this._currentFrame = 0;
  51077. this._blendingFactor = 0;
  51078. this._originalValue = new Array();
  51079. // Events
  51080. for (var index = 0; index < this._events.length; index++) {
  51081. this._events[index].isDone = false;
  51082. }
  51083. };
  51084. /**
  51085. * Specifies if the runtime animation is stopped
  51086. * @returns Boolean specifying if the runtime animation is stopped
  51087. */
  51088. RuntimeAnimation.prototype.isStopped = function () {
  51089. return this._stopped;
  51090. };
  51091. /**
  51092. * Disposes of the runtime animation
  51093. */
  51094. RuntimeAnimation.prototype.dispose = function () {
  51095. var index = this._animation.runtimeAnimations.indexOf(this);
  51096. if (index > -1) {
  51097. this._animation.runtimeAnimations.splice(index, 1);
  51098. }
  51099. };
  51100. /**
  51101. * Interpolates the animation from the current frame
  51102. * @param currentFrame The frame to interpolate the animation to
  51103. * @param repeatCount The number of times that the animation should loop
  51104. * @param loopMode The type of looping mode to use
  51105. * @param offsetValue Animation offset value
  51106. * @param highLimitValue The high limit value
  51107. * @returns The interpolated value
  51108. */
  51109. RuntimeAnimation.prototype._interpolate = function (currentFrame, repeatCount, loopMode, offsetValue, highLimitValue) {
  51110. this._currentFrame = currentFrame;
  51111. if (this._animation.dataType === BABYLON.Animation.ANIMATIONTYPE_MATRIX && !this._workValue) {
  51112. this._workValue = BABYLON.Matrix.Zero();
  51113. }
  51114. return this._animation._interpolate(currentFrame, repeatCount, this._workValue, loopMode, offsetValue, highLimitValue);
  51115. };
  51116. /**
  51117. * Apply the interpolated value to the target
  51118. * @param currentValue defines the value computed by the animation
  51119. * @param weight defines the weight to apply to this value (Defaults to 1.0)
  51120. */
  51121. RuntimeAnimation.prototype.setValue = function (currentValue, weight) {
  51122. if (weight === void 0) { weight = 1.0; }
  51123. if (this._target instanceof Array) {
  51124. var index = 0;
  51125. for (var _i = 0, _a = this._target; _i < _a.length; _i++) {
  51126. var target = _a[_i];
  51127. this._setValue(target, currentValue, weight, index);
  51128. index++;
  51129. }
  51130. }
  51131. else {
  51132. this._setValue(this._target, currentValue, weight);
  51133. }
  51134. };
  51135. RuntimeAnimation.prototype._setValue = function (target, currentValue, weight, targetIndex) {
  51136. if (targetIndex === void 0) { targetIndex = 0; }
  51137. // Set value
  51138. var path;
  51139. var destination;
  51140. var targetPropertyPath = this._animation.targetPropertyPath;
  51141. if (targetPropertyPath.length > 1) {
  51142. var property = target[targetPropertyPath[0]];
  51143. for (var index = 1; index < targetPropertyPath.length - 1; index++) {
  51144. property = property[targetPropertyPath[index]];
  51145. }
  51146. path = targetPropertyPath[targetPropertyPath.length - 1];
  51147. destination = property;
  51148. }
  51149. else {
  51150. path = targetPropertyPath[0];
  51151. destination = target;
  51152. }
  51153. this._targetPath = path;
  51154. this._activeTarget = destination;
  51155. this._weight = weight;
  51156. if (this._originalValue[targetIndex] === undefined) {
  51157. var originalValue = void 0;
  51158. if (destination.getRestPose && path === "_matrix") { // For bones
  51159. originalValue = destination.getRestPose();
  51160. }
  51161. else {
  51162. originalValue = destination[path];
  51163. }
  51164. if (originalValue && originalValue.clone) {
  51165. this._originalValue[targetIndex] = originalValue.clone();
  51166. }
  51167. else {
  51168. this._originalValue[targetIndex] = originalValue;
  51169. }
  51170. }
  51171. // Blending
  51172. var enableBlending = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.enableBlending : this._animation.enableBlending;
  51173. if (enableBlending && this._blendingFactor <= 1.0) {
  51174. if (!this._originalBlendValue) {
  51175. var originalValue = destination[path];
  51176. if (originalValue.clone) {
  51177. this._originalBlendValue = originalValue.clone();
  51178. }
  51179. else {
  51180. this._originalBlendValue = originalValue;
  51181. }
  51182. }
  51183. if (this._originalBlendValue.m) { // Matrix
  51184. if (BABYLON.Animation.AllowMatrixDecomposeForInterpolation) {
  51185. if (this._currentValue) {
  51186. BABYLON.Matrix.DecomposeLerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51187. }
  51188. else {
  51189. this._currentValue = BABYLON.Matrix.DecomposeLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51190. }
  51191. }
  51192. else {
  51193. if (this._currentValue) {
  51194. BABYLON.Matrix.LerpToRef(this._originalBlendValue, currentValue, this._blendingFactor, this._currentValue);
  51195. }
  51196. else {
  51197. this._currentValue = BABYLON.Matrix.Lerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51198. }
  51199. }
  51200. }
  51201. else {
  51202. this._currentValue = BABYLON.Animation._UniversalLerp(this._originalBlendValue, currentValue, this._blendingFactor);
  51203. }
  51204. var blendingSpeed = target && target.animationPropertiesOverride ? target.animationPropertiesOverride.blendingSpeed : this._animation.blendingSpeed;
  51205. this._blendingFactor += blendingSpeed;
  51206. }
  51207. else {
  51208. this._currentValue = currentValue;
  51209. }
  51210. if (weight !== -1.0) {
  51211. this._scene._registerTargetForLateAnimationBinding(this, this._originalValue[targetIndex]);
  51212. }
  51213. else {
  51214. destination[path] = this._currentValue;
  51215. }
  51216. if (target.markAsDirty) {
  51217. target.markAsDirty(this._animation.targetProperty);
  51218. }
  51219. };
  51220. /**
  51221. * Gets the loop pmode of the runtime animation
  51222. * @returns Loop Mode
  51223. */
  51224. RuntimeAnimation.prototype._getCorrectLoopMode = function () {
  51225. if (this._target && this._target.animationPropertiesOverride) {
  51226. return this._target.animationPropertiesOverride.loopMode;
  51227. }
  51228. return this._animation.loopMode;
  51229. };
  51230. /**
  51231. * Move the current animation to a given frame
  51232. * @param frame defines the frame to move to
  51233. */
  51234. RuntimeAnimation.prototype.goToFrame = function (frame) {
  51235. var keys = this._animation.getKeys();
  51236. if (frame < keys[0].frame) {
  51237. frame = keys[0].frame;
  51238. }
  51239. else if (frame > keys[keys.length - 1].frame) {
  51240. frame = keys[keys.length - 1].frame;
  51241. }
  51242. var currentValue = this._interpolate(frame, 0, this._getCorrectLoopMode());
  51243. this.setValue(currentValue, -1);
  51244. };
  51245. /**
  51246. * @hidden Internal use only
  51247. */
  51248. RuntimeAnimation.prototype._prepareForSpeedRatioChange = function (newSpeedRatio) {
  51249. var newRatio = this._previousDelay * (this._animation.framePerSecond * newSpeedRatio) / 1000.0;
  51250. this._ratioOffset = this._previousRatio - newRatio;
  51251. };
  51252. /**
  51253. * Execute the current animation
  51254. * @param delay defines the delay to add to the current frame
  51255. * @param from defines the lower bound of the animation range
  51256. * @param to defines the upper bound of the animation range
  51257. * @param loop defines if the current animation must loop
  51258. * @param speedRatio defines the current speed ratio
  51259. * @param weight defines the weight of the animation (default is -1 so no weight)
  51260. * @returns a boolean indicating if the animation has ended
  51261. */
  51262. RuntimeAnimation.prototype.animate = function (delay, from, to, loop, speedRatio, weight) {
  51263. if (weight === void 0) { weight = -1.0; }
  51264. var targetPropertyPath = this._animation.targetPropertyPath;
  51265. if (!targetPropertyPath || targetPropertyPath.length < 1) {
  51266. this._stopped = true;
  51267. return false;
  51268. }
  51269. var keys = this._animation.getKeys();
  51270. // Return immediately if there is only one key frame.
  51271. if (keys.length === 1) {
  51272. this.setValue(keys[0].value, weight);
  51273. return !loop;
  51274. }
  51275. var returnValue = true;
  51276. // Adding a start key at frame 0 if missing
  51277. if (keys[0].frame !== 0) {
  51278. var newKey = { frame: 0, value: keys[0].value };
  51279. keys.splice(0, 0, newKey);
  51280. }
  51281. // Check limits
  51282. if (from < keys[0].frame || from > keys[keys.length - 1].frame) {
  51283. from = keys[0].frame;
  51284. }
  51285. if (to < keys[0].frame || to > keys[keys.length - 1].frame) {
  51286. to = keys[keys.length - 1].frame;
  51287. }
  51288. //to and from cannot be the same key
  51289. if (from === to) {
  51290. if (from > keys[0].frame) {
  51291. from--;
  51292. }
  51293. else if (to < keys[keys.length - 1].frame) {
  51294. to++;
  51295. }
  51296. }
  51297. // Compute ratio
  51298. var range = to - from;
  51299. var offsetValue;
  51300. // ratio represents the frame delta between from and to
  51301. var ratio = (delay * (this._animation.framePerSecond * speedRatio) / 1000.0) + this._ratioOffset;
  51302. var highLimitValue = 0;
  51303. this._previousDelay = delay;
  51304. this._previousRatio = ratio;
  51305. if (((to > from && ratio >= range) || (from > to && ratio <= range)) && !loop) { // If we are out of range and not looping get back to caller
  51306. returnValue = false;
  51307. highLimitValue = this._animation._getKeyValue(keys[keys.length - 1].value);
  51308. }
  51309. else {
  51310. // Get max value if required
  51311. if (this._getCorrectLoopMode() !== BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE) {
  51312. var keyOffset = to.toString() + from.toString();
  51313. if (!this._offsetsCache[keyOffset]) {
  51314. var fromValue = this._interpolate(from, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51315. var toValue = this._interpolate(to, 0, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  51316. switch (this._animation.dataType) {
  51317. // Float
  51318. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51319. this._offsetsCache[keyOffset] = toValue - fromValue;
  51320. break;
  51321. // Quaternion
  51322. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51323. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51324. break;
  51325. // Vector3
  51326. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51327. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51328. // Vector2
  51329. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51330. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51331. // Size
  51332. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51333. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51334. // Color3
  51335. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51336. this._offsetsCache[keyOffset] = toValue.subtract(fromValue);
  51337. default:
  51338. break;
  51339. }
  51340. this._highLimitsCache[keyOffset] = toValue;
  51341. }
  51342. highLimitValue = this._highLimitsCache[keyOffset];
  51343. offsetValue = this._offsetsCache[keyOffset];
  51344. }
  51345. }
  51346. if (offsetValue === undefined) {
  51347. switch (this._animation.dataType) {
  51348. // Float
  51349. case BABYLON.Animation.ANIMATIONTYPE_FLOAT:
  51350. offsetValue = 0;
  51351. break;
  51352. // Quaternion
  51353. case BABYLON.Animation.ANIMATIONTYPE_QUATERNION:
  51354. offsetValue = new BABYLON.Quaternion(0, 0, 0, 0);
  51355. break;
  51356. // Vector3
  51357. case BABYLON.Animation.ANIMATIONTYPE_VECTOR3:
  51358. offsetValue = BABYLON.Vector3.Zero();
  51359. break;
  51360. // Vector2
  51361. case BABYLON.Animation.ANIMATIONTYPE_VECTOR2:
  51362. offsetValue = BABYLON.Vector2.Zero();
  51363. break;
  51364. // Size
  51365. case BABYLON.Animation.ANIMATIONTYPE_SIZE:
  51366. offsetValue = BABYLON.Size.Zero();
  51367. break;
  51368. // Color3
  51369. case BABYLON.Animation.ANIMATIONTYPE_COLOR3:
  51370. offsetValue = BABYLON.Color3.Black();
  51371. }
  51372. }
  51373. // Compute value
  51374. var repeatCount = (ratio / range) >> 0;
  51375. var currentFrame = returnValue ? from + ratio % range : to;
  51376. // Need to normalize?
  51377. if (this._host && this._host.syncRoot) {
  51378. var syncRoot = this._host.syncRoot;
  51379. var hostNormalizedFrame = (syncRoot.masterFrame - syncRoot.fromFrame) / (syncRoot.toFrame - syncRoot.fromFrame);
  51380. currentFrame = from + (to - from) * hostNormalizedFrame;
  51381. }
  51382. // Reset events if looping
  51383. var events = this._events;
  51384. if (range > 0 && this.currentFrame > currentFrame ||
  51385. range < 0 && this.currentFrame < currentFrame) {
  51386. // Need to reset animation events
  51387. for (var index = 0; index < events.length; index++) {
  51388. if (!events[index].onlyOnce) {
  51389. // reset event, the animation is looping
  51390. events[index].isDone = false;
  51391. }
  51392. }
  51393. }
  51394. var currentValue = this._interpolate(currentFrame, repeatCount, this._getCorrectLoopMode(), offsetValue, highLimitValue);
  51395. // Set value
  51396. this.setValue(currentValue, weight);
  51397. // Check events
  51398. for (var index = 0; index < events.length; index++) {
  51399. // Make sure current frame has passed event frame and that event frame is within the current range
  51400. // Also, handle both forward and reverse animations
  51401. if ((range > 0 && currentFrame >= events[index].frame && events[index].frame >= from) ||
  51402. (range < 0 && currentFrame <= events[index].frame && events[index].frame <= from)) {
  51403. var event = events[index];
  51404. if (!event.isDone) {
  51405. // If event should be done only once, remove it.
  51406. if (event.onlyOnce) {
  51407. events.splice(index, 1);
  51408. index--;
  51409. }
  51410. event.isDone = true;
  51411. event.action();
  51412. } // Don't do anything if the event has already be done.
  51413. }
  51414. }
  51415. if (!returnValue) {
  51416. this._stopped = true;
  51417. }
  51418. return returnValue;
  51419. };
  51420. return RuntimeAnimation;
  51421. }());
  51422. BABYLON.RuntimeAnimation = RuntimeAnimation;
  51423. })(BABYLON || (BABYLON = {}));
  51424. //# sourceMappingURL=babylon.runtimeAnimation.js.map
  51425. var BABYLON;
  51426. (function (BABYLON) {
  51427. var Animatable = /** @class */ (function () {
  51428. function Animatable(scene, target, fromFrame, toFrame, loopAnimation, speedRatio, onAnimationEnd, animations) {
  51429. if (fromFrame === void 0) { fromFrame = 0; }
  51430. if (toFrame === void 0) { toFrame = 100; }
  51431. if (loopAnimation === void 0) { loopAnimation = false; }
  51432. if (speedRatio === void 0) { speedRatio = 1.0; }
  51433. this.target = target;
  51434. this.fromFrame = fromFrame;
  51435. this.toFrame = toFrame;
  51436. this.loopAnimation = loopAnimation;
  51437. this.onAnimationEnd = onAnimationEnd;
  51438. this._localDelayOffset = null;
  51439. this._pausedDelay = null;
  51440. this._runtimeAnimations = new Array();
  51441. this._paused = false;
  51442. this._speedRatio = 1;
  51443. this._weight = -1.0;
  51444. this.animationStarted = false;
  51445. /**
  51446. * Observer raised when the animation ends
  51447. */
  51448. this.onAnimationEndObservable = new BABYLON.Observable();
  51449. this._scene = scene;
  51450. if (animations) {
  51451. this.appendAnimations(target, animations);
  51452. }
  51453. this._speedRatio = speedRatio;
  51454. scene._activeAnimatables.push(this);
  51455. }
  51456. Object.defineProperty(Animatable.prototype, "syncRoot", {
  51457. /**
  51458. * Gets the root Animatable used to synchronize and normalize animations
  51459. */
  51460. get: function () {
  51461. return this._syncRoot;
  51462. },
  51463. enumerable: true,
  51464. configurable: true
  51465. });
  51466. Object.defineProperty(Animatable.prototype, "masterFrame", {
  51467. /**
  51468. * Gets the current frame of the first RuntimeAnimation
  51469. * Used to synchronize Animatables
  51470. */
  51471. get: function () {
  51472. if (this._runtimeAnimations.length === 0) {
  51473. return 0;
  51474. }
  51475. return this._runtimeAnimations[0].currentFrame;
  51476. },
  51477. enumerable: true,
  51478. configurable: true
  51479. });
  51480. Object.defineProperty(Animatable.prototype, "weight", {
  51481. /**
  51482. * Gets or sets the animatable weight (-1.0 by default meaning not weighted)
  51483. */
  51484. get: function () {
  51485. return this._weight;
  51486. },
  51487. set: function (value) {
  51488. if (value === -1) { // -1 is ok and means no weight
  51489. this._weight = -1;
  51490. return;
  51491. }
  51492. // Else weight must be in [0, 1] range
  51493. this._weight = Math.min(Math.max(value, 0), 1.0);
  51494. },
  51495. enumerable: true,
  51496. configurable: true
  51497. });
  51498. Object.defineProperty(Animatable.prototype, "speedRatio", {
  51499. /**
  51500. * Gets or sets the speed ratio to apply to the animatable (1.0 by default)
  51501. */
  51502. get: function () {
  51503. return this._speedRatio;
  51504. },
  51505. set: function (value) {
  51506. for (var index = 0; index < this._runtimeAnimations.length; index++) {
  51507. var animation = this._runtimeAnimations[index];
  51508. animation._prepareForSpeedRatioChange(value);
  51509. }
  51510. this._speedRatio = value;
  51511. },
  51512. enumerable: true,
  51513. configurable: true
  51514. });
  51515. // Methods
  51516. /**
  51517. * Synchronize and normalize current Animatable with a source Animatable
  51518. * This is useful when using animation weights and when animations are not of the same length
  51519. * @param root defines the root Animatable to synchronize with
  51520. * @returns the current Animatable
  51521. */
  51522. Animatable.prototype.syncWith = function (root) {
  51523. this._syncRoot = root;
  51524. if (root) {
  51525. // Make sure this animatable will animate after the root
  51526. var index = this._scene._activeAnimatables.indexOf(this);
  51527. if (index > -1) {
  51528. this._scene._activeAnimatables.splice(index, 1);
  51529. this._scene._activeAnimatables.push(this);
  51530. }
  51531. }
  51532. return this;
  51533. };
  51534. Animatable.prototype.getAnimations = function () {
  51535. return this._runtimeAnimations;
  51536. };
  51537. Animatable.prototype.appendAnimations = function (target, animations) {
  51538. for (var index = 0; index < animations.length; index++) {
  51539. var animation = animations[index];
  51540. this._runtimeAnimations.push(new BABYLON.RuntimeAnimation(target, animation, this._scene, this));
  51541. }
  51542. };
  51543. Animatable.prototype.getAnimationByTargetProperty = function (property) {
  51544. var runtimeAnimations = this._runtimeAnimations;
  51545. for (var index = 0; index < runtimeAnimations.length; index++) {
  51546. if (runtimeAnimations[index].animation.targetProperty === property) {
  51547. return runtimeAnimations[index].animation;
  51548. }
  51549. }
  51550. return null;
  51551. };
  51552. Animatable.prototype.getRuntimeAnimationByTargetProperty = function (property) {
  51553. var runtimeAnimations = this._runtimeAnimations;
  51554. for (var index = 0; index < runtimeAnimations.length; index++) {
  51555. if (runtimeAnimations[index].animation.targetProperty === property) {
  51556. return runtimeAnimations[index];
  51557. }
  51558. }
  51559. return null;
  51560. };
  51561. Animatable.prototype.reset = function () {
  51562. var runtimeAnimations = this._runtimeAnimations;
  51563. for (var index = 0; index < runtimeAnimations.length; index++) {
  51564. runtimeAnimations[index].reset(true);
  51565. }
  51566. this._localDelayOffset = null;
  51567. this._pausedDelay = null;
  51568. };
  51569. Animatable.prototype.enableBlending = function (blendingSpeed) {
  51570. var runtimeAnimations = this._runtimeAnimations;
  51571. for (var index = 0; index < runtimeAnimations.length; index++) {
  51572. runtimeAnimations[index].animation.enableBlending = true;
  51573. runtimeAnimations[index].animation.blendingSpeed = blendingSpeed;
  51574. }
  51575. };
  51576. Animatable.prototype.disableBlending = function () {
  51577. var runtimeAnimations = this._runtimeAnimations;
  51578. for (var index = 0; index < runtimeAnimations.length; index++) {
  51579. runtimeAnimations[index].animation.enableBlending = false;
  51580. }
  51581. };
  51582. Animatable.prototype.goToFrame = function (frame) {
  51583. var runtimeAnimations = this._runtimeAnimations;
  51584. if (runtimeAnimations[0]) {
  51585. var fps = runtimeAnimations[0].animation.framePerSecond;
  51586. var currentFrame = runtimeAnimations[0].currentFrame;
  51587. var adjustTime = frame - currentFrame;
  51588. var delay = adjustTime * 1000 / (fps * this.speedRatio);
  51589. if (this._localDelayOffset === null) {
  51590. this._localDelayOffset = 0;
  51591. }
  51592. this._localDelayOffset -= delay;
  51593. }
  51594. for (var index = 0; index < runtimeAnimations.length; index++) {
  51595. runtimeAnimations[index].goToFrame(frame);
  51596. }
  51597. };
  51598. Animatable.prototype.pause = function () {
  51599. if (this._paused) {
  51600. return;
  51601. }
  51602. this._paused = true;
  51603. };
  51604. Animatable.prototype.restart = function () {
  51605. this._paused = false;
  51606. };
  51607. Animatable.prototype._raiseOnAnimationEnd = function () {
  51608. if (this.onAnimationEnd) {
  51609. this.onAnimationEnd();
  51610. }
  51611. this.onAnimationEndObservable.notifyObservers(this);
  51612. };
  51613. Animatable.prototype.stop = function (animationName) {
  51614. if (animationName) {
  51615. var idx = this._scene._activeAnimatables.indexOf(this);
  51616. if (idx > -1) {
  51617. var runtimeAnimations = this._runtimeAnimations;
  51618. for (var index = runtimeAnimations.length - 1; index >= 0; index--) {
  51619. if (typeof animationName === "string" && runtimeAnimations[index].animation.name != animationName) {
  51620. continue;
  51621. }
  51622. runtimeAnimations[index].dispose();
  51623. runtimeAnimations.splice(index, 1);
  51624. }
  51625. if (runtimeAnimations.length == 0) {
  51626. this._scene._activeAnimatables.splice(idx, 1);
  51627. this._raiseOnAnimationEnd();
  51628. }
  51629. }
  51630. }
  51631. else {
  51632. var index = this._scene._activeAnimatables.indexOf(this);
  51633. if (index > -1) {
  51634. this._scene._activeAnimatables.splice(index, 1);
  51635. var runtimeAnimations = this._runtimeAnimations;
  51636. for (var index = 0; index < runtimeAnimations.length; index++) {
  51637. runtimeAnimations[index].dispose();
  51638. }
  51639. this._raiseOnAnimationEnd();
  51640. }
  51641. }
  51642. };
  51643. /**
  51644. * Wait asynchronously for the animation to end
  51645. * @returns a promise which will be fullfilled when the animation ends
  51646. */
  51647. Animatable.prototype.waitAsync = function () {
  51648. var _this = this;
  51649. return new Promise(function (resolve, reject) {
  51650. _this.onAnimationEndObservable.add(function () {
  51651. resolve(_this);
  51652. }, undefined, undefined, _this, true);
  51653. });
  51654. };
  51655. /** @hidden */
  51656. Animatable.prototype._animate = function (delay) {
  51657. if (this._paused) {
  51658. this.animationStarted = false;
  51659. if (this._pausedDelay === null) {
  51660. this._pausedDelay = delay;
  51661. }
  51662. return true;
  51663. }
  51664. if (this._localDelayOffset === null) {
  51665. this._localDelayOffset = delay;
  51666. this._pausedDelay = null;
  51667. }
  51668. else if (this._pausedDelay !== null) {
  51669. this._localDelayOffset += delay - this._pausedDelay;
  51670. this._pausedDelay = null;
  51671. }
  51672. if (this._weight === 0) { // We consider that an animation with a weight === 0 is "actively" paused
  51673. return true;
  51674. }
  51675. // Animating
  51676. var running = false;
  51677. var runtimeAnimations = this._runtimeAnimations;
  51678. var index;
  51679. for (index = 0; index < runtimeAnimations.length; index++) {
  51680. var animation = runtimeAnimations[index];
  51681. var isRunning = animation.animate(delay - this._localDelayOffset, this.fromFrame, this.toFrame, this.loopAnimation, this._speedRatio, this._weight);
  51682. running = running || isRunning;
  51683. }
  51684. this.animationStarted = running;
  51685. if (!running) {
  51686. // Remove from active animatables
  51687. index = this._scene._activeAnimatables.indexOf(this);
  51688. this._scene._activeAnimatables.splice(index, 1);
  51689. // Dispose all runtime animations
  51690. for (index = 0; index < runtimeAnimations.length; index++) {
  51691. runtimeAnimations[index].dispose();
  51692. }
  51693. this._raiseOnAnimationEnd();
  51694. this.onAnimationEnd = null;
  51695. this.onAnimationEndObservable.clear();
  51696. }
  51697. return running;
  51698. };
  51699. return Animatable;
  51700. }());
  51701. BABYLON.Animatable = Animatable;
  51702. })(BABYLON || (BABYLON = {}));
  51703. //# sourceMappingURL=babylon.animatable.js.map
  51704. var BABYLON;
  51705. (function (BABYLON) {
  51706. var EasingFunction = /** @class */ (function () {
  51707. function EasingFunction() {
  51708. // Properties
  51709. this._easingMode = EasingFunction.EASINGMODE_EASEIN;
  51710. }
  51711. Object.defineProperty(EasingFunction, "EASINGMODE_EASEIN", {
  51712. get: function () {
  51713. return EasingFunction._EASINGMODE_EASEIN;
  51714. },
  51715. enumerable: true,
  51716. configurable: true
  51717. });
  51718. Object.defineProperty(EasingFunction, "EASINGMODE_EASEOUT", {
  51719. get: function () {
  51720. return EasingFunction._EASINGMODE_EASEOUT;
  51721. },
  51722. enumerable: true,
  51723. configurable: true
  51724. });
  51725. Object.defineProperty(EasingFunction, "EASINGMODE_EASEINOUT", {
  51726. get: function () {
  51727. return EasingFunction._EASINGMODE_EASEINOUT;
  51728. },
  51729. enumerable: true,
  51730. configurable: true
  51731. });
  51732. EasingFunction.prototype.setEasingMode = function (easingMode) {
  51733. var n = Math.min(Math.max(easingMode, 0), 2);
  51734. this._easingMode = n;
  51735. };
  51736. EasingFunction.prototype.getEasingMode = function () {
  51737. return this._easingMode;
  51738. };
  51739. EasingFunction.prototype.easeInCore = function (gradient) {
  51740. throw new Error('You must implement this method');
  51741. };
  51742. EasingFunction.prototype.ease = function (gradient) {
  51743. switch (this._easingMode) {
  51744. case EasingFunction.EASINGMODE_EASEIN:
  51745. return this.easeInCore(gradient);
  51746. case EasingFunction.EASINGMODE_EASEOUT:
  51747. return (1 - this.easeInCore(1 - gradient));
  51748. }
  51749. if (gradient >= 0.5) {
  51750. return (((1 - this.easeInCore((1 - gradient) * 2)) * 0.5) + 0.5);
  51751. }
  51752. return (this.easeInCore(gradient * 2) * 0.5);
  51753. };
  51754. //Statics
  51755. EasingFunction._EASINGMODE_EASEIN = 0;
  51756. EasingFunction._EASINGMODE_EASEOUT = 1;
  51757. EasingFunction._EASINGMODE_EASEINOUT = 2;
  51758. return EasingFunction;
  51759. }());
  51760. BABYLON.EasingFunction = EasingFunction;
  51761. var CircleEase = /** @class */ (function (_super) {
  51762. __extends(CircleEase, _super);
  51763. function CircleEase() {
  51764. return _super !== null && _super.apply(this, arguments) || this;
  51765. }
  51766. CircleEase.prototype.easeInCore = function (gradient) {
  51767. gradient = Math.max(0, Math.min(1, gradient));
  51768. return (1.0 - Math.sqrt(1.0 - (gradient * gradient)));
  51769. };
  51770. return CircleEase;
  51771. }(EasingFunction));
  51772. BABYLON.CircleEase = CircleEase;
  51773. var BackEase = /** @class */ (function (_super) {
  51774. __extends(BackEase, _super);
  51775. function BackEase(amplitude) {
  51776. if (amplitude === void 0) { amplitude = 1; }
  51777. var _this = _super.call(this) || this;
  51778. _this.amplitude = amplitude;
  51779. return _this;
  51780. }
  51781. BackEase.prototype.easeInCore = function (gradient) {
  51782. var num = Math.max(0, this.amplitude);
  51783. return (Math.pow(gradient, 3.0) - ((gradient * num) * Math.sin(3.1415926535897931 * gradient)));
  51784. };
  51785. return BackEase;
  51786. }(EasingFunction));
  51787. BABYLON.BackEase = BackEase;
  51788. var BounceEase = /** @class */ (function (_super) {
  51789. __extends(BounceEase, _super);
  51790. function BounceEase(bounces, bounciness) {
  51791. if (bounces === void 0) { bounces = 3; }
  51792. if (bounciness === void 0) { bounciness = 2; }
  51793. var _this = _super.call(this) || this;
  51794. _this.bounces = bounces;
  51795. _this.bounciness = bounciness;
  51796. return _this;
  51797. }
  51798. BounceEase.prototype.easeInCore = function (gradient) {
  51799. var y = Math.max(0.0, this.bounces);
  51800. var bounciness = this.bounciness;
  51801. if (bounciness <= 1.0) {
  51802. bounciness = 1.001;
  51803. }
  51804. var num9 = Math.pow(bounciness, y);
  51805. var num5 = 1.0 - bounciness;
  51806. var num4 = ((1.0 - num9) / num5) + (num9 * 0.5);
  51807. var num15 = gradient * num4;
  51808. var num65 = Math.log((-num15 * (1.0 - bounciness)) + 1.0) / Math.log(bounciness);
  51809. var num3 = Math.floor(num65);
  51810. var num13 = num3 + 1.0;
  51811. var num8 = (1.0 - Math.pow(bounciness, num3)) / (num5 * num4);
  51812. var num12 = (1.0 - Math.pow(bounciness, num13)) / (num5 * num4);
  51813. var num7 = (num8 + num12) * 0.5;
  51814. var num6 = gradient - num7;
  51815. var num2 = num7 - num8;
  51816. return (((-Math.pow(1.0 / bounciness, y - num3) / (num2 * num2)) * (num6 - num2)) * (num6 + num2));
  51817. };
  51818. return BounceEase;
  51819. }(EasingFunction));
  51820. BABYLON.BounceEase = BounceEase;
  51821. var CubicEase = /** @class */ (function (_super) {
  51822. __extends(CubicEase, _super);
  51823. function CubicEase() {
  51824. return _super !== null && _super.apply(this, arguments) || this;
  51825. }
  51826. CubicEase.prototype.easeInCore = function (gradient) {
  51827. return (gradient * gradient * gradient);
  51828. };
  51829. return CubicEase;
  51830. }(EasingFunction));
  51831. BABYLON.CubicEase = CubicEase;
  51832. var ElasticEase = /** @class */ (function (_super) {
  51833. __extends(ElasticEase, _super);
  51834. function ElasticEase(oscillations, springiness) {
  51835. if (oscillations === void 0) { oscillations = 3; }
  51836. if (springiness === void 0) { springiness = 3; }
  51837. var _this = _super.call(this) || this;
  51838. _this.oscillations = oscillations;
  51839. _this.springiness = springiness;
  51840. return _this;
  51841. }
  51842. ElasticEase.prototype.easeInCore = function (gradient) {
  51843. var num2;
  51844. var num3 = Math.max(0.0, this.oscillations);
  51845. var num = Math.max(0.0, this.springiness);
  51846. if (num == 0) {
  51847. num2 = gradient;
  51848. }
  51849. else {
  51850. num2 = (Math.exp(num * gradient) - 1.0) / (Math.exp(num) - 1.0);
  51851. }
  51852. return (num2 * Math.sin(((6.2831853071795862 * num3) + 1.5707963267948966) * gradient));
  51853. };
  51854. return ElasticEase;
  51855. }(EasingFunction));
  51856. BABYLON.ElasticEase = ElasticEase;
  51857. var ExponentialEase = /** @class */ (function (_super) {
  51858. __extends(ExponentialEase, _super);
  51859. function ExponentialEase(exponent) {
  51860. if (exponent === void 0) { exponent = 2; }
  51861. var _this = _super.call(this) || this;
  51862. _this.exponent = exponent;
  51863. return _this;
  51864. }
  51865. ExponentialEase.prototype.easeInCore = function (gradient) {
  51866. if (this.exponent <= 0) {
  51867. return gradient;
  51868. }
  51869. return ((Math.exp(this.exponent * gradient) - 1.0) / (Math.exp(this.exponent) - 1.0));
  51870. };
  51871. return ExponentialEase;
  51872. }(EasingFunction));
  51873. BABYLON.ExponentialEase = ExponentialEase;
  51874. var PowerEase = /** @class */ (function (_super) {
  51875. __extends(PowerEase, _super);
  51876. function PowerEase(power) {
  51877. if (power === void 0) { power = 2; }
  51878. var _this = _super.call(this) || this;
  51879. _this.power = power;
  51880. return _this;
  51881. }
  51882. PowerEase.prototype.easeInCore = function (gradient) {
  51883. var y = Math.max(0.0, this.power);
  51884. return Math.pow(gradient, y);
  51885. };
  51886. return PowerEase;
  51887. }(EasingFunction));
  51888. BABYLON.PowerEase = PowerEase;
  51889. var QuadraticEase = /** @class */ (function (_super) {
  51890. __extends(QuadraticEase, _super);
  51891. function QuadraticEase() {
  51892. return _super !== null && _super.apply(this, arguments) || this;
  51893. }
  51894. QuadraticEase.prototype.easeInCore = function (gradient) {
  51895. return (gradient * gradient);
  51896. };
  51897. return QuadraticEase;
  51898. }(EasingFunction));
  51899. BABYLON.QuadraticEase = QuadraticEase;
  51900. var QuarticEase = /** @class */ (function (_super) {
  51901. __extends(QuarticEase, _super);
  51902. function QuarticEase() {
  51903. return _super !== null && _super.apply(this, arguments) || this;
  51904. }
  51905. QuarticEase.prototype.easeInCore = function (gradient) {
  51906. return (gradient * gradient * gradient * gradient);
  51907. };
  51908. return QuarticEase;
  51909. }(EasingFunction));
  51910. BABYLON.QuarticEase = QuarticEase;
  51911. var QuinticEase = /** @class */ (function (_super) {
  51912. __extends(QuinticEase, _super);
  51913. function QuinticEase() {
  51914. return _super !== null && _super.apply(this, arguments) || this;
  51915. }
  51916. QuinticEase.prototype.easeInCore = function (gradient) {
  51917. return (gradient * gradient * gradient * gradient * gradient);
  51918. };
  51919. return QuinticEase;
  51920. }(EasingFunction));
  51921. BABYLON.QuinticEase = QuinticEase;
  51922. var SineEase = /** @class */ (function (_super) {
  51923. __extends(SineEase, _super);
  51924. function SineEase() {
  51925. return _super !== null && _super.apply(this, arguments) || this;
  51926. }
  51927. SineEase.prototype.easeInCore = function (gradient) {
  51928. return (1.0 - Math.sin(1.5707963267948966 * (1.0 - gradient)));
  51929. };
  51930. return SineEase;
  51931. }(EasingFunction));
  51932. BABYLON.SineEase = SineEase;
  51933. var BezierCurveEase = /** @class */ (function (_super) {
  51934. __extends(BezierCurveEase, _super);
  51935. function BezierCurveEase(x1, y1, x2, y2) {
  51936. if (x1 === void 0) { x1 = 0; }
  51937. if (y1 === void 0) { y1 = 0; }
  51938. if (x2 === void 0) { x2 = 1; }
  51939. if (y2 === void 0) { y2 = 1; }
  51940. var _this = _super.call(this) || this;
  51941. _this.x1 = x1;
  51942. _this.y1 = y1;
  51943. _this.x2 = x2;
  51944. _this.y2 = y2;
  51945. return _this;
  51946. }
  51947. BezierCurveEase.prototype.easeInCore = function (gradient) {
  51948. return BABYLON.BezierCurve.interpolate(gradient, this.x1, this.y1, this.x2, this.y2);
  51949. };
  51950. return BezierCurveEase;
  51951. }(EasingFunction));
  51952. BABYLON.BezierCurveEase = BezierCurveEase;
  51953. })(BABYLON || (BABYLON = {}));
  51954. //# sourceMappingURL=babylon.easing.js.map
  51955. var BABYLON;
  51956. (function (BABYLON) {
  51957. /**
  51958. * A Condition applied to an Action
  51959. */
  51960. var Condition = /** @class */ (function () {
  51961. /**
  51962. * Creates a new Condition
  51963. * @param actionManager the manager of the action the condition is applied to
  51964. */
  51965. function Condition(actionManager) {
  51966. this._actionManager = actionManager;
  51967. }
  51968. /**
  51969. * Check if the current condition is valid
  51970. * @returns a boolean
  51971. */
  51972. Condition.prototype.isValid = function () {
  51973. return true;
  51974. };
  51975. /**
  51976. * Internal only
  51977. * @hidden
  51978. */
  51979. Condition.prototype._getProperty = function (propertyPath) {
  51980. return this._actionManager._getProperty(propertyPath);
  51981. };
  51982. /**
  51983. * Internal only
  51984. * @hidden
  51985. */
  51986. Condition.prototype._getEffectiveTarget = function (target, propertyPath) {
  51987. return this._actionManager._getEffectiveTarget(target, propertyPath);
  51988. };
  51989. /**
  51990. * Serialize placeholder for child classes
  51991. * @returns the serialized object
  51992. */
  51993. Condition.prototype.serialize = function () {
  51994. };
  51995. /**
  51996. * Internal only
  51997. * @hidden
  51998. */
  51999. Condition.prototype._serialize = function (serializedCondition) {
  52000. return {
  52001. type: 2,
  52002. children: [],
  52003. name: serializedCondition.name,
  52004. properties: serializedCondition.properties
  52005. };
  52006. };
  52007. return Condition;
  52008. }());
  52009. BABYLON.Condition = Condition;
  52010. /**
  52011. * Defines specific conditional operators as extensions of Condition
  52012. */
  52013. var ValueCondition = /** @class */ (function (_super) {
  52014. __extends(ValueCondition, _super);
  52015. /**
  52016. * Creates a new ValueCondition
  52017. * @param actionManager manager for the action the condition applies to
  52018. * @param target for the action
  52019. * @param propertyPath path to specify the property of the target the conditional operator uses
  52020. * @param value the value compared by the conditional operator against the current value of the property
  52021. * @param operator the conditional operator, default ValueCondition.IsEqual
  52022. */
  52023. function ValueCondition(actionManager, target,
  52024. /** path to specify the property of the target the conditional operator uses */
  52025. propertyPath,
  52026. /** the value compared by the conditional operator against the current value of the property */
  52027. value,
  52028. /** the conditional operator, default ValueCondition.IsEqual */
  52029. operator) {
  52030. if (operator === void 0) { operator = ValueCondition.IsEqual; }
  52031. var _this = _super.call(this, actionManager) || this;
  52032. _this.propertyPath = propertyPath;
  52033. _this.value = value;
  52034. _this.operator = operator;
  52035. _this._target = target;
  52036. _this._effectiveTarget = _this._getEffectiveTarget(target, _this.propertyPath);
  52037. _this._property = _this._getProperty(_this.propertyPath);
  52038. return _this;
  52039. }
  52040. Object.defineProperty(ValueCondition, "IsEqual", {
  52041. /**
  52042. * returns the number for IsEqual
  52043. */
  52044. get: function () {
  52045. return ValueCondition._IsEqual;
  52046. },
  52047. enumerable: true,
  52048. configurable: true
  52049. });
  52050. Object.defineProperty(ValueCondition, "IsDifferent", {
  52051. /**
  52052. * Returns the number for IsDifferent
  52053. */
  52054. get: function () {
  52055. return ValueCondition._IsDifferent;
  52056. },
  52057. enumerable: true,
  52058. configurable: true
  52059. });
  52060. Object.defineProperty(ValueCondition, "IsGreater", {
  52061. /**
  52062. * Returns the number for IsGreater
  52063. */
  52064. get: function () {
  52065. return ValueCondition._IsGreater;
  52066. },
  52067. enumerable: true,
  52068. configurable: true
  52069. });
  52070. Object.defineProperty(ValueCondition, "IsLesser", {
  52071. /**
  52072. * Returns the number for IsLesser
  52073. */
  52074. get: function () {
  52075. return ValueCondition._IsLesser;
  52076. },
  52077. enumerable: true,
  52078. configurable: true
  52079. });
  52080. /**
  52081. * Compares the given value with the property value for the specified conditional operator
  52082. * @returns the result of the comparison
  52083. */
  52084. ValueCondition.prototype.isValid = function () {
  52085. switch (this.operator) {
  52086. case ValueCondition.IsGreater:
  52087. return this._effectiveTarget[this._property] > this.value;
  52088. case ValueCondition.IsLesser:
  52089. return this._effectiveTarget[this._property] < this.value;
  52090. case ValueCondition.IsEqual:
  52091. case ValueCondition.IsDifferent:
  52092. var check;
  52093. if (this.value.equals) {
  52094. check = this.value.equals(this._effectiveTarget[this._property]);
  52095. }
  52096. else {
  52097. check = this.value === this._effectiveTarget[this._property];
  52098. }
  52099. return this.operator === ValueCondition.IsEqual ? check : !check;
  52100. }
  52101. return false;
  52102. };
  52103. /**
  52104. * Serialize the ValueCondition into a JSON compatible object
  52105. * @returns serialization object
  52106. */
  52107. ValueCondition.prototype.serialize = function () {
  52108. return this._serialize({
  52109. name: "ValueCondition",
  52110. properties: [
  52111. BABYLON.Action._GetTargetProperty(this._target),
  52112. { name: "propertyPath", value: this.propertyPath },
  52113. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  52114. { name: "operator", value: ValueCondition.GetOperatorName(this.operator) }
  52115. ]
  52116. });
  52117. };
  52118. /**
  52119. * Gets the name of the conditional operator for the ValueCondition
  52120. * @param operator the conditional operator
  52121. * @returns the name
  52122. */
  52123. ValueCondition.GetOperatorName = function (operator) {
  52124. switch (operator) {
  52125. case ValueCondition._IsEqual: return "IsEqual";
  52126. case ValueCondition._IsDifferent: return "IsDifferent";
  52127. case ValueCondition._IsGreater: return "IsGreater";
  52128. case ValueCondition._IsLesser: return "IsLesser";
  52129. default: return "";
  52130. }
  52131. };
  52132. /**
  52133. * Internal only
  52134. * @hidden
  52135. */
  52136. ValueCondition._IsEqual = 0;
  52137. /**
  52138. * Internal only
  52139. * @hidden
  52140. */
  52141. ValueCondition._IsDifferent = 1;
  52142. /**
  52143. * Internal only
  52144. * @hidden
  52145. */
  52146. ValueCondition._IsGreater = 2;
  52147. /**
  52148. * Internal only
  52149. * @hidden
  52150. */
  52151. ValueCondition._IsLesser = 3;
  52152. return ValueCondition;
  52153. }(Condition));
  52154. BABYLON.ValueCondition = ValueCondition;
  52155. /**
  52156. * Defines a predicate condition as an extension of Condition
  52157. */
  52158. var PredicateCondition = /** @class */ (function (_super) {
  52159. __extends(PredicateCondition, _super);
  52160. /**
  52161. * Creates a new PredicateCondition
  52162. * @param actionManager manager for the action the condition applies to
  52163. * @param predicate defines the predicate function used to validate the condition
  52164. */
  52165. function PredicateCondition(actionManager,
  52166. /** defines the predicate function used to validate the condition */
  52167. predicate) {
  52168. var _this = _super.call(this, actionManager) || this;
  52169. _this.predicate = predicate;
  52170. return _this;
  52171. }
  52172. /**
  52173. * @returns the validity of the predicate condition
  52174. */
  52175. PredicateCondition.prototype.isValid = function () {
  52176. return this.predicate();
  52177. };
  52178. return PredicateCondition;
  52179. }(Condition));
  52180. BABYLON.PredicateCondition = PredicateCondition;
  52181. /**
  52182. * Defines a state condition as an extension of Condition
  52183. */
  52184. var StateCondition = /** @class */ (function (_super) {
  52185. __extends(StateCondition, _super);
  52186. /**
  52187. * Creates a new StateCondition
  52188. * @param actionManager manager for the action the condition applies to
  52189. * @param target of the condition
  52190. * @param value to compare with target state
  52191. */
  52192. function StateCondition(actionManager, target, value) {
  52193. var _this = _super.call(this, actionManager) || this;
  52194. _this.value = value;
  52195. _this._target = target;
  52196. return _this;
  52197. }
  52198. /**
  52199. * @returns the validity of the state
  52200. */
  52201. StateCondition.prototype.isValid = function () {
  52202. return this._target.state === this.value;
  52203. };
  52204. /**
  52205. * Serialize the StateCondition into a JSON compatible object
  52206. * @returns serialization object
  52207. */
  52208. StateCondition.prototype.serialize = function () {
  52209. return this._serialize({
  52210. name: "StateCondition",
  52211. properties: [
  52212. BABYLON.Action._GetTargetProperty(this._target),
  52213. { name: "value", value: this.value }
  52214. ]
  52215. });
  52216. };
  52217. return StateCondition;
  52218. }(Condition));
  52219. BABYLON.StateCondition = StateCondition;
  52220. })(BABYLON || (BABYLON = {}));
  52221. //# sourceMappingURL=babylon.condition.js.map
  52222. var BABYLON;
  52223. (function (BABYLON) {
  52224. /**
  52225. * The action to be carried out following a trigger
  52226. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#available-actions
  52227. */
  52228. var Action = /** @class */ (function () {
  52229. /**
  52230. * Creates a new Action
  52231. * @param triggerOptions the trigger, with or without parameters, for the action
  52232. * @param condition an optional determinant of action
  52233. */
  52234. function Action(
  52235. /** the trigger, with or without parameters, for the action */
  52236. triggerOptions, condition) {
  52237. this.triggerOptions = triggerOptions;
  52238. /**
  52239. * An event triggered prior to action being executed.
  52240. */
  52241. this.onBeforeExecuteObservable = new BABYLON.Observable();
  52242. if (triggerOptions.parameter) {
  52243. this.trigger = triggerOptions.trigger;
  52244. this._triggerParameter = triggerOptions.parameter;
  52245. }
  52246. else {
  52247. this.trigger = triggerOptions;
  52248. }
  52249. this._nextActiveAction = this;
  52250. this._condition = condition;
  52251. }
  52252. /**
  52253. * Internal only
  52254. * @hidden
  52255. */
  52256. Action.prototype._prepare = function () {
  52257. };
  52258. /**
  52259. * Gets the trigger parameters
  52260. * @returns the trigger parameters
  52261. */
  52262. Action.prototype.getTriggerParameter = function () {
  52263. return this._triggerParameter;
  52264. };
  52265. /**
  52266. * Internal only - executes current action event
  52267. * @hidden
  52268. */
  52269. Action.prototype._executeCurrent = function (evt) {
  52270. if (this._nextActiveAction._condition) {
  52271. var condition = this._nextActiveAction._condition;
  52272. var currentRenderId = this._actionManager.getScene().getRenderId();
  52273. // We cache the current evaluation for the current frame
  52274. if (condition._evaluationId === currentRenderId) {
  52275. if (!condition._currentResult) {
  52276. return;
  52277. }
  52278. }
  52279. else {
  52280. condition._evaluationId = currentRenderId;
  52281. if (!condition.isValid()) {
  52282. condition._currentResult = false;
  52283. return;
  52284. }
  52285. condition._currentResult = true;
  52286. }
  52287. }
  52288. this.onBeforeExecuteObservable.notifyObservers(this);
  52289. this._nextActiveAction.execute(evt);
  52290. this.skipToNextActiveAction();
  52291. };
  52292. /**
  52293. * Execute placeholder for child classes
  52294. * @param evt optional action event
  52295. */
  52296. Action.prototype.execute = function (evt) {
  52297. };
  52298. /**
  52299. * Skips to next active action
  52300. */
  52301. Action.prototype.skipToNextActiveAction = function () {
  52302. if (this._nextActiveAction._child) {
  52303. if (!this._nextActiveAction._child._actionManager) {
  52304. this._nextActiveAction._child._actionManager = this._actionManager;
  52305. }
  52306. this._nextActiveAction = this._nextActiveAction._child;
  52307. }
  52308. else {
  52309. this._nextActiveAction = this;
  52310. }
  52311. };
  52312. /**
  52313. * Adds action to chain of actions, may be a DoNothingAction
  52314. * @param action defines the next action to execute
  52315. * @returns The action passed in
  52316. * @see https://www.babylonjs-playground.com/#1T30HR#0
  52317. */
  52318. Action.prototype.then = function (action) {
  52319. this._child = action;
  52320. action._actionManager = this._actionManager;
  52321. action._prepare();
  52322. return action;
  52323. };
  52324. /**
  52325. * Internal only
  52326. * @hidden
  52327. */
  52328. Action.prototype._getProperty = function (propertyPath) {
  52329. return this._actionManager._getProperty(propertyPath);
  52330. };
  52331. /**
  52332. * Internal only
  52333. * @hidden
  52334. */
  52335. Action.prototype._getEffectiveTarget = function (target, propertyPath) {
  52336. return this._actionManager._getEffectiveTarget(target, propertyPath);
  52337. };
  52338. /**
  52339. * Serialize placeholder for child classes
  52340. * @param parent of child
  52341. * @returns the serialized object
  52342. */
  52343. Action.prototype.serialize = function (parent) {
  52344. };
  52345. /**
  52346. * Internal only called by serialize
  52347. * @hidden
  52348. */
  52349. Action.prototype._serialize = function (serializedAction, parent) {
  52350. var serializationObject = {
  52351. type: 1,
  52352. children: [],
  52353. name: serializedAction.name,
  52354. properties: serializedAction.properties || []
  52355. };
  52356. // Serialize child
  52357. if (this._child) {
  52358. this._child.serialize(serializationObject);
  52359. }
  52360. // Check if "this" has a condition
  52361. if (this._condition) {
  52362. var serializedCondition = this._condition.serialize();
  52363. serializedCondition.children.push(serializationObject);
  52364. if (parent) {
  52365. parent.children.push(serializedCondition);
  52366. }
  52367. return serializedCondition;
  52368. }
  52369. if (parent) {
  52370. parent.children.push(serializationObject);
  52371. }
  52372. return serializationObject;
  52373. };
  52374. /**
  52375. * Internal only
  52376. * @hidden
  52377. */
  52378. Action._SerializeValueAsString = function (value) {
  52379. if (typeof value === "number") {
  52380. return value.toString();
  52381. }
  52382. if (typeof value === "boolean") {
  52383. return value ? "true" : "false";
  52384. }
  52385. if (value instanceof BABYLON.Vector2) {
  52386. return value.x + ", " + value.y;
  52387. }
  52388. if (value instanceof BABYLON.Vector3) {
  52389. return value.x + ", " + value.y + ", " + value.z;
  52390. }
  52391. if (value instanceof BABYLON.Color3) {
  52392. return value.r + ", " + value.g + ", " + value.b;
  52393. }
  52394. if (value instanceof BABYLON.Color4) {
  52395. return value.r + ", " + value.g + ", " + value.b + ", " + value.a;
  52396. }
  52397. return value; // string
  52398. };
  52399. /**
  52400. * Internal only
  52401. * @hidden
  52402. */
  52403. Action._GetTargetProperty = function (target) {
  52404. return {
  52405. name: "target",
  52406. targetType: target instanceof BABYLON.Mesh ? "MeshProperties"
  52407. : target instanceof BABYLON.Light ? "LightProperties"
  52408. : target instanceof BABYLON.Camera ? "CameraProperties"
  52409. : "SceneProperties",
  52410. value: target instanceof BABYLON.Scene ? "Scene" : target.name
  52411. };
  52412. };
  52413. return Action;
  52414. }());
  52415. BABYLON.Action = Action;
  52416. })(BABYLON || (BABYLON = {}));
  52417. //# sourceMappingURL=babylon.action.js.map
  52418. var BABYLON;
  52419. (function (BABYLON) {
  52420. /**
  52421. * ActionEvent is the event being sent when an action is triggered.
  52422. */
  52423. var ActionEvent = /** @class */ (function () {
  52424. /**
  52425. * Creates a new ActionEvent
  52426. * @param source The mesh or sprite that triggered the action
  52427. * @param pointerX The X mouse cursor position at the time of the event
  52428. * @param pointerY The Y mouse cursor position at the time of the event
  52429. * @param meshUnderPointer The mesh that is currently pointed at (can be null)
  52430. * @param sourceEvent the original (browser) event that triggered the ActionEvent
  52431. * @param additionalData additional data for the event
  52432. */
  52433. function ActionEvent(
  52434. /** The mesh or sprite that triggered the action */
  52435. source,
  52436. /** The X mouse cursor position at the time of the event */
  52437. pointerX,
  52438. /** The Y mouse cursor position at the time of the event */
  52439. pointerY,
  52440. /** The mesh that is currently pointed at (can be null) */
  52441. meshUnderPointer,
  52442. /** the original (browser) event that triggered the ActionEvent */
  52443. sourceEvent,
  52444. /** additional data for the event */
  52445. additionalData) {
  52446. this.source = source;
  52447. this.pointerX = pointerX;
  52448. this.pointerY = pointerY;
  52449. this.meshUnderPointer = meshUnderPointer;
  52450. this.sourceEvent = sourceEvent;
  52451. this.additionalData = additionalData;
  52452. }
  52453. /**
  52454. * Helper function to auto-create an ActionEvent from a source mesh.
  52455. * @param source The source mesh that triggered the event
  52456. * @param evt The original (browser) event
  52457. * @param additionalData additional data for the event
  52458. * @returns the new ActionEvent
  52459. */
  52460. ActionEvent.CreateNew = function (source, evt, additionalData) {
  52461. var scene = source.getScene();
  52462. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52463. };
  52464. /**
  52465. * Helper function to auto-create an ActionEvent from a source sprite
  52466. * @param source The source sprite that triggered the event
  52467. * @param scene Scene associated with the sprite
  52468. * @param evt The original (browser) event
  52469. * @param additionalData additional data for the event
  52470. * @returns the new ActionEvent
  52471. */
  52472. ActionEvent.CreateNewFromSprite = function (source, scene, evt, additionalData) {
  52473. return new ActionEvent(source, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt, additionalData);
  52474. };
  52475. /**
  52476. * Helper function to auto-create an ActionEvent from a scene. If triggered by a mesh use ActionEvent.CreateNew
  52477. * @param scene the scene where the event occurred
  52478. * @param evt The original (browser) event
  52479. * @returns the new ActionEvent
  52480. */
  52481. ActionEvent.CreateNewFromScene = function (scene, evt) {
  52482. return new ActionEvent(null, scene.pointerX, scene.pointerY, scene.meshUnderPointer, evt);
  52483. };
  52484. /**
  52485. * Helper function to auto-create an ActionEvent from a primitive
  52486. * @param prim defines the target primitive
  52487. * @param pointerPos defines the pointer position
  52488. * @param evt The original (browser) event
  52489. * @param additionalData additional data for the event
  52490. * @returns the new ActionEvent
  52491. */
  52492. ActionEvent.CreateNewFromPrimitive = function (prim, pointerPos, evt, additionalData) {
  52493. return new ActionEvent(prim, pointerPos.x, pointerPos.y, null, evt, additionalData);
  52494. };
  52495. return ActionEvent;
  52496. }());
  52497. BABYLON.ActionEvent = ActionEvent;
  52498. /**
  52499. * Action Manager manages all events to be triggered on a given mesh or the global scene.
  52500. * A single scene can have many Action Managers to handle predefined actions on specific meshes.
  52501. * @see http://doc.babylonjs.com/how_to/how_to_use_actions
  52502. */
  52503. var ActionManager = /** @class */ (function () {
  52504. /**
  52505. * Creates a new action manager
  52506. * @param scene defines the hosting scene
  52507. */
  52508. function ActionManager(scene) {
  52509. // Members
  52510. /** Gets the list of actions */
  52511. this.actions = new Array();
  52512. /** Gets the cursor to use when hovering items */
  52513. this.hoverCursor = '';
  52514. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  52515. scene._actionManagers.push(this);
  52516. }
  52517. Object.defineProperty(ActionManager, "NothingTrigger", {
  52518. /**
  52519. * Nothing
  52520. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52521. */
  52522. get: function () {
  52523. return ActionManager._NothingTrigger;
  52524. },
  52525. enumerable: true,
  52526. configurable: true
  52527. });
  52528. Object.defineProperty(ActionManager, "OnPickTrigger", {
  52529. /**
  52530. * On pick
  52531. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52532. */
  52533. get: function () {
  52534. return ActionManager._OnPickTrigger;
  52535. },
  52536. enumerable: true,
  52537. configurable: true
  52538. });
  52539. Object.defineProperty(ActionManager, "OnLeftPickTrigger", {
  52540. /**
  52541. * On left pick
  52542. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52543. */
  52544. get: function () {
  52545. return ActionManager._OnLeftPickTrigger;
  52546. },
  52547. enumerable: true,
  52548. configurable: true
  52549. });
  52550. Object.defineProperty(ActionManager, "OnRightPickTrigger", {
  52551. /**
  52552. * On right pick
  52553. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52554. */
  52555. get: function () {
  52556. return ActionManager._OnRightPickTrigger;
  52557. },
  52558. enumerable: true,
  52559. configurable: true
  52560. });
  52561. Object.defineProperty(ActionManager, "OnCenterPickTrigger", {
  52562. /**
  52563. * On center pick
  52564. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52565. */
  52566. get: function () {
  52567. return ActionManager._OnCenterPickTrigger;
  52568. },
  52569. enumerable: true,
  52570. configurable: true
  52571. });
  52572. Object.defineProperty(ActionManager, "OnPickDownTrigger", {
  52573. /**
  52574. * On pick down
  52575. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52576. */
  52577. get: function () {
  52578. return ActionManager._OnPickDownTrigger;
  52579. },
  52580. enumerable: true,
  52581. configurable: true
  52582. });
  52583. Object.defineProperty(ActionManager, "OnDoublePickTrigger", {
  52584. /**
  52585. * On double pick
  52586. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52587. */
  52588. get: function () {
  52589. return ActionManager._OnDoublePickTrigger;
  52590. },
  52591. enumerable: true,
  52592. configurable: true
  52593. });
  52594. Object.defineProperty(ActionManager, "OnPickUpTrigger", {
  52595. /**
  52596. * On pick up
  52597. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52598. */
  52599. get: function () {
  52600. return ActionManager._OnPickUpTrigger;
  52601. },
  52602. enumerable: true,
  52603. configurable: true
  52604. });
  52605. Object.defineProperty(ActionManager, "OnPickOutTrigger", {
  52606. /**
  52607. * On pick out.
  52608. * This trigger will only be raised if you also declared a OnPickDown
  52609. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52610. */
  52611. get: function () {
  52612. return ActionManager._OnPickOutTrigger;
  52613. },
  52614. enumerable: true,
  52615. configurable: true
  52616. });
  52617. Object.defineProperty(ActionManager, "OnLongPressTrigger", {
  52618. /**
  52619. * On long press
  52620. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52621. */
  52622. get: function () {
  52623. return ActionManager._OnLongPressTrigger;
  52624. },
  52625. enumerable: true,
  52626. configurable: true
  52627. });
  52628. Object.defineProperty(ActionManager, "OnPointerOverTrigger", {
  52629. /**
  52630. * On pointer over
  52631. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52632. */
  52633. get: function () {
  52634. return ActionManager._OnPointerOverTrigger;
  52635. },
  52636. enumerable: true,
  52637. configurable: true
  52638. });
  52639. Object.defineProperty(ActionManager, "OnPointerOutTrigger", {
  52640. /**
  52641. * On pointer out
  52642. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52643. */
  52644. get: function () {
  52645. return ActionManager._OnPointerOutTrigger;
  52646. },
  52647. enumerable: true,
  52648. configurable: true
  52649. });
  52650. Object.defineProperty(ActionManager, "OnEveryFrameTrigger", {
  52651. /**
  52652. * On every frame
  52653. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52654. */
  52655. get: function () {
  52656. return ActionManager._OnEveryFrameTrigger;
  52657. },
  52658. enumerable: true,
  52659. configurable: true
  52660. });
  52661. Object.defineProperty(ActionManager, "OnIntersectionEnterTrigger", {
  52662. /**
  52663. * On intersection enter
  52664. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52665. */
  52666. get: function () {
  52667. return ActionManager._OnIntersectionEnterTrigger;
  52668. },
  52669. enumerable: true,
  52670. configurable: true
  52671. });
  52672. Object.defineProperty(ActionManager, "OnIntersectionExitTrigger", {
  52673. /**
  52674. * On intersection exit
  52675. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52676. */
  52677. get: function () {
  52678. return ActionManager._OnIntersectionExitTrigger;
  52679. },
  52680. enumerable: true,
  52681. configurable: true
  52682. });
  52683. Object.defineProperty(ActionManager, "OnKeyDownTrigger", {
  52684. /**
  52685. * On key down
  52686. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52687. */
  52688. get: function () {
  52689. return ActionManager._OnKeyDownTrigger;
  52690. },
  52691. enumerable: true,
  52692. configurable: true
  52693. });
  52694. Object.defineProperty(ActionManager, "OnKeyUpTrigger", {
  52695. /**
  52696. * On key up
  52697. * @see http://doc.babylonjs.com/how_to/how_to_use_actions#triggers
  52698. */
  52699. get: function () {
  52700. return ActionManager._OnKeyUpTrigger;
  52701. },
  52702. enumerable: true,
  52703. configurable: true
  52704. });
  52705. // Methods
  52706. /**
  52707. * Releases all associated resources
  52708. */
  52709. ActionManager.prototype.dispose = function () {
  52710. var index = this._scene._actionManagers.indexOf(this);
  52711. for (var i = 0; i < this.actions.length; i++) {
  52712. var action = this.actions[i];
  52713. ActionManager.Triggers[action.trigger]--;
  52714. if (ActionManager.Triggers[action.trigger] === 0) {
  52715. delete ActionManager.Triggers[action.trigger];
  52716. }
  52717. }
  52718. if (index > -1) {
  52719. this._scene._actionManagers.splice(index, 1);
  52720. }
  52721. };
  52722. /**
  52723. * Gets hosting scene
  52724. * @returns the hosting scene
  52725. */
  52726. ActionManager.prototype.getScene = function () {
  52727. return this._scene;
  52728. };
  52729. /**
  52730. * Does this action manager handles actions of any of the given triggers
  52731. * @param triggers defines the triggers to be tested
  52732. * @return a boolean indicating whether one (or more) of the triggers is handled
  52733. */
  52734. ActionManager.prototype.hasSpecificTriggers = function (triggers) {
  52735. for (var index = 0; index < this.actions.length; index++) {
  52736. var action = this.actions[index];
  52737. if (triggers.indexOf(action.trigger) > -1) {
  52738. return true;
  52739. }
  52740. }
  52741. return false;
  52742. };
  52743. /**
  52744. * Does this action manager handles actions of a given trigger
  52745. * @param trigger defines the trigger to be tested
  52746. * @param parameterPredicate defines an optional predicate to filter triggers by parameter
  52747. * @return whether the trigger is handled
  52748. */
  52749. ActionManager.prototype.hasSpecificTrigger = function (trigger, parameterPredicate) {
  52750. for (var index = 0; index < this.actions.length; index++) {
  52751. var action = this.actions[index];
  52752. if (action.trigger === trigger) {
  52753. if (parameterPredicate) {
  52754. if (parameterPredicate(action.getTriggerParameter())) {
  52755. return true;
  52756. }
  52757. }
  52758. else {
  52759. return true;
  52760. }
  52761. }
  52762. }
  52763. return false;
  52764. };
  52765. Object.defineProperty(ActionManager.prototype, "hasPointerTriggers", {
  52766. /**
  52767. * Does this action manager has pointer triggers
  52768. */
  52769. get: function () {
  52770. for (var index = 0; index < this.actions.length; index++) {
  52771. var action = this.actions[index];
  52772. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPointerOutTrigger) {
  52773. return true;
  52774. }
  52775. }
  52776. return false;
  52777. },
  52778. enumerable: true,
  52779. configurable: true
  52780. });
  52781. Object.defineProperty(ActionManager.prototype, "hasPickTriggers", {
  52782. /**
  52783. * Does this action manager has pick triggers
  52784. */
  52785. get: function () {
  52786. for (var index = 0; index < this.actions.length; index++) {
  52787. var action = this.actions[index];
  52788. if (action.trigger >= ActionManager._OnPickTrigger && action.trigger <= ActionManager._OnPickUpTrigger) {
  52789. return true;
  52790. }
  52791. }
  52792. return false;
  52793. },
  52794. enumerable: true,
  52795. configurable: true
  52796. });
  52797. Object.defineProperty(ActionManager, "HasTriggers", {
  52798. /**
  52799. * Does exist one action manager with at least one trigger
  52800. **/
  52801. get: function () {
  52802. for (var t in ActionManager.Triggers) {
  52803. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52804. return true;
  52805. }
  52806. }
  52807. return false;
  52808. },
  52809. enumerable: true,
  52810. configurable: true
  52811. });
  52812. Object.defineProperty(ActionManager, "HasPickTriggers", {
  52813. /**
  52814. * Does exist one action manager with at least one pick trigger
  52815. **/
  52816. get: function () {
  52817. for (var t in ActionManager.Triggers) {
  52818. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52819. var t_int = parseInt(t);
  52820. if (t_int >= ActionManager._OnPickTrigger && t_int <= ActionManager._OnPickUpTrigger) {
  52821. return true;
  52822. }
  52823. }
  52824. }
  52825. return false;
  52826. },
  52827. enumerable: true,
  52828. configurable: true
  52829. });
  52830. /**
  52831. * Does exist one action manager that handles actions of a given trigger
  52832. * @param trigger defines the trigger to be tested
  52833. * @return a boolean indicating whether the trigger is handeled by at least one action manager
  52834. **/
  52835. ActionManager.HasSpecificTrigger = function (trigger) {
  52836. for (var t in ActionManager.Triggers) {
  52837. if (ActionManager.Triggers.hasOwnProperty(t)) {
  52838. var t_int = parseInt(t);
  52839. if (t_int === trigger) {
  52840. return true;
  52841. }
  52842. }
  52843. }
  52844. return false;
  52845. };
  52846. /**
  52847. * Registers an action to this action manager
  52848. * @param action defines the action to be registered
  52849. * @return the action amended (prepared) after registration
  52850. */
  52851. ActionManager.prototype.registerAction = function (action) {
  52852. if (action.trigger === ActionManager.OnEveryFrameTrigger) {
  52853. if (this.getScene().actionManager !== this) {
  52854. BABYLON.Tools.Warn("OnEveryFrameTrigger can only be used with scene.actionManager");
  52855. return null;
  52856. }
  52857. }
  52858. this.actions.push(action);
  52859. if (ActionManager.Triggers[action.trigger]) {
  52860. ActionManager.Triggers[action.trigger]++;
  52861. }
  52862. else {
  52863. ActionManager.Triggers[action.trigger] = 1;
  52864. }
  52865. action._actionManager = this;
  52866. action._prepare();
  52867. return action;
  52868. };
  52869. /**
  52870. * Unregisters an action to this action manager
  52871. * @param action defines the action to be unregistered
  52872. * @return a boolean indicating whether the action has been unregistered
  52873. */
  52874. ActionManager.prototype.unregisterAction = function (action) {
  52875. var index = this.actions.indexOf(action);
  52876. if (index !== -1) {
  52877. this.actions.splice(index, 1);
  52878. ActionManager.Triggers[action.trigger] -= 1;
  52879. if (ActionManager.Triggers[action.trigger] === 0) {
  52880. delete ActionManager.Triggers[action.trigger];
  52881. }
  52882. delete action._actionManager;
  52883. return true;
  52884. }
  52885. return false;
  52886. };
  52887. /**
  52888. * Process a specific trigger
  52889. * @param trigger defines the trigger to process
  52890. * @param evt defines the event details to be processed
  52891. */
  52892. ActionManager.prototype.processTrigger = function (trigger, evt) {
  52893. for (var index = 0; index < this.actions.length; index++) {
  52894. var action = this.actions[index];
  52895. if (action.trigger === trigger) {
  52896. if (evt) {
  52897. if (trigger === ActionManager.OnKeyUpTrigger
  52898. || trigger === ActionManager.OnKeyDownTrigger) {
  52899. var parameter = action.getTriggerParameter();
  52900. if (parameter && parameter !== evt.sourceEvent.keyCode) {
  52901. if (!parameter.toLowerCase) {
  52902. continue;
  52903. }
  52904. var lowerCase = parameter.toLowerCase();
  52905. if (lowerCase !== evt.sourceEvent.key) {
  52906. var unicode = evt.sourceEvent.charCode ? evt.sourceEvent.charCode : evt.sourceEvent.keyCode;
  52907. var actualkey = String.fromCharCode(unicode).toLowerCase();
  52908. if (actualkey !== lowerCase) {
  52909. continue;
  52910. }
  52911. }
  52912. }
  52913. }
  52914. }
  52915. action._executeCurrent(evt);
  52916. }
  52917. }
  52918. };
  52919. /** @hidden */
  52920. ActionManager.prototype._getEffectiveTarget = function (target, propertyPath) {
  52921. var properties = propertyPath.split(".");
  52922. for (var index = 0; index < properties.length - 1; index++) {
  52923. target = target[properties[index]];
  52924. }
  52925. return target;
  52926. };
  52927. /** @hidden */
  52928. ActionManager.prototype._getProperty = function (propertyPath) {
  52929. var properties = propertyPath.split(".");
  52930. return properties[properties.length - 1];
  52931. };
  52932. /**
  52933. * Serialize this manager to a JSON object
  52934. * @param name defines the property name to store this manager
  52935. * @returns a JSON representation of this manager
  52936. */
  52937. ActionManager.prototype.serialize = function (name) {
  52938. var root = {
  52939. children: new Array(),
  52940. name: name,
  52941. type: 3,
  52942. properties: new Array() // Empty for root but required
  52943. };
  52944. for (var i = 0; i < this.actions.length; i++) {
  52945. var triggerObject = {
  52946. type: 0,
  52947. children: new Array(),
  52948. name: ActionManager.GetTriggerName(this.actions[i].trigger),
  52949. properties: new Array()
  52950. };
  52951. var triggerOptions = this.actions[i].triggerOptions;
  52952. if (triggerOptions && typeof triggerOptions !== "number") {
  52953. if (triggerOptions.parameter instanceof BABYLON.Node) {
  52954. triggerObject.properties.push(BABYLON.Action._GetTargetProperty(triggerOptions.parameter));
  52955. }
  52956. else {
  52957. var parameter = {};
  52958. BABYLON.Tools.DeepCopy(triggerOptions.parameter, parameter, ["mesh"]);
  52959. if (triggerOptions.parameter.mesh) {
  52960. parameter._meshId = triggerOptions.parameter.mesh.id;
  52961. }
  52962. triggerObject.properties.push({ name: "parameter", targetType: null, value: parameter });
  52963. }
  52964. }
  52965. // Serialize child action, recursively
  52966. this.actions[i].serialize(triggerObject);
  52967. // Add serialized trigger
  52968. root.children.push(triggerObject);
  52969. }
  52970. return root;
  52971. };
  52972. /**
  52973. * Creates a new ActionManager from a JSON data
  52974. * @param parsedActions defines the JSON data to read from
  52975. * @param object defines the hosting mesh
  52976. * @param scene defines the hosting scene
  52977. */
  52978. ActionManager.Parse = function (parsedActions, object, scene) {
  52979. var actionManager = new ActionManager(scene);
  52980. if (object === null)
  52981. scene.actionManager = actionManager;
  52982. else
  52983. object.actionManager = actionManager;
  52984. // instanciate a new object
  52985. var instanciate = function (name, params) {
  52986. // TODO: We will need to find a solution for the next line when using commonjs / es6 .
  52987. var newInstance = Object.create(BABYLON.Tools.Instantiate("BABYLON." + name).prototype);
  52988. newInstance.constructor.apply(newInstance, params);
  52989. return newInstance;
  52990. };
  52991. var parseParameter = function (name, value, target, propertyPath) {
  52992. if (propertyPath === null) {
  52993. // String, boolean or float
  52994. var floatValue = parseFloat(value);
  52995. if (value === "true" || value === "false")
  52996. return value === "true";
  52997. else
  52998. return isNaN(floatValue) ? value : floatValue;
  52999. }
  53000. var effectiveTarget = propertyPath.split(".");
  53001. var values = value.split(",");
  53002. // Get effective Target
  53003. for (var i = 0; i < effectiveTarget.length; i++) {
  53004. target = target[effectiveTarget[i]];
  53005. }
  53006. // Return appropriate value with its type
  53007. if (typeof (target) === "boolean")
  53008. return values[0] === "true";
  53009. if (typeof (target) === "string")
  53010. return values[0];
  53011. // Parameters with multiple values such as Vector3 etc.
  53012. var split = new Array();
  53013. for (var i = 0; i < values.length; i++)
  53014. split.push(parseFloat(values[i]));
  53015. if (target instanceof BABYLON.Vector3)
  53016. return BABYLON.Vector3.FromArray(split);
  53017. if (target instanceof BABYLON.Vector4)
  53018. return BABYLON.Vector4.FromArray(split);
  53019. if (target instanceof BABYLON.Color3)
  53020. return BABYLON.Color3.FromArray(split);
  53021. if (target instanceof BABYLON.Color4)
  53022. return BABYLON.Color4.FromArray(split);
  53023. return parseFloat(values[0]);
  53024. };
  53025. // traverse graph per trigger
  53026. var traverse = function (parsedAction, trigger, condition, action, combineArray) {
  53027. if (combineArray === void 0) { combineArray = null; }
  53028. if (parsedAction.detached)
  53029. return;
  53030. var parameters = new Array();
  53031. var target = null;
  53032. var propertyPath = null;
  53033. var combine = parsedAction.combine && parsedAction.combine.length > 0;
  53034. // Parameters
  53035. if (parsedAction.type === 2)
  53036. parameters.push(actionManager);
  53037. else
  53038. parameters.push(trigger);
  53039. if (combine) {
  53040. var actions = new Array();
  53041. for (var j = 0; j < parsedAction.combine.length; j++) {
  53042. traverse(parsedAction.combine[j], ActionManager.NothingTrigger, condition, action, actions);
  53043. }
  53044. parameters.push(actions);
  53045. }
  53046. else {
  53047. for (var i = 0; i < parsedAction.properties.length; i++) {
  53048. var value = parsedAction.properties[i].value;
  53049. var name = parsedAction.properties[i].name;
  53050. var targetType = parsedAction.properties[i].targetType;
  53051. if (name === "target")
  53052. if (targetType !== null && targetType === "SceneProperties")
  53053. value = target = scene;
  53054. else
  53055. value = target = scene.getNodeByName(value);
  53056. else if (name === "parent")
  53057. value = scene.getNodeByName(value);
  53058. else if (name === "sound")
  53059. value = scene.getSoundByName(value);
  53060. else if (name !== "propertyPath") {
  53061. if (parsedAction.type === 2 && name === "operator")
  53062. value = BABYLON.ValueCondition[value];
  53063. else
  53064. value = parseParameter(name, value, target, name === "value" ? propertyPath : null);
  53065. }
  53066. else {
  53067. propertyPath = value;
  53068. }
  53069. parameters.push(value);
  53070. }
  53071. }
  53072. if (combineArray === null) {
  53073. parameters.push(condition);
  53074. }
  53075. else {
  53076. parameters.push(null);
  53077. }
  53078. // If interpolate value action
  53079. if (parsedAction.name === "InterpolateValueAction") {
  53080. var param = parameters[parameters.length - 2];
  53081. parameters[parameters.length - 1] = param;
  53082. parameters[parameters.length - 2] = condition;
  53083. }
  53084. // Action or condition(s) and not CombineAction
  53085. var newAction = instanciate(parsedAction.name, parameters);
  53086. if (newAction instanceof BABYLON.Condition && condition !== null) {
  53087. var nothing = new BABYLON.DoNothingAction(trigger, condition);
  53088. if (action)
  53089. action.then(nothing);
  53090. else
  53091. actionManager.registerAction(nothing);
  53092. action = nothing;
  53093. }
  53094. if (combineArray === null) {
  53095. if (newAction instanceof BABYLON.Condition) {
  53096. condition = newAction;
  53097. newAction = action;
  53098. }
  53099. else {
  53100. condition = null;
  53101. if (action)
  53102. action.then(newAction);
  53103. else
  53104. actionManager.registerAction(newAction);
  53105. }
  53106. }
  53107. else {
  53108. combineArray.push(newAction);
  53109. }
  53110. for (var i = 0; i < parsedAction.children.length; i++)
  53111. traverse(parsedAction.children[i], trigger, condition, newAction, null);
  53112. };
  53113. // triggers
  53114. for (var i = 0; i < parsedActions.children.length; i++) {
  53115. var triggerParams;
  53116. var trigger = parsedActions.children[i];
  53117. if (trigger.properties.length > 0) {
  53118. var param = trigger.properties[0].value;
  53119. var value = trigger.properties[0].targetType === null ? param : scene.getMeshByName(param);
  53120. if (value._meshId) {
  53121. value.mesh = scene.getMeshByID(value._meshId);
  53122. }
  53123. triggerParams = { trigger: ActionManager[trigger.name], parameter: value };
  53124. }
  53125. else
  53126. triggerParams = ActionManager[trigger.name];
  53127. for (var j = 0; j < trigger.children.length; j++) {
  53128. if (!trigger.detached)
  53129. traverse(trigger.children[j], triggerParams, null, null);
  53130. }
  53131. }
  53132. };
  53133. /**
  53134. * Get a trigger name by index
  53135. * @param trigger defines the trigger index
  53136. * @returns a trigger name
  53137. */
  53138. ActionManager.GetTriggerName = function (trigger) {
  53139. switch (trigger) {
  53140. case 0: return "NothingTrigger";
  53141. case 1: return "OnPickTrigger";
  53142. case 2: return "OnLeftPickTrigger";
  53143. case 3: return "OnRightPickTrigger";
  53144. case 4: return "OnCenterPickTrigger";
  53145. case 5: return "OnPickDownTrigger";
  53146. case 6: return "OnPickUpTrigger";
  53147. case 7: return "OnLongPressTrigger";
  53148. case 8: return "OnPointerOverTrigger";
  53149. case 9: return "OnPointerOutTrigger";
  53150. case 10: return "OnEveryFrameTrigger";
  53151. case 11: return "OnIntersectionEnterTrigger";
  53152. case 12: return "OnIntersectionExitTrigger";
  53153. case 13: return "OnKeyDownTrigger";
  53154. case 14: return "OnKeyUpTrigger";
  53155. case 15: return "OnPickOutTrigger";
  53156. default: return "";
  53157. }
  53158. };
  53159. // Statics
  53160. ActionManager._NothingTrigger = 0;
  53161. ActionManager._OnPickTrigger = 1;
  53162. ActionManager._OnLeftPickTrigger = 2;
  53163. ActionManager._OnRightPickTrigger = 3;
  53164. ActionManager._OnCenterPickTrigger = 4;
  53165. ActionManager._OnPickDownTrigger = 5;
  53166. ActionManager._OnDoublePickTrigger = 6;
  53167. ActionManager._OnPickUpTrigger = 7;
  53168. ActionManager._OnLongPressTrigger = 8;
  53169. ActionManager._OnPointerOverTrigger = 9;
  53170. ActionManager._OnPointerOutTrigger = 10;
  53171. ActionManager._OnEveryFrameTrigger = 11;
  53172. ActionManager._OnIntersectionEnterTrigger = 12;
  53173. ActionManager._OnIntersectionExitTrigger = 13;
  53174. ActionManager._OnKeyDownTrigger = 14;
  53175. ActionManager._OnKeyUpTrigger = 15;
  53176. ActionManager._OnPickOutTrigger = 16;
  53177. /** Gets the list of active triggers */
  53178. ActionManager.Triggers = {};
  53179. return ActionManager;
  53180. }());
  53181. BABYLON.ActionManager = ActionManager;
  53182. })(BABYLON || (BABYLON = {}));
  53183. //# sourceMappingURL=babylon.actionManager.js.map
  53184. var BABYLON;
  53185. (function (BABYLON) {
  53186. var InterpolateValueAction = /** @class */ (function (_super) {
  53187. __extends(InterpolateValueAction, _super);
  53188. function InterpolateValueAction(triggerOptions, target, propertyPath, value, duration, condition, stopOtherAnimations, onInterpolationDone) {
  53189. if (duration === void 0) { duration = 1000; }
  53190. var _this = _super.call(this, triggerOptions, condition) || this;
  53191. _this.propertyPath = propertyPath;
  53192. _this.value = value;
  53193. _this.duration = duration;
  53194. _this.stopOtherAnimations = stopOtherAnimations;
  53195. _this.onInterpolationDone = onInterpolationDone;
  53196. _this.onInterpolationDoneObservable = new BABYLON.Observable();
  53197. _this._target = _this._effectiveTarget = target;
  53198. return _this;
  53199. }
  53200. InterpolateValueAction.prototype._prepare = function () {
  53201. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53202. this._property = this._getProperty(this.propertyPath);
  53203. };
  53204. InterpolateValueAction.prototype.execute = function () {
  53205. var _this = this;
  53206. var scene = this._actionManager.getScene();
  53207. var keys = [
  53208. {
  53209. frame: 0,
  53210. value: this._effectiveTarget[this._property]
  53211. }, {
  53212. frame: 100,
  53213. value: this.value
  53214. }
  53215. ];
  53216. var dataType;
  53217. if (typeof this.value === "number") {
  53218. dataType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  53219. }
  53220. else if (this.value instanceof BABYLON.Color3) {
  53221. dataType = BABYLON.Animation.ANIMATIONTYPE_COLOR3;
  53222. }
  53223. else if (this.value instanceof BABYLON.Vector3) {
  53224. dataType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  53225. }
  53226. else if (this.value instanceof BABYLON.Matrix) {
  53227. dataType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  53228. }
  53229. else if (this.value instanceof BABYLON.Quaternion) {
  53230. dataType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  53231. }
  53232. else {
  53233. BABYLON.Tools.Warn("InterpolateValueAction: Unsupported type (" + typeof this.value + ")");
  53234. return;
  53235. }
  53236. var animation = new BABYLON.Animation("InterpolateValueAction", this._property, 100 * (1000.0 / this.duration), dataType, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  53237. animation.setKeys(keys);
  53238. if (this.stopOtherAnimations) {
  53239. scene.stopAnimation(this._effectiveTarget);
  53240. }
  53241. var wrapper = function () {
  53242. _this.onInterpolationDoneObservable.notifyObservers(_this);
  53243. if (_this.onInterpolationDone) {
  53244. _this.onInterpolationDone();
  53245. }
  53246. };
  53247. scene.beginDirectAnimation(this._effectiveTarget, [animation], 0, 100, false, 1, wrapper);
  53248. };
  53249. InterpolateValueAction.prototype.serialize = function (parent) {
  53250. return _super.prototype._serialize.call(this, {
  53251. name: "InterpolateValueAction",
  53252. properties: [
  53253. BABYLON.Action._GetTargetProperty(this._target),
  53254. { name: "propertyPath", value: this.propertyPath },
  53255. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) },
  53256. { name: "duration", value: BABYLON.Action._SerializeValueAsString(this.duration) },
  53257. { name: "stopOtherAnimations", value: BABYLON.Action._SerializeValueAsString(this.stopOtherAnimations) || false }
  53258. ]
  53259. }, parent);
  53260. };
  53261. return InterpolateValueAction;
  53262. }(BABYLON.Action));
  53263. BABYLON.InterpolateValueAction = InterpolateValueAction;
  53264. })(BABYLON || (BABYLON = {}));
  53265. //# sourceMappingURL=babylon.interpolateValueAction.js.map
  53266. var BABYLON;
  53267. (function (BABYLON) {
  53268. var SwitchBooleanAction = /** @class */ (function (_super) {
  53269. __extends(SwitchBooleanAction, _super);
  53270. function SwitchBooleanAction(triggerOptions, target, propertyPath, condition) {
  53271. var _this = _super.call(this, triggerOptions, condition) || this;
  53272. _this.propertyPath = propertyPath;
  53273. _this._target = _this._effectiveTarget = target;
  53274. return _this;
  53275. }
  53276. SwitchBooleanAction.prototype._prepare = function () {
  53277. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53278. this._property = this._getProperty(this.propertyPath);
  53279. };
  53280. SwitchBooleanAction.prototype.execute = function () {
  53281. this._effectiveTarget[this._property] = !this._effectiveTarget[this._property];
  53282. };
  53283. SwitchBooleanAction.prototype.serialize = function (parent) {
  53284. return _super.prototype._serialize.call(this, {
  53285. name: "SwitchBooleanAction",
  53286. properties: [
  53287. BABYLON.Action._GetTargetProperty(this._target),
  53288. { name: "propertyPath", value: this.propertyPath }
  53289. ]
  53290. }, parent);
  53291. };
  53292. return SwitchBooleanAction;
  53293. }(BABYLON.Action));
  53294. BABYLON.SwitchBooleanAction = SwitchBooleanAction;
  53295. var SetStateAction = /** @class */ (function (_super) {
  53296. __extends(SetStateAction, _super);
  53297. function SetStateAction(triggerOptions, target, value, condition) {
  53298. var _this = _super.call(this, triggerOptions, condition) || this;
  53299. _this.value = value;
  53300. _this._target = target;
  53301. return _this;
  53302. }
  53303. SetStateAction.prototype.execute = function () {
  53304. this._target.state = this.value;
  53305. };
  53306. SetStateAction.prototype.serialize = function (parent) {
  53307. return _super.prototype._serialize.call(this, {
  53308. name: "SetStateAction",
  53309. properties: [
  53310. BABYLON.Action._GetTargetProperty(this._target),
  53311. { name: "value", value: this.value }
  53312. ]
  53313. }, parent);
  53314. };
  53315. return SetStateAction;
  53316. }(BABYLON.Action));
  53317. BABYLON.SetStateAction = SetStateAction;
  53318. var SetValueAction = /** @class */ (function (_super) {
  53319. __extends(SetValueAction, _super);
  53320. function SetValueAction(triggerOptions, target, propertyPath, value, condition) {
  53321. var _this = _super.call(this, triggerOptions, condition) || this;
  53322. _this.propertyPath = propertyPath;
  53323. _this.value = value;
  53324. _this._target = _this._effectiveTarget = target;
  53325. return _this;
  53326. }
  53327. SetValueAction.prototype._prepare = function () {
  53328. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53329. this._property = this._getProperty(this.propertyPath);
  53330. };
  53331. SetValueAction.prototype.execute = function () {
  53332. this._effectiveTarget[this._property] = this.value;
  53333. if (this._target.markAsDirty) {
  53334. this._target.markAsDirty(this._property);
  53335. }
  53336. };
  53337. SetValueAction.prototype.serialize = function (parent) {
  53338. return _super.prototype._serialize.call(this, {
  53339. name: "SetValueAction",
  53340. properties: [
  53341. BABYLON.Action._GetTargetProperty(this._target),
  53342. { name: "propertyPath", value: this.propertyPath },
  53343. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53344. ]
  53345. }, parent);
  53346. };
  53347. return SetValueAction;
  53348. }(BABYLON.Action));
  53349. BABYLON.SetValueAction = SetValueAction;
  53350. var IncrementValueAction = /** @class */ (function (_super) {
  53351. __extends(IncrementValueAction, _super);
  53352. function IncrementValueAction(triggerOptions, target, propertyPath, value, condition) {
  53353. var _this = _super.call(this, triggerOptions, condition) || this;
  53354. _this.propertyPath = propertyPath;
  53355. _this.value = value;
  53356. _this._target = _this._effectiveTarget = target;
  53357. return _this;
  53358. }
  53359. IncrementValueAction.prototype._prepare = function () {
  53360. this._effectiveTarget = this._getEffectiveTarget(this._effectiveTarget, this.propertyPath);
  53361. this._property = this._getProperty(this.propertyPath);
  53362. if (typeof this._effectiveTarget[this._property] !== "number") {
  53363. BABYLON.Tools.Warn("Warning: IncrementValueAction can only be used with number values");
  53364. }
  53365. };
  53366. IncrementValueAction.prototype.execute = function () {
  53367. this._effectiveTarget[this._property] += this.value;
  53368. if (this._target.markAsDirty) {
  53369. this._target.markAsDirty(this._property);
  53370. }
  53371. };
  53372. IncrementValueAction.prototype.serialize = function (parent) {
  53373. return _super.prototype._serialize.call(this, {
  53374. name: "IncrementValueAction",
  53375. properties: [
  53376. BABYLON.Action._GetTargetProperty(this._target),
  53377. { name: "propertyPath", value: this.propertyPath },
  53378. { name: "value", value: BABYLON.Action._SerializeValueAsString(this.value) }
  53379. ]
  53380. }, parent);
  53381. };
  53382. return IncrementValueAction;
  53383. }(BABYLON.Action));
  53384. BABYLON.IncrementValueAction = IncrementValueAction;
  53385. var PlayAnimationAction = /** @class */ (function (_super) {
  53386. __extends(PlayAnimationAction, _super);
  53387. function PlayAnimationAction(triggerOptions, target, from, to, loop, condition) {
  53388. var _this = _super.call(this, triggerOptions, condition) || this;
  53389. _this.from = from;
  53390. _this.to = to;
  53391. _this.loop = loop;
  53392. _this._target = target;
  53393. return _this;
  53394. }
  53395. PlayAnimationAction.prototype._prepare = function () {
  53396. };
  53397. PlayAnimationAction.prototype.execute = function () {
  53398. var scene = this._actionManager.getScene();
  53399. scene.beginAnimation(this._target, this.from, this.to, this.loop);
  53400. };
  53401. PlayAnimationAction.prototype.serialize = function (parent) {
  53402. return _super.prototype._serialize.call(this, {
  53403. name: "PlayAnimationAction",
  53404. properties: [
  53405. BABYLON.Action._GetTargetProperty(this._target),
  53406. { name: "from", value: String(this.from) },
  53407. { name: "to", value: String(this.to) },
  53408. { name: "loop", value: BABYLON.Action._SerializeValueAsString(this.loop) || false }
  53409. ]
  53410. }, parent);
  53411. };
  53412. return PlayAnimationAction;
  53413. }(BABYLON.Action));
  53414. BABYLON.PlayAnimationAction = PlayAnimationAction;
  53415. var StopAnimationAction = /** @class */ (function (_super) {
  53416. __extends(StopAnimationAction, _super);
  53417. function StopAnimationAction(triggerOptions, target, condition) {
  53418. var _this = _super.call(this, triggerOptions, condition) || this;
  53419. _this._target = target;
  53420. return _this;
  53421. }
  53422. StopAnimationAction.prototype._prepare = function () {
  53423. };
  53424. StopAnimationAction.prototype.execute = function () {
  53425. var scene = this._actionManager.getScene();
  53426. scene.stopAnimation(this._target);
  53427. };
  53428. StopAnimationAction.prototype.serialize = function (parent) {
  53429. return _super.prototype._serialize.call(this, {
  53430. name: "StopAnimationAction",
  53431. properties: [BABYLON.Action._GetTargetProperty(this._target)]
  53432. }, parent);
  53433. };
  53434. return StopAnimationAction;
  53435. }(BABYLON.Action));
  53436. BABYLON.StopAnimationAction = StopAnimationAction;
  53437. var DoNothingAction = /** @class */ (function (_super) {
  53438. __extends(DoNothingAction, _super);
  53439. function DoNothingAction(triggerOptions, condition) {
  53440. if (triggerOptions === void 0) { triggerOptions = BABYLON.ActionManager.NothingTrigger; }
  53441. return _super.call(this, triggerOptions, condition) || this;
  53442. }
  53443. DoNothingAction.prototype.execute = function () {
  53444. };
  53445. DoNothingAction.prototype.serialize = function (parent) {
  53446. return _super.prototype._serialize.call(this, {
  53447. name: "DoNothingAction",
  53448. properties: []
  53449. }, parent);
  53450. };
  53451. return DoNothingAction;
  53452. }(BABYLON.Action));
  53453. BABYLON.DoNothingAction = DoNothingAction;
  53454. var CombineAction = /** @class */ (function (_super) {
  53455. __extends(CombineAction, _super);
  53456. function CombineAction(triggerOptions, children, condition) {
  53457. var _this = _super.call(this, triggerOptions, condition) || this;
  53458. _this.children = children;
  53459. return _this;
  53460. }
  53461. CombineAction.prototype._prepare = function () {
  53462. for (var index = 0; index < this.children.length; index++) {
  53463. this.children[index]._actionManager = this._actionManager;
  53464. this.children[index]._prepare();
  53465. }
  53466. };
  53467. CombineAction.prototype.execute = function (evt) {
  53468. for (var index = 0; index < this.children.length; index++) {
  53469. this.children[index].execute(evt);
  53470. }
  53471. };
  53472. CombineAction.prototype.serialize = function (parent) {
  53473. var serializationObject = _super.prototype._serialize.call(this, {
  53474. name: "CombineAction",
  53475. properties: [],
  53476. combine: []
  53477. }, parent);
  53478. for (var i = 0; i < this.children.length; i++) {
  53479. serializationObject.combine.push(this.children[i].serialize(null));
  53480. }
  53481. return serializationObject;
  53482. };
  53483. return CombineAction;
  53484. }(BABYLON.Action));
  53485. BABYLON.CombineAction = CombineAction;
  53486. var ExecuteCodeAction = /** @class */ (function (_super) {
  53487. __extends(ExecuteCodeAction, _super);
  53488. function ExecuteCodeAction(triggerOptions, func, condition) {
  53489. var _this = _super.call(this, triggerOptions, condition) || this;
  53490. _this.func = func;
  53491. return _this;
  53492. }
  53493. ExecuteCodeAction.prototype.execute = function (evt) {
  53494. this.func(evt);
  53495. };
  53496. return ExecuteCodeAction;
  53497. }(BABYLON.Action));
  53498. BABYLON.ExecuteCodeAction = ExecuteCodeAction;
  53499. var SetParentAction = /** @class */ (function (_super) {
  53500. __extends(SetParentAction, _super);
  53501. function SetParentAction(triggerOptions, target, parent, condition) {
  53502. var _this = _super.call(this, triggerOptions, condition) || this;
  53503. _this._target = target;
  53504. _this._parent = parent;
  53505. return _this;
  53506. }
  53507. SetParentAction.prototype._prepare = function () {
  53508. };
  53509. SetParentAction.prototype.execute = function () {
  53510. if (this._target.parent === this._parent) {
  53511. return;
  53512. }
  53513. var invertParentWorldMatrix = this._parent.getWorldMatrix().clone();
  53514. invertParentWorldMatrix.invert();
  53515. this._target.position = BABYLON.Vector3.TransformCoordinates(this._target.position, invertParentWorldMatrix);
  53516. this._target.parent = this._parent;
  53517. };
  53518. SetParentAction.prototype.serialize = function (parent) {
  53519. return _super.prototype._serialize.call(this, {
  53520. name: "SetParentAction",
  53521. properties: [
  53522. BABYLON.Action._GetTargetProperty(this._target),
  53523. BABYLON.Action._GetTargetProperty(this._parent),
  53524. ]
  53525. }, parent);
  53526. };
  53527. return SetParentAction;
  53528. }(BABYLON.Action));
  53529. BABYLON.SetParentAction = SetParentAction;
  53530. var PlaySoundAction = /** @class */ (function (_super) {
  53531. __extends(PlaySoundAction, _super);
  53532. function PlaySoundAction(triggerOptions, sound, condition) {
  53533. var _this = _super.call(this, triggerOptions, condition) || this;
  53534. _this._sound = sound;
  53535. return _this;
  53536. }
  53537. PlaySoundAction.prototype._prepare = function () {
  53538. };
  53539. PlaySoundAction.prototype.execute = function () {
  53540. if (this._sound !== undefined)
  53541. this._sound.play();
  53542. };
  53543. PlaySoundAction.prototype.serialize = function (parent) {
  53544. return _super.prototype._serialize.call(this, {
  53545. name: "PlaySoundAction",
  53546. properties: [{ name: "sound", value: this._sound.name }]
  53547. }, parent);
  53548. };
  53549. return PlaySoundAction;
  53550. }(BABYLON.Action));
  53551. BABYLON.PlaySoundAction = PlaySoundAction;
  53552. var StopSoundAction = /** @class */ (function (_super) {
  53553. __extends(StopSoundAction, _super);
  53554. function StopSoundAction(triggerOptions, sound, condition) {
  53555. var _this = _super.call(this, triggerOptions, condition) || this;
  53556. _this._sound = sound;
  53557. return _this;
  53558. }
  53559. StopSoundAction.prototype._prepare = function () {
  53560. };
  53561. StopSoundAction.prototype.execute = function () {
  53562. if (this._sound !== undefined)
  53563. this._sound.stop();
  53564. };
  53565. StopSoundAction.prototype.serialize = function (parent) {
  53566. return _super.prototype._serialize.call(this, {
  53567. name: "StopSoundAction",
  53568. properties: [{ name: "sound", value: this._sound.name }]
  53569. }, parent);
  53570. };
  53571. return StopSoundAction;
  53572. }(BABYLON.Action));
  53573. BABYLON.StopSoundAction = StopSoundAction;
  53574. })(BABYLON || (BABYLON = {}));
  53575. //# sourceMappingURL=babylon.directActions.js.map
  53576. var BABYLON;
  53577. (function (BABYLON) {
  53578. var SpriteManager = /** @class */ (function () {
  53579. function SpriteManager(name, imgUrl, capacity, cellSize, scene, epsilon, samplingMode) {
  53580. if (epsilon === void 0) { epsilon = 0.01; }
  53581. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  53582. this.name = name;
  53583. this.sprites = new Array();
  53584. this.renderingGroupId = 0;
  53585. this.layerMask = 0x0FFFFFFF;
  53586. this.fogEnabled = true;
  53587. this.isPickable = false;
  53588. /**
  53589. * An event triggered when the manager is disposed.
  53590. */
  53591. this.onDisposeObservable = new BABYLON.Observable();
  53592. this._vertexBuffers = {};
  53593. this._capacity = capacity;
  53594. this._spriteTexture = new BABYLON.Texture(imgUrl, scene, true, false, samplingMode);
  53595. this._spriteTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53596. this._spriteTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  53597. if (cellSize.width && cellSize.height) {
  53598. this.cellWidth = cellSize.width;
  53599. this.cellHeight = cellSize.height;
  53600. }
  53601. else if (cellSize !== undefined) {
  53602. this.cellWidth = cellSize;
  53603. this.cellHeight = cellSize;
  53604. }
  53605. else {
  53606. return;
  53607. }
  53608. this._epsilon = epsilon;
  53609. this._scene = scene;
  53610. this._scene.spriteManagers.push(this);
  53611. var indices = [];
  53612. var index = 0;
  53613. for (var count = 0; count < capacity; count++) {
  53614. indices.push(index);
  53615. indices.push(index + 1);
  53616. indices.push(index + 2);
  53617. indices.push(index);
  53618. indices.push(index + 2);
  53619. indices.push(index + 3);
  53620. index += 4;
  53621. }
  53622. this._indexBuffer = scene.getEngine().createIndexBuffer(indices);
  53623. // VBO
  53624. // 16 floats per sprite (x, y, z, angle, sizeX, sizeY, offsetX, offsetY, invertU, invertV, cellIndexX, cellIndexY, color r, color g, color b, color a)
  53625. this._vertexData = new Float32Array(capacity * 16 * 4);
  53626. this._buffer = new BABYLON.Buffer(scene.getEngine(), this._vertexData, true, 16);
  53627. var positions = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, 0, 4);
  53628. var options = this._buffer.createVertexBuffer("options", 4, 4);
  53629. var cellInfo = this._buffer.createVertexBuffer("cellInfo", 8, 4);
  53630. var colors = this._buffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, 12, 4);
  53631. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  53632. this._vertexBuffers["options"] = options;
  53633. this._vertexBuffers["cellInfo"] = cellInfo;
  53634. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  53635. // Effects
  53636. this._effectBase = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest"], ["diffuseSampler"], "");
  53637. this._effectFog = this._scene.getEngine().createEffect("sprites", [BABYLON.VertexBuffer.PositionKind, "options", "cellInfo", BABYLON.VertexBuffer.ColorKind], ["view", "projection", "textureInfos", "alphaTest", "vFogInfos", "vFogColor"], ["diffuseSampler"], "#define FOG");
  53638. }
  53639. Object.defineProperty(SpriteManager.prototype, "onDispose", {
  53640. set: function (callback) {
  53641. if (this._onDisposeObserver) {
  53642. this.onDisposeObservable.remove(this._onDisposeObserver);
  53643. }
  53644. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  53645. },
  53646. enumerable: true,
  53647. configurable: true
  53648. });
  53649. Object.defineProperty(SpriteManager.prototype, "texture", {
  53650. get: function () {
  53651. return this._spriteTexture;
  53652. },
  53653. set: function (value) {
  53654. this._spriteTexture = value;
  53655. },
  53656. enumerable: true,
  53657. configurable: true
  53658. });
  53659. SpriteManager.prototype._appendSpriteVertex = function (index, sprite, offsetX, offsetY, rowSize) {
  53660. var arrayOffset = index * 16;
  53661. if (offsetX === 0)
  53662. offsetX = this._epsilon;
  53663. else if (offsetX === 1)
  53664. offsetX = 1 - this._epsilon;
  53665. if (offsetY === 0)
  53666. offsetY = this._epsilon;
  53667. else if (offsetY === 1)
  53668. offsetY = 1 - this._epsilon;
  53669. this._vertexData[arrayOffset] = sprite.position.x;
  53670. this._vertexData[arrayOffset + 1] = sprite.position.y;
  53671. this._vertexData[arrayOffset + 2] = sprite.position.z;
  53672. this._vertexData[arrayOffset + 3] = sprite.angle;
  53673. this._vertexData[arrayOffset + 4] = sprite.width;
  53674. this._vertexData[arrayOffset + 5] = sprite.height;
  53675. this._vertexData[arrayOffset + 6] = offsetX;
  53676. this._vertexData[arrayOffset + 7] = offsetY;
  53677. this._vertexData[arrayOffset + 8] = sprite.invertU ? 1 : 0;
  53678. this._vertexData[arrayOffset + 9] = sprite.invertV ? 1 : 0;
  53679. var offset = (sprite.cellIndex / rowSize) >> 0;
  53680. this._vertexData[arrayOffset + 10] = sprite.cellIndex - offset * rowSize;
  53681. this._vertexData[arrayOffset + 11] = offset;
  53682. // Color
  53683. this._vertexData[arrayOffset + 12] = sprite.color.r;
  53684. this._vertexData[arrayOffset + 13] = sprite.color.g;
  53685. this._vertexData[arrayOffset + 14] = sprite.color.b;
  53686. this._vertexData[arrayOffset + 15] = sprite.color.a;
  53687. };
  53688. SpriteManager.prototype.intersects = function (ray, camera, predicate, fastCheck) {
  53689. var count = Math.min(this._capacity, this.sprites.length);
  53690. var min = BABYLON.Vector3.Zero();
  53691. var max = BABYLON.Vector3.Zero();
  53692. var distance = Number.MAX_VALUE;
  53693. var currentSprite = null;
  53694. var cameraSpacePosition = BABYLON.Vector3.Zero();
  53695. var cameraView = camera.getViewMatrix();
  53696. for (var index = 0; index < count; index++) {
  53697. var sprite = this.sprites[index];
  53698. if (!sprite) {
  53699. continue;
  53700. }
  53701. if (predicate) {
  53702. if (!predicate(sprite)) {
  53703. continue;
  53704. }
  53705. }
  53706. else if (!sprite.isPickable) {
  53707. continue;
  53708. }
  53709. BABYLON.Vector3.TransformCoordinatesToRef(sprite.position, cameraView, cameraSpacePosition);
  53710. min.copyFromFloats(cameraSpacePosition.x - sprite.width / 2, cameraSpacePosition.y - sprite.height / 2, cameraSpacePosition.z);
  53711. max.copyFromFloats(cameraSpacePosition.x + sprite.width / 2, cameraSpacePosition.y + sprite.height / 2, cameraSpacePosition.z);
  53712. if (ray.intersectsBoxMinMax(min, max)) {
  53713. var currentDistance = BABYLON.Vector3.Distance(cameraSpacePosition, ray.origin);
  53714. if (distance > currentDistance) {
  53715. distance = currentDistance;
  53716. currentSprite = sprite;
  53717. if (fastCheck) {
  53718. break;
  53719. }
  53720. }
  53721. }
  53722. }
  53723. if (currentSprite) {
  53724. var result = new BABYLON.PickingInfo();
  53725. result.hit = true;
  53726. result.pickedSprite = currentSprite;
  53727. result.distance = distance;
  53728. return result;
  53729. }
  53730. return null;
  53731. };
  53732. SpriteManager.prototype.render = function () {
  53733. // Check
  53734. if (!this._effectBase.isReady() || !this._effectFog.isReady() || !this._spriteTexture || !this._spriteTexture.isReady())
  53735. return;
  53736. var engine = this._scene.getEngine();
  53737. var baseSize = this._spriteTexture.getBaseSize();
  53738. // Sprites
  53739. var deltaTime = engine.getDeltaTime();
  53740. var max = Math.min(this._capacity, this.sprites.length);
  53741. var rowSize = baseSize.width / this.cellWidth;
  53742. var offset = 0;
  53743. for (var index = 0; index < max; index++) {
  53744. var sprite = this.sprites[index];
  53745. if (!sprite || !sprite.isVisible) {
  53746. continue;
  53747. }
  53748. sprite._animate(deltaTime);
  53749. this._appendSpriteVertex(offset++, sprite, 0, 0, rowSize);
  53750. this._appendSpriteVertex(offset++, sprite, 1, 0, rowSize);
  53751. this._appendSpriteVertex(offset++, sprite, 1, 1, rowSize);
  53752. this._appendSpriteVertex(offset++, sprite, 0, 1, rowSize);
  53753. }
  53754. this._buffer.update(this._vertexData);
  53755. // Render
  53756. var effect = this._effectBase;
  53757. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53758. effect = this._effectFog;
  53759. }
  53760. engine.enableEffect(effect);
  53761. var viewMatrix = this._scene.getViewMatrix();
  53762. effect.setTexture("diffuseSampler", this._spriteTexture);
  53763. effect.setMatrix("view", viewMatrix);
  53764. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  53765. effect.setFloat2("textureInfos", this.cellWidth / baseSize.width, this.cellHeight / baseSize.height);
  53766. // Fog
  53767. if (this._scene.fogEnabled && this._scene.fogMode !== BABYLON.Scene.FOGMODE_NONE && this.fogEnabled) {
  53768. effect.setFloat4("vFogInfos", this._scene.fogMode, this._scene.fogStart, this._scene.fogEnd, this._scene.fogDensity);
  53769. effect.setColor3("vFogColor", this._scene.fogColor);
  53770. }
  53771. // VBOs
  53772. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  53773. // Draw order
  53774. engine.setDepthFunctionToLessOrEqual();
  53775. effect.setBool("alphaTest", true);
  53776. engine.setColorWrite(false);
  53777. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53778. engine.setColorWrite(true);
  53779. effect.setBool("alphaTest", false);
  53780. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  53781. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, (offset / 4) * 6);
  53782. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  53783. };
  53784. SpriteManager.prototype.dispose = function () {
  53785. if (this._buffer) {
  53786. this._buffer.dispose();
  53787. this._buffer = null;
  53788. }
  53789. if (this._indexBuffer) {
  53790. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  53791. this._indexBuffer = null;
  53792. }
  53793. if (this._spriteTexture) {
  53794. this._spriteTexture.dispose();
  53795. this._spriteTexture = null;
  53796. }
  53797. // Remove from scene
  53798. var index = this._scene.spriteManagers.indexOf(this);
  53799. this._scene.spriteManagers.splice(index, 1);
  53800. // Callback
  53801. this.onDisposeObservable.notifyObservers(this);
  53802. this.onDisposeObservable.clear();
  53803. };
  53804. return SpriteManager;
  53805. }());
  53806. BABYLON.SpriteManager = SpriteManager;
  53807. })(BABYLON || (BABYLON = {}));
  53808. //# sourceMappingURL=babylon.spriteManager.js.map
  53809. var BABYLON;
  53810. (function (BABYLON) {
  53811. var Sprite = /** @class */ (function () {
  53812. function Sprite(name, manager) {
  53813. this.name = name;
  53814. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  53815. this.width = 1.0;
  53816. this.height = 1.0;
  53817. this.angle = 0;
  53818. this.cellIndex = 0;
  53819. this.invertU = 0;
  53820. this.invertV = 0;
  53821. this.animations = new Array();
  53822. this.isPickable = false;
  53823. this._animationStarted = false;
  53824. this._loopAnimation = false;
  53825. this._fromIndex = 0;
  53826. this._toIndex = 0;
  53827. this._delay = 0;
  53828. this._direction = 1;
  53829. this._time = 0;
  53830. /**
  53831. * Gets or sets a boolean indicating if the sprite is visible (renderable). Default is true
  53832. */
  53833. this.isVisible = true;
  53834. this._manager = manager;
  53835. this._manager.sprites.push(this);
  53836. this.position = BABYLON.Vector3.Zero();
  53837. }
  53838. Object.defineProperty(Sprite.prototype, "size", {
  53839. get: function () {
  53840. return this.width;
  53841. },
  53842. set: function (value) {
  53843. this.width = value;
  53844. this.height = value;
  53845. },
  53846. enumerable: true,
  53847. configurable: true
  53848. });
  53849. Sprite.prototype.playAnimation = function (from, to, loop, delay, onAnimationEnd) {
  53850. this._fromIndex = from;
  53851. this._toIndex = to;
  53852. this._loopAnimation = loop;
  53853. this._delay = delay;
  53854. this._animationStarted = true;
  53855. this._direction = from < to ? 1 : -1;
  53856. this.cellIndex = from;
  53857. this._time = 0;
  53858. this._onAnimationEnd = onAnimationEnd;
  53859. };
  53860. Sprite.prototype.stopAnimation = function () {
  53861. this._animationStarted = false;
  53862. };
  53863. Sprite.prototype._animate = function (deltaTime) {
  53864. if (!this._animationStarted)
  53865. return;
  53866. this._time += deltaTime;
  53867. if (this._time > this._delay) {
  53868. this._time = this._time % this._delay;
  53869. this.cellIndex += this._direction;
  53870. if (this.cellIndex > this._toIndex) {
  53871. if (this._loopAnimation) {
  53872. this.cellIndex = this._fromIndex;
  53873. }
  53874. else {
  53875. this.cellIndex = this._toIndex;
  53876. this._animationStarted = false;
  53877. if (this._onAnimationEnd) {
  53878. this._onAnimationEnd();
  53879. }
  53880. if (this.disposeWhenFinishedAnimating) {
  53881. this.dispose();
  53882. }
  53883. }
  53884. }
  53885. }
  53886. };
  53887. Sprite.prototype.dispose = function () {
  53888. for (var i = 0; i < this._manager.sprites.length; i++) {
  53889. if (this._manager.sprites[i] == this) {
  53890. this._manager.sprites.splice(i, 1);
  53891. }
  53892. }
  53893. };
  53894. return Sprite;
  53895. }());
  53896. BABYLON.Sprite = Sprite;
  53897. })(BABYLON || (BABYLON = {}));
  53898. //# sourceMappingURL=babylon.sprite.js.map
  53899. var BABYLON;
  53900. (function (BABYLON) {
  53901. var IntersectionInfo = /** @class */ (function () {
  53902. function IntersectionInfo(bu, bv, distance) {
  53903. this.bu = bu;
  53904. this.bv = bv;
  53905. this.distance = distance;
  53906. this.faceId = 0;
  53907. this.subMeshId = 0;
  53908. }
  53909. return IntersectionInfo;
  53910. }());
  53911. BABYLON.IntersectionInfo = IntersectionInfo;
  53912. /**
  53913. * Information about the result of picking within a scene
  53914. * See https://doc.babylonjs.com/babylon101/picking_collisions
  53915. */
  53916. var PickingInfo = /** @class */ (function () {
  53917. function PickingInfo() {
  53918. /**
  53919. * If the pick collided with an object
  53920. */
  53921. this.hit = false;
  53922. /**
  53923. * Distance away where the pick collided
  53924. */
  53925. this.distance = 0;
  53926. /**
  53927. * The location of pick collision
  53928. */
  53929. this.pickedPoint = null;
  53930. /**
  53931. * The mesh corrisponding the the pick collision
  53932. */
  53933. this.pickedMesh = null;
  53934. /** (See getTextureCoordinates) The barycentric U coordinate that is used when calulating the texture coordinates of the collision.*/
  53935. this.bu = 0;
  53936. /** (See getTextureCoordinates) The barycentric V coordinate that is used when calulating the texture coordinates of the collision.*/
  53937. this.bv = 0;
  53938. /** The id of the face on the mesh that was picked */
  53939. this.faceId = -1;
  53940. /** Id of the the submesh that was picked */
  53941. this.subMeshId = 0;
  53942. /** If a sprite was picked, this will be the sprite the pick collided with */
  53943. this.pickedSprite = null;
  53944. /**
  53945. * If a mesh was used to do the picking (eg. 6dof controller) this will be populated.
  53946. */
  53947. this.originMesh = null;
  53948. /**
  53949. * The ray that was used to perform the picking.
  53950. */
  53951. this.ray = null;
  53952. }
  53953. /**
  53954. * Gets the normal corrispodning to the face the pick collided with
  53955. * @param useWorldCoordinates If the resulting normal should be relative to the world (default: false)
  53956. * @param useVerticesNormals If the vertices normals should be used to calculate the normal instead of the normal map
  53957. * @returns The normal corrispodning to the face the pick collided with
  53958. */
  53959. PickingInfo.prototype.getNormal = function (useWorldCoordinates, useVerticesNormals) {
  53960. if (useWorldCoordinates === void 0) { useWorldCoordinates = false; }
  53961. if (useVerticesNormals === void 0) { useVerticesNormals = true; }
  53962. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  53963. return null;
  53964. }
  53965. var indices = this.pickedMesh.getIndices();
  53966. if (!indices) {
  53967. return null;
  53968. }
  53969. var result;
  53970. if (useVerticesNormals) {
  53971. var normals = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  53972. var normal0 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3] * 3);
  53973. var normal1 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 1] * 3);
  53974. var normal2 = BABYLON.Vector3.FromArray(normals, indices[this.faceId * 3 + 2] * 3);
  53975. normal0 = normal0.scale(this.bu);
  53976. normal1 = normal1.scale(this.bv);
  53977. normal2 = normal2.scale(1.0 - this.bu - this.bv);
  53978. result = new BABYLON.Vector3(normal0.x + normal1.x + normal2.x, normal0.y + normal1.y + normal2.y, normal0.z + normal1.z + normal2.z);
  53979. }
  53980. else {
  53981. var positions = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  53982. var vertex1 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3] * 3);
  53983. var vertex2 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 1] * 3);
  53984. var vertex3 = BABYLON.Vector3.FromArray(positions, indices[this.faceId * 3 + 2] * 3);
  53985. var p1p2 = vertex1.subtract(vertex2);
  53986. var p3p2 = vertex3.subtract(vertex2);
  53987. result = BABYLON.Vector3.Cross(p1p2, p3p2);
  53988. }
  53989. if (useWorldCoordinates) {
  53990. var wm = this.pickedMesh.getWorldMatrix();
  53991. if (this.pickedMesh.nonUniformScaling) {
  53992. BABYLON.Tmp.Matrix[0].copyFrom(wm);
  53993. wm = BABYLON.Tmp.Matrix[0];
  53994. wm.setTranslationFromFloats(0, 0, 0);
  53995. wm.invert();
  53996. wm.transposeToRef(BABYLON.Tmp.Matrix[1]);
  53997. wm = BABYLON.Tmp.Matrix[1];
  53998. }
  53999. result = BABYLON.Vector3.TransformNormal(result, wm);
  54000. }
  54001. result.normalize();
  54002. return result;
  54003. };
  54004. /**
  54005. * Gets the texture coordinates of where the pick occured
  54006. * @returns the vector containing the coordnates of the texture
  54007. */
  54008. PickingInfo.prototype.getTextureCoordinates = function () {
  54009. if (!this.pickedMesh || !this.pickedMesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  54010. return null;
  54011. }
  54012. var indices = this.pickedMesh.getIndices();
  54013. if (!indices) {
  54014. return null;
  54015. }
  54016. var uvs = this.pickedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  54017. if (!uvs) {
  54018. return null;
  54019. }
  54020. var uv0 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3] * 2);
  54021. var uv1 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 1] * 2);
  54022. var uv2 = BABYLON.Vector2.FromArray(uvs, indices[this.faceId * 3 + 2] * 2);
  54023. uv0 = uv0.scale(1.0 - this.bu - this.bv);
  54024. uv1 = uv1.scale(this.bu);
  54025. uv2 = uv2.scale(this.bv);
  54026. return new BABYLON.Vector2(uv0.x + uv1.x + uv2.x, uv0.y + uv1.y + uv2.y);
  54027. };
  54028. return PickingInfo;
  54029. }());
  54030. BABYLON.PickingInfo = PickingInfo;
  54031. })(BABYLON || (BABYLON = {}));
  54032. //# sourceMappingURL=babylon.pickingInfo.js.map
  54033. var BABYLON;
  54034. (function (BABYLON) {
  54035. var Ray = /** @class */ (function () {
  54036. function Ray(origin, direction, length) {
  54037. if (length === void 0) { length = Number.MAX_VALUE; }
  54038. this.origin = origin;
  54039. this.direction = direction;
  54040. this.length = length;
  54041. }
  54042. // Methods
  54043. Ray.prototype.intersectsBoxMinMax = function (minimum, maximum) {
  54044. var d = 0.0;
  54045. var maxValue = Number.MAX_VALUE;
  54046. var inv;
  54047. var min;
  54048. var max;
  54049. var temp;
  54050. if (Math.abs(this.direction.x) < 0.0000001) {
  54051. if (this.origin.x < minimum.x || this.origin.x > maximum.x) {
  54052. return false;
  54053. }
  54054. }
  54055. else {
  54056. inv = 1.0 / this.direction.x;
  54057. min = (minimum.x - this.origin.x) * inv;
  54058. max = (maximum.x - this.origin.x) * inv;
  54059. if (max === -Infinity) {
  54060. max = Infinity;
  54061. }
  54062. if (min > max) {
  54063. temp = min;
  54064. min = max;
  54065. max = temp;
  54066. }
  54067. d = Math.max(min, d);
  54068. maxValue = Math.min(max, maxValue);
  54069. if (d > maxValue) {
  54070. return false;
  54071. }
  54072. }
  54073. if (Math.abs(this.direction.y) < 0.0000001) {
  54074. if (this.origin.y < minimum.y || this.origin.y > maximum.y) {
  54075. return false;
  54076. }
  54077. }
  54078. else {
  54079. inv = 1.0 / this.direction.y;
  54080. min = (minimum.y - this.origin.y) * inv;
  54081. max = (maximum.y - this.origin.y) * inv;
  54082. if (max === -Infinity) {
  54083. max = Infinity;
  54084. }
  54085. if (min > max) {
  54086. temp = min;
  54087. min = max;
  54088. max = temp;
  54089. }
  54090. d = Math.max(min, d);
  54091. maxValue = Math.min(max, maxValue);
  54092. if (d > maxValue) {
  54093. return false;
  54094. }
  54095. }
  54096. if (Math.abs(this.direction.z) < 0.0000001) {
  54097. if (this.origin.z < minimum.z || this.origin.z > maximum.z) {
  54098. return false;
  54099. }
  54100. }
  54101. else {
  54102. inv = 1.0 / this.direction.z;
  54103. min = (minimum.z - this.origin.z) * inv;
  54104. max = (maximum.z - this.origin.z) * inv;
  54105. if (max === -Infinity) {
  54106. max = Infinity;
  54107. }
  54108. if (min > max) {
  54109. temp = min;
  54110. min = max;
  54111. max = temp;
  54112. }
  54113. d = Math.max(min, d);
  54114. maxValue = Math.min(max, maxValue);
  54115. if (d > maxValue) {
  54116. return false;
  54117. }
  54118. }
  54119. return true;
  54120. };
  54121. Ray.prototype.intersectsBox = function (box) {
  54122. return this.intersectsBoxMinMax(box.minimum, box.maximum);
  54123. };
  54124. Ray.prototype.intersectsSphere = function (sphere) {
  54125. var x = sphere.center.x - this.origin.x;
  54126. var y = sphere.center.y - this.origin.y;
  54127. var z = sphere.center.z - this.origin.z;
  54128. var pyth = (x * x) + (y * y) + (z * z);
  54129. var rr = sphere.radius * sphere.radius;
  54130. if (pyth <= rr) {
  54131. return true;
  54132. }
  54133. var dot = (x * this.direction.x) + (y * this.direction.y) + (z * this.direction.z);
  54134. if (dot < 0.0) {
  54135. return false;
  54136. }
  54137. var temp = pyth - (dot * dot);
  54138. return temp <= rr;
  54139. };
  54140. Ray.prototype.intersectsTriangle = function (vertex0, vertex1, vertex2) {
  54141. if (!this._edge1) {
  54142. this._edge1 = BABYLON.Vector3.Zero();
  54143. this._edge2 = BABYLON.Vector3.Zero();
  54144. this._pvec = BABYLON.Vector3.Zero();
  54145. this._tvec = BABYLON.Vector3.Zero();
  54146. this._qvec = BABYLON.Vector3.Zero();
  54147. }
  54148. vertex1.subtractToRef(vertex0, this._edge1);
  54149. vertex2.subtractToRef(vertex0, this._edge2);
  54150. BABYLON.Vector3.CrossToRef(this.direction, this._edge2, this._pvec);
  54151. var det = BABYLON.Vector3.Dot(this._edge1, this._pvec);
  54152. if (det === 0) {
  54153. return null;
  54154. }
  54155. var invdet = 1 / det;
  54156. this.origin.subtractToRef(vertex0, this._tvec);
  54157. var bu = BABYLON.Vector3.Dot(this._tvec, this._pvec) * invdet;
  54158. if (bu < 0 || bu > 1.0) {
  54159. return null;
  54160. }
  54161. BABYLON.Vector3.CrossToRef(this._tvec, this._edge1, this._qvec);
  54162. var bv = BABYLON.Vector3.Dot(this.direction, this._qvec) * invdet;
  54163. if (bv < 0 || bu + bv > 1.0) {
  54164. return null;
  54165. }
  54166. //check if the distance is longer than the predefined length.
  54167. var distance = BABYLON.Vector3.Dot(this._edge2, this._qvec) * invdet;
  54168. if (distance > this.length) {
  54169. return null;
  54170. }
  54171. return new BABYLON.IntersectionInfo(bu, bv, distance);
  54172. };
  54173. Ray.prototype.intersectsPlane = function (plane) {
  54174. var distance;
  54175. var result1 = BABYLON.Vector3.Dot(plane.normal, this.direction);
  54176. if (Math.abs(result1) < 9.99999997475243E-07) {
  54177. return null;
  54178. }
  54179. else {
  54180. var result2 = BABYLON.Vector3.Dot(plane.normal, this.origin);
  54181. distance = (-plane.d - result2) / result1;
  54182. if (distance < 0.0) {
  54183. if (distance < -9.99999997475243E-07) {
  54184. return null;
  54185. }
  54186. else {
  54187. return 0;
  54188. }
  54189. }
  54190. return distance;
  54191. }
  54192. };
  54193. Ray.prototype.intersectsMesh = function (mesh, fastCheck) {
  54194. var tm = BABYLON.Tmp.Matrix[0];
  54195. mesh.getWorldMatrix().invertToRef(tm);
  54196. if (this._tmpRay) {
  54197. Ray.TransformToRef(this, tm, this._tmpRay);
  54198. }
  54199. else {
  54200. this._tmpRay = Ray.Transform(this, tm);
  54201. }
  54202. return mesh.intersects(this._tmpRay, fastCheck);
  54203. };
  54204. Ray.prototype.intersectsMeshes = function (meshes, fastCheck, results) {
  54205. if (results) {
  54206. results.length = 0;
  54207. }
  54208. else {
  54209. results = [];
  54210. }
  54211. for (var i = 0; i < meshes.length; i++) {
  54212. var pickInfo = this.intersectsMesh(meshes[i], fastCheck);
  54213. if (pickInfo.hit) {
  54214. results.push(pickInfo);
  54215. }
  54216. }
  54217. results.sort(this._comparePickingInfo);
  54218. return results;
  54219. };
  54220. Ray.prototype._comparePickingInfo = function (pickingInfoA, pickingInfoB) {
  54221. if (pickingInfoA.distance < pickingInfoB.distance) {
  54222. return -1;
  54223. }
  54224. else if (pickingInfoA.distance > pickingInfoB.distance) {
  54225. return 1;
  54226. }
  54227. else {
  54228. return 0;
  54229. }
  54230. };
  54231. /**
  54232. * Intersection test between the ray and a given segment whithin a given tolerance (threshold)
  54233. * @param sega the first point of the segment to test the intersection against
  54234. * @param segb the second point of the segment to test the intersection against
  54235. * @param threshold the tolerance margin, if the ray doesn't intersect the segment but is close to the given threshold, the intersection is successful
  54236. * @return the distance from the ray origin to the intersection point if there's intersection, or -1 if there's no intersection
  54237. */
  54238. Ray.prototype.intersectionSegment = function (sega, segb, threshold) {
  54239. var rsegb = this.origin.add(this.direction.multiplyByFloats(Ray.rayl, Ray.rayl, Ray.rayl));
  54240. var u = segb.subtract(sega);
  54241. var v = rsegb.subtract(this.origin);
  54242. var w = sega.subtract(this.origin);
  54243. var a = BABYLON.Vector3.Dot(u, u); // always >= 0
  54244. var b = BABYLON.Vector3.Dot(u, v);
  54245. var c = BABYLON.Vector3.Dot(v, v); // always >= 0
  54246. var d = BABYLON.Vector3.Dot(u, w);
  54247. var e = BABYLON.Vector3.Dot(v, w);
  54248. var D = a * c - b * b; // always >= 0
  54249. var sc, sN, sD = D; // sc = sN / sD, default sD = D >= 0
  54250. var tc, tN, tD = D; // tc = tN / tD, default tD = D >= 0
  54251. // compute the line parameters of the two closest points
  54252. if (D < Ray.smallnum) { // the lines are almost parallel
  54253. sN = 0.0; // force using point P0 on segment S1
  54254. sD = 1.0; // to prevent possible division by 0.0 later
  54255. tN = e;
  54256. tD = c;
  54257. }
  54258. else { // get the closest points on the infinite lines
  54259. sN = (b * e - c * d);
  54260. tN = (a * e - b * d);
  54261. if (sN < 0.0) { // sc < 0 => the s=0 edge is visible
  54262. sN = 0.0;
  54263. tN = e;
  54264. tD = c;
  54265. }
  54266. else if (sN > sD) { // sc > 1 => the s=1 edge is visible
  54267. sN = sD;
  54268. tN = e + b;
  54269. tD = c;
  54270. }
  54271. }
  54272. if (tN < 0.0) { // tc < 0 => the t=0 edge is visible
  54273. tN = 0.0;
  54274. // recompute sc for this edge
  54275. if (-d < 0.0) {
  54276. sN = 0.0;
  54277. }
  54278. else if (-d > a)
  54279. sN = sD;
  54280. else {
  54281. sN = -d;
  54282. sD = a;
  54283. }
  54284. }
  54285. else if (tN > tD) { // tc > 1 => the t=1 edge is visible
  54286. tN = tD;
  54287. // recompute sc for this edge
  54288. if ((-d + b) < 0.0) {
  54289. sN = 0;
  54290. }
  54291. else if ((-d + b) > a) {
  54292. sN = sD;
  54293. }
  54294. else {
  54295. sN = (-d + b);
  54296. sD = a;
  54297. }
  54298. }
  54299. // finally do the division to get sc and tc
  54300. sc = (Math.abs(sN) < Ray.smallnum ? 0.0 : sN / sD);
  54301. tc = (Math.abs(tN) < Ray.smallnum ? 0.0 : tN / tD);
  54302. // get the difference of the two closest points
  54303. var qtc = v.multiplyByFloats(tc, tc, tc);
  54304. var dP = w.add(u.multiplyByFloats(sc, sc, sc)).subtract(qtc); // = S1(sc) - S2(tc)
  54305. var isIntersected = (tc > 0) && (tc <= this.length) && (dP.lengthSquared() < (threshold * threshold)); // return intersection result
  54306. if (isIntersected) {
  54307. return qtc.length();
  54308. }
  54309. return -1;
  54310. };
  54311. Ray.prototype.update = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54312. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 0, viewportWidth, viewportHeight, world, view, projection, this.origin);
  54313. BABYLON.Vector3.UnprojectFloatsToRef(x, y, 1, viewportWidth, viewportHeight, world, view, projection, BABYLON.Tmp.Vector3[0]);
  54314. BABYLON.Tmp.Vector3[0].subtractToRef(this.origin, this.direction);
  54315. this.direction.normalize();
  54316. return this;
  54317. };
  54318. // Statics
  54319. Ray.Zero = function () {
  54320. return new Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero());
  54321. };
  54322. Ray.CreateNew = function (x, y, viewportWidth, viewportHeight, world, view, projection) {
  54323. var result = Ray.Zero();
  54324. return result.update(x, y, viewportWidth, viewportHeight, world, view, projection);
  54325. };
  54326. /**
  54327. * 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
  54328. * transformed to the given world matrix.
  54329. * @param origin The origin point
  54330. * @param end The end point
  54331. * @param world a matrix to transform the ray to. Default is the identity matrix.
  54332. */
  54333. Ray.CreateNewFromTo = function (origin, end, world) {
  54334. if (world === void 0) { world = BABYLON.Matrix.Identity(); }
  54335. var direction = end.subtract(origin);
  54336. var length = Math.sqrt((direction.x * direction.x) + (direction.y * direction.y) + (direction.z * direction.z));
  54337. direction.normalize();
  54338. return Ray.Transform(new Ray(origin, direction, length), world);
  54339. };
  54340. Ray.Transform = function (ray, matrix) {
  54341. var result = new Ray(new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, 0));
  54342. Ray.TransformToRef(ray, matrix, result);
  54343. return result;
  54344. };
  54345. Ray.TransformToRef = function (ray, matrix, result) {
  54346. BABYLON.Vector3.TransformCoordinatesToRef(ray.origin, matrix, result.origin);
  54347. BABYLON.Vector3.TransformNormalToRef(ray.direction, matrix, result.direction);
  54348. result.length = ray.length;
  54349. var dir = result.direction;
  54350. var len = dir.length();
  54351. if (!(len === 0 || len === 1)) {
  54352. var num = 1.0 / len;
  54353. dir.x *= num;
  54354. dir.y *= num;
  54355. dir.z *= num;
  54356. result.length *= len;
  54357. }
  54358. };
  54359. Ray.smallnum = 0.00000001;
  54360. Ray.rayl = 10e8;
  54361. return Ray;
  54362. }());
  54363. BABYLON.Ray = Ray;
  54364. })(BABYLON || (BABYLON = {}));
  54365. //# sourceMappingURL=babylon.ray.js.map
  54366. var BABYLON;
  54367. (function (BABYLON) {
  54368. var intersectBoxAASphere = function (boxMin, boxMax, sphereCenter, sphereRadius) {
  54369. if (boxMin.x > sphereCenter.x + sphereRadius)
  54370. return false;
  54371. if (sphereCenter.x - sphereRadius > boxMax.x)
  54372. return false;
  54373. if (boxMin.y > sphereCenter.y + sphereRadius)
  54374. return false;
  54375. if (sphereCenter.y - sphereRadius > boxMax.y)
  54376. return false;
  54377. if (boxMin.z > sphereCenter.z + sphereRadius)
  54378. return false;
  54379. if (sphereCenter.z - sphereRadius > boxMax.z)
  54380. return false;
  54381. return true;
  54382. };
  54383. var getLowestRoot = (function () {
  54384. var result = { root: 0, found: false };
  54385. return function (a, b, c, maxR) {
  54386. result.root = 0;
  54387. result.found = false;
  54388. var determinant = b * b - 4.0 * a * c;
  54389. if (determinant < 0)
  54390. return result;
  54391. var sqrtD = Math.sqrt(determinant);
  54392. var r1 = (-b - sqrtD) / (2.0 * a);
  54393. var r2 = (-b + sqrtD) / (2.0 * a);
  54394. if (r1 > r2) {
  54395. var temp = r2;
  54396. r2 = r1;
  54397. r1 = temp;
  54398. }
  54399. if (r1 > 0 && r1 < maxR) {
  54400. result.root = r1;
  54401. result.found = true;
  54402. return result;
  54403. }
  54404. if (r2 > 0 && r2 < maxR) {
  54405. result.root = r2;
  54406. result.found = true;
  54407. return result;
  54408. }
  54409. return result;
  54410. };
  54411. })();
  54412. var Collider = /** @class */ (function () {
  54413. function Collider() {
  54414. this._collisionPoint = BABYLON.Vector3.Zero();
  54415. this._planeIntersectionPoint = BABYLON.Vector3.Zero();
  54416. this._tempVector = BABYLON.Vector3.Zero();
  54417. this._tempVector2 = BABYLON.Vector3.Zero();
  54418. this._tempVector3 = BABYLON.Vector3.Zero();
  54419. this._tempVector4 = BABYLON.Vector3.Zero();
  54420. this._edge = BABYLON.Vector3.Zero();
  54421. this._baseToVertex = BABYLON.Vector3.Zero();
  54422. this._destinationPoint = BABYLON.Vector3.Zero();
  54423. this._slidePlaneNormal = BABYLON.Vector3.Zero();
  54424. this._displacementVector = BABYLON.Vector3.Zero();
  54425. this._radius = BABYLON.Vector3.One();
  54426. this._retry = 0;
  54427. this._basePointWorld = BABYLON.Vector3.Zero();
  54428. this._velocityWorld = BABYLON.Vector3.Zero();
  54429. this._normalizedVelocity = BABYLON.Vector3.Zero();
  54430. this._collisionMask = -1;
  54431. }
  54432. Object.defineProperty(Collider.prototype, "collisionMask", {
  54433. get: function () {
  54434. return this._collisionMask;
  54435. },
  54436. set: function (mask) {
  54437. this._collisionMask = !isNaN(mask) ? mask : -1;
  54438. },
  54439. enumerable: true,
  54440. configurable: true
  54441. });
  54442. Object.defineProperty(Collider.prototype, "slidePlaneNormal", {
  54443. /**
  54444. * Gets the plane normal used to compute the sliding response (in local space)
  54445. */
  54446. get: function () {
  54447. return this._slidePlaneNormal;
  54448. },
  54449. enumerable: true,
  54450. configurable: true
  54451. });
  54452. // Methods
  54453. Collider.prototype._initialize = function (source, dir, e) {
  54454. this._velocity = dir;
  54455. BABYLON.Vector3.NormalizeToRef(dir, this._normalizedVelocity);
  54456. this._basePoint = source;
  54457. source.multiplyToRef(this._radius, this._basePointWorld);
  54458. dir.multiplyToRef(this._radius, this._velocityWorld);
  54459. this._velocityWorldLength = this._velocityWorld.length();
  54460. this._epsilon = e;
  54461. this.collisionFound = false;
  54462. };
  54463. Collider.prototype._checkPointInTriangle = function (point, pa, pb, pc, n) {
  54464. pa.subtractToRef(point, this._tempVector);
  54465. pb.subtractToRef(point, this._tempVector2);
  54466. BABYLON.Vector3.CrossToRef(this._tempVector, this._tempVector2, this._tempVector4);
  54467. var d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54468. if (d < 0)
  54469. return false;
  54470. pc.subtractToRef(point, this._tempVector3);
  54471. BABYLON.Vector3.CrossToRef(this._tempVector2, this._tempVector3, this._tempVector4);
  54472. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54473. if (d < 0)
  54474. return false;
  54475. BABYLON.Vector3.CrossToRef(this._tempVector3, this._tempVector, this._tempVector4);
  54476. d = BABYLON.Vector3.Dot(this._tempVector4, n);
  54477. return d >= 0;
  54478. };
  54479. Collider.prototype._canDoCollision = function (sphereCenter, sphereRadius, vecMin, vecMax) {
  54480. var distance = BABYLON.Vector3.Distance(this._basePointWorld, sphereCenter);
  54481. var max = Math.max(this._radius.x, this._radius.y, this._radius.z);
  54482. if (distance > this._velocityWorldLength + max + sphereRadius) {
  54483. return false;
  54484. }
  54485. if (!intersectBoxAASphere(vecMin, vecMax, this._basePointWorld, this._velocityWorldLength + max))
  54486. return false;
  54487. return true;
  54488. };
  54489. Collider.prototype._testTriangle = function (faceIndex, trianglePlaneArray, p1, p2, p3, hasMaterial) {
  54490. var t0;
  54491. var embeddedInPlane = false;
  54492. //defensive programming, actually not needed.
  54493. if (!trianglePlaneArray) {
  54494. trianglePlaneArray = [];
  54495. }
  54496. if (!trianglePlaneArray[faceIndex]) {
  54497. trianglePlaneArray[faceIndex] = new BABYLON.Plane(0, 0, 0, 0);
  54498. trianglePlaneArray[faceIndex].copyFromPoints(p1, p2, p3);
  54499. }
  54500. var trianglePlane = trianglePlaneArray[faceIndex];
  54501. if ((!hasMaterial) && !trianglePlane.isFrontFacingTo(this._normalizedVelocity, 0))
  54502. return;
  54503. var signedDistToTrianglePlane = trianglePlane.signedDistanceTo(this._basePoint);
  54504. var normalDotVelocity = BABYLON.Vector3.Dot(trianglePlane.normal, this._velocity);
  54505. if (normalDotVelocity == 0) {
  54506. if (Math.abs(signedDistToTrianglePlane) >= 1.0)
  54507. return;
  54508. embeddedInPlane = true;
  54509. t0 = 0;
  54510. }
  54511. else {
  54512. t0 = (-1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54513. var t1 = (1.0 - signedDistToTrianglePlane) / normalDotVelocity;
  54514. if (t0 > t1) {
  54515. var temp = t1;
  54516. t1 = t0;
  54517. t0 = temp;
  54518. }
  54519. if (t0 > 1.0 || t1 < 0.0)
  54520. return;
  54521. if (t0 < 0)
  54522. t0 = 0;
  54523. if (t0 > 1.0)
  54524. t0 = 1.0;
  54525. }
  54526. this._collisionPoint.copyFromFloats(0, 0, 0);
  54527. var found = false;
  54528. var t = 1.0;
  54529. if (!embeddedInPlane) {
  54530. this._basePoint.subtractToRef(trianglePlane.normal, this._planeIntersectionPoint);
  54531. this._velocity.scaleToRef(t0, this._tempVector);
  54532. this._planeIntersectionPoint.addInPlace(this._tempVector);
  54533. if (this._checkPointInTriangle(this._planeIntersectionPoint, p1, p2, p3, trianglePlane.normal)) {
  54534. found = true;
  54535. t = t0;
  54536. this._collisionPoint.copyFrom(this._planeIntersectionPoint);
  54537. }
  54538. }
  54539. if (!found) {
  54540. var velocitySquaredLength = this._velocity.lengthSquared();
  54541. var a = velocitySquaredLength;
  54542. this._basePoint.subtractToRef(p1, this._tempVector);
  54543. var b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54544. var c = this._tempVector.lengthSquared() - 1.0;
  54545. var lowestRoot = getLowestRoot(a, b, c, t);
  54546. if (lowestRoot.found) {
  54547. t = lowestRoot.root;
  54548. found = true;
  54549. this._collisionPoint.copyFrom(p1);
  54550. }
  54551. this._basePoint.subtractToRef(p2, this._tempVector);
  54552. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54553. c = this._tempVector.lengthSquared() - 1.0;
  54554. lowestRoot = getLowestRoot(a, b, c, t);
  54555. if (lowestRoot.found) {
  54556. t = lowestRoot.root;
  54557. found = true;
  54558. this._collisionPoint.copyFrom(p2);
  54559. }
  54560. this._basePoint.subtractToRef(p3, this._tempVector);
  54561. b = 2.0 * (BABYLON.Vector3.Dot(this._velocity, this._tempVector));
  54562. c = this._tempVector.lengthSquared() - 1.0;
  54563. lowestRoot = getLowestRoot(a, b, c, t);
  54564. if (lowestRoot.found) {
  54565. t = lowestRoot.root;
  54566. found = true;
  54567. this._collisionPoint.copyFrom(p3);
  54568. }
  54569. p2.subtractToRef(p1, this._edge);
  54570. p1.subtractToRef(this._basePoint, this._baseToVertex);
  54571. var edgeSquaredLength = this._edge.lengthSquared();
  54572. var edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54573. var edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54574. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54575. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54576. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54577. lowestRoot = getLowestRoot(a, b, c, t);
  54578. if (lowestRoot.found) {
  54579. var f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54580. if (f >= 0.0 && f <= 1.0) {
  54581. t = lowestRoot.root;
  54582. found = true;
  54583. this._edge.scaleInPlace(f);
  54584. p1.addToRef(this._edge, this._collisionPoint);
  54585. }
  54586. }
  54587. p3.subtractToRef(p2, this._edge);
  54588. p2.subtractToRef(this._basePoint, this._baseToVertex);
  54589. edgeSquaredLength = this._edge.lengthSquared();
  54590. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54591. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54592. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54593. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54594. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54595. lowestRoot = getLowestRoot(a, b, c, t);
  54596. if (lowestRoot.found) {
  54597. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54598. if (f >= 0.0 && f <= 1.0) {
  54599. t = lowestRoot.root;
  54600. found = true;
  54601. this._edge.scaleInPlace(f);
  54602. p2.addToRef(this._edge, this._collisionPoint);
  54603. }
  54604. }
  54605. p1.subtractToRef(p3, this._edge);
  54606. p3.subtractToRef(this._basePoint, this._baseToVertex);
  54607. edgeSquaredLength = this._edge.lengthSquared();
  54608. edgeDotVelocity = BABYLON.Vector3.Dot(this._edge, this._velocity);
  54609. edgeDotBaseToVertex = BABYLON.Vector3.Dot(this._edge, this._baseToVertex);
  54610. a = edgeSquaredLength * (-velocitySquaredLength) + edgeDotVelocity * edgeDotVelocity;
  54611. b = edgeSquaredLength * (2.0 * BABYLON.Vector3.Dot(this._velocity, this._baseToVertex)) - 2.0 * edgeDotVelocity * edgeDotBaseToVertex;
  54612. c = edgeSquaredLength * (1.0 - this._baseToVertex.lengthSquared()) + edgeDotBaseToVertex * edgeDotBaseToVertex;
  54613. lowestRoot = getLowestRoot(a, b, c, t);
  54614. if (lowestRoot.found) {
  54615. f = (edgeDotVelocity * lowestRoot.root - edgeDotBaseToVertex) / edgeSquaredLength;
  54616. if (f >= 0.0 && f <= 1.0) {
  54617. t = lowestRoot.root;
  54618. found = true;
  54619. this._edge.scaleInPlace(f);
  54620. p3.addToRef(this._edge, this._collisionPoint);
  54621. }
  54622. }
  54623. }
  54624. if (found) {
  54625. var distToCollision = t * this._velocity.length();
  54626. if (!this.collisionFound || distToCollision < this._nearestDistance) {
  54627. if (!this.intersectionPoint) {
  54628. this.intersectionPoint = this._collisionPoint.clone();
  54629. }
  54630. else {
  54631. this.intersectionPoint.copyFrom(this._collisionPoint);
  54632. }
  54633. this._nearestDistance = distToCollision;
  54634. this.collisionFound = true;
  54635. }
  54636. }
  54637. };
  54638. Collider.prototype._collide = function (trianglePlaneArray, pts, indices, indexStart, indexEnd, decal, hasMaterial) {
  54639. for (var i = indexStart; i < indexEnd; i += 3) {
  54640. var p1 = pts[indices[i] - decal];
  54641. var p2 = pts[indices[i + 1] - decal];
  54642. var p3 = pts[indices[i + 2] - decal];
  54643. this._testTriangle(i, trianglePlaneArray, p3, p2, p1, hasMaterial);
  54644. }
  54645. };
  54646. Collider.prototype._getResponse = function (pos, vel) {
  54647. pos.addToRef(vel, this._destinationPoint);
  54648. vel.scaleInPlace((this._nearestDistance / vel.length()));
  54649. this._basePoint.addToRef(vel, pos);
  54650. pos.subtractToRef(this.intersectionPoint, this._slidePlaneNormal);
  54651. this._slidePlaneNormal.normalize();
  54652. this._slidePlaneNormal.scaleToRef(this._epsilon, this._displacementVector);
  54653. pos.addInPlace(this._displacementVector);
  54654. this.intersectionPoint.addInPlace(this._displacementVector);
  54655. this._slidePlaneNormal.scaleInPlace(BABYLON.Plane.SignedDistanceToPlaneFromPositionAndNormal(this.intersectionPoint, this._slidePlaneNormal, this._destinationPoint));
  54656. this._destinationPoint.subtractInPlace(this._slidePlaneNormal);
  54657. this._destinationPoint.subtractToRef(this.intersectionPoint, vel);
  54658. };
  54659. return Collider;
  54660. }());
  54661. BABYLON.Collider = Collider;
  54662. })(BABYLON || (BABYLON = {}));
  54663. //# sourceMappingURL=babylon.collider.js.map
  54664. var BABYLON;
  54665. (function (BABYLON) {
  54666. //WebWorker code will be inserted to this variable.
  54667. BABYLON.CollisionWorker = "";
  54668. /** Defines supported task for worker process */
  54669. var WorkerTaskType;
  54670. (function (WorkerTaskType) {
  54671. /** Initialization */
  54672. WorkerTaskType[WorkerTaskType["INIT"] = 0] = "INIT";
  54673. /** Update of geometry */
  54674. WorkerTaskType[WorkerTaskType["UPDATE"] = 1] = "UPDATE";
  54675. /** Evaluate collision */
  54676. WorkerTaskType[WorkerTaskType["COLLIDE"] = 2] = "COLLIDE";
  54677. })(WorkerTaskType = BABYLON.WorkerTaskType || (BABYLON.WorkerTaskType = {}));
  54678. /** Defines kind of replies returned by worker */
  54679. var WorkerReplyType;
  54680. (function (WorkerReplyType) {
  54681. /** Success */
  54682. WorkerReplyType[WorkerReplyType["SUCCESS"] = 0] = "SUCCESS";
  54683. /** Unkown error */
  54684. WorkerReplyType[WorkerReplyType["UNKNOWN_ERROR"] = 1] = "UNKNOWN_ERROR";
  54685. })(WorkerReplyType = BABYLON.WorkerReplyType || (BABYLON.WorkerReplyType = {}));
  54686. var CollisionCoordinatorWorker = /** @class */ (function () {
  54687. function CollisionCoordinatorWorker() {
  54688. var _this = this;
  54689. this._scaledPosition = BABYLON.Vector3.Zero();
  54690. this._scaledVelocity = BABYLON.Vector3.Zero();
  54691. this.onMeshUpdated = function (transformNode) {
  54692. _this._addUpdateMeshesList[transformNode.uniqueId] = CollisionCoordinatorWorker.SerializeMesh(transformNode);
  54693. };
  54694. this.onGeometryUpdated = function (geometry) {
  54695. _this._addUpdateGeometriesList[geometry.id] = CollisionCoordinatorWorker.SerializeGeometry(geometry);
  54696. };
  54697. this._afterRender = function () {
  54698. if (!_this._init)
  54699. return;
  54700. if (_this._toRemoveGeometryArray.length == 0 && _this._toRemoveMeshesArray.length == 0 && Object.keys(_this._addUpdateGeometriesList).length == 0 && Object.keys(_this._addUpdateMeshesList).length == 0) {
  54701. return;
  54702. }
  54703. //5 concurrent updates were sent to the web worker and were not yet processed. Abort next update.
  54704. //TODO make sure update runs as fast as possible to be able to update 60 FPS.
  54705. if (_this._runningUpdated > 4) {
  54706. return;
  54707. }
  54708. ++_this._runningUpdated;
  54709. var payload = {
  54710. updatedMeshes: _this._addUpdateMeshesList,
  54711. updatedGeometries: _this._addUpdateGeometriesList,
  54712. removedGeometries: _this._toRemoveGeometryArray,
  54713. removedMeshes: _this._toRemoveMeshesArray
  54714. };
  54715. var message = {
  54716. payload: payload,
  54717. taskType: WorkerTaskType.UPDATE
  54718. };
  54719. var serializable = [];
  54720. for (var id in payload.updatedGeometries) {
  54721. if (payload.updatedGeometries.hasOwnProperty(id)) {
  54722. //prepare transferables
  54723. serializable.push(message.payload.updatedGeometries[id].indices.buffer);
  54724. serializable.push(message.payload.updatedGeometries[id].normals.buffer);
  54725. serializable.push(message.payload.updatedGeometries[id].positions.buffer);
  54726. }
  54727. }
  54728. _this._worker.postMessage(message, serializable);
  54729. _this._addUpdateMeshesList = {};
  54730. _this._addUpdateGeometriesList = {};
  54731. _this._toRemoveGeometryArray = [];
  54732. _this._toRemoveMeshesArray = [];
  54733. };
  54734. this._onMessageFromWorker = function (e) {
  54735. var returnData = e.data;
  54736. if (returnData.error != WorkerReplyType.SUCCESS) {
  54737. //TODO what errors can be returned from the worker?
  54738. BABYLON.Tools.Warn("error returned from worker!");
  54739. return;
  54740. }
  54741. switch (returnData.taskType) {
  54742. case WorkerTaskType.INIT:
  54743. _this._init = true;
  54744. //Update the worked with ALL of the scene's current state
  54745. _this._scene.meshes.forEach(function (mesh) {
  54746. _this.onMeshAdded(mesh);
  54747. });
  54748. _this._scene.getGeometries().forEach(function (geometry) {
  54749. _this.onGeometryAdded(geometry);
  54750. });
  54751. break;
  54752. case WorkerTaskType.UPDATE:
  54753. _this._runningUpdated--;
  54754. break;
  54755. case WorkerTaskType.COLLIDE:
  54756. var returnPayload = returnData.payload;
  54757. if (!_this._collisionsCallbackArray[returnPayload.collisionId])
  54758. return;
  54759. var callback = _this._collisionsCallbackArray[returnPayload.collisionId];
  54760. if (callback) {
  54761. var mesh = _this._scene.getMeshByUniqueID(returnPayload.collidedMeshUniqueId);
  54762. if (mesh) {
  54763. callback(returnPayload.collisionId, BABYLON.Vector3.FromArray(returnPayload.newPosition), mesh);
  54764. }
  54765. }
  54766. //cleanup
  54767. _this._collisionsCallbackArray[returnPayload.collisionId] = null;
  54768. break;
  54769. }
  54770. };
  54771. this._collisionsCallbackArray = [];
  54772. this._init = false;
  54773. this._runningUpdated = 0;
  54774. this._addUpdateMeshesList = {};
  54775. this._addUpdateGeometriesList = {};
  54776. this._toRemoveGeometryArray = [];
  54777. this._toRemoveMeshesArray = [];
  54778. }
  54779. CollisionCoordinatorWorker.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54780. if (!this._init)
  54781. return;
  54782. if (this._collisionsCallbackArray[collisionIndex] || this._collisionsCallbackArray[collisionIndex + 100000])
  54783. return;
  54784. position.divideToRef(collider._radius, this._scaledPosition);
  54785. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54786. this._collisionsCallbackArray[collisionIndex] = onNewPosition;
  54787. var payload = {
  54788. collider: {
  54789. position: this._scaledPosition.asArray(),
  54790. velocity: this._scaledVelocity.asArray(),
  54791. radius: collider._radius.asArray()
  54792. },
  54793. collisionId: collisionIndex,
  54794. excludedMeshUniqueId: excludedMesh ? excludedMesh.uniqueId : null,
  54795. maximumRetry: maximumRetry
  54796. };
  54797. var message = {
  54798. payload: payload,
  54799. taskType: WorkerTaskType.COLLIDE
  54800. };
  54801. this._worker.postMessage(message);
  54802. };
  54803. CollisionCoordinatorWorker.prototype.init = function (scene) {
  54804. this._scene = scene;
  54805. this._scene.registerAfterRender(this._afterRender);
  54806. var workerUrl = BABYLON.WorkerIncluded ? BABYLON.Engine.CodeRepository + "Collisions/babylon.collisionWorker.js" : URL.createObjectURL(new Blob([BABYLON.CollisionWorker], { type: 'application/javascript' }));
  54807. this._worker = new Worker(workerUrl);
  54808. this._worker.onmessage = this._onMessageFromWorker;
  54809. var message = {
  54810. payload: {},
  54811. taskType: WorkerTaskType.INIT
  54812. };
  54813. this._worker.postMessage(message);
  54814. };
  54815. CollisionCoordinatorWorker.prototype.destroy = function () {
  54816. this._scene.unregisterAfterRender(this._afterRender);
  54817. this._worker.terminate();
  54818. };
  54819. CollisionCoordinatorWorker.prototype.onMeshAdded = function (mesh) {
  54820. mesh.registerAfterWorldMatrixUpdate(this.onMeshUpdated);
  54821. this.onMeshUpdated(mesh);
  54822. };
  54823. CollisionCoordinatorWorker.prototype.onMeshRemoved = function (mesh) {
  54824. this._toRemoveMeshesArray.push(mesh.uniqueId);
  54825. };
  54826. CollisionCoordinatorWorker.prototype.onGeometryAdded = function (geometry) {
  54827. //TODO this will break if the user uses his own function. This should be an array of callbacks!
  54828. geometry.onGeometryUpdated = this.onGeometryUpdated;
  54829. this.onGeometryUpdated(geometry);
  54830. };
  54831. CollisionCoordinatorWorker.prototype.onGeometryDeleted = function (geometry) {
  54832. this._toRemoveGeometryArray.push(geometry.id);
  54833. };
  54834. CollisionCoordinatorWorker.SerializeMesh = function (mesh) {
  54835. var submeshes = [];
  54836. if (mesh.subMeshes) {
  54837. submeshes = mesh.subMeshes.map(function (sm, idx) {
  54838. var boundingInfo = sm.getBoundingInfo();
  54839. return {
  54840. position: idx,
  54841. verticesStart: sm.verticesStart,
  54842. verticesCount: sm.verticesCount,
  54843. indexStart: sm.indexStart,
  54844. indexCount: sm.indexCount,
  54845. hasMaterial: !!sm.getMaterial(),
  54846. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54847. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54848. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54849. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray()
  54850. };
  54851. });
  54852. }
  54853. var geometryId = null;
  54854. if (mesh instanceof BABYLON.Mesh) {
  54855. var geometry = mesh.geometry;
  54856. geometryId = geometry ? geometry.id : null;
  54857. }
  54858. else if (mesh instanceof BABYLON.InstancedMesh) {
  54859. var geometry = mesh.sourceMesh && mesh.sourceMesh.geometry;
  54860. geometryId = geometry ? geometry.id : null;
  54861. }
  54862. var boundingInfo = mesh.getBoundingInfo();
  54863. return {
  54864. uniqueId: mesh.uniqueId,
  54865. id: mesh.id,
  54866. name: mesh.name,
  54867. geometryId: geometryId,
  54868. sphereCenter: boundingInfo.boundingSphere.centerWorld.asArray(),
  54869. sphereRadius: boundingInfo.boundingSphere.radiusWorld,
  54870. boxMinimum: boundingInfo.boundingBox.minimumWorld.asArray(),
  54871. boxMaximum: boundingInfo.boundingBox.maximumWorld.asArray(),
  54872. worldMatrixFromCache: mesh.worldMatrixFromCache.asArray(),
  54873. subMeshes: submeshes,
  54874. checkCollisions: mesh.checkCollisions
  54875. };
  54876. };
  54877. CollisionCoordinatorWorker.SerializeGeometry = function (geometry) {
  54878. return {
  54879. id: geometry.id,
  54880. positions: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []),
  54881. normals: new Float32Array(geometry.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []),
  54882. indices: new Uint32Array(geometry.getIndices() || []),
  54883. };
  54884. };
  54885. return CollisionCoordinatorWorker;
  54886. }());
  54887. BABYLON.CollisionCoordinatorWorker = CollisionCoordinatorWorker;
  54888. var CollisionCoordinatorLegacy = /** @class */ (function () {
  54889. function CollisionCoordinatorLegacy() {
  54890. this._scaledPosition = BABYLON.Vector3.Zero();
  54891. this._scaledVelocity = BABYLON.Vector3.Zero();
  54892. this._finalPosition = BABYLON.Vector3.Zero();
  54893. }
  54894. CollisionCoordinatorLegacy.prototype.getNewPosition = function (position, displacement, collider, maximumRetry, excludedMesh, onNewPosition, collisionIndex) {
  54895. position.divideToRef(collider._radius, this._scaledPosition);
  54896. displacement.divideToRef(collider._radius, this._scaledVelocity);
  54897. collider.collidedMesh = null;
  54898. collider._retry = 0;
  54899. collider._initialVelocity = this._scaledVelocity;
  54900. collider._initialPosition = this._scaledPosition;
  54901. this._collideWithWorld(this._scaledPosition, this._scaledVelocity, collider, maximumRetry, this._finalPosition, excludedMesh);
  54902. this._finalPosition.multiplyInPlace(collider._radius);
  54903. //run the callback
  54904. onNewPosition(collisionIndex, this._finalPosition, collider.collidedMesh);
  54905. };
  54906. CollisionCoordinatorLegacy.prototype.init = function (scene) {
  54907. this._scene = scene;
  54908. };
  54909. CollisionCoordinatorLegacy.prototype.destroy = function () {
  54910. //Legacy need no destruction method.
  54911. };
  54912. //No update in legacy mode
  54913. CollisionCoordinatorLegacy.prototype.onMeshAdded = function (mesh) { };
  54914. CollisionCoordinatorLegacy.prototype.onMeshUpdated = function (mesh) { };
  54915. CollisionCoordinatorLegacy.prototype.onMeshRemoved = function (mesh) { };
  54916. CollisionCoordinatorLegacy.prototype.onGeometryAdded = function (geometry) { };
  54917. CollisionCoordinatorLegacy.prototype.onGeometryUpdated = function (geometry) { };
  54918. CollisionCoordinatorLegacy.prototype.onGeometryDeleted = function (geometry) { };
  54919. CollisionCoordinatorLegacy.prototype._collideWithWorld = function (position, velocity, collider, maximumRetry, finalPosition, excludedMesh) {
  54920. if (excludedMesh === void 0) { excludedMesh = null; }
  54921. var closeDistance = BABYLON.Engine.CollisionsEpsilon * 10.0;
  54922. if (collider._retry >= maximumRetry) {
  54923. finalPosition.copyFrom(position);
  54924. return;
  54925. }
  54926. // Check if this is a mesh else camera or -1
  54927. var collisionMask = (excludedMesh ? excludedMesh.collisionMask : collider.collisionMask);
  54928. collider._initialize(position, velocity, closeDistance);
  54929. // Check all meshes
  54930. for (var index = 0; index < this._scene.meshes.length; index++) {
  54931. var mesh = this._scene.meshes[index];
  54932. if (mesh.isEnabled() && mesh.checkCollisions && mesh.subMeshes && mesh !== excludedMesh && ((collisionMask & mesh.collisionGroup) !== 0)) {
  54933. mesh._checkCollision(collider);
  54934. }
  54935. }
  54936. if (!collider.collisionFound) {
  54937. position.addToRef(velocity, finalPosition);
  54938. return;
  54939. }
  54940. if (velocity.x !== 0 || velocity.y !== 0 || velocity.z !== 0) {
  54941. collider._getResponse(position, velocity);
  54942. }
  54943. if (velocity.length() <= closeDistance) {
  54944. finalPosition.copyFrom(position);
  54945. return;
  54946. }
  54947. collider._retry++;
  54948. this._collideWithWorld(position, velocity, collider, maximumRetry, finalPosition, excludedMesh);
  54949. };
  54950. return CollisionCoordinatorLegacy;
  54951. }());
  54952. BABYLON.CollisionCoordinatorLegacy = CollisionCoordinatorLegacy;
  54953. })(BABYLON || (BABYLON = {}));
  54954. //# sourceMappingURL=babylon.collisionCoordinator.js.map
  54955. var BABYLON;
  54956. (function (BABYLON) {
  54957. /**
  54958. * A particle represents one of the element emitted by a particle system.
  54959. * This is mainly define by its coordinates, direction, velocity and age.
  54960. */
  54961. var Particle = /** @class */ (function () {
  54962. /**
  54963. * Creates a new instance Particle
  54964. * @param particleSystem the particle system the particle belongs to
  54965. */
  54966. function Particle(
  54967. /**
  54968. * particleSystem the particle system the particle belongs to.
  54969. */
  54970. particleSystem) {
  54971. this.particleSystem = particleSystem;
  54972. /**
  54973. * The world position of the particle in the scene.
  54974. */
  54975. this.position = BABYLON.Vector3.Zero();
  54976. /**
  54977. * The world direction of the particle in the scene.
  54978. */
  54979. this.direction = BABYLON.Vector3.Zero();
  54980. /**
  54981. * The color of the particle.
  54982. */
  54983. this.color = new BABYLON.Color4(0, 0, 0, 0);
  54984. /**
  54985. * The color change of the particle per step.
  54986. */
  54987. this.colorStep = new BABYLON.Color4(0, 0, 0, 0);
  54988. /**
  54989. * Defines how long will the life of the particle be.
  54990. */
  54991. this.lifeTime = 1.0;
  54992. /**
  54993. * The current age of the particle.
  54994. */
  54995. this.age = 0;
  54996. /**
  54997. * The current size of the particle.
  54998. */
  54999. this.size = 0;
  55000. /**
  55001. * The current scale of the particle.
  55002. */
  55003. this.scale = new BABYLON.Vector2(1, 1);
  55004. /**
  55005. * The current angle of the particle.
  55006. */
  55007. this.angle = 0;
  55008. /**
  55009. * Defines how fast is the angle changing.
  55010. */
  55011. this.angularSpeed = 0;
  55012. /**
  55013. * Defines the cell index used by the particle to be rendered from a sprite.
  55014. */
  55015. this.cellIndex = 0;
  55016. /** @hidden */
  55017. this._currentColor1 = new BABYLON.Color4(0, 0, 0, 0);
  55018. /** @hidden */
  55019. this._currentColor2 = new BABYLON.Color4(0, 0, 0, 0);
  55020. /** @hidden */
  55021. this._currentSize1 = 0;
  55022. /** @hidden */
  55023. this._currentSize2 = 0;
  55024. if (!this.particleSystem.isAnimationSheetEnabled) {
  55025. return;
  55026. }
  55027. this.updateCellInfoFromSystem();
  55028. }
  55029. Particle.prototype.updateCellInfoFromSystem = function () {
  55030. this.cellIndex = this.particleSystem.startSpriteCellID;
  55031. };
  55032. /**
  55033. * Defines how the sprite cell index is updated for the particle
  55034. */
  55035. Particle.prototype.updateCellIndex = function () {
  55036. var dist = (this._initialEndSpriteCellID - this._initialStartSpriteCellID);
  55037. var ratio = BABYLON.Scalar.Clamp(((this.age * this.particleSystem.spriteCellChangeSpeed) % this.lifeTime) / this.lifeTime);
  55038. this.cellIndex = this._initialStartSpriteCellID + (ratio * dist) | 0;
  55039. };
  55040. /**
  55041. * Copy the properties of particle to another one.
  55042. * @param other the particle to copy the information to.
  55043. */
  55044. Particle.prototype.copyTo = function (other) {
  55045. other.position.copyFrom(this.position);
  55046. if (this._initialDirection) {
  55047. if (other._initialDirection) {
  55048. other._initialDirection.copyFrom(this._initialDirection);
  55049. }
  55050. else {
  55051. other._initialDirection = this._initialDirection.clone();
  55052. }
  55053. }
  55054. else {
  55055. other._initialDirection = null;
  55056. }
  55057. other.direction.copyFrom(this.direction);
  55058. other.color.copyFrom(this.color);
  55059. other.colorStep.copyFrom(this.colorStep);
  55060. other.lifeTime = this.lifeTime;
  55061. other.age = this.age;
  55062. other.size = this.size;
  55063. other.scale.copyFrom(this.scale);
  55064. other.angle = this.angle;
  55065. other.angularSpeed = this.angularSpeed;
  55066. other.particleSystem = this.particleSystem;
  55067. other.cellIndex = this.cellIndex;
  55068. if (this._currentColorGradient) {
  55069. other._currentColorGradient = this._currentColorGradient;
  55070. other._currentColor1.copyFrom(this._currentColor1);
  55071. other._currentColor2.copyFrom(this._currentColor2);
  55072. }
  55073. if (this._currentSizeGradient) {
  55074. other._currentSizeGradient = this._currentSizeGradient;
  55075. other._currentSize1 = this._currentSize1;
  55076. other._currentSize2 = this._currentSize2;
  55077. }
  55078. if (this.particleSystem.isAnimationSheetEnabled) {
  55079. other._initialStartSpriteCellID = this._initialStartSpriteCellID;
  55080. other._initialEndSpriteCellID = this._initialEndSpriteCellID;
  55081. }
  55082. };
  55083. return Particle;
  55084. }());
  55085. BABYLON.Particle = Particle;
  55086. })(BABYLON || (BABYLON = {}));
  55087. //# sourceMappingURL=babylon.particle.js.map
  55088. var BABYLON;
  55089. (function (BABYLON) {
  55090. /**
  55091. * This represents a particle system in Babylon.
  55092. * 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.
  55093. * Particles can take different shapes while emitted like box, sphere, cone or you can write your custom function.
  55094. * @example https://doc.babylonjs.com/babylon101/particles
  55095. */
  55096. var ParticleSystem = /** @class */ (function () {
  55097. /**
  55098. * Instantiates a particle system.
  55099. * 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.
  55100. * @param name The name of the particle system
  55101. * @param capacity The max number of particles alive at the same time
  55102. * @param scene The scene the particle system belongs to
  55103. * @param customEffect a custom effect used to change the way particles are rendered by default
  55104. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  55105. * @param epsilon Offset used to render the particles
  55106. */
  55107. function ParticleSystem(name, capacity, scene, customEffect, isAnimationSheetEnabled, epsilon) {
  55108. if (customEffect === void 0) { customEffect = null; }
  55109. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55110. if (epsilon === void 0) { epsilon = 0.01; }
  55111. var _this = this;
  55112. /**
  55113. * List of animations used by the particle system.
  55114. */
  55115. this.animations = [];
  55116. /**
  55117. * The rendering group used by the Particle system to chose when to render.
  55118. */
  55119. this.renderingGroupId = 0;
  55120. /**
  55121. * The emitter represents the Mesh or position we are attaching the particle system to.
  55122. */
  55123. this.emitter = null;
  55124. /**
  55125. * The maximum number of particles to emit per frame
  55126. */
  55127. this.emitRate = 10;
  55128. /**
  55129. * If you want to launch only a few particles at once, that can be done, as well.
  55130. */
  55131. this.manualEmitCount = -1;
  55132. /**
  55133. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  55134. */
  55135. this.updateSpeed = 0.01;
  55136. /**
  55137. * The amount of time the particle system is running (depends of the overall update speed).
  55138. */
  55139. this.targetStopDuration = 0;
  55140. /**
  55141. * Specifies whether the particle system will be disposed once it reaches the end of the animation.
  55142. */
  55143. this.disposeOnStop = false;
  55144. /**
  55145. * Minimum power of emitting particles.
  55146. */
  55147. this.minEmitPower = 1;
  55148. /**
  55149. * Maximum power of emitting particles.
  55150. */
  55151. this.maxEmitPower = 1;
  55152. /**
  55153. * Minimum life time of emitting particles.
  55154. */
  55155. this.minLifeTime = 1;
  55156. /**
  55157. * Maximum life time of emitting particles.
  55158. */
  55159. this.maxLifeTime = 1;
  55160. /**
  55161. * Minimum Size of emitting particles.
  55162. */
  55163. this.minSize = 1;
  55164. /**
  55165. * Maximum Size of emitting particles.
  55166. */
  55167. this.maxSize = 1;
  55168. /**
  55169. * Minimum scale of emitting particles on X axis.
  55170. */
  55171. this.minScaleX = 1;
  55172. /**
  55173. * Maximum scale of emitting particles on X axis.
  55174. */
  55175. this.maxScaleX = 1;
  55176. /**
  55177. * Minimum scale of emitting particles on Y axis.
  55178. */
  55179. this.minScaleY = 1;
  55180. /**
  55181. * Maximum scale of emitting particles on Y axis.
  55182. */
  55183. this.maxScaleY = 1;
  55184. /**
  55185. * Gets or sets the minimal initial rotation in radians.
  55186. */
  55187. this.minInitialRotation = 0;
  55188. /**
  55189. * Gets or sets the maximal initial rotation in radians.
  55190. */
  55191. this.maxInitialRotation = 0;
  55192. /**
  55193. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  55194. */
  55195. this.minAngularSpeed = 0;
  55196. /**
  55197. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  55198. */
  55199. this.maxAngularSpeed = 0;
  55200. /**
  55201. * The layer mask we are rendering the particles through.
  55202. */
  55203. this.layerMask = 0x0FFFFFFF;
  55204. /**
  55205. * This can help using your own shader to render the particle system.
  55206. * The according effect will be created
  55207. */
  55208. this.customShader = null;
  55209. /**
  55210. * By default particle system starts as soon as they are created. This prevents the
  55211. * automatic start to happen and let you decide when to start emitting particles.
  55212. */
  55213. this.preventAutoStart = false;
  55214. /**
  55215. * Callback triggered when the particle animation is ending.
  55216. */
  55217. this.onAnimationEnd = null;
  55218. /**
  55219. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  55220. */
  55221. this.blendMode = ParticleSystem.BLENDMODE_ONEONE;
  55222. /**
  55223. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  55224. * to override the particles.
  55225. */
  55226. this.forceDepthWrite = false;
  55227. /**
  55228. * You can use gravity if you want to give an orientation to your particles.
  55229. */
  55230. this.gravity = BABYLON.Vector3.Zero();
  55231. this._colorGradients = null;
  55232. this._sizeGradients = null;
  55233. this._lifeTimeGradients = null;
  55234. /**
  55235. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55236. */
  55237. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55238. /**
  55239. * Random color of each particle after it has been emitted, between color1 and color2 vectors
  55240. */
  55241. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55242. /**
  55243. * Color the particle will have at the end of its lifetime
  55244. */
  55245. this.colorDead = new BABYLON.Color4(0, 0, 0, 1.0);
  55246. /**
  55247. * An optional mask to filter some colors out of the texture, or filter a part of the alpha channel
  55248. */
  55249. this.textureMask = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  55250. /**
  55251. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  55252. */
  55253. this.spriteCellChangeSpeed = 1;
  55254. /**
  55255. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  55256. */
  55257. this.startSpriteCellID = 0;
  55258. /**
  55259. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  55260. */
  55261. this.endSpriteCellID = 0;
  55262. /**
  55263. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  55264. */
  55265. this.spriteCellWidth = 0;
  55266. /**
  55267. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  55268. */
  55269. this.spriteCellHeight = 0;
  55270. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  55271. this.preWarmCycles = 0;
  55272. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  55273. this.preWarmStepOffset = 1;
  55274. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  55275. this.translationPivot = new BABYLON.Vector2(0, 0);
  55276. /**
  55277. * An event triggered when the system is disposed
  55278. */
  55279. this.onDisposeObservable = new BABYLON.Observable();
  55280. /**
  55281. * Gets or sets the billboard mode to use when isBillboardBased = true.
  55282. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  55283. */
  55284. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  55285. this._particles = new Array();
  55286. this._stockParticles = new Array();
  55287. this._newPartsExcess = 0;
  55288. this._vertexBuffers = {};
  55289. this._scaledColorStep = new BABYLON.Color4(0, 0, 0, 0);
  55290. this._colorDiff = new BABYLON.Color4(0, 0, 0, 0);
  55291. this._scaledDirection = BABYLON.Vector3.Zero();
  55292. this._scaledGravity = BABYLON.Vector3.Zero();
  55293. this._currentRenderId = -1;
  55294. this._useInstancing = false;
  55295. this._started = false;
  55296. this._stopped = false;
  55297. this._actualFrame = 0;
  55298. this._isBillboardBased = true;
  55299. // start of sub system methods
  55300. /**
  55301. * "Recycles" one of the particle by copying it back to the "stock" of particles and removing it from the active list.
  55302. * Its lifetime will start back at 0.
  55303. */
  55304. this.recycleParticle = function (particle) {
  55305. var lastParticle = _this._particles.pop();
  55306. if (lastParticle !== particle) {
  55307. lastParticle.copyTo(particle);
  55308. }
  55309. _this._stockParticles.push(lastParticle);
  55310. };
  55311. this._createParticle = function () {
  55312. var particle;
  55313. if (_this._stockParticles.length !== 0) {
  55314. particle = _this._stockParticles.pop();
  55315. particle.age = 0;
  55316. particle._currentColorGradient = null;
  55317. particle.cellIndex = _this.startSpriteCellID;
  55318. }
  55319. else {
  55320. particle = new BABYLON.Particle(_this);
  55321. }
  55322. return particle;
  55323. };
  55324. this._emitFromParticle = function (particle) {
  55325. if (!_this.subEmitters || _this.subEmitters.length === 0) {
  55326. return;
  55327. }
  55328. var templateIndex = Math.floor(Math.random() * _this.subEmitters.length);
  55329. var subSystem = _this.subEmitters[templateIndex].clone(_this.name + "_sub", particle.position.clone());
  55330. subSystem._rootParticleSystem = _this;
  55331. _this.activeSubSystems.push(subSystem);
  55332. subSystem.start();
  55333. };
  55334. this.id = name;
  55335. this.name = name;
  55336. this._capacity = capacity;
  55337. this._epsilon = epsilon;
  55338. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  55339. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  55340. this._customEffect = customEffect;
  55341. scene.particleSystems.push(this);
  55342. this._useInstancing = this._scene.getEngine().getCaps().instancedArrays;
  55343. this._createIndexBuffer();
  55344. this._createVertexBuffers();
  55345. // Default emitter type
  55346. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  55347. this.updateFunction = function (particles) {
  55348. for (var index = 0; index < particles.length; index++) {
  55349. var particle = particles[index];
  55350. particle.age += _this._scaledUpdateSpeed;
  55351. if (particle.age >= particle.lifeTime) { // Recycle by swapping with last particle
  55352. _this._emitFromParticle(particle);
  55353. _this.recycleParticle(particle);
  55354. index--;
  55355. continue;
  55356. }
  55357. else {
  55358. var ratio = particle.age / particle.lifeTime;
  55359. // Color
  55360. if (_this._colorGradients && _this._colorGradients.length > 0) {
  55361. BABYLON.Tools.GetCurrentGradient(ratio, _this._colorGradients, function (currentGradient, nextGradient, scale) {
  55362. if (currentGradient !== particle._currentColorGradient) {
  55363. particle._currentColor1.copyFrom(particle._currentColor2);
  55364. nextGradient.getColorToRef(particle._currentColor2);
  55365. particle._currentColorGradient = currentGradient;
  55366. }
  55367. BABYLON.Color4.LerpToRef(particle._currentColor1, particle._currentColor2, scale, particle.color);
  55368. });
  55369. }
  55370. else {
  55371. particle.colorStep.scaleToRef(_this._scaledUpdateSpeed, _this._scaledColorStep);
  55372. particle.color.addInPlace(_this._scaledColorStep);
  55373. if (particle.color.a < 0) {
  55374. particle.color.a = 0;
  55375. }
  55376. }
  55377. particle.angle += particle.angularSpeed * _this._scaledUpdateSpeed;
  55378. particle.direction.scaleToRef(_this._scaledUpdateSpeed, _this._scaledDirection);
  55379. particle.position.addInPlace(_this._scaledDirection);
  55380. _this.gravity.scaleToRef(_this._scaledUpdateSpeed, _this._scaledGravity);
  55381. particle.direction.addInPlace(_this._scaledGravity);
  55382. // Gradient
  55383. if (_this._sizeGradients && _this._sizeGradients.length > 0) {
  55384. BABYLON.Tools.GetCurrentGradient(ratio, _this._sizeGradients, function (currentGradient, nextGradient, scale) {
  55385. if (currentGradient !== particle._currentSizeGradient) {
  55386. particle._currentSize1 = particle._currentSize2;
  55387. particle._currentSize2 = nextGradient.getFactor();
  55388. particle._currentSizeGradient = currentGradient;
  55389. }
  55390. particle.size = BABYLON.Scalar.Lerp(particle._currentSize1, particle._currentSize2, scale);
  55391. });
  55392. }
  55393. if (_this._isAnimationSheetEnabled) {
  55394. particle.updateCellIndex();
  55395. }
  55396. }
  55397. }
  55398. };
  55399. }
  55400. /**
  55401. * Gets the current list of color gradients.
  55402. * You must use addColorGradient and removeColorGradient to udpate this list
  55403. * @returns the list of color gradients
  55404. */
  55405. ParticleSystem.prototype.getColorGradients = function () {
  55406. return this._colorGradients;
  55407. };
  55408. /**
  55409. * Gets the current list of size gradients.
  55410. * You must use addSizeGradient and removeSizeGradient to udpate this list
  55411. * @returns the list of size gradients
  55412. */
  55413. ParticleSystem.prototype.getSizeGradients = function () {
  55414. return this._sizeGradients;
  55415. };
  55416. /**
  55417. * Gets the current list of life time gradients.
  55418. * You must use addLifeTimeGradient and removeLifeTimeGradient to udpate this list
  55419. * @returns the list of life time gradients
  55420. */
  55421. ParticleSystem.prototype.getLifeTimeGradients = function () {
  55422. return this._lifeTimeGradients;
  55423. };
  55424. Object.defineProperty(ParticleSystem.prototype, "direction1", {
  55425. /**
  55426. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55427. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55428. */
  55429. get: function () {
  55430. if (this.particleEmitterType.direction1) {
  55431. return this.particleEmitterType.direction1;
  55432. }
  55433. return BABYLON.Vector3.Zero();
  55434. },
  55435. set: function (value) {
  55436. if (this.particleEmitterType.direction1) {
  55437. this.particleEmitterType.direction1 = value;
  55438. }
  55439. },
  55440. enumerable: true,
  55441. configurable: true
  55442. });
  55443. Object.defineProperty(ParticleSystem.prototype, "direction2", {
  55444. /**
  55445. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  55446. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55447. */
  55448. get: function () {
  55449. if (this.particleEmitterType.direction2) {
  55450. return this.particleEmitterType.direction2;
  55451. }
  55452. return BABYLON.Vector3.Zero();
  55453. },
  55454. set: function (value) {
  55455. if (this.particleEmitterType.direction2) {
  55456. this.particleEmitterType.direction2 = value;
  55457. }
  55458. },
  55459. enumerable: true,
  55460. configurable: true
  55461. });
  55462. Object.defineProperty(ParticleSystem.prototype, "minEmitBox", {
  55463. /**
  55464. * 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.
  55465. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55466. */
  55467. get: function () {
  55468. if (this.particleEmitterType.minEmitBox) {
  55469. return this.particleEmitterType.minEmitBox;
  55470. }
  55471. return BABYLON.Vector3.Zero();
  55472. },
  55473. set: function (value) {
  55474. if (this.particleEmitterType.minEmitBox) {
  55475. this.particleEmitterType.minEmitBox = value;
  55476. }
  55477. },
  55478. enumerable: true,
  55479. configurable: true
  55480. });
  55481. Object.defineProperty(ParticleSystem.prototype, "maxEmitBox", {
  55482. /**
  55483. * 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.
  55484. * This only works when particleEmitterTyps is a BoxParticleEmitter
  55485. */
  55486. get: function () {
  55487. if (this.particleEmitterType.maxEmitBox) {
  55488. return this.particleEmitterType.maxEmitBox;
  55489. }
  55490. return BABYLON.Vector3.Zero();
  55491. },
  55492. set: function (value) {
  55493. if (this.particleEmitterType.maxEmitBox) {
  55494. this.particleEmitterType.maxEmitBox = value;
  55495. }
  55496. },
  55497. enumerable: true,
  55498. configurable: true
  55499. });
  55500. Object.defineProperty(ParticleSystem.prototype, "onDispose", {
  55501. /**
  55502. * Sets a callback that will be triggered when the system is disposed
  55503. */
  55504. set: function (callback) {
  55505. if (this._onDisposeObserver) {
  55506. this.onDisposeObservable.remove(this._onDisposeObserver);
  55507. }
  55508. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  55509. },
  55510. enumerable: true,
  55511. configurable: true
  55512. });
  55513. Object.defineProperty(ParticleSystem.prototype, "isAnimationSheetEnabled", {
  55514. /**
  55515. * Gets whether an animation sprite sheet is enabled or not on the particle system
  55516. */
  55517. get: function () {
  55518. return this._isAnimationSheetEnabled;
  55519. },
  55520. enumerable: true,
  55521. configurable: true
  55522. });
  55523. Object.defineProperty(ParticleSystem.prototype, "isBillboardBased", {
  55524. /**
  55525. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  55526. */
  55527. get: function () {
  55528. return this._isBillboardBased;
  55529. },
  55530. set: function (value) {
  55531. if (this._isBillboardBased === value) {
  55532. return;
  55533. }
  55534. this._isBillboardBased = value;
  55535. this._resetEffect();
  55536. },
  55537. enumerable: true,
  55538. configurable: true
  55539. });
  55540. Object.defineProperty(ParticleSystem.prototype, "particles", {
  55541. //end of Sub-emitter
  55542. /**
  55543. * Gets the current list of active particles
  55544. */
  55545. get: function () {
  55546. return this._particles;
  55547. },
  55548. enumerable: true,
  55549. configurable: true
  55550. });
  55551. /**
  55552. * Returns the string "ParticleSystem"
  55553. * @returns a string containing the class name
  55554. */
  55555. ParticleSystem.prototype.getClassName = function () {
  55556. return "ParticleSystem";
  55557. };
  55558. ParticleSystem.prototype._addFactorGradient = function (factorGradients, gradient, factor, factor2) {
  55559. var newGradient = new BABYLON.FactorGradient();
  55560. newGradient.gradient = gradient;
  55561. newGradient.factor1 = factor;
  55562. newGradient.factor2 = factor2;
  55563. factorGradients.push(newGradient);
  55564. factorGradients.sort(function (a, b) {
  55565. if (a.gradient < b.gradient) {
  55566. return -1;
  55567. }
  55568. else if (a.gradient > b.gradient) {
  55569. return 1;
  55570. }
  55571. return 0;
  55572. });
  55573. };
  55574. ParticleSystem.prototype._removeFactorGradient = function (factorGradients, gradient) {
  55575. if (!factorGradients) {
  55576. return;
  55577. }
  55578. var index = 0;
  55579. for (var _i = 0, factorGradients_1 = factorGradients; _i < factorGradients_1.length; _i++) {
  55580. var factorGradient = factorGradients_1[_i];
  55581. if (factorGradient.gradient === gradient) {
  55582. factorGradients.splice(index, 1);
  55583. break;
  55584. }
  55585. index++;
  55586. }
  55587. };
  55588. /**
  55589. * Adds a new life time gradient
  55590. * @param gradient defines the gradient to use (between 0 and 1)
  55591. * @param factor defines the life time factor to affect to the specified gradient
  55592. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55593. */
  55594. ParticleSystem.prototype.addLifeTimeGradient = function (gradient, factor, factor2) {
  55595. if (!this._lifeTimeGradients) {
  55596. this._lifeTimeGradients = [];
  55597. }
  55598. this._addFactorGradient(this._lifeTimeGradients, gradient, factor, factor2);
  55599. return this;
  55600. };
  55601. /**
  55602. * Remove a specific life time gradient
  55603. * @param gradient defines the gradient to remove
  55604. */
  55605. ParticleSystem.prototype.removeLifeTimeGradient = function (gradient) {
  55606. this._removeFactorGradient(this._lifeTimeGradients, gradient);
  55607. return this;
  55608. };
  55609. /**
  55610. * Adds a new size gradient
  55611. * @param gradient defines the gradient to use (between 0 and 1)
  55612. * @param factor defines the size factor to affect to the specified gradient
  55613. * @param factor2 defines an additional factor used to define a range ([factor, factor2]) with main value to pick the final value from
  55614. */
  55615. ParticleSystem.prototype.addSizeGradient = function (gradient, factor, factor2) {
  55616. if (!this._sizeGradients) {
  55617. this._sizeGradients = [];
  55618. }
  55619. this._addFactorGradient(this._sizeGradients, gradient, factor, factor2);
  55620. return this;
  55621. };
  55622. /**
  55623. * Remove a specific size gradient
  55624. * @param gradient defines the gradient to remove
  55625. */
  55626. ParticleSystem.prototype.removeSizeGradient = function (gradient) {
  55627. this._removeFactorGradient(this._sizeGradients, gradient);
  55628. return this;
  55629. };
  55630. /**
  55631. * Adds a new color gradient
  55632. * @param gradient defines the gradient to use (between 0 and 1)
  55633. * @param color defines the color to affect to the specified gradient
  55634. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  55635. */
  55636. ParticleSystem.prototype.addColorGradient = function (gradient, color, color2) {
  55637. if (!this._colorGradients) {
  55638. this._colorGradients = [];
  55639. }
  55640. var colorGradient = new BABYLON.ColorGradient();
  55641. colorGradient.gradient = gradient;
  55642. colorGradient.color1 = color;
  55643. colorGradient.color2 = color2;
  55644. this._colorGradients.push(colorGradient);
  55645. this._colorGradients.sort(function (a, b) {
  55646. if (a.gradient < b.gradient) {
  55647. return -1;
  55648. }
  55649. else if (a.gradient > b.gradient) {
  55650. return 1;
  55651. }
  55652. return 0;
  55653. });
  55654. return this;
  55655. };
  55656. /**
  55657. * Remove a specific color gradient
  55658. * @param gradient defines the gradient to remove
  55659. */
  55660. ParticleSystem.prototype.removeColorGradient = function (gradient) {
  55661. if (!this._colorGradients) {
  55662. return this;
  55663. }
  55664. var index = 0;
  55665. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  55666. var colorGradient = _a[_i];
  55667. if (colorGradient.gradient === gradient) {
  55668. this._colorGradients.splice(index, 1);
  55669. break;
  55670. }
  55671. index++;
  55672. }
  55673. return this;
  55674. };
  55675. ParticleSystem.prototype._resetEffect = function () {
  55676. if (this._vertexBuffer) {
  55677. this._vertexBuffer.dispose();
  55678. this._vertexBuffer = null;
  55679. }
  55680. if (this._spriteBuffer) {
  55681. this._spriteBuffer.dispose();
  55682. this._spriteBuffer = null;
  55683. }
  55684. this._createVertexBuffers();
  55685. };
  55686. ParticleSystem.prototype._createVertexBuffers = function () {
  55687. this._vertexBufferSize = this._useInstancing ? 10 : 12;
  55688. if (this._isAnimationSheetEnabled) {
  55689. this._vertexBufferSize += 1;
  55690. }
  55691. if (!this._isBillboardBased) {
  55692. this._vertexBufferSize += 3;
  55693. }
  55694. var engine = this._scene.getEngine();
  55695. this._vertexData = new Float32Array(this._capacity * this._vertexBufferSize * (this._useInstancing ? 1 : 4));
  55696. this._vertexBuffer = new BABYLON.Buffer(engine, this._vertexData, true, this._vertexBufferSize);
  55697. var dataOffset = 0;
  55698. var positions = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.PositionKind, dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55699. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = positions;
  55700. dataOffset += 3;
  55701. var colors = this._vertexBuffer.createVertexBuffer(BABYLON.VertexBuffer.ColorKind, dataOffset, 4, this._vertexBufferSize, this._useInstancing);
  55702. this._vertexBuffers[BABYLON.VertexBuffer.ColorKind] = colors;
  55703. dataOffset += 4;
  55704. var options = this._vertexBuffer.createVertexBuffer("angle", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55705. this._vertexBuffers["angle"] = options;
  55706. dataOffset += 1;
  55707. var size = this._vertexBuffer.createVertexBuffer("size", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55708. this._vertexBuffers["size"] = size;
  55709. dataOffset += 2;
  55710. if (this._isAnimationSheetEnabled) {
  55711. var cellIndexBuffer = this._vertexBuffer.createVertexBuffer("cellIndex", dataOffset, 1, this._vertexBufferSize, this._useInstancing);
  55712. this._vertexBuffers["cellIndex"] = cellIndexBuffer;
  55713. dataOffset += 1;
  55714. }
  55715. if (!this._isBillboardBased) {
  55716. var directionBuffer = this._vertexBuffer.createVertexBuffer("direction", dataOffset, 3, this._vertexBufferSize, this._useInstancing);
  55717. this._vertexBuffers["direction"] = directionBuffer;
  55718. dataOffset += 3;
  55719. }
  55720. var offsets;
  55721. if (this._useInstancing) {
  55722. var spriteData = new Float32Array([0, 0, 1, 0, 1, 1, 0, 1]);
  55723. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 2);
  55724. offsets = this._spriteBuffer.createVertexBuffer("offset", 0, 2);
  55725. }
  55726. else {
  55727. offsets = this._vertexBuffer.createVertexBuffer("offset", dataOffset, 2, this._vertexBufferSize, this._useInstancing);
  55728. dataOffset += 2;
  55729. }
  55730. this._vertexBuffers["offset"] = offsets;
  55731. };
  55732. ParticleSystem.prototype._createIndexBuffer = function () {
  55733. if (this._useInstancing) {
  55734. return;
  55735. }
  55736. var indices = [];
  55737. var index = 0;
  55738. for (var count = 0; count < this._capacity; count++) {
  55739. indices.push(index);
  55740. indices.push(index + 1);
  55741. indices.push(index + 2);
  55742. indices.push(index);
  55743. indices.push(index + 2);
  55744. indices.push(index + 3);
  55745. index += 4;
  55746. }
  55747. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  55748. };
  55749. /**
  55750. * Gets the maximum number of particles active at the same time.
  55751. * @returns The max number of active particles.
  55752. */
  55753. ParticleSystem.prototype.getCapacity = function () {
  55754. return this._capacity;
  55755. };
  55756. /**
  55757. * Gets Wether there are still active particles in the system.
  55758. * @returns True if it is alive, otherwise false.
  55759. */
  55760. ParticleSystem.prototype.isAlive = function () {
  55761. return this._alive;
  55762. };
  55763. /**
  55764. * Gets Wether the system has been started.
  55765. * @returns True if it has been started, otherwise false.
  55766. */
  55767. ParticleSystem.prototype.isStarted = function () {
  55768. return this._started;
  55769. };
  55770. /**
  55771. * Starts the particle system and begins to emit.
  55772. */
  55773. ParticleSystem.prototype.start = function () {
  55774. this._started = true;
  55775. this._stopped = false;
  55776. this._actualFrame = 0;
  55777. if (this.subEmitters && this.subEmitters.length != 0) {
  55778. this.activeSubSystems = new Array();
  55779. }
  55780. if (this.preWarmCycles) {
  55781. for (var index = 0; index < this.preWarmCycles; index++) {
  55782. this.animate(true);
  55783. }
  55784. }
  55785. };
  55786. /**
  55787. * Stops the particle system.
  55788. * @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.
  55789. */
  55790. ParticleSystem.prototype.stop = function (stopSubEmitters) {
  55791. if (stopSubEmitters === void 0) { stopSubEmitters = true; }
  55792. this._stopped = true;
  55793. if (stopSubEmitters) {
  55794. this._stopSubEmitters();
  55795. }
  55796. };
  55797. // animation sheet
  55798. /**
  55799. * Remove all active particles
  55800. */
  55801. ParticleSystem.prototype.reset = function () {
  55802. this._stockParticles = [];
  55803. this._particles = [];
  55804. };
  55805. /**
  55806. * @hidden (for internal use only)
  55807. */
  55808. ParticleSystem.prototype._appendParticleVertex = function (index, particle, offsetX, offsetY) {
  55809. var offset = index * this._vertexBufferSize;
  55810. this._vertexData[offset++] = particle.position.x;
  55811. this._vertexData[offset++] = particle.position.y;
  55812. this._vertexData[offset++] = particle.position.z;
  55813. this._vertexData[offset++] = particle.color.r;
  55814. this._vertexData[offset++] = particle.color.g;
  55815. this._vertexData[offset++] = particle.color.b;
  55816. this._vertexData[offset++] = particle.color.a;
  55817. this._vertexData[offset++] = particle.angle;
  55818. this._vertexData[offset++] = particle.scale.x * particle.size;
  55819. this._vertexData[offset++] = particle.scale.y * particle.size;
  55820. if (this._isAnimationSheetEnabled) {
  55821. this._vertexData[offset++] = particle.cellIndex;
  55822. }
  55823. if (!this._isBillboardBased) {
  55824. if (particle._initialDirection) {
  55825. this._vertexData[offset++] = particle._initialDirection.x;
  55826. this._vertexData[offset++] = particle._initialDirection.y;
  55827. this._vertexData[offset++] = particle._initialDirection.z;
  55828. }
  55829. else {
  55830. this._vertexData[offset++] = particle.direction.x;
  55831. this._vertexData[offset++] = particle.direction.y;
  55832. this._vertexData[offset++] = particle.direction.z;
  55833. }
  55834. }
  55835. if (!this._useInstancing) {
  55836. if (this._isAnimationSheetEnabled) {
  55837. if (offsetX === 0)
  55838. offsetX = this._epsilon;
  55839. else if (offsetX === 1)
  55840. offsetX = 1 - this._epsilon;
  55841. if (offsetY === 0)
  55842. offsetY = this._epsilon;
  55843. else if (offsetY === 1)
  55844. offsetY = 1 - this._epsilon;
  55845. }
  55846. this._vertexData[offset++] = offsetX;
  55847. this._vertexData[offset++] = offsetY;
  55848. }
  55849. };
  55850. ParticleSystem.prototype._stopSubEmitters = function () {
  55851. if (!this.activeSubSystems) {
  55852. return;
  55853. }
  55854. this.activeSubSystems.forEach(function (subSystem) {
  55855. subSystem.stop(true);
  55856. });
  55857. this.activeSubSystems = new Array();
  55858. };
  55859. ParticleSystem.prototype._removeFromRoot = function () {
  55860. if (!this._rootParticleSystem) {
  55861. return;
  55862. }
  55863. var index = this._rootParticleSystem.activeSubSystems.indexOf(this);
  55864. if (index !== -1) {
  55865. this._rootParticleSystem.activeSubSystems.splice(index, 1);
  55866. }
  55867. };
  55868. // End of sub system methods
  55869. ParticleSystem.prototype._update = function (newParticles) {
  55870. // Update current
  55871. this._alive = this._particles.length > 0;
  55872. this.updateFunction(this._particles);
  55873. // Add new ones
  55874. var worldMatrix;
  55875. if (this.emitter.position) {
  55876. var emitterMesh = this.emitter;
  55877. worldMatrix = emitterMesh.getWorldMatrix();
  55878. }
  55879. else {
  55880. var emitterPosition = this.emitter;
  55881. worldMatrix = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  55882. }
  55883. var particle;
  55884. var _loop_1 = function () {
  55885. if (this_1._particles.length === this_1._capacity) {
  55886. return "break";
  55887. }
  55888. particle = this_1._createParticle();
  55889. this_1._particles.push(particle);
  55890. // Emitter
  55891. var emitPower = BABYLON.Scalar.RandomRange(this_1.minEmitPower, this_1.maxEmitPower);
  55892. if (this_1.startPositionFunction) {
  55893. this_1.startPositionFunction(worldMatrix, particle.position, particle);
  55894. }
  55895. else {
  55896. this_1.particleEmitterType.startPositionFunction(worldMatrix, particle.position, particle);
  55897. }
  55898. if (this_1.startDirectionFunction) {
  55899. this_1.startDirectionFunction(worldMatrix, particle.direction, particle);
  55900. }
  55901. else {
  55902. this_1.particleEmitterType.startDirectionFunction(worldMatrix, particle.direction, particle);
  55903. }
  55904. if (emitPower === 0) {
  55905. if (!particle._initialDirection) {
  55906. particle._initialDirection = particle.direction.clone();
  55907. }
  55908. else {
  55909. particle._initialDirection.copyFrom(particle.direction);
  55910. }
  55911. }
  55912. else {
  55913. particle._initialDirection = null;
  55914. }
  55915. particle.direction.scaleInPlace(emitPower);
  55916. // Life time
  55917. if (this_1.targetStopDuration && this_1._lifeTimeGradients && this_1._lifeTimeGradients.length > 0) {
  55918. var ratio_1 = BABYLON.Scalar.Clamp(this_1._actualFrame / this_1.targetStopDuration);
  55919. BABYLON.Tools.GetCurrentGradient(ratio_1, this_1._lifeTimeGradients, function (currentGradient, nextGradient, scale) {
  55920. var factorGradient1 = currentGradient;
  55921. var factorGradient2 = nextGradient;
  55922. var lifeTime1 = factorGradient1.getFactor();
  55923. var lifeTime2 = factorGradient2.getFactor();
  55924. var gradient = (ratio_1 - factorGradient1.gradient) / (factorGradient2.gradient - factorGradient1.gradient);
  55925. particle.lifeTime = BABYLON.Scalar.Lerp(lifeTime1, lifeTime2, gradient);
  55926. });
  55927. }
  55928. else {
  55929. particle.lifeTime = BABYLON.Scalar.RandomRange(this_1.minLifeTime, this_1.maxLifeTime);
  55930. }
  55931. // Size
  55932. if (!this_1._sizeGradients || this_1._sizeGradients.length === 0) {
  55933. particle.size = BABYLON.Scalar.RandomRange(this_1.minSize, this_1.maxSize);
  55934. }
  55935. else {
  55936. particle._currentSizeGradient = this_1._sizeGradients[0];
  55937. particle._currentSize1 = particle._currentSizeGradient.getFactor();
  55938. particle.size = particle._currentSize1;
  55939. if (this_1._sizeGradients.length > 1) {
  55940. particle._currentSize2 = this_1._sizeGradients[1].getFactor();
  55941. }
  55942. else {
  55943. particle._currentSize2 = particle._currentSize1;
  55944. }
  55945. }
  55946. // Size and scale
  55947. particle.scale.copyFromFloats(BABYLON.Scalar.RandomRange(this_1.minScaleX, this_1.maxScaleX), BABYLON.Scalar.RandomRange(this_1.minScaleY, this_1.maxScaleY));
  55948. // Angle
  55949. particle.angularSpeed = BABYLON.Scalar.RandomRange(this_1.minAngularSpeed, this_1.maxAngularSpeed);
  55950. particle.angle = BABYLON.Scalar.RandomRange(this_1.minInitialRotation, this_1.maxInitialRotation);
  55951. // Color
  55952. if (!this_1._colorGradients || this_1._colorGradients.length === 0) {
  55953. step = BABYLON.Scalar.RandomRange(0, 1.0);
  55954. BABYLON.Color4.LerpToRef(this_1.color1, this_1.color2, step, particle.color);
  55955. this_1.colorDead.subtractToRef(particle.color, this_1._colorDiff);
  55956. this_1._colorDiff.scaleToRef(1.0 / particle.lifeTime, particle.colorStep);
  55957. }
  55958. else {
  55959. particle._currentColorGradient = this_1._colorGradients[0];
  55960. particle._currentColorGradient.getColorToRef(particle.color);
  55961. particle._currentColor1.copyFrom(particle.color);
  55962. if (this_1._colorGradients.length > 1) {
  55963. this_1._colorGradients[1].getColorToRef(particle._currentColor2);
  55964. }
  55965. else {
  55966. particle._currentColor2.copyFrom(particle.color);
  55967. }
  55968. }
  55969. // Sheet
  55970. if (this_1._isAnimationSheetEnabled) {
  55971. particle._initialStartSpriteCellID = this_1.startSpriteCellID;
  55972. particle._initialEndSpriteCellID = this_1.endSpriteCellID;
  55973. }
  55974. };
  55975. var this_1 = this, step;
  55976. for (var index = 0; index < newParticles; index++) {
  55977. var state_1 = _loop_1();
  55978. if (state_1 === "break")
  55979. break;
  55980. }
  55981. };
  55982. /** @hidden */
  55983. ParticleSystem._GetAttributeNamesOrOptions = function (isAnimationSheetEnabled, isBillboardBased) {
  55984. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55985. if (isBillboardBased === void 0) { isBillboardBased = false; }
  55986. var attributeNamesOrOptions = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.ColorKind, "angle", "offset", "size"];
  55987. if (isAnimationSheetEnabled) {
  55988. attributeNamesOrOptions.push("cellIndex");
  55989. }
  55990. if (!isBillboardBased) {
  55991. attributeNamesOrOptions.push("direction");
  55992. }
  55993. return attributeNamesOrOptions;
  55994. };
  55995. ParticleSystem._GetEffectCreationOptions = function (isAnimationSheetEnabled) {
  55996. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  55997. var effectCreationOption = ["invView", "view", "projection", "vClipPlane", "textureMask", "translationPivot", "eyePosition"];
  55998. if (isAnimationSheetEnabled) {
  55999. effectCreationOption.push("particlesInfos");
  56000. }
  56001. return effectCreationOption;
  56002. };
  56003. ParticleSystem.prototype._getEffect = function () {
  56004. if (this._customEffect) {
  56005. return this._customEffect;
  56006. }
  56007. ;
  56008. var defines = [];
  56009. if (this._scene.clipPlane) {
  56010. defines.push("#define CLIPPLANE");
  56011. }
  56012. if (this._isAnimationSheetEnabled) {
  56013. defines.push("#define ANIMATESHEET");
  56014. }
  56015. if (this._isBillboardBased) {
  56016. defines.push("#define BILLBOARD");
  56017. switch (this.billboardMode) {
  56018. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  56019. defines.push("#define BILLBOARDY");
  56020. break;
  56021. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  56022. default:
  56023. break;
  56024. }
  56025. }
  56026. // Effect
  56027. var join = defines.join("\n");
  56028. if (this._cachedDefines !== join) {
  56029. this._cachedDefines = join;
  56030. var attributesNamesOrOptions = ParticleSystem._GetAttributeNamesOrOptions(this._isAnimationSheetEnabled, this._isBillboardBased);
  56031. var effectCreationOption = ParticleSystem._GetEffectCreationOptions(this._isAnimationSheetEnabled);
  56032. this._effect = this._scene.getEngine().createEffect("particles", attributesNamesOrOptions, effectCreationOption, ["diffuseSampler"], join);
  56033. }
  56034. return this._effect;
  56035. };
  56036. /**
  56037. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  56038. * @param preWarmOnly will prevent the system from updating the vertex buffer (default is false)
  56039. */
  56040. ParticleSystem.prototype.animate = function (preWarmOnly) {
  56041. if (preWarmOnly === void 0) { preWarmOnly = false; }
  56042. if (!this._started)
  56043. return;
  56044. if (!preWarmOnly) {
  56045. var effect = this._getEffect();
  56046. // Check
  56047. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady())
  56048. return;
  56049. if (this._currentRenderId === this._scene.getRenderId()) {
  56050. return;
  56051. }
  56052. this._currentRenderId = this._scene.getRenderId();
  56053. }
  56054. this._scaledUpdateSpeed = this.updateSpeed * (preWarmOnly ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  56055. // determine the number of particles we need to create
  56056. var newParticles;
  56057. if (this.manualEmitCount > -1) {
  56058. newParticles = this.manualEmitCount;
  56059. this._newPartsExcess = 0;
  56060. this.manualEmitCount = 0;
  56061. }
  56062. else {
  56063. newParticles = ((this.emitRate * this._scaledUpdateSpeed) >> 0);
  56064. this._newPartsExcess += this.emitRate * this._scaledUpdateSpeed - newParticles;
  56065. }
  56066. if (this._newPartsExcess > 1.0) {
  56067. newParticles += this._newPartsExcess >> 0;
  56068. this._newPartsExcess -= this._newPartsExcess >> 0;
  56069. }
  56070. this._alive = false;
  56071. if (!this._stopped) {
  56072. this._actualFrame += this._scaledUpdateSpeed;
  56073. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration)
  56074. this.stop();
  56075. }
  56076. else {
  56077. newParticles = 0;
  56078. }
  56079. this._update(newParticles);
  56080. // Stopped?
  56081. if (this._stopped) {
  56082. if (!this._alive) {
  56083. this._started = false;
  56084. if (this.onAnimationEnd) {
  56085. this.onAnimationEnd();
  56086. }
  56087. if (this.disposeOnStop) {
  56088. this._scene._toBeDisposed.push(this);
  56089. }
  56090. }
  56091. }
  56092. if (!preWarmOnly) {
  56093. // Update VBO
  56094. var offset = 0;
  56095. for (var index = 0; index < this._particles.length; index++) {
  56096. var particle = this._particles[index];
  56097. this._appendParticleVertices(offset, particle);
  56098. offset += this._useInstancing ? 1 : 4;
  56099. }
  56100. if (this._vertexBuffer) {
  56101. this._vertexBuffer.update(this._vertexData);
  56102. }
  56103. }
  56104. if (this.manualEmitCount === 0 && this.disposeOnStop) {
  56105. this.stop();
  56106. }
  56107. };
  56108. ParticleSystem.prototype._appendParticleVertices = function (offset, particle) {
  56109. this._appendParticleVertex(offset++, particle, 0, 0);
  56110. if (!this._useInstancing) {
  56111. this._appendParticleVertex(offset++, particle, 1, 0);
  56112. this._appendParticleVertex(offset++, particle, 1, 1);
  56113. this._appendParticleVertex(offset++, particle, 0, 1);
  56114. }
  56115. };
  56116. /**
  56117. * Rebuilds the particle system.
  56118. */
  56119. ParticleSystem.prototype.rebuild = function () {
  56120. this._createIndexBuffer();
  56121. if (this._vertexBuffer) {
  56122. this._vertexBuffer._rebuild();
  56123. }
  56124. };
  56125. /**
  56126. * Is this system ready to be used/rendered
  56127. * @return true if the system is ready
  56128. */
  56129. ParticleSystem.prototype.isReady = function () {
  56130. var effect = this._getEffect();
  56131. if (!this.emitter || !effect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  56132. return false;
  56133. }
  56134. return true;
  56135. };
  56136. /**
  56137. * Renders the particle system in its current state.
  56138. * @returns the current number of particles
  56139. */
  56140. ParticleSystem.prototype.render = function () {
  56141. var effect = this._getEffect();
  56142. // Check
  56143. if (!this.isReady() || !this._particles.length) {
  56144. return 0;
  56145. }
  56146. var engine = this._scene.getEngine();
  56147. // Render
  56148. engine.enableEffect(effect);
  56149. engine.setState(false);
  56150. var viewMatrix = this._scene.getViewMatrix();
  56151. effect.setTexture("diffuseSampler", this.particleTexture);
  56152. effect.setMatrix("view", viewMatrix);
  56153. effect.setMatrix("projection", this._scene.getProjectionMatrix());
  56154. if (this._isAnimationSheetEnabled && this.particleTexture) {
  56155. var baseSize = this.particleTexture.getBaseSize();
  56156. effect.setFloat3("particlesInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  56157. }
  56158. effect.setVector2("translationPivot", this.translationPivot);
  56159. effect.setFloat4("textureMask", this.textureMask.r, this.textureMask.g, this.textureMask.b, this.textureMask.a);
  56160. if (this._isBillboardBased) {
  56161. var camera = this._scene.activeCamera;
  56162. effect.setVector3("eyePosition", camera.globalPosition);
  56163. }
  56164. if (this._scene.clipPlane) {
  56165. var clipPlane = this._scene.clipPlane;
  56166. var invView = viewMatrix.clone();
  56167. invView.invert();
  56168. effect.setMatrix("invView", invView);
  56169. effect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  56170. }
  56171. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  56172. // Draw order
  56173. switch (this.blendMode) {
  56174. case ParticleSystem.BLENDMODE_ADD:
  56175. engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  56176. break;
  56177. case ParticleSystem.BLENDMODE_ONEONE:
  56178. engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  56179. break;
  56180. case ParticleSystem.BLENDMODE_STANDARD:
  56181. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  56182. break;
  56183. }
  56184. if (this.forceDepthWrite) {
  56185. engine.setDepthWrite(true);
  56186. }
  56187. if (this._useInstancing) {
  56188. engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._particles.length);
  56189. engine.unbindInstanceAttributes();
  56190. }
  56191. else {
  56192. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._particles.length * 6);
  56193. }
  56194. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  56195. return this._particles.length;
  56196. };
  56197. /**
  56198. * Disposes the particle system and free the associated resources
  56199. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  56200. */
  56201. ParticleSystem.prototype.dispose = function (disposeTexture) {
  56202. if (disposeTexture === void 0) { disposeTexture = true; }
  56203. if (this._vertexBuffer) {
  56204. this._vertexBuffer.dispose();
  56205. this._vertexBuffer = null;
  56206. }
  56207. if (this._spriteBuffer) {
  56208. this._spriteBuffer.dispose();
  56209. this._spriteBuffer = null;
  56210. }
  56211. if (this._indexBuffer) {
  56212. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  56213. this._indexBuffer = null;
  56214. }
  56215. if (disposeTexture && this.particleTexture) {
  56216. this.particleTexture.dispose();
  56217. this.particleTexture = null;
  56218. }
  56219. this._removeFromRoot();
  56220. // Remove from scene
  56221. var index = this._scene.particleSystems.indexOf(this);
  56222. if (index > -1) {
  56223. this._scene.particleSystems.splice(index, 1);
  56224. }
  56225. // Callback
  56226. this.onDisposeObservable.notifyObservers(this);
  56227. this.onDisposeObservable.clear();
  56228. };
  56229. /**
  56230. * Creates a Sphere Emitter for the particle system. (emits along the sphere radius)
  56231. * @param radius The radius of the sphere to emit from
  56232. * @returns the emitter
  56233. */
  56234. ParticleSystem.prototype.createSphereEmitter = function (radius) {
  56235. if (radius === void 0) { radius = 1; }
  56236. var particleEmitter = new BABYLON.SphereParticleEmitter(radius);
  56237. this.particleEmitterType = particleEmitter;
  56238. return particleEmitter;
  56239. };
  56240. /**
  56241. * Creates a Directed Sphere Emitter for the particle system. (emits between direction1 and direction2)
  56242. * @param radius The radius of the sphere to emit from
  56243. * @param direction1 Particles are emitted between the direction1 and direction2 from within the sphere
  56244. * @param direction2 Particles are emitted between the direction1 and direction2 from within the sphere
  56245. * @returns the emitter
  56246. */
  56247. ParticleSystem.prototype.createDirectedSphereEmitter = function (radius, direction1, direction2) {
  56248. if (radius === void 0) { radius = 1; }
  56249. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1.0, 0); }
  56250. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1.0, 0); }
  56251. var particleEmitter = new BABYLON.SphereDirectedParticleEmitter(radius, direction1, direction2);
  56252. this.particleEmitterType = particleEmitter;
  56253. return particleEmitter;
  56254. };
  56255. /**
  56256. * Creates a Cone Emitter for the particle system. (emits from the cone to the particle position)
  56257. * @param radius The radius of the cone to emit from
  56258. * @param angle The base angle of the cone
  56259. * @returns the emitter
  56260. */
  56261. ParticleSystem.prototype.createConeEmitter = function (radius, angle) {
  56262. if (radius === void 0) { radius = 1; }
  56263. if (angle === void 0) { angle = Math.PI / 4; }
  56264. var particleEmitter = new BABYLON.ConeParticleEmitter(radius, angle);
  56265. this.particleEmitterType = particleEmitter;
  56266. return particleEmitter;
  56267. };
  56268. // 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.
  56269. /**
  56270. * Creates a Box Emitter for the particle system. (emits between direction1 and direction2 from withing the box defined by minEmitBox and maxEmitBox)
  56271. * @param direction1 Particles are emitted between the direction1 and direction2 from within the box
  56272. * @param direction2 Particles are emitted between the direction1 and direction2 from within the box
  56273. * @param minEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56274. * @param maxEmitBox Particles are emitted from the box between minEmitBox and maxEmitBox
  56275. * @returns the emitter
  56276. */
  56277. ParticleSystem.prototype.createBoxEmitter = function (direction1, direction2, minEmitBox, maxEmitBox) {
  56278. var particleEmitter = new BABYLON.BoxParticleEmitter();
  56279. this.particleEmitterType = particleEmitter;
  56280. this.direction1 = direction1;
  56281. this.direction2 = direction2;
  56282. this.minEmitBox = minEmitBox;
  56283. this.maxEmitBox = maxEmitBox;
  56284. return particleEmitter;
  56285. };
  56286. // Clone
  56287. /**
  56288. * Clones the particle system.
  56289. * @param name The name of the cloned object
  56290. * @param newEmitter The new emitter to use
  56291. * @returns the cloned particle system
  56292. */
  56293. ParticleSystem.prototype.clone = function (name, newEmitter) {
  56294. var custom = null;
  56295. var program = null;
  56296. if (this.customShader != null) {
  56297. program = this.customShader;
  56298. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56299. custom = this._scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56300. }
  56301. else if (this._customEffect) {
  56302. custom = this._customEffect;
  56303. }
  56304. var result = new ParticleSystem(name, this._capacity, this._scene, custom);
  56305. result.customShader = program;
  56306. BABYLON.Tools.DeepCopy(this, result, ["particles", "customShader"]);
  56307. if (newEmitter === undefined) {
  56308. newEmitter = this.emitter;
  56309. }
  56310. result.emitter = newEmitter;
  56311. if (this.particleTexture) {
  56312. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  56313. }
  56314. if (!this.preventAutoStart) {
  56315. result.start();
  56316. }
  56317. return result;
  56318. };
  56319. /**
  56320. * Serializes the particle system to a JSON object.
  56321. * @returns the JSON object
  56322. */
  56323. ParticleSystem.prototype.serialize = function () {
  56324. var serializationObject = {};
  56325. ParticleSystem._Serialize(serializationObject, this);
  56326. serializationObject.textureMask = this.textureMask.asArray();
  56327. serializationObject.customShader = this.customShader;
  56328. serializationObject.preventAutoStart = this.preventAutoStart;
  56329. serializationObject.isAnimationSheetEnabled = this._isAnimationSheetEnabled;
  56330. return serializationObject;
  56331. };
  56332. /** @hidden */
  56333. ParticleSystem._Serialize = function (serializationObject, particleSystem) {
  56334. serializationObject.name = particleSystem.name;
  56335. serializationObject.id = particleSystem.id;
  56336. serializationObject.capacity = particleSystem.getCapacity();
  56337. // Emitter
  56338. if (particleSystem.emitter.position) {
  56339. var emitterMesh = particleSystem.emitter;
  56340. serializationObject.emitterId = emitterMesh.id;
  56341. }
  56342. else {
  56343. var emitterPosition = particleSystem.emitter;
  56344. serializationObject.emitter = emitterPosition.asArray();
  56345. }
  56346. // Emitter
  56347. if (particleSystem.particleEmitterType) {
  56348. serializationObject.particleEmitterType = particleSystem.particleEmitterType.serialize();
  56349. }
  56350. if (particleSystem.particleTexture) {
  56351. serializationObject.textureName = particleSystem.particleTexture.name;
  56352. }
  56353. // Animations
  56354. BABYLON.Animation.AppendSerializedAnimations(particleSystem, serializationObject);
  56355. // Particle system
  56356. serializationObject.renderingGroupId = particleSystem.renderingGroupId;
  56357. serializationObject.isBillboardBased = particleSystem.isBillboardBased;
  56358. serializationObject.minAngularSpeed = particleSystem.minAngularSpeed;
  56359. serializationObject.maxAngularSpeed = particleSystem.maxAngularSpeed;
  56360. serializationObject.minSize = particleSystem.minSize;
  56361. serializationObject.maxSize = particleSystem.maxSize;
  56362. serializationObject.minScaleX = particleSystem.minScaleX;
  56363. serializationObject.maxScaleX = particleSystem.maxScaleX;
  56364. serializationObject.minScaleY = particleSystem.minScaleY;
  56365. serializationObject.maxScaleY = particleSystem.maxScaleY;
  56366. serializationObject.minEmitPower = particleSystem.minEmitPower;
  56367. serializationObject.maxEmitPower = particleSystem.maxEmitPower;
  56368. serializationObject.minLifeTime = particleSystem.minLifeTime;
  56369. serializationObject.maxLifeTime = particleSystem.maxLifeTime;
  56370. serializationObject.emitRate = particleSystem.emitRate;
  56371. serializationObject.gravity = particleSystem.gravity.asArray();
  56372. serializationObject.color1 = particleSystem.color1.asArray();
  56373. serializationObject.color2 = particleSystem.color2.asArray();
  56374. serializationObject.colorDead = particleSystem.colorDead.asArray();
  56375. serializationObject.updateSpeed = particleSystem.updateSpeed;
  56376. serializationObject.targetStopDuration = particleSystem.targetStopDuration;
  56377. serializationObject.blendMode = particleSystem.blendMode;
  56378. serializationObject.preWarmCycles = particleSystem.preWarmCycles;
  56379. serializationObject.preWarmStepOffset = particleSystem.preWarmStepOffset;
  56380. serializationObject.minInitialRotation = particleSystem.minInitialRotation;
  56381. serializationObject.maxInitialRotation = particleSystem.maxInitialRotation;
  56382. serializationObject.startSpriteCellID = particleSystem.startSpriteCellID;
  56383. serializationObject.endSpriteCellID = particleSystem.endSpriteCellID;
  56384. serializationObject.spriteCellChangeSpeed = particleSystem.spriteCellChangeSpeed;
  56385. serializationObject.spriteCellWidth = particleSystem.spriteCellWidth;
  56386. serializationObject.spriteCellHeight = particleSystem.spriteCellHeight;
  56387. var colorGradients = particleSystem.getColorGradients();
  56388. if (colorGradients) {
  56389. serializationObject.colorGradients = [];
  56390. for (var _i = 0, colorGradients_1 = colorGradients; _i < colorGradients_1.length; _i++) {
  56391. var colorGradient = colorGradients_1[_i];
  56392. var serializedGradient = {
  56393. gradient: colorGradient.gradient,
  56394. color1: colorGradient.color1.asArray()
  56395. };
  56396. if (colorGradient.color2) {
  56397. serializedGradient.color2 = colorGradient.color2.asArray();
  56398. }
  56399. serializationObject.colorGradients.push(serializedGradient);
  56400. }
  56401. }
  56402. var sizeGradients = particleSystem.getSizeGradients();
  56403. if (sizeGradients) {
  56404. serializationObject.sizeGradients = [];
  56405. for (var _a = 0, sizeGradients_1 = sizeGradients; _a < sizeGradients_1.length; _a++) {
  56406. var sizeGradient = sizeGradients_1[_a];
  56407. var serializedGradient = {
  56408. gradient: sizeGradient.gradient,
  56409. factor1: sizeGradient.factor1
  56410. };
  56411. if (sizeGradient.factor2 !== undefined) {
  56412. serializedGradient.factor2 = sizeGradient.factor2;
  56413. }
  56414. serializationObject.sizeGradients.push(serializedGradient);
  56415. }
  56416. }
  56417. };
  56418. /** @hidden */
  56419. ParticleSystem._Parse = function (parsedParticleSystem, particleSystem, scene, rootUrl) {
  56420. // Texture
  56421. if (parsedParticleSystem.textureName) {
  56422. particleSystem.particleTexture = new BABYLON.Texture(rootUrl + parsedParticleSystem.textureName, scene);
  56423. particleSystem.particleTexture.name = parsedParticleSystem.textureName;
  56424. }
  56425. // Emitter
  56426. if (parsedParticleSystem.emitterId === undefined) {
  56427. particleSystem.emitter = BABYLON.Vector3.Zero();
  56428. }
  56429. else if (parsedParticleSystem.emitterId) {
  56430. particleSystem.emitter = scene.getLastMeshByID(parsedParticleSystem.emitterId);
  56431. }
  56432. else {
  56433. particleSystem.emitter = BABYLON.Vector3.FromArray(parsedParticleSystem.emitter);
  56434. }
  56435. // Misc.
  56436. if (parsedParticleSystem.renderingGroupId !== undefined) {
  56437. particleSystem.renderingGroupId = parsedParticleSystem.renderingGroupId;
  56438. }
  56439. if (parsedParticleSystem.isBillboardBased !== undefined) {
  56440. particleSystem.isBillboardBased = parsedParticleSystem.isBillboardBased;
  56441. }
  56442. // Animations
  56443. if (parsedParticleSystem.animations) {
  56444. for (var animationIndex = 0; animationIndex < parsedParticleSystem.animations.length; animationIndex++) {
  56445. var parsedAnimation = parsedParticleSystem.animations[animationIndex];
  56446. particleSystem.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  56447. }
  56448. }
  56449. if (parsedParticleSystem.autoAnimate) {
  56450. scene.beginAnimation(particleSystem, parsedParticleSystem.autoAnimateFrom, parsedParticleSystem.autoAnimateTo, parsedParticleSystem.autoAnimateLoop, parsedParticleSystem.autoAnimateSpeed || 1.0);
  56451. }
  56452. // Particle system
  56453. particleSystem.minAngularSpeed = parsedParticleSystem.minAngularSpeed;
  56454. particleSystem.maxAngularSpeed = parsedParticleSystem.maxAngularSpeed;
  56455. particleSystem.minSize = parsedParticleSystem.minSize;
  56456. particleSystem.maxSize = parsedParticleSystem.maxSize;
  56457. if (parsedParticleSystem.minScaleX) {
  56458. particleSystem.minScaleX = parsedParticleSystem.minScaleX;
  56459. particleSystem.maxScaleX = parsedParticleSystem.maxScaleX;
  56460. particleSystem.minScaleY = parsedParticleSystem.minScaleY;
  56461. particleSystem.maxScaleY = parsedParticleSystem.maxScaleY;
  56462. }
  56463. if (parsedParticleSystem.preWarmCycles !== undefined) {
  56464. particleSystem.preWarmCycles = parsedParticleSystem.preWarmCycles;
  56465. particleSystem.preWarmStepOffset = parsedParticleSystem.preWarmStepOffset;
  56466. }
  56467. if (parsedParticleSystem.minInitialRotation !== undefined) {
  56468. particleSystem.minInitialRotation = parsedParticleSystem.minInitialRotation;
  56469. particleSystem.maxInitialRotation = parsedParticleSystem.maxInitialRotation;
  56470. }
  56471. particleSystem.minLifeTime = parsedParticleSystem.minLifeTime;
  56472. particleSystem.maxLifeTime = parsedParticleSystem.maxLifeTime;
  56473. particleSystem.minEmitPower = parsedParticleSystem.minEmitPower;
  56474. particleSystem.maxEmitPower = parsedParticleSystem.maxEmitPower;
  56475. particleSystem.emitRate = parsedParticleSystem.emitRate;
  56476. particleSystem.gravity = BABYLON.Vector3.FromArray(parsedParticleSystem.gravity);
  56477. particleSystem.color1 = BABYLON.Color4.FromArray(parsedParticleSystem.color1);
  56478. particleSystem.color2 = BABYLON.Color4.FromArray(parsedParticleSystem.color2);
  56479. particleSystem.colorDead = BABYLON.Color4.FromArray(parsedParticleSystem.colorDead);
  56480. particleSystem.updateSpeed = parsedParticleSystem.updateSpeed;
  56481. particleSystem.targetStopDuration = parsedParticleSystem.targetStopDuration;
  56482. particleSystem.blendMode = parsedParticleSystem.blendMode;
  56483. if (parsedParticleSystem.colorGradients) {
  56484. for (var _i = 0, _a = parsedParticleSystem.colorGradients; _i < _a.length; _i++) {
  56485. var colorGradient = _a[_i];
  56486. particleSystem.addColorGradient(colorGradient.gradient, BABYLON.Color4.FromArray(colorGradient.color1), colorGradient.color2 ? BABYLON.Color4.FromArray(colorGradient.color2) : undefined);
  56487. }
  56488. }
  56489. if (parsedParticleSystem.sizeGradients) {
  56490. for (var _b = 0, _c = parsedParticleSystem.sizeGradients; _b < _c.length; _b++) {
  56491. var sizeGradient = _c[_b];
  56492. particleSystem.addSizeGradient(sizeGradient.gradient, sizeGradient.factor1 !== undefined ? sizeGradient.factor1 : sizeGradient.factor, sizeGradient.factor2);
  56493. }
  56494. }
  56495. // Emitter
  56496. var emitterType;
  56497. if (parsedParticleSystem.particleEmitterType) {
  56498. switch (parsedParticleSystem.particleEmitterType.type) {
  56499. case "SphereParticleEmitter":
  56500. emitterType = new BABYLON.SphereParticleEmitter();
  56501. break;
  56502. case "SphereDirectedParticleEmitter":
  56503. emitterType = new BABYLON.SphereDirectedParticleEmitter();
  56504. break;
  56505. case "ConeEmitter":
  56506. case "ConeParticleEmitter":
  56507. emitterType = new BABYLON.ConeParticleEmitter();
  56508. break;
  56509. case "BoxEmitter":
  56510. case "BoxParticleEmitter":
  56511. default:
  56512. emitterType = new BABYLON.BoxParticleEmitter();
  56513. break;
  56514. }
  56515. emitterType.parse(parsedParticleSystem.particleEmitterType);
  56516. }
  56517. else {
  56518. emitterType = new BABYLON.BoxParticleEmitter();
  56519. emitterType.parse(parsedParticleSystem);
  56520. }
  56521. particleSystem.particleEmitterType = emitterType;
  56522. // Animation sheet
  56523. particleSystem.startSpriteCellID = parsedParticleSystem.startSpriteCellID;
  56524. particleSystem.endSpriteCellID = parsedParticleSystem.endSpriteCellID;
  56525. particleSystem.spriteCellWidth = parsedParticleSystem.spriteCellWidth;
  56526. particleSystem.spriteCellHeight = parsedParticleSystem.spriteCellHeight;
  56527. particleSystem.spriteCellChangeSpeed = parsedParticleSystem.spriteCellChangeSpeed;
  56528. };
  56529. /**
  56530. * Parses a JSON object to create a particle system.
  56531. * @param parsedParticleSystem The JSON object to parse
  56532. * @param scene The scene to create the particle system in
  56533. * @param rootUrl The root url to use to load external dependencies like texture
  56534. * @returns the Parsed particle system
  56535. */
  56536. ParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  56537. var name = parsedParticleSystem.name;
  56538. var custom = null;
  56539. var program = null;
  56540. if (parsedParticleSystem.customShader) {
  56541. program = parsedParticleSystem.customShader;
  56542. var defines = (program.shaderOptions.defines.length > 0) ? program.shaderOptions.defines.join("\n") : "";
  56543. custom = scene.getEngine().createEffectForParticles(program.shaderPath.fragmentElement, program.shaderOptions.uniforms, program.shaderOptions.samplers, defines);
  56544. }
  56545. var particleSystem = new ParticleSystem(name, parsedParticleSystem.capacity, scene, custom, parsedParticleSystem.isAnimationSheetEnabled);
  56546. particleSystem.customShader = program;
  56547. if (parsedParticleSystem.id) {
  56548. particleSystem.id = parsedParticleSystem.id;
  56549. }
  56550. // Auto start
  56551. if (parsedParticleSystem.preventAutoStart) {
  56552. particleSystem.preventAutoStart = parsedParticleSystem.preventAutoStart;
  56553. }
  56554. ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  56555. particleSystem.textureMask = BABYLON.Color4.FromArray(parsedParticleSystem.textureMask);
  56556. if (!particleSystem.preventAutoStart) {
  56557. particleSystem.start();
  56558. }
  56559. return particleSystem;
  56560. };
  56561. /**
  56562. * Source color is added to the destination color without alpha affecting the result.
  56563. */
  56564. ParticleSystem.BLENDMODE_ONEONE = 0;
  56565. /**
  56566. * Blend current color and particle color using particle’s alpha.
  56567. */
  56568. ParticleSystem.BLENDMODE_STANDARD = 1;
  56569. /**
  56570. * Add current color and particle color multiplied by particle’s alpha.
  56571. */
  56572. ParticleSystem.BLENDMODE_ADD = 2;
  56573. return ParticleSystem;
  56574. }());
  56575. BABYLON.ParticleSystem = ParticleSystem;
  56576. })(BABYLON || (BABYLON = {}));
  56577. //# sourceMappingURL=babylon.particleSystem.js.map
  56578. //# sourceMappingURL=babylon.IParticleEmitterType.js.map
  56579. var BABYLON;
  56580. (function (BABYLON) {
  56581. /**
  56582. * Particle emitter emitting particles from the inside of a box.
  56583. * It emits the particles randomly between 2 given directions.
  56584. */
  56585. var BoxParticleEmitter = /** @class */ (function () {
  56586. /**
  56587. * Creates a new instance BoxParticleEmitter
  56588. */
  56589. function BoxParticleEmitter() {
  56590. /**
  56591. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56592. */
  56593. this.direction1 = new BABYLON.Vector3(0, 1.0, 0);
  56594. /**
  56595. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  56596. */
  56597. this.direction2 = new BABYLON.Vector3(0, 1.0, 0);
  56598. /**
  56599. * 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.
  56600. */
  56601. this.minEmitBox = new BABYLON.Vector3(-0.5, -0.5, -0.5);
  56602. /**
  56603. * 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.
  56604. */
  56605. this.maxEmitBox = new BABYLON.Vector3(0.5, 0.5, 0.5);
  56606. }
  56607. /**
  56608. * Called by the particle System when the direction is computed for the created particle.
  56609. * @param worldMatrix is the world matrix of the particle system
  56610. * @param directionToUpdate is the direction vector to update with the result
  56611. * @param particle is the particle we are computed the direction for
  56612. */
  56613. BoxParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56614. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  56615. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  56616. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  56617. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  56618. };
  56619. /**
  56620. * Called by the particle System when the position is computed for the created particle.
  56621. * @param worldMatrix is the world matrix of the particle system
  56622. * @param positionToUpdate is the position vector to update with the result
  56623. * @param particle is the particle we are computed the position for
  56624. */
  56625. BoxParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56626. var randX = BABYLON.Scalar.RandomRange(this.minEmitBox.x, this.maxEmitBox.x);
  56627. var randY = BABYLON.Scalar.RandomRange(this.minEmitBox.y, this.maxEmitBox.y);
  56628. var randZ = BABYLON.Scalar.RandomRange(this.minEmitBox.z, this.maxEmitBox.z);
  56629. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56630. };
  56631. /**
  56632. * Clones the current emitter and returns a copy of it
  56633. * @returns the new emitter
  56634. */
  56635. BoxParticleEmitter.prototype.clone = function () {
  56636. var newOne = new BoxParticleEmitter();
  56637. BABYLON.Tools.DeepCopy(this, newOne);
  56638. return newOne;
  56639. };
  56640. /**
  56641. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56642. * @param effect defines the update shader
  56643. */
  56644. BoxParticleEmitter.prototype.applyToShader = function (effect) {
  56645. effect.setVector3("direction1", this.direction1);
  56646. effect.setVector3("direction2", this.direction2);
  56647. effect.setVector3("minEmitBox", this.minEmitBox);
  56648. effect.setVector3("maxEmitBox", this.maxEmitBox);
  56649. };
  56650. /**
  56651. * Returns a string to use to update the GPU particles update shader
  56652. * @returns a string containng the defines string
  56653. */
  56654. BoxParticleEmitter.prototype.getEffectDefines = function () {
  56655. return "#define BOXEMITTER";
  56656. };
  56657. /**
  56658. * Returns the string "BoxParticleEmitter"
  56659. * @returns a string containing the class name
  56660. */
  56661. BoxParticleEmitter.prototype.getClassName = function () {
  56662. return "BoxParticleEmitter";
  56663. };
  56664. /**
  56665. * Serializes the particle system to a JSON object.
  56666. * @returns the JSON object
  56667. */
  56668. BoxParticleEmitter.prototype.serialize = function () {
  56669. var serializationObject = {};
  56670. serializationObject.type = this.getClassName();
  56671. serializationObject.direction1 = this.direction1.asArray();
  56672. serializationObject.direction2 = this.direction2.asArray();
  56673. serializationObject.minEmitBox = this.minEmitBox.asArray();
  56674. serializationObject.maxEmitBox = this.maxEmitBox.asArray();
  56675. return serializationObject;
  56676. };
  56677. /**
  56678. * Parse properties from a JSON object
  56679. * @param serializationObject defines the JSON object
  56680. */
  56681. BoxParticleEmitter.prototype.parse = function (serializationObject) {
  56682. BABYLON.Vector3.FromArrayToRef(serializationObject.direction1, 0, this.direction1);
  56683. BABYLON.Vector3.FromArrayToRef(serializationObject.direction2, 0, this.direction2);
  56684. BABYLON.Vector3.FromArrayToRef(serializationObject.minEmitBox, 0, this.minEmitBox);
  56685. BABYLON.Vector3.FromArrayToRef(serializationObject.maxEmitBox, 0, this.maxEmitBox);
  56686. };
  56687. return BoxParticleEmitter;
  56688. }());
  56689. BABYLON.BoxParticleEmitter = BoxParticleEmitter;
  56690. })(BABYLON || (BABYLON = {}));
  56691. //# sourceMappingURL=babylon.boxParticleEmitter.js.map
  56692. var BABYLON;
  56693. (function (BABYLON) {
  56694. /**
  56695. * Particle emitter emitting particles from the inside of a cone.
  56696. * It emits the particles alongside the cone volume from the base to the particle.
  56697. * The emission direction might be randomized.
  56698. */
  56699. var ConeParticleEmitter = /** @class */ (function () {
  56700. /**
  56701. * Creates a new instance ConeParticleEmitter
  56702. * @param radius the radius of the emission cone (1 by default)
  56703. * @param angles the cone base angle (PI by default)
  56704. * @param directionRandomizer defines how much to randomize the particle direction [0-1] (default is 0)
  56705. */
  56706. function ConeParticleEmitter(radius, angle,
  56707. /** defines how much to randomize the particle direction [0-1] (default is 0) */
  56708. directionRandomizer) {
  56709. if (radius === void 0) { radius = 1; }
  56710. if (angle === void 0) { angle = Math.PI; }
  56711. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56712. this.directionRandomizer = directionRandomizer;
  56713. /**
  56714. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56715. */
  56716. this.radiusRange = 1;
  56717. /**
  56718. * Gets or sets a value indicating where on the height the start position should be picked (1 = everywhere, 0 = only surface)
  56719. */
  56720. this.heightRange = 1;
  56721. this.angle = angle;
  56722. this.radius = radius;
  56723. }
  56724. Object.defineProperty(ConeParticleEmitter.prototype, "radius", {
  56725. /**
  56726. * Gets or sets the radius of the emission cone
  56727. */
  56728. get: function () {
  56729. return this._radius;
  56730. },
  56731. set: function (value) {
  56732. this._radius = value;
  56733. this._buildHeight();
  56734. },
  56735. enumerable: true,
  56736. configurable: true
  56737. });
  56738. Object.defineProperty(ConeParticleEmitter.prototype, "angle", {
  56739. /**
  56740. * Gets or sets the angle of the emission cone
  56741. */
  56742. get: function () {
  56743. return this._angle;
  56744. },
  56745. set: function (value) {
  56746. this._angle = value;
  56747. this._buildHeight();
  56748. },
  56749. enumerable: true,
  56750. configurable: true
  56751. });
  56752. ConeParticleEmitter.prototype._buildHeight = function () {
  56753. if (this._angle !== 0) {
  56754. this._height = this._radius / Math.tan(this._angle / 2);
  56755. }
  56756. else {
  56757. this._height = 1;
  56758. }
  56759. };
  56760. /**
  56761. * Called by the particle System when the direction is computed for the created particle.
  56762. * @param worldMatrix is the world matrix of the particle system
  56763. * @param directionToUpdate is the direction vector to update with the result
  56764. * @param particle is the particle we are computed the direction for
  56765. */
  56766. ConeParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56767. if (Math.abs(Math.cos(this._angle)) === 1.0) {
  56768. BABYLON.Vector3.TransformNormalFromFloatsToRef(0, 1.0, 0, worldMatrix, directionToUpdate);
  56769. }
  56770. else {
  56771. // measure the direction Vector from the emitter to the particle.
  56772. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56773. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56774. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56775. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56776. direction.x += randX;
  56777. direction.y += randY;
  56778. direction.z += randZ;
  56779. direction.normalize();
  56780. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56781. }
  56782. };
  56783. /**
  56784. * Called by the particle System when the position is computed for the created particle.
  56785. * @param worldMatrix is the world matrix of the particle system
  56786. * @param positionToUpdate is the position vector to update with the result
  56787. * @param particle is the particle we are computed the position for
  56788. */
  56789. ConeParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56790. var s = BABYLON.Scalar.RandomRange(0, Math.PI * 2);
  56791. var h = BABYLON.Scalar.RandomRange(0, this.heightRange);
  56792. // Better distribution in a cone at normal angles.
  56793. h = 1 - h * h;
  56794. var radius = this._radius - BABYLON.Scalar.RandomRange(0, this._radius * this.radiusRange);
  56795. radius = radius * h;
  56796. var randX = radius * Math.sin(s);
  56797. var randZ = radius * Math.cos(s);
  56798. var randY = h * this._height;
  56799. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56800. };
  56801. /**
  56802. * Clones the current emitter and returns a copy of it
  56803. * @returns the new emitter
  56804. */
  56805. ConeParticleEmitter.prototype.clone = function () {
  56806. var newOne = new ConeParticleEmitter(this._radius, this._angle, this.directionRandomizer);
  56807. BABYLON.Tools.DeepCopy(this, newOne);
  56808. return newOne;
  56809. };
  56810. /**
  56811. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56812. * @param effect defines the update shader
  56813. */
  56814. ConeParticleEmitter.prototype.applyToShader = function (effect) {
  56815. effect.setFloat2("radius", this._radius, this.radiusRange);
  56816. effect.setFloat("coneAngle", this._angle);
  56817. effect.setFloat2("height", this._height, this.heightRange);
  56818. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56819. };
  56820. /**
  56821. * Returns a string to use to update the GPU particles update shader
  56822. * @returns a string containng the defines string
  56823. */
  56824. ConeParticleEmitter.prototype.getEffectDefines = function () {
  56825. return "#define CONEEMITTER";
  56826. };
  56827. /**
  56828. * Returns the string "ConeParticleEmitter"
  56829. * @returns a string containing the class name
  56830. */
  56831. ConeParticleEmitter.prototype.getClassName = function () {
  56832. return "ConeParticleEmitter";
  56833. };
  56834. /**
  56835. * Serializes the particle system to a JSON object.
  56836. * @returns the JSON object
  56837. */
  56838. ConeParticleEmitter.prototype.serialize = function () {
  56839. var serializationObject = {};
  56840. serializationObject.type = this.getClassName();
  56841. serializationObject.radius = this._radius;
  56842. serializationObject.angle = this._angle;
  56843. serializationObject.directionRandomizer = this.directionRandomizer;
  56844. return serializationObject;
  56845. };
  56846. /**
  56847. * Parse properties from a JSON object
  56848. * @param serializationObject defines the JSON object
  56849. */
  56850. ConeParticleEmitter.prototype.parse = function (serializationObject) {
  56851. this.radius = serializationObject.radius;
  56852. this.angle = serializationObject.angle;
  56853. this.directionRandomizer = serializationObject.directionRandomizer;
  56854. };
  56855. return ConeParticleEmitter;
  56856. }());
  56857. BABYLON.ConeParticleEmitter = ConeParticleEmitter;
  56858. })(BABYLON || (BABYLON = {}));
  56859. //# sourceMappingURL=babylon.coneParticleEmitter.js.map
  56860. var BABYLON;
  56861. (function (BABYLON) {
  56862. /**
  56863. * Particle emitter emitting particles from the inside of a sphere.
  56864. * It emits the particles alongside the sphere radius. The emission direction might be randomized.
  56865. */
  56866. var SphereParticleEmitter = /** @class */ (function () {
  56867. /**
  56868. * Creates a new instance SphereParticleEmitter
  56869. * @param radius the radius of the emission sphere (1 by default)
  56870. * @param directionRandomizer defines how much to randomize the particle direction [0-1]
  56871. */
  56872. function SphereParticleEmitter(
  56873. /**
  56874. * The radius of the emission sphere.
  56875. */
  56876. radius,
  56877. /**
  56878. * How much to randomize the particle direction [0-1].
  56879. */
  56880. directionRandomizer) {
  56881. if (radius === void 0) { radius = 1; }
  56882. if (directionRandomizer === void 0) { directionRandomizer = 0; }
  56883. this.radius = radius;
  56884. this.directionRandomizer = directionRandomizer;
  56885. /**
  56886. * Gets or sets a value indicating where on the radius the start position should be picked (1 = everywhere, 0 = only surface)
  56887. */
  56888. this.radiusRange = 1;
  56889. }
  56890. /**
  56891. * Called by the particle System when the direction is computed for the created particle.
  56892. * @param worldMatrix is the world matrix of the particle system
  56893. * @param directionToUpdate is the direction vector to update with the result
  56894. * @param particle is the particle we are computed the direction for
  56895. */
  56896. SphereParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  56897. var direction = particle.position.subtract(worldMatrix.getTranslation()).normalize();
  56898. var randX = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56899. var randY = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56900. var randZ = BABYLON.Scalar.RandomRange(0, this.directionRandomizer);
  56901. direction.x += randX;
  56902. direction.y += randY;
  56903. direction.z += randZ;
  56904. direction.normalize();
  56905. BABYLON.Vector3.TransformNormalFromFloatsToRef(direction.x, direction.y, direction.z, worldMatrix, directionToUpdate);
  56906. };
  56907. /**
  56908. * Called by the particle System when the position is computed for the created particle.
  56909. * @param worldMatrix is the world matrix of the particle system
  56910. * @param positionToUpdate is the position vector to update with the result
  56911. * @param particle is the particle we are computed the position for
  56912. */
  56913. SphereParticleEmitter.prototype.startPositionFunction = function (worldMatrix, positionToUpdate, particle) {
  56914. var randRadius = this.radius - BABYLON.Scalar.RandomRange(0, this.radius * this.radiusRange);
  56915. var v = BABYLON.Scalar.RandomRange(0, 1.0);
  56916. var phi = BABYLON.Scalar.RandomRange(0, 2 * Math.PI);
  56917. var theta = Math.acos(2 * v - 1);
  56918. var randX = randRadius * Math.cos(phi) * Math.sin(theta);
  56919. var randY = randRadius * Math.cos(theta);
  56920. var randZ = randRadius * Math.sin(phi) * Math.sin(theta);
  56921. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(randX, randY, randZ, worldMatrix, positionToUpdate);
  56922. };
  56923. /**
  56924. * Clones the current emitter and returns a copy of it
  56925. * @returns the new emitter
  56926. */
  56927. SphereParticleEmitter.prototype.clone = function () {
  56928. var newOne = new SphereParticleEmitter(this.radius, this.directionRandomizer);
  56929. BABYLON.Tools.DeepCopy(this, newOne);
  56930. return newOne;
  56931. };
  56932. /**
  56933. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  56934. * @param effect defines the update shader
  56935. */
  56936. SphereParticleEmitter.prototype.applyToShader = function (effect) {
  56937. effect.setFloat("radius", this.radius);
  56938. effect.setFloat("radiusRange", this.radiusRange);
  56939. effect.setFloat("directionRandomizer", this.directionRandomizer);
  56940. };
  56941. /**
  56942. * Returns a string to use to update the GPU particles update shader
  56943. * @returns a string containng the defines string
  56944. */
  56945. SphereParticleEmitter.prototype.getEffectDefines = function () {
  56946. return "#define SPHEREEMITTER";
  56947. };
  56948. /**
  56949. * Returns the string "SphereParticleEmitter"
  56950. * @returns a string containing the class name
  56951. */
  56952. SphereParticleEmitter.prototype.getClassName = function () {
  56953. return "SphereParticleEmitter";
  56954. };
  56955. /**
  56956. * Serializes the particle system to a JSON object.
  56957. * @returns the JSON object
  56958. */
  56959. SphereParticleEmitter.prototype.serialize = function () {
  56960. var serializationObject = {};
  56961. serializationObject.type = this.getClassName();
  56962. serializationObject.radius = this.radius;
  56963. serializationObject.radiusRange = this.radiusRange;
  56964. serializationObject.directionRandomizer = this.directionRandomizer;
  56965. return serializationObject;
  56966. };
  56967. /**
  56968. * Parse properties from a JSON object
  56969. * @param serializationObject defines the JSON object
  56970. */
  56971. SphereParticleEmitter.prototype.parse = function (serializationObject) {
  56972. this.radius = serializationObject.radius;
  56973. this.radiusRange = serializationObject.radiusRange;
  56974. this.directionRandomizer = serializationObject.directionRandomizer;
  56975. };
  56976. return SphereParticleEmitter;
  56977. }());
  56978. BABYLON.SphereParticleEmitter = SphereParticleEmitter;
  56979. /**
  56980. * Particle emitter emitting particles from the inside of a sphere.
  56981. * It emits the particles randomly between two vectors.
  56982. */
  56983. var SphereDirectedParticleEmitter = /** @class */ (function (_super) {
  56984. __extends(SphereDirectedParticleEmitter, _super);
  56985. /**
  56986. * Creates a new instance SphereDirectedParticleEmitter
  56987. * @param radius the radius of the emission sphere (1 by default)
  56988. * @param direction1 the min limit of the emission direction (up vector by default)
  56989. * @param direction2 the max limit of the emission direction (up vector by default)
  56990. */
  56991. function SphereDirectedParticleEmitter(radius,
  56992. /**
  56993. * The min limit of the emission direction.
  56994. */
  56995. direction1,
  56996. /**
  56997. * The max limit of the emission direction.
  56998. */
  56999. direction2) {
  57000. if (radius === void 0) { radius = 1; }
  57001. if (direction1 === void 0) { direction1 = new BABYLON.Vector3(0, 1, 0); }
  57002. if (direction2 === void 0) { direction2 = new BABYLON.Vector3(0, 1, 0); }
  57003. var _this = _super.call(this, radius) || this;
  57004. _this.direction1 = direction1;
  57005. _this.direction2 = direction2;
  57006. return _this;
  57007. }
  57008. /**
  57009. * Called by the particle System when the direction is computed for the created particle.
  57010. * @param worldMatrix is the world matrix of the particle system
  57011. * @param directionToUpdate is the direction vector to update with the result
  57012. * @param particle is the particle we are computed the direction for
  57013. */
  57014. SphereDirectedParticleEmitter.prototype.startDirectionFunction = function (worldMatrix, directionToUpdate, particle) {
  57015. var randX = BABYLON.Scalar.RandomRange(this.direction1.x, this.direction2.x);
  57016. var randY = BABYLON.Scalar.RandomRange(this.direction1.y, this.direction2.y);
  57017. var randZ = BABYLON.Scalar.RandomRange(this.direction1.z, this.direction2.z);
  57018. BABYLON.Vector3.TransformNormalFromFloatsToRef(randX, randY, randZ, worldMatrix, directionToUpdate);
  57019. };
  57020. /**
  57021. * Clones the current emitter and returns a copy of it
  57022. * @returns the new emitter
  57023. */
  57024. SphereDirectedParticleEmitter.prototype.clone = function () {
  57025. var newOne = new SphereDirectedParticleEmitter(this.radius, this.direction1, this.direction2);
  57026. BABYLON.Tools.DeepCopy(this, newOne);
  57027. return newOne;
  57028. };
  57029. /**
  57030. * Called by the {BABYLON.GPUParticleSystem} to setup the update shader
  57031. * @param effect defines the update shader
  57032. */
  57033. SphereDirectedParticleEmitter.prototype.applyToShader = function (effect) {
  57034. effect.setFloat("radius", this.radius);
  57035. effect.setFloat("radiusRange", this.radiusRange);
  57036. effect.setVector3("direction1", this.direction1);
  57037. effect.setVector3("direction2", this.direction2);
  57038. };
  57039. /**
  57040. * Returns a string to use to update the GPU particles update shader
  57041. * @returns a string containng the defines string
  57042. */
  57043. SphereDirectedParticleEmitter.prototype.getEffectDefines = function () {
  57044. return "#define SPHEREEMITTER\n#define DIRECTEDSPHEREEMITTER";
  57045. };
  57046. /**
  57047. * Returns the string "SphereDirectedParticleEmitter"
  57048. * @returns a string containing the class name
  57049. */
  57050. SphereDirectedParticleEmitter.prototype.getClassName = function () {
  57051. return "SphereDirectedParticleEmitter";
  57052. };
  57053. /**
  57054. * Serializes the particle system to a JSON object.
  57055. * @returns the JSON object
  57056. */
  57057. SphereDirectedParticleEmitter.prototype.serialize = function () {
  57058. var serializationObject = _super.prototype.serialize.call(this);
  57059. serializationObject.direction1 = this.direction1.asArray();
  57060. serializationObject.direction2 = this.direction2.asArray();
  57061. return serializationObject;
  57062. };
  57063. /**
  57064. * Parse properties from a JSON object
  57065. * @param serializationObject defines the JSON object
  57066. */
  57067. SphereDirectedParticleEmitter.prototype.parse = function (serializationObject) {
  57068. _super.prototype.parse.call(this, serializationObject);
  57069. this.direction1.copyFrom(serializationObject.direction1);
  57070. this.direction2.copyFrom(serializationObject.direction2);
  57071. };
  57072. return SphereDirectedParticleEmitter;
  57073. }(SphereParticleEmitter));
  57074. BABYLON.SphereDirectedParticleEmitter = SphereDirectedParticleEmitter;
  57075. })(BABYLON || (BABYLON = {}));
  57076. //# sourceMappingURL=babylon.sphereParticleEmitter.js.map
  57077. var __assign = (this && this.__assign) || Object.assign || function(t) {
  57078. for (var s, i = 1, n = arguments.length; i < n; i++) {
  57079. s = arguments[i];
  57080. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  57081. t[p] = s[p];
  57082. }
  57083. return t;
  57084. };
  57085. var BABYLON;
  57086. (function (BABYLON) {
  57087. /**
  57088. * This represents a GPU particle system in Babylon
  57089. * This is the fastest particle system in Babylon as it uses the GPU to update the individual particle data
  57090. * @see https://www.babylonjs-playground.com/#PU4WYI#4
  57091. */
  57092. var GPUParticleSystem = /** @class */ (function () {
  57093. /**
  57094. * Instantiates a GPU particle system.
  57095. * 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.
  57096. * @param name The name of the particle system
  57097. * @param options The options used to create the system
  57098. * @param scene The scene the particle system belongs to
  57099. * @param isAnimationSheetEnabled Must be true if using a spritesheet to animate the particles texture
  57100. */
  57101. function GPUParticleSystem(name, options, scene, isAnimationSheetEnabled) {
  57102. if (isAnimationSheetEnabled === void 0) { isAnimationSheetEnabled = false; }
  57103. /**
  57104. * The emitter represents the Mesh or position we are attaching the particle system to.
  57105. */
  57106. this.emitter = null;
  57107. /**
  57108. * The rendering group used by the Particle system to chose when to render.
  57109. */
  57110. this.renderingGroupId = 0;
  57111. /**
  57112. * The layer mask we are rendering the particles through.
  57113. */
  57114. this.layerMask = 0x0FFFFFFF;
  57115. this._accumulatedCount = 0;
  57116. this._targetIndex = 0;
  57117. this._currentRenderId = -1;
  57118. this._started = false;
  57119. this._stopped = false;
  57120. this._timeDelta = 0;
  57121. this._attributesStrideSize = 21;
  57122. this._actualFrame = 0;
  57123. /**
  57124. * List of animations used by the particle system.
  57125. */
  57126. this.animations = [];
  57127. /**
  57128. * An event triggered when the system is disposed.
  57129. */
  57130. this.onDisposeObservable = new BABYLON.Observable();
  57131. /**
  57132. * The overall motion speed (0.01 is default update speed, faster updates = faster animation)
  57133. */
  57134. this.updateSpeed = 0.01;
  57135. /**
  57136. * The amount of time the particle system is running (depends of the overall update speed).
  57137. */
  57138. this.targetStopDuration = 0;
  57139. /**
  57140. * Blend mode use to render the particle, it can be either ParticleSystem.BLENDMODE_ONEONE or ParticleSystem.BLENDMODE_STANDARD.
  57141. */
  57142. this.blendMode = BABYLON.ParticleSystem.BLENDMODE_ONEONE;
  57143. /**
  57144. * Minimum life time of emitting particles.
  57145. */
  57146. this.minLifeTime = 1;
  57147. /**
  57148. * Maximum life time of emitting particles.
  57149. */
  57150. this.maxLifeTime = 1;
  57151. /**
  57152. * Minimum Size of emitting particles.
  57153. */
  57154. this.minSize = 1;
  57155. /**
  57156. * Maximum Size of emitting particles.
  57157. */
  57158. this.maxSize = 1;
  57159. /**
  57160. * Minimum scale of emitting particles on X axis.
  57161. */
  57162. this.minScaleX = 1;
  57163. /**
  57164. * Maximum scale of emitting particles on X axis.
  57165. */
  57166. this.maxScaleX = 1;
  57167. /**
  57168. * Minimum scale of emitting particles on Y axis.
  57169. */
  57170. this.minScaleY = 1;
  57171. /**
  57172. * Maximum scale of emitting particles on Y axis.
  57173. */
  57174. this.maxScaleY = 1;
  57175. /**
  57176. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57177. */
  57178. this.color1 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57179. /**
  57180. * Random color of each particle after it has been emitted, between color1 and color2 vectors.
  57181. */
  57182. this.color2 = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  57183. /**
  57184. * Color the particle will have at the end of its lifetime.
  57185. */
  57186. this.colorDead = new BABYLON.Color4(0, 0, 0, 0);
  57187. /**
  57188. * The maximum number of particles to emit per frame until we reach the activeParticleCount value
  57189. */
  57190. this.emitRate = 100;
  57191. /**
  57192. * You can use gravity if you want to give an orientation to your particles.
  57193. */
  57194. this.gravity = BABYLON.Vector3.Zero();
  57195. /**
  57196. * Minimum power of emitting particles.
  57197. */
  57198. this.minEmitPower = 1;
  57199. /**
  57200. * Maximum power of emitting particles.
  57201. */
  57202. this.maxEmitPower = 1;
  57203. /**
  57204. * Minimum angular speed of emitting particles (Z-axis rotation for each particle).
  57205. */
  57206. this.minAngularSpeed = 0;
  57207. /**
  57208. * Maximum angular speed of emitting particles (Z-axis rotation for each particle).
  57209. */
  57210. this.maxAngularSpeed = 0;
  57211. /**
  57212. * Forces the particle to write their depth information to the depth buffer. This can help preventing other draw calls
  57213. * to override the particles.
  57214. */
  57215. this.forceDepthWrite = false;
  57216. this._preWarmDone = false;
  57217. /** Gets or sets a value indicating how many cycles (or frames) must be executed before first rendering (this value has to be set before starting the system). Default is 0 */
  57218. this.preWarmCycles = 0;
  57219. /** Gets or sets a value indicating the time step multiplier to use in pre-warm mode (default is 1) */
  57220. this.preWarmStepOffset = 1;
  57221. /**
  57222. * Gets or sets the minimal initial rotation in radians.
  57223. */
  57224. this.minInitialRotation = 0;
  57225. /**
  57226. * Gets or sets the maximal initial rotation in radians.
  57227. */
  57228. this.maxInitialRotation = 0;
  57229. /**
  57230. * If using a spritesheet (isAnimationSheetEnabled) defines the speed of the sprite loop (default is 1 meaning the animation will play once during the entire particle lifetime)
  57231. */
  57232. this.spriteCellChangeSpeed = 1;
  57233. /**
  57234. * If using a spritesheet (isAnimationSheetEnabled) defines the first sprite cell to display
  57235. */
  57236. this.startSpriteCellID = 0;
  57237. /**
  57238. * If using a spritesheet (isAnimationSheetEnabled) defines the last sprite cell to display
  57239. */
  57240. this.endSpriteCellID = 0;
  57241. /**
  57242. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell width to use
  57243. */
  57244. this.spriteCellWidth = 0;
  57245. /**
  57246. * If using a spritesheet (isAnimationSheetEnabled), defines the sprite cell height to use
  57247. */
  57248. this.spriteCellHeight = 0;
  57249. /** Gets or sets a Vector2 used to move the pivot (by default (0,0)) */
  57250. this.translationPivot = new BABYLON.Vector2(0, 0);
  57251. /**
  57252. * Gets or sets the billboard mode to use when isBillboardBased = true.
  57253. * Only BABYLON.AbstractMesh.BILLBOARDMODE_ALL and AbstractMesh.BILLBOARDMODE_Y are supported so far
  57254. */
  57255. this.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  57256. this._isBillboardBased = true;
  57257. this._colorGradients = null;
  57258. this._sizeGradients = null;
  57259. this.id = name;
  57260. this.name = name;
  57261. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  57262. this._engine = this._scene.getEngine();
  57263. if (!options.randomTextureSize) {
  57264. delete options.randomTextureSize;
  57265. }
  57266. var fullOptions = __assign({ capacity: 50000, randomTextureSize: this._engine.getCaps().maxTextureSize }, options);
  57267. var optionsAsNumber = options;
  57268. if (isFinite(optionsAsNumber)) {
  57269. fullOptions.capacity = optionsAsNumber;
  57270. }
  57271. this._capacity = fullOptions.capacity;
  57272. this._activeCount = fullOptions.capacity;
  57273. this._currentActiveCount = 0;
  57274. this._isAnimationSheetEnabled = isAnimationSheetEnabled;
  57275. this._scene.particleSystems.push(this);
  57276. this._updateEffectOptions = {
  57277. attributes: ["position", "age", "life", "seed", "size", "color", "direction", "initialDirection", "angle", "cellIndex"],
  57278. uniformsNames: ["currentCount", "timeDelta", "emitterWM", "lifeTime", "color1", "color2", "sizeRange", "scaleRange", "gravity", "emitPower",
  57279. "direction1", "direction2", "minEmitBox", "maxEmitBox", "radius", "directionRandomizer", "height", "coneAngle", "stopFactor",
  57280. "angleRange", "radiusRange", "cellInfos"],
  57281. uniformBuffersNames: [],
  57282. samplers: ["randomSampler", "randomSampler2", "sizeGradientSampler"],
  57283. defines: "",
  57284. fallbacks: null,
  57285. onCompiled: null,
  57286. onError: null,
  57287. indexParameters: null,
  57288. maxSimultaneousLights: 0,
  57289. transformFeedbackVaryings: []
  57290. };
  57291. this.particleEmitterType = new BABYLON.BoxParticleEmitter();
  57292. // Random data
  57293. var maxTextureSize = Math.min(this._engine.getCaps().maxTextureSize, fullOptions.randomTextureSize);
  57294. var d = [];
  57295. for (var i = 0; i < maxTextureSize; ++i) {
  57296. d.push(Math.random());
  57297. d.push(Math.random());
  57298. d.push(Math.random());
  57299. d.push(Math.random());
  57300. }
  57301. this._randomTexture = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57302. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57303. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57304. d = [];
  57305. for (var i = 0; i < maxTextureSize; ++i) {
  57306. d.push(Math.random());
  57307. d.push(Math.random());
  57308. d.push(Math.random());
  57309. d.push(Math.random());
  57310. }
  57311. this._randomTexture2 = new BABYLON.RawTexture(new Float32Array(d), maxTextureSize, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, BABYLON.Engine.TEXTURETYPE_FLOAT);
  57312. this._randomTexture2.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  57313. this._randomTexture2.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  57314. this._randomTextureSize = maxTextureSize;
  57315. }
  57316. Object.defineProperty(GPUParticleSystem, "IsSupported", {
  57317. /**
  57318. * Gets a boolean indicating if the GPU particles can be rendered on current browser
  57319. */
  57320. get: function () {
  57321. if (!BABYLON.Engine.LastCreatedEngine) {
  57322. return false;
  57323. }
  57324. return BABYLON.Engine.LastCreatedEngine.webGLVersion > 1;
  57325. },
  57326. enumerable: true,
  57327. configurable: true
  57328. });
  57329. Object.defineProperty(GPUParticleSystem.prototype, "direction1", {
  57330. /**
  57331. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57332. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57333. */
  57334. get: function () {
  57335. if (this.particleEmitterType.direction1) {
  57336. return this.particleEmitterType.direction1;
  57337. }
  57338. return BABYLON.Vector3.Zero();
  57339. },
  57340. set: function (value) {
  57341. if (this.particleEmitterType.direction1) {
  57342. this.particleEmitterType.direction1 = value;
  57343. }
  57344. },
  57345. enumerable: true,
  57346. configurable: true
  57347. });
  57348. Object.defineProperty(GPUParticleSystem.prototype, "direction2", {
  57349. /**
  57350. * Random direction of each particle after it has been emitted, between direction1 and direction2 vectors.
  57351. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57352. */
  57353. get: function () {
  57354. if (this.particleEmitterType.direction2) {
  57355. return this.particleEmitterType.direction2;
  57356. }
  57357. return BABYLON.Vector3.Zero();
  57358. },
  57359. set: function (value) {
  57360. if (this.particleEmitterType.direction2) {
  57361. this.particleEmitterType.direction2 = value;
  57362. }
  57363. },
  57364. enumerable: true,
  57365. configurable: true
  57366. });
  57367. Object.defineProperty(GPUParticleSystem.prototype, "minEmitBox", {
  57368. /**
  57369. * 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.
  57370. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57371. */
  57372. get: function () {
  57373. if (this.particleEmitterType.minEmitBox) {
  57374. return this.particleEmitterType.minEmitBox;
  57375. }
  57376. return BABYLON.Vector3.Zero();
  57377. },
  57378. set: function (value) {
  57379. if (this.particleEmitterType.minEmitBox) {
  57380. this.particleEmitterType.minEmitBox = value;
  57381. }
  57382. },
  57383. enumerable: true,
  57384. configurable: true
  57385. });
  57386. Object.defineProperty(GPUParticleSystem.prototype, "maxEmitBox", {
  57387. /**
  57388. * 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.
  57389. * This only works when particleEmitterTyps is a BoxParticleEmitter
  57390. */
  57391. get: function () {
  57392. if (this.particleEmitterType.maxEmitBox) {
  57393. return this.particleEmitterType.maxEmitBox;
  57394. }
  57395. return BABYLON.Vector3.Zero();
  57396. },
  57397. set: function (value) {
  57398. if (this.particleEmitterType.maxEmitBox) {
  57399. this.particleEmitterType.maxEmitBox = value;
  57400. }
  57401. },
  57402. enumerable: true,
  57403. configurable: true
  57404. });
  57405. /**
  57406. * Gets the maximum number of particles active at the same time.
  57407. * @returns The max number of active particles.
  57408. */
  57409. GPUParticleSystem.prototype.getCapacity = function () {
  57410. return this._capacity;
  57411. };
  57412. Object.defineProperty(GPUParticleSystem.prototype, "activeParticleCount", {
  57413. /**
  57414. * Gets or set the number of active particles
  57415. */
  57416. get: function () {
  57417. return this._activeCount;
  57418. },
  57419. set: function (value) {
  57420. this._activeCount = Math.min(value, this._capacity);
  57421. },
  57422. enumerable: true,
  57423. configurable: true
  57424. });
  57425. Object.defineProperty(GPUParticleSystem.prototype, "isAnimationSheetEnabled", {
  57426. /**
  57427. * Gets whether an animation sprite sheet is enabled or not on the particle system
  57428. */
  57429. get: function () {
  57430. return this._isAnimationSheetEnabled;
  57431. },
  57432. enumerable: true,
  57433. configurable: true
  57434. });
  57435. /**
  57436. * Is this system ready to be used/rendered
  57437. * @return true if the system is ready
  57438. */
  57439. GPUParticleSystem.prototype.isReady = function () {
  57440. if (!this._updateEffect) {
  57441. this._recreateUpdateEffect();
  57442. this._recreateRenderEffect();
  57443. return false;
  57444. }
  57445. if (!this.emitter || !this._updateEffect.isReady() || !this._renderEffect.isReady() || !this.particleTexture || !this.particleTexture.isReady()) {
  57446. return false;
  57447. }
  57448. return true;
  57449. };
  57450. /**
  57451. * Gets Wether the system has been started.
  57452. * @returns True if it has been started, otherwise false.
  57453. */
  57454. GPUParticleSystem.prototype.isStarted = function () {
  57455. return this._started;
  57456. };
  57457. /**
  57458. * Starts the particle system and begins to emit.
  57459. */
  57460. GPUParticleSystem.prototype.start = function () {
  57461. this._started = true;
  57462. this._stopped = false;
  57463. this._preWarmDone = false;
  57464. };
  57465. /**
  57466. * Stops the particle system.
  57467. */
  57468. GPUParticleSystem.prototype.stop = function () {
  57469. this._stopped = true;
  57470. };
  57471. /**
  57472. * Remove all active particles
  57473. */
  57474. GPUParticleSystem.prototype.reset = function () {
  57475. this._releaseBuffers();
  57476. this._releaseVAOs();
  57477. this._currentActiveCount = 0;
  57478. this._targetIndex = 0;
  57479. };
  57480. /**
  57481. * Returns the string "GPUParticleSystem"
  57482. * @returns a string containing the class name
  57483. */
  57484. GPUParticleSystem.prototype.getClassName = function () {
  57485. return "GPUParticleSystem";
  57486. };
  57487. Object.defineProperty(GPUParticleSystem.prototype, "isBillboardBased", {
  57488. /**
  57489. * Gets or sets a boolean indicating if the particles must be rendered as billboard or aligned with the direction
  57490. */
  57491. get: function () {
  57492. return this._isBillboardBased;
  57493. },
  57494. set: function (value) {
  57495. if (this._isBillboardBased === value) {
  57496. return;
  57497. }
  57498. this._isBillboardBased = value;
  57499. this._releaseBuffers();
  57500. },
  57501. enumerable: true,
  57502. configurable: true
  57503. });
  57504. /**
  57505. * Gets the current list of color gradients.
  57506. * You must use addColorGradient and removeColorGradient to udpate this list
  57507. * @returns the list of color gradients
  57508. */
  57509. GPUParticleSystem.prototype.getColorGradients = function () {
  57510. return this._colorGradients;
  57511. };
  57512. /**
  57513. * Gets the current list of size gradients.
  57514. * You must use addSizeGradient and removeSizeGradient to udpate this list
  57515. * @returns the list of size gradients
  57516. */
  57517. GPUParticleSystem.prototype.getSizeGradients = function () {
  57518. return this._sizeGradients;
  57519. };
  57520. /**
  57521. * Adds a new color gradient
  57522. * @param gradient defines the gradient to use (between 0 and 1)
  57523. * @param color defines the color to affect to the specified gradient
  57524. * @param color2 defines an additional color used to define a range ([color, color2]) with main color to pick the final color from
  57525. */
  57526. GPUParticleSystem.prototype.addColorGradient = function (gradient, color1, color2) {
  57527. if (!this._colorGradients) {
  57528. this._colorGradients = [];
  57529. }
  57530. var colorGradient = new BABYLON.ColorGradient();
  57531. colorGradient.gradient = gradient;
  57532. colorGradient.color1 = color1;
  57533. this._colorGradients.push(colorGradient);
  57534. this._colorGradients.sort(function (a, b) {
  57535. if (a.gradient < b.gradient) {
  57536. return -1;
  57537. }
  57538. else if (a.gradient > b.gradient) {
  57539. return 1;
  57540. }
  57541. return 0;
  57542. });
  57543. if (this._colorGradientsTexture) {
  57544. this._colorGradientsTexture.dispose();
  57545. this._colorGradientsTexture = null;
  57546. }
  57547. this._releaseBuffers();
  57548. return this;
  57549. };
  57550. /**
  57551. * Remove a specific color gradient
  57552. * @param gradient defines the gradient to remove
  57553. */
  57554. GPUParticleSystem.prototype.removeColorGradient = function (gradient) {
  57555. if (!this._colorGradients) {
  57556. return this;
  57557. }
  57558. var index = 0;
  57559. for (var _i = 0, _a = this._colorGradients; _i < _a.length; _i++) {
  57560. var colorGradient = _a[_i];
  57561. if (colorGradient.gradient === gradient) {
  57562. this._colorGradients.splice(index, 1);
  57563. break;
  57564. }
  57565. index++;
  57566. }
  57567. if (this._colorGradientsTexture) {
  57568. this._colorGradientsTexture.dispose();
  57569. this._colorGradientsTexture = null;
  57570. }
  57571. this._releaseBuffers();
  57572. return this;
  57573. };
  57574. /**
  57575. * Adds a new size gradient
  57576. * @param gradient defines the gradient to use (between 0 and 1)
  57577. * @param factor defines the size factor to affect to the specified gradient
  57578. */
  57579. GPUParticleSystem.prototype.addSizeGradient = function (gradient, factor) {
  57580. if (!this._sizeGradients) {
  57581. this._sizeGradients = [];
  57582. }
  57583. var sizeGradient = new BABYLON.FactorGradient();
  57584. sizeGradient.gradient = gradient;
  57585. sizeGradient.factor1 = factor;
  57586. this._sizeGradients.push(sizeGradient);
  57587. this._sizeGradients.sort(function (a, b) {
  57588. if (a.gradient < b.gradient) {
  57589. return -1;
  57590. }
  57591. else if (a.gradient > b.gradient) {
  57592. return 1;
  57593. }
  57594. return 0;
  57595. });
  57596. if (this._sizeGradientsTexture) {
  57597. this._sizeGradientsTexture.dispose();
  57598. this._sizeGradientsTexture = null;
  57599. }
  57600. this._releaseBuffers();
  57601. return this;
  57602. };
  57603. /**
  57604. * Remove a specific size gradient
  57605. * @param gradient defines the gradient to remove
  57606. */
  57607. GPUParticleSystem.prototype.removeSizeGradient = function (gradient) {
  57608. if (!this._sizeGradients) {
  57609. return this;
  57610. }
  57611. var index = 0;
  57612. for (var _i = 0, _a = this._sizeGradients; _i < _a.length; _i++) {
  57613. var sizeGradient = _a[_i];
  57614. if (sizeGradient.gradient === gradient) {
  57615. this._sizeGradients.splice(index, 1);
  57616. break;
  57617. }
  57618. index++;
  57619. }
  57620. if (this._sizeGradientsTexture) {
  57621. this._sizeGradientsTexture.dispose();
  57622. this._sizeGradientsTexture = null;
  57623. }
  57624. this._releaseBuffers();
  57625. return this;
  57626. };
  57627. GPUParticleSystem.prototype._createUpdateVAO = function (source) {
  57628. var updateVertexBuffers = {};
  57629. updateVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3);
  57630. updateVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1);
  57631. updateVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1);
  57632. updateVertexBuffers["seed"] = source.createVertexBuffer("seed", 5, 4);
  57633. updateVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3);
  57634. var offset = 12;
  57635. if (!this._colorGradientsTexture) {
  57636. updateVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4);
  57637. offset += 4;
  57638. }
  57639. updateVertexBuffers["direction"] = source.createVertexBuffer("direction", offset, 3);
  57640. offset += 3;
  57641. if (!this._isBillboardBased) {
  57642. updateVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3);
  57643. offset += 3;
  57644. }
  57645. updateVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2);
  57646. offset += 2;
  57647. if (this._isAnimationSheetEnabled) {
  57648. updateVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1);
  57649. offset += 1;
  57650. }
  57651. var vao = this._engine.recordVertexArrayObject(updateVertexBuffers, null, this._updateEffect);
  57652. this._engine.bindArrayBuffer(null);
  57653. return vao;
  57654. };
  57655. GPUParticleSystem.prototype._createRenderVAO = function (source, spriteSource) {
  57656. var renderVertexBuffers = {};
  57657. renderVertexBuffers["position"] = source.createVertexBuffer("position", 0, 3, this._attributesStrideSize, true);
  57658. renderVertexBuffers["age"] = source.createVertexBuffer("age", 3, 1, this._attributesStrideSize, true);
  57659. renderVertexBuffers["life"] = source.createVertexBuffer("life", 4, 1, this._attributesStrideSize, true);
  57660. renderVertexBuffers["size"] = source.createVertexBuffer("size", 9, 3, this._attributesStrideSize, true);
  57661. var offset = 12;
  57662. if (!this._colorGradientsTexture) {
  57663. renderVertexBuffers["color"] = source.createVertexBuffer("color", offset, 4, this._attributesStrideSize, true);
  57664. offset += 4;
  57665. }
  57666. offset += 3; // Direction
  57667. if (!this._isBillboardBased) {
  57668. renderVertexBuffers["initialDirection"] = source.createVertexBuffer("initialDirection", offset, 3, this._attributesStrideSize, true);
  57669. offset += 3;
  57670. }
  57671. renderVertexBuffers["angle"] = source.createVertexBuffer("angle", offset, 2, this._attributesStrideSize, true);
  57672. offset += 2;
  57673. if (this._isAnimationSheetEnabled) {
  57674. renderVertexBuffers["cellIndex"] = source.createVertexBuffer("cellIndex", offset, 1, this._attributesStrideSize, true);
  57675. offset += 1;
  57676. }
  57677. renderVertexBuffers["offset"] = spriteSource.createVertexBuffer("offset", 0, 2);
  57678. renderVertexBuffers["uv"] = spriteSource.createVertexBuffer("uv", 2, 2);
  57679. var vao = this._engine.recordVertexArrayObject(renderVertexBuffers, null, this._renderEffect);
  57680. this._engine.bindArrayBuffer(null);
  57681. return vao;
  57682. };
  57683. GPUParticleSystem.prototype._initialize = function (force) {
  57684. if (force === void 0) { force = false; }
  57685. if (this._buffer0 && !force) {
  57686. return;
  57687. }
  57688. var engine = this._scene.getEngine();
  57689. var data = new Array();
  57690. if (!this.isBillboardBased) {
  57691. this._attributesStrideSize += 3;
  57692. }
  57693. if (this._colorGradientsTexture) {
  57694. this._attributesStrideSize -= 4;
  57695. }
  57696. if (this._isAnimationSheetEnabled) {
  57697. this._attributesStrideSize += 1;
  57698. }
  57699. for (var particleIndex = 0; particleIndex < this._capacity; particleIndex++) {
  57700. // position
  57701. data.push(0.0);
  57702. data.push(0.0);
  57703. data.push(0.0);
  57704. // Age and life
  57705. data.push(0.0); // create the particle as a dead one to create a new one at start
  57706. data.push(0.0);
  57707. // Seed
  57708. data.push(Math.random());
  57709. data.push(Math.random());
  57710. data.push(Math.random());
  57711. data.push(Math.random());
  57712. // Size
  57713. data.push(0.0);
  57714. data.push(0.0);
  57715. data.push(0.0);
  57716. if (!this._colorGradientsTexture) {
  57717. // color
  57718. data.push(0.0);
  57719. data.push(0.0);
  57720. data.push(0.0);
  57721. data.push(0.0);
  57722. }
  57723. // direction
  57724. data.push(0.0);
  57725. data.push(0.0);
  57726. data.push(0.0);
  57727. if (!this.isBillboardBased) {
  57728. // initialDirection
  57729. data.push(0.0);
  57730. data.push(0.0);
  57731. data.push(0.0);
  57732. }
  57733. // angle
  57734. data.push(0.0);
  57735. data.push(0.0);
  57736. if (this._isAnimationSheetEnabled) {
  57737. data.push(0.0);
  57738. }
  57739. }
  57740. // Sprite data
  57741. var spriteData = new Float32Array([0.5, 0.5, 1, 1,
  57742. -0.5, 0.5, 0, 1,
  57743. -0.5, -0.5, 0, 0,
  57744. 0.5, -0.5, 1, 0]);
  57745. // Buffers
  57746. this._buffer0 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57747. this._buffer1 = new BABYLON.Buffer(engine, data, false, this._attributesStrideSize);
  57748. this._spriteBuffer = new BABYLON.Buffer(engine, spriteData, false, 4);
  57749. // Update VAO
  57750. this._updateVAO = [];
  57751. this._updateVAO.push(this._createUpdateVAO(this._buffer0));
  57752. this._updateVAO.push(this._createUpdateVAO(this._buffer1));
  57753. // Render VAO
  57754. this._renderVAO = [];
  57755. this._renderVAO.push(this._createRenderVAO(this._buffer1, this._spriteBuffer));
  57756. this._renderVAO.push(this._createRenderVAO(this._buffer0, this._spriteBuffer));
  57757. // Links
  57758. this._sourceBuffer = this._buffer0;
  57759. this._targetBuffer = this._buffer1;
  57760. };
  57761. /** @hidden */
  57762. GPUParticleSystem.prototype._recreateUpdateEffect = function () {
  57763. var defines = this.particleEmitterType ? this.particleEmitterType.getEffectDefines() : "";
  57764. if (this._isBillboardBased) {
  57765. defines += "\n#define BILLBOARD";
  57766. }
  57767. if (this._colorGradientsTexture) {
  57768. defines += "\n#define COLORGRADIENTS";
  57769. }
  57770. if (this._sizeGradientsTexture) {
  57771. defines += "\n#define SIZEGRADIENTS";
  57772. }
  57773. if (this.isAnimationSheetEnabled) {
  57774. defines += "\n#define ANIMATESHEET";
  57775. }
  57776. if (this._updateEffect && this._updateEffectOptions.defines === defines) {
  57777. return;
  57778. }
  57779. this._updateEffectOptions.transformFeedbackVaryings = ["outPosition", "outAge", "outLife", "outSeed", "outSize"];
  57780. if (!this._colorGradientsTexture) {
  57781. this._updateEffectOptions.transformFeedbackVaryings.push("outColor");
  57782. }
  57783. this._updateEffectOptions.transformFeedbackVaryings.push("outDirection");
  57784. if (!this._isBillboardBased) {
  57785. this._updateEffectOptions.transformFeedbackVaryings.push("outInitialDirection");
  57786. }
  57787. this._updateEffectOptions.transformFeedbackVaryings.push("outAngle");
  57788. if (this.isAnimationSheetEnabled) {
  57789. this._updateEffectOptions.transformFeedbackVaryings.push("outCellIndex");
  57790. }
  57791. this._updateEffectOptions.defines = defines;
  57792. this._updateEffect = new BABYLON.Effect("gpuUpdateParticles", this._updateEffectOptions, this._scene.getEngine());
  57793. };
  57794. /** @hidden */
  57795. GPUParticleSystem.prototype._recreateRenderEffect = function () {
  57796. var defines = "";
  57797. if (this._scene.clipPlane) {
  57798. defines = "\n#define CLIPPLANE";
  57799. }
  57800. if (this._isBillboardBased) {
  57801. defines += "\n#define BILLBOARD";
  57802. switch (this.billboardMode) {
  57803. case BABYLON.AbstractMesh.BILLBOARDMODE_Y:
  57804. defines += "\n#define BILLBOARDY";
  57805. break;
  57806. case BABYLON.AbstractMesh.BILLBOARDMODE_ALL:
  57807. default:
  57808. break;
  57809. }
  57810. }
  57811. if (this._colorGradientsTexture) {
  57812. defines += "\n#define COLORGRADIENTS";
  57813. }
  57814. if (this.isAnimationSheetEnabled) {
  57815. defines += "\n#define ANIMATESHEET";
  57816. }
  57817. if (this._renderEffect && this._renderEffect.defines === defines) {
  57818. return;
  57819. }
  57820. this._renderEffect = new BABYLON.Effect("gpuRenderParticles", ["position", "age", "life", "size", "color", "offset", "uv", "initialDirection", "angle", "cellIndex"], ["view", "projection", "colorDead", "invView", "vClipPlane", "sheetInfos", "translationPivot", "eyePosition"], ["textureSampler", "colorGradientSampler"], this._scene.getEngine(), defines);
  57821. };
  57822. /**
  57823. * Animates the particle system for the current frame by emitting new particles and or animating the living ones.
  57824. * @param preWarm defines if we are in the pre-warmimg phase
  57825. */
  57826. GPUParticleSystem.prototype.animate = function (preWarm) {
  57827. if (preWarm === void 0) { preWarm = false; }
  57828. this._timeDelta = this.updateSpeed * (preWarm ? this.preWarmStepOffset : this._scene.getAnimationRatio());
  57829. this._actualFrame += this._timeDelta;
  57830. if (!this._stopped) {
  57831. if (this.targetStopDuration && this._actualFrame >= this.targetStopDuration) {
  57832. this.stop();
  57833. }
  57834. }
  57835. };
  57836. GPUParticleSystem.prototype._createSizeGradientTexture = function () {
  57837. if (!this._sizeGradients || !this._sizeGradients.length || this._sizeGradientsTexture) {
  57838. return;
  57839. }
  57840. var textureWidth = 256;
  57841. var data = new Float32Array(textureWidth);
  57842. for (var x = 0; x < textureWidth; x++) {
  57843. var ratio = x / textureWidth;
  57844. BABYLON.Tools.GetCurrentGradient(ratio, this._sizeGradients, function (currentGradient, nextGradient, scale) {
  57845. data[x] = BABYLON.Scalar.Lerp(currentGradient.factor1, nextGradient.factor1, scale);
  57846. });
  57847. }
  57848. this._sizeGradientsTexture = BABYLON.RawTexture.CreateRTexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57849. };
  57850. GPUParticleSystem.prototype._createColorGradientTexture = function () {
  57851. if (!this._colorGradients || !this._colorGradients.length || this._colorGradientsTexture) {
  57852. return;
  57853. }
  57854. var textureWidth = 256;
  57855. var data = new Uint8Array(textureWidth * 4);
  57856. var tmpColor = BABYLON.Tmp.Color4[0];
  57857. for (var x = 0; x < textureWidth; x++) {
  57858. var ratio = x / textureWidth;
  57859. BABYLON.Tools.GetCurrentGradient(ratio, this._colorGradients, function (currentGradient, nextGradient, scale) {
  57860. BABYLON.Color4.LerpToRef(currentGradient.color1, nextGradient.color1, scale, tmpColor);
  57861. data[x * 4] = tmpColor.r * 255;
  57862. data[x * 4 + 1] = tmpColor.g * 255;
  57863. data[x * 4 + 2] = tmpColor.b * 255;
  57864. data[x * 4 + 3] = tmpColor.a * 255;
  57865. });
  57866. }
  57867. this._colorGradientsTexture = BABYLON.RawTexture.CreateRGBATexture(data, textureWidth, 1, this._scene, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE);
  57868. };
  57869. /**
  57870. * Renders the particle system in its current state
  57871. * @param preWarm defines if the system should only update the particles but not render them
  57872. * @returns the current number of particles
  57873. */
  57874. GPUParticleSystem.prototype.render = function (preWarm) {
  57875. if (preWarm === void 0) { preWarm = false; }
  57876. if (!this._started) {
  57877. return 0;
  57878. }
  57879. this._createColorGradientTexture();
  57880. this._createSizeGradientTexture();
  57881. this._recreateUpdateEffect();
  57882. this._recreateRenderEffect();
  57883. if (!this.isReady()) {
  57884. return 0;
  57885. }
  57886. if (!preWarm) {
  57887. if (!this._preWarmDone && this.preWarmCycles) {
  57888. for (var index = 0; index < this.preWarmCycles; index++) {
  57889. this.animate(true);
  57890. this.render(true);
  57891. }
  57892. this._preWarmDone = true;
  57893. }
  57894. if (this._currentRenderId === this._scene.getRenderId()) {
  57895. return 0;
  57896. }
  57897. this._currentRenderId = this._scene.getRenderId();
  57898. }
  57899. // Get everything ready to render
  57900. this._initialize();
  57901. this._accumulatedCount += this.emitRate * this._timeDelta;
  57902. if (this._accumulatedCount > 1) {
  57903. var intPart = this._accumulatedCount | 0;
  57904. this._accumulatedCount -= intPart;
  57905. this._currentActiveCount = Math.min(this._activeCount, this._currentActiveCount + intPart);
  57906. }
  57907. if (!this._currentActiveCount) {
  57908. return 0;
  57909. }
  57910. // Enable update effect
  57911. this._engine.enableEffect(this._updateEffect);
  57912. this._engine.setState(false);
  57913. this._updateEffect.setFloat("currentCount", this._currentActiveCount);
  57914. this._updateEffect.setFloat("timeDelta", this._timeDelta);
  57915. this._updateEffect.setFloat("stopFactor", this._stopped ? 0 : 1);
  57916. this._updateEffect.setTexture("randomSampler", this._randomTexture);
  57917. this._updateEffect.setTexture("randomSampler2", this._randomTexture2);
  57918. this._updateEffect.setFloat2("lifeTime", this.minLifeTime, this.maxLifeTime);
  57919. this._updateEffect.setFloat2("emitPower", this.minEmitPower, this.maxEmitPower);
  57920. if (!this._colorGradientsTexture) {
  57921. this._updateEffect.setDirectColor4("color1", this.color1);
  57922. this._updateEffect.setDirectColor4("color2", this.color2);
  57923. }
  57924. this._updateEffect.setFloat2("sizeRange", this.minSize, this.maxSize);
  57925. this._updateEffect.setFloat4("scaleRange", this.minScaleX, this.maxScaleX, this.minScaleY, this.maxScaleY);
  57926. this._updateEffect.setFloat4("angleRange", this.minAngularSpeed, this.maxAngularSpeed, this.minInitialRotation, this.maxInitialRotation);
  57927. this._updateEffect.setVector3("gravity", this.gravity);
  57928. if (this._sizeGradientsTexture) {
  57929. this._updateEffect.setTexture("sizeGradientSampler", this._sizeGradientsTexture);
  57930. }
  57931. if (this.particleEmitterType) {
  57932. this.particleEmitterType.applyToShader(this._updateEffect);
  57933. }
  57934. if (this._isAnimationSheetEnabled) {
  57935. this._updateEffect.setFloat3("cellInfos", this.startSpriteCellID, this.endSpriteCellID, this.spriteCellChangeSpeed);
  57936. }
  57937. var emitterWM;
  57938. if (this.emitter.position) {
  57939. var emitterMesh = this.emitter;
  57940. emitterWM = emitterMesh.getWorldMatrix();
  57941. }
  57942. else {
  57943. var emitterPosition = this.emitter;
  57944. emitterWM = BABYLON.Matrix.Translation(emitterPosition.x, emitterPosition.y, emitterPosition.z);
  57945. }
  57946. this._updateEffect.setMatrix("emitterWM", emitterWM);
  57947. // Bind source VAO
  57948. this._engine.bindVertexArrayObject(this._updateVAO[this._targetIndex], null);
  57949. // Update
  57950. this._engine.bindTransformFeedbackBuffer(this._targetBuffer.getBuffer());
  57951. this._engine.setRasterizerState(false);
  57952. this._engine.beginTransformFeedback();
  57953. this._engine.drawArraysType(BABYLON.Material.PointListDrawMode, 0, this._currentActiveCount);
  57954. this._engine.endTransformFeedback();
  57955. this._engine.setRasterizerState(true);
  57956. this._engine.bindTransformFeedbackBuffer(null);
  57957. if (!preWarm) {
  57958. // Enable render effect
  57959. this._engine.enableEffect(this._renderEffect);
  57960. var viewMatrix = this._scene.getViewMatrix();
  57961. this._renderEffect.setMatrix("view", viewMatrix);
  57962. this._renderEffect.setMatrix("projection", this._scene.getProjectionMatrix());
  57963. this._renderEffect.setTexture("textureSampler", this.particleTexture);
  57964. this._renderEffect.setVector2("translationPivot", this.translationPivot);
  57965. if (this._colorGradientsTexture) {
  57966. this._renderEffect.setTexture("colorGradientSampler", this._colorGradientsTexture);
  57967. }
  57968. else {
  57969. this._renderEffect.setDirectColor4("colorDead", this.colorDead);
  57970. }
  57971. if (this._isAnimationSheetEnabled && this.particleTexture) {
  57972. var baseSize = this.particleTexture.getBaseSize();
  57973. this._renderEffect.setFloat3("sheetInfos", this.spriteCellWidth / baseSize.width, this.spriteCellHeight / baseSize.height, baseSize.width / this.spriteCellWidth);
  57974. }
  57975. if (this._isBillboardBased) {
  57976. var camera = this._scene.activeCamera;
  57977. this._renderEffect.setVector3("eyePosition", camera.globalPosition);
  57978. }
  57979. if (this._scene.clipPlane) {
  57980. var clipPlane = this._scene.clipPlane;
  57981. var invView = viewMatrix.clone();
  57982. invView.invert();
  57983. this._renderEffect.setMatrix("invView", invView);
  57984. this._renderEffect.setFloat4("vClipPlane", clipPlane.normal.x, clipPlane.normal.y, clipPlane.normal.z, clipPlane.d);
  57985. }
  57986. // Draw order
  57987. switch (this.blendMode) {
  57988. case BABYLON.ParticleSystem.BLENDMODE_ADD:
  57989. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ADD);
  57990. break;
  57991. case BABYLON.ParticleSystem.BLENDMODE_ONEONE:
  57992. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_ONEONE);
  57993. break;
  57994. case BABYLON.ParticleSystem.BLENDMODE_STANDARD:
  57995. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  57996. break;
  57997. }
  57998. if (this.forceDepthWrite) {
  57999. this._engine.setDepthWrite(true);
  58000. }
  58001. // Bind source VAO
  58002. this._engine.bindVertexArrayObject(this._renderVAO[this._targetIndex], null);
  58003. // Render
  58004. this._engine.drawArraysType(BABYLON.Material.TriangleFanDrawMode, 0, 4, this._currentActiveCount);
  58005. this._engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  58006. }
  58007. // Switch VAOs
  58008. this._targetIndex++;
  58009. if (this._targetIndex === 2) {
  58010. this._targetIndex = 0;
  58011. }
  58012. // Switch buffers
  58013. var tmpBuffer = this._sourceBuffer;
  58014. this._sourceBuffer = this._targetBuffer;
  58015. this._targetBuffer = tmpBuffer;
  58016. return this._currentActiveCount;
  58017. };
  58018. /**
  58019. * Rebuilds the particle system
  58020. */
  58021. GPUParticleSystem.prototype.rebuild = function () {
  58022. this._initialize(true);
  58023. };
  58024. GPUParticleSystem.prototype._releaseBuffers = function () {
  58025. if (this._buffer0) {
  58026. this._buffer0.dispose();
  58027. this._buffer0 = null;
  58028. }
  58029. if (this._buffer1) {
  58030. this._buffer1.dispose();
  58031. this._buffer1 = null;
  58032. }
  58033. if (this._spriteBuffer) {
  58034. this._spriteBuffer.dispose();
  58035. this._spriteBuffer = null;
  58036. }
  58037. };
  58038. GPUParticleSystem.prototype._releaseVAOs = function () {
  58039. if (!this._updateVAO) {
  58040. return;
  58041. }
  58042. for (var index = 0; index < this._updateVAO.length; index++) {
  58043. this._engine.releaseVertexArrayObject(this._updateVAO[index]);
  58044. }
  58045. this._updateVAO = [];
  58046. for (var index = 0; index < this._renderVAO.length; index++) {
  58047. this._engine.releaseVertexArrayObject(this._renderVAO[index]);
  58048. }
  58049. this._renderVAO = [];
  58050. };
  58051. /**
  58052. * Disposes the particle system and free the associated resources
  58053. * @param disposeTexture defines if the particule texture must be disposed as well (true by default)
  58054. */
  58055. GPUParticleSystem.prototype.dispose = function (disposeTexture) {
  58056. if (disposeTexture === void 0) { disposeTexture = true; }
  58057. var index = this._scene.particleSystems.indexOf(this);
  58058. if (index > -1) {
  58059. this._scene.particleSystems.splice(index, 1);
  58060. }
  58061. this._releaseBuffers();
  58062. this._releaseVAOs();
  58063. if (this._colorGradientsTexture) {
  58064. this._colorGradientsTexture.dispose();
  58065. this._colorGradientsTexture = null;
  58066. }
  58067. if (this._sizeGradientsTexture) {
  58068. this._sizeGradientsTexture.dispose();
  58069. this._sizeGradientsTexture = null;
  58070. }
  58071. if (this._randomTexture) {
  58072. this._randomTexture.dispose();
  58073. this._randomTexture = null;
  58074. }
  58075. if (this._randomTexture2) {
  58076. this._randomTexture2.dispose();
  58077. this._randomTexture2 = null;
  58078. }
  58079. if (disposeTexture && this.particleTexture) {
  58080. this.particleTexture.dispose();
  58081. this.particleTexture = null;
  58082. }
  58083. // Callback
  58084. this.onDisposeObservable.notifyObservers(this);
  58085. this.onDisposeObservable.clear();
  58086. };
  58087. /**
  58088. * Clones the particle system.
  58089. * @param name The name of the cloned object
  58090. * @param newEmitter The new emitter to use
  58091. * @returns the cloned particle system
  58092. */
  58093. GPUParticleSystem.prototype.clone = function (name, newEmitter) {
  58094. var result = new GPUParticleSystem(name, { capacity: this._capacity, randomTextureSize: this._randomTextureSize }, this._scene);
  58095. BABYLON.Tools.DeepCopy(this, result);
  58096. if (newEmitter === undefined) {
  58097. newEmitter = this.emitter;
  58098. }
  58099. result.emitter = newEmitter;
  58100. if (this.particleTexture) {
  58101. result.particleTexture = new BABYLON.Texture(this.particleTexture.url, this._scene);
  58102. }
  58103. return result;
  58104. };
  58105. /**
  58106. * Serializes the particle system to a JSON object.
  58107. * @returns the JSON object
  58108. */
  58109. GPUParticleSystem.prototype.serialize = function () {
  58110. var serializationObject = {};
  58111. BABYLON.ParticleSystem._Serialize(serializationObject, this);
  58112. serializationObject.activeParticleCount = this.activeParticleCount;
  58113. return serializationObject;
  58114. };
  58115. /**
  58116. * Parses a JSON object to create a GPU particle system.
  58117. * @param parsedParticleSystem The JSON object to parse
  58118. * @param scene The scene to create the particle system in
  58119. * @param rootUrl The root url to use to load external dependencies like texture
  58120. * @returns the parsed GPU particle system
  58121. */
  58122. GPUParticleSystem.Parse = function (parsedParticleSystem, scene, rootUrl) {
  58123. var name = parsedParticleSystem.name;
  58124. var particleSystem = new GPUParticleSystem(name, { capacity: parsedParticleSystem.capacity, randomTextureSize: parsedParticleSystem.randomTextureSize }, scene);
  58125. if (parsedParticleSystem.activeParticleCount) {
  58126. particleSystem.activeParticleCount = parsedParticleSystem.activeParticleCount;
  58127. }
  58128. BABYLON.ParticleSystem._Parse(parsedParticleSystem, particleSystem, scene, rootUrl);
  58129. return particleSystem;
  58130. };
  58131. return GPUParticleSystem;
  58132. }());
  58133. BABYLON.GPUParticleSystem = GPUParticleSystem;
  58134. })(BABYLON || (BABYLON = {}));
  58135. //# sourceMappingURL=babylon.gpuParticleSystem.js.map
  58136. var BABYLON;
  58137. (function (BABYLON) {
  58138. /**
  58139. * Represents one particle of a solid particle system.
  58140. */
  58141. var SolidParticle = /** @class */ (function () {
  58142. /**
  58143. * Creates a Solid Particle object.
  58144. * Don't create particles manually, use instead the Solid Particle System internal tools like _addParticle()
  58145. * @param particleIndex (integer) is the particle index in the Solid Particle System pool. It's also the particle identifier.
  58146. * @param positionIndex (integer) is the starting index of the particle vertices in the SPS "positions" array.
  58147. * @param indiceIndex (integer) is the starting index of the particle indices in the SPS "indices" array.
  58148. * @param model (ModelShape) is a reference to the model shape on what the particle is designed.
  58149. * @param shapeId (integer) is the model shape identifier in the SPS.
  58150. * @param idxInShape (integer) is the index of the particle in the current model (ex: the 10th box of addShape(box, 30))
  58151. * @param modelBoundingInfo is the reference to the model BoundingInfo used for intersection computations.
  58152. */
  58153. function SolidParticle(particleIndex, positionIndex, indiceIndex, model, shapeId, idxInShape, sps, modelBoundingInfo) {
  58154. if (modelBoundingInfo === void 0) { modelBoundingInfo = null; }
  58155. /**
  58156. * particle global index
  58157. */
  58158. this.idx = 0;
  58159. /**
  58160. * The color of the particle
  58161. */
  58162. this.color = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  58163. /**
  58164. * The world space position of the particle.
  58165. */
  58166. this.position = BABYLON.Vector3.Zero();
  58167. /**
  58168. * The world space rotation of the particle. (Not use if rotationQuaternion is set)
  58169. */
  58170. this.rotation = BABYLON.Vector3.Zero();
  58171. /**
  58172. * The scaling of the particle.
  58173. */
  58174. this.scaling = BABYLON.Vector3.One();
  58175. /**
  58176. * The uvs of the particle.
  58177. */
  58178. this.uvs = new BABYLON.Vector4(0.0, 0.0, 1.0, 1.0);
  58179. /**
  58180. * The current speed of the particle.
  58181. */
  58182. this.velocity = BABYLON.Vector3.Zero();
  58183. /**
  58184. * The pivot point in the particle local space.
  58185. */
  58186. this.pivot = BABYLON.Vector3.Zero();
  58187. /**
  58188. * Must the particle be translated from its pivot point in its local space ?
  58189. * In this case, the pivot point is set at the origin of the particle local space and the particle is translated.
  58190. * Default : false
  58191. */
  58192. this.translateFromPivot = false;
  58193. /**
  58194. * Is the particle active or not ?
  58195. */
  58196. this.alive = true;
  58197. /**
  58198. * Is the particle visible or not ?
  58199. */
  58200. this.isVisible = true;
  58201. /**
  58202. * Index of this particle in the global "positions" array (Internal use)
  58203. */
  58204. this._pos = 0;
  58205. /**
  58206. * Index of this particle in the global "indices" array (Internal use)
  58207. */
  58208. this._ind = 0;
  58209. /**
  58210. * ModelShape id of this particle
  58211. */
  58212. this.shapeId = 0;
  58213. /**
  58214. * Index of the particle in its shape id (Internal use)
  58215. */
  58216. this.idxInShape = 0;
  58217. /**
  58218. * Still set as invisible in order to skip useless computations (Internal use)
  58219. */
  58220. this._stillInvisible = false;
  58221. /**
  58222. * Last computed particle rotation matrix
  58223. */
  58224. this._rotationMatrix = [1.0, 0.0, 0.0, 0.0, 1.0, 0.0, 0.0, 0.0, 1.0];
  58225. /**
  58226. * Parent particle Id, if any.
  58227. * Default null.
  58228. */
  58229. this.parentId = null;
  58230. /**
  58231. * Internal global position in the SPS.
  58232. */
  58233. this._globalPosition = BABYLON.Vector3.Zero();
  58234. this.idx = particleIndex;
  58235. this._pos = positionIndex;
  58236. this._ind = indiceIndex;
  58237. this._model = model;
  58238. this.shapeId = shapeId;
  58239. this.idxInShape = idxInShape;
  58240. this._sps = sps;
  58241. if (modelBoundingInfo) {
  58242. this._modelBoundingInfo = modelBoundingInfo;
  58243. this._boundingInfo = new BABYLON.BoundingInfo(modelBoundingInfo.minimum, modelBoundingInfo.maximum);
  58244. }
  58245. }
  58246. Object.defineProperty(SolidParticle.prototype, "scale", {
  58247. /**
  58248. * Legacy support, changed scale to scaling
  58249. */
  58250. get: function () {
  58251. return this.scaling;
  58252. },
  58253. /**
  58254. * Legacy support, changed scale to scaling
  58255. */
  58256. set: function (scale) {
  58257. this.scaling = scale;
  58258. },
  58259. enumerable: true,
  58260. configurable: true
  58261. });
  58262. Object.defineProperty(SolidParticle.prototype, "quaternion", {
  58263. /**
  58264. * Legacy support, changed quaternion to rotationQuaternion
  58265. */
  58266. get: function () {
  58267. return this.rotationQuaternion;
  58268. },
  58269. /**
  58270. * Legacy support, changed quaternion to rotationQuaternion
  58271. */
  58272. set: function (q) {
  58273. this.rotationQuaternion = q;
  58274. },
  58275. enumerable: true,
  58276. configurable: true
  58277. });
  58278. /**
  58279. * Returns a boolean. True if the particle intersects another particle or another mesh, else false.
  58280. * The intersection is computed on the particle bounding sphere and Axis Aligned Bounding Box (AABB)
  58281. * @param target is the object (solid particle or mesh) what the intersection is computed against.
  58282. * @returns true if it intersects
  58283. */
  58284. SolidParticle.prototype.intersectsMesh = function (target) {
  58285. if (!this._boundingInfo || !target._boundingInfo) {
  58286. return false;
  58287. }
  58288. if (this._sps._bSphereOnly) {
  58289. return BABYLON.BoundingSphere.Intersects(this._boundingInfo.boundingSphere, target._boundingInfo.boundingSphere);
  58290. }
  58291. return this._boundingInfo.intersects(target._boundingInfo, false);
  58292. };
  58293. return SolidParticle;
  58294. }());
  58295. BABYLON.SolidParticle = SolidParticle;
  58296. /**
  58297. * Represents the shape of the model used by one particle of a solid particle system.
  58298. * SPS internal tool, don't use it manually.
  58299. */
  58300. var ModelShape = /** @class */ (function () {
  58301. /**
  58302. * 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.
  58303. * SPS internal tool, don't use it manually.
  58304. * @hidden
  58305. */
  58306. function ModelShape(id, shape, indicesLength, shapeUV, posFunction, vtxFunction) {
  58307. /**
  58308. * length of the shape in the model indices array (internal use)
  58309. */
  58310. this._indicesLength = 0;
  58311. this.shapeID = id;
  58312. this._shape = shape;
  58313. this._indicesLength = indicesLength;
  58314. this._shapeUV = shapeUV;
  58315. this._positionFunction = posFunction;
  58316. this._vertexFunction = vtxFunction;
  58317. }
  58318. return ModelShape;
  58319. }());
  58320. BABYLON.ModelShape = ModelShape;
  58321. /**
  58322. * Represents a Depth Sorted Particle in the solid particle system.
  58323. */
  58324. var DepthSortedParticle = /** @class */ (function () {
  58325. function DepthSortedParticle() {
  58326. /**
  58327. * Index of the particle in the "indices" array
  58328. */
  58329. this.ind = 0;
  58330. /**
  58331. * Length of the particle shape in the "indices" array
  58332. */
  58333. this.indicesLength = 0;
  58334. /**
  58335. * Squared distance from the particle to the camera
  58336. */
  58337. this.sqDistance = 0.0;
  58338. }
  58339. return DepthSortedParticle;
  58340. }());
  58341. BABYLON.DepthSortedParticle = DepthSortedParticle;
  58342. })(BABYLON || (BABYLON = {}));
  58343. //# sourceMappingURL=babylon.solidParticle.js.map
  58344. var BABYLON;
  58345. (function (BABYLON) {
  58346. /**
  58347. * The SPS is a single updatable mesh. The solid particles are simply separate parts or faces fo this big mesh.
  58348. *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.
  58349. * The SPS is also a particle system. It provides some methods to manage the particles.
  58350. * However it is behavior agnostic. This means it has no emitter, no particle physics, no particle recycler. You have to implement your own behavior.
  58351. *
  58352. * Full documentation here : http://doc.babylonjs.com/overviews/Solid_Particle_System
  58353. */
  58354. var SolidParticleSystem = /** @class */ (function () {
  58355. /**
  58356. * Creates a SPS (Solid Particle System) object.
  58357. * @param name (String) is the SPS name, this will be the underlying mesh name.
  58358. * @param scene (Scene) is the scene in which the SPS is added.
  58359. * @param updatable (optional boolean, default true) : if the SPS must be updatable or immutable.
  58360. * @param isPickable (optional boolean, default false) : if the solid particles must be pickable.
  58361. * @param enableDepthSort (optional boolean, default false) : if the solid particles must be sorted in the geometry according to their distance to the camera.
  58362. * @param particleIntersection (optional boolean, default false) : if the solid particle intersections must be computed.
  58363. * @param boundingSphereOnly (optional boolean, default false) : if the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster).
  58364. * @param bSphereRadiusFactor (optional float, default 1.0) : a number to multiply the boundind sphere radius by in order to reduce it for instance.
  58365. * @example bSphereRadiusFactor = 1.0 / Math.sqrt(3.0) => the bounding sphere exactly matches a spherical mesh.
  58366. */
  58367. function SolidParticleSystem(name, scene, options) {
  58368. /**
  58369. * The SPS array of Solid Particle objects. Just access each particle as with any classic array.
  58370. * Example : var p = SPS.particles[i];
  58371. */
  58372. this.particles = new Array();
  58373. /**
  58374. * The SPS total number of particles. Read only. Use SPS.counter instead if you need to set your own value.
  58375. */
  58376. this.nbParticles = 0;
  58377. /**
  58378. * If the particles must ever face the camera (default false). Useful for planar particles.
  58379. */
  58380. this.billboard = false;
  58381. /**
  58382. * Recompute normals when adding a shape
  58383. */
  58384. this.recomputeNormals = true;
  58385. /**
  58386. * This a counter ofr your own usage. It's not set by any SPS functions.
  58387. */
  58388. this.counter = 0;
  58389. /**
  58390. * This empty object is intended to store some SPS specific or temporary values in order to lower the Garbage Collector activity.
  58391. * Please read : http://doc.babylonjs.com/overviews/Solid_Particle_System#garbage-collector-concerns
  58392. */
  58393. this.vars = {};
  58394. /**
  58395. * If the particle intersection must be computed only with the bounding sphere (no bounding box computation, so faster). (Internal use only)
  58396. */
  58397. this._bSphereOnly = false;
  58398. /**
  58399. * A number to multiply the boundind sphere radius by in order to reduce it for instance. (Internal use only)
  58400. */
  58401. this._bSphereRadiusFactor = 1.0;
  58402. this._positions = new Array();
  58403. this._indices = new Array();
  58404. this._normals = new Array();
  58405. this._colors = new Array();
  58406. this._uvs = new Array();
  58407. this._index = 0; // indices index
  58408. this._updatable = true;
  58409. this._pickable = false;
  58410. this._isVisibilityBoxLocked = false;
  58411. this._alwaysVisible = false;
  58412. this._depthSort = false;
  58413. this._shapeCounter = 0;
  58414. this._copy = new BABYLON.SolidParticle(0, 0, 0, null, 0, 0, this);
  58415. this._color = new BABYLON.Color4(0, 0, 0, 0);
  58416. this._computeParticleColor = true;
  58417. this._computeParticleTexture = true;
  58418. this._computeParticleRotation = true;
  58419. this._computeParticleVertex = false;
  58420. this._computeBoundingBox = false;
  58421. this._depthSortParticles = true;
  58422. this._cam_axisZ = BABYLON.Vector3.Zero();
  58423. this._cam_axisY = BABYLON.Vector3.Zero();
  58424. this._cam_axisX = BABYLON.Vector3.Zero();
  58425. this._axisZ = BABYLON.Axis.Z;
  58426. this._camDir = BABYLON.Vector3.Zero();
  58427. this._camInvertedPosition = BABYLON.Vector3.Zero();
  58428. this._rotMatrix = new BABYLON.Matrix();
  58429. this._invertMatrix = new BABYLON.Matrix();
  58430. this._rotated = BABYLON.Vector3.Zero();
  58431. this._quaternion = new BABYLON.Quaternion();
  58432. this._vertex = BABYLON.Vector3.Zero();
  58433. this._normal = BABYLON.Vector3.Zero();
  58434. this._yaw = 0.0;
  58435. this._pitch = 0.0;
  58436. this._roll = 0.0;
  58437. this._halfroll = 0.0;
  58438. this._halfpitch = 0.0;
  58439. this._halfyaw = 0.0;
  58440. this._sinRoll = 0.0;
  58441. this._cosRoll = 0.0;
  58442. this._sinPitch = 0.0;
  58443. this._cosPitch = 0.0;
  58444. this._sinYaw = 0.0;
  58445. this._cosYaw = 0.0;
  58446. this._mustUnrotateFixedNormals = false;
  58447. this._minimum = BABYLON.Vector3.Zero();
  58448. this._maximum = BABYLON.Vector3.Zero();
  58449. this._minBbox = BABYLON.Vector3.Zero();
  58450. this._maxBbox = BABYLON.Vector3.Zero();
  58451. this._particlesIntersect = false;
  58452. this._depthSortFunction = function (p1, p2) {
  58453. return (p2.sqDistance - p1.sqDistance);
  58454. };
  58455. this._needs32Bits = false;
  58456. this._pivotBackTranslation = BABYLON.Vector3.Zero();
  58457. this._scaledPivot = BABYLON.Vector3.Zero();
  58458. this._particleHasParent = false;
  58459. this.name = name;
  58460. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  58461. this._camera = scene.activeCamera;
  58462. this._pickable = options ? options.isPickable : false;
  58463. this._depthSort = options ? options.enableDepthSort : false;
  58464. this._particlesIntersect = options ? options.particleIntersection : false;
  58465. this._bSphereOnly = options ? options.boundingSphereOnly : false;
  58466. this._bSphereRadiusFactor = (options && options.bSphereRadiusFactor) ? options.bSphereRadiusFactor : 1.0;
  58467. if (options && options.updatable !== undefined) {
  58468. this._updatable = options.updatable;
  58469. }
  58470. else {
  58471. this._updatable = true;
  58472. }
  58473. if (this._pickable) {
  58474. this.pickedParticles = [];
  58475. }
  58476. if (this._depthSort) {
  58477. this.depthSortedParticles = [];
  58478. }
  58479. }
  58480. /**
  58481. * Builds the SPS underlying mesh. Returns a standard Mesh.
  58482. * If no model shape was added to the SPS, the returned mesh is just a single triangular plane.
  58483. * @returns the created mesh
  58484. */
  58485. SolidParticleSystem.prototype.buildMesh = function () {
  58486. if (this.nbParticles === 0) {
  58487. var triangle = BABYLON.MeshBuilder.CreateDisc("", { radius: 1, tessellation: 3 }, this._scene);
  58488. this.addShape(triangle, 1);
  58489. triangle.dispose();
  58490. }
  58491. this._indices32 = (this._needs32Bits) ? new Uint32Array(this._indices) : new Uint16Array(this._indices);
  58492. this._positions32 = new Float32Array(this._positions);
  58493. this._uvs32 = new Float32Array(this._uvs);
  58494. this._colors32 = new Float32Array(this._colors);
  58495. if (this.recomputeNormals) {
  58496. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals);
  58497. }
  58498. this._normals32 = new Float32Array(this._normals);
  58499. this._fixedNormal32 = new Float32Array(this._normals);
  58500. if (this._mustUnrotateFixedNormals) { // the particles could be created already rotated in the mesh with a positionFunction
  58501. this._unrotateFixedNormals();
  58502. }
  58503. var vertexData = new BABYLON.VertexData();
  58504. vertexData.indices = (this._depthSort) ? this._indices : this._indices32;
  58505. vertexData.set(this._positions32, BABYLON.VertexBuffer.PositionKind);
  58506. vertexData.set(this._normals32, BABYLON.VertexBuffer.NormalKind);
  58507. if (this._uvs32.length > 0) {
  58508. vertexData.set(this._uvs32, BABYLON.VertexBuffer.UVKind);
  58509. }
  58510. if (this._colors32.length > 0) {
  58511. vertexData.set(this._colors32, BABYLON.VertexBuffer.ColorKind);
  58512. }
  58513. var mesh = new BABYLON.Mesh(this.name, this._scene);
  58514. vertexData.applyToMesh(mesh, this._updatable);
  58515. this.mesh = mesh;
  58516. this.mesh.isPickable = this._pickable;
  58517. // free memory
  58518. if (!this._depthSort) {
  58519. this._indices = null;
  58520. }
  58521. this._positions = null;
  58522. this._normals = null;
  58523. this._uvs = null;
  58524. this._colors = null;
  58525. if (!this._updatable) {
  58526. this.particles.length = 0;
  58527. }
  58528. return mesh;
  58529. };
  58530. /**
  58531. * Digests the mesh and generates as many solid particles in the system as wanted. Returns the SPS.
  58532. * These particles will have the same geometry than the mesh parts and will be positioned at the same localisation than the mesh original places.
  58533. * Thus the particles generated from `digest()` have their property `position` set yet.
  58534. * @param mesh ( Mesh ) is the mesh to be digested
  58535. * @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
  58536. * {delta} (optional integer, default 0) is the random extra number of facets per particle , each particle will have between `facetNb` and `facetNb + delta` facets
  58537. * {number} (optional positive integer) is the wanted number of particles : each particle is built with `mesh_total_facets / number` facets
  58538. * @returns the current SPS
  58539. */
  58540. SolidParticleSystem.prototype.digest = function (mesh, options) {
  58541. var size = (options && options.facetNb) || 1;
  58542. var number = (options && options.number) || 0;
  58543. var delta = (options && options.delta) || 0;
  58544. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58545. var meshInd = mesh.getIndices();
  58546. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58547. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58548. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58549. var f = 0; // facet counter
  58550. var totalFacets = meshInd.length / 3; // a facet is a triangle, so 3 indices
  58551. // compute size from number
  58552. if (number) {
  58553. number = (number > totalFacets) ? totalFacets : number;
  58554. size = Math.round(totalFacets / number);
  58555. delta = 0;
  58556. }
  58557. else {
  58558. size = (size > totalFacets) ? totalFacets : size;
  58559. }
  58560. var facetPos = []; // submesh positions
  58561. var facetInd = []; // submesh indices
  58562. var facetUV = []; // submesh UV
  58563. var facetCol = []; // submesh colors
  58564. var barycenter = BABYLON.Vector3.Zero();
  58565. var sizeO = size;
  58566. while (f < totalFacets) {
  58567. size = sizeO + Math.floor((1 + delta) * Math.random());
  58568. if (f > totalFacets - size) {
  58569. size = totalFacets - f;
  58570. }
  58571. // reset temp arrays
  58572. facetPos.length = 0;
  58573. facetInd.length = 0;
  58574. facetUV.length = 0;
  58575. facetCol.length = 0;
  58576. // iterate over "size" facets
  58577. var fi = 0;
  58578. for (var j = f * 3; j < (f + size) * 3; j++) {
  58579. facetInd.push(fi);
  58580. var i = meshInd[j];
  58581. facetPos.push(meshPos[i * 3], meshPos[i * 3 + 1], meshPos[i * 3 + 2]);
  58582. if (meshUV) {
  58583. facetUV.push(meshUV[i * 2], meshUV[i * 2 + 1]);
  58584. }
  58585. if (meshCol) {
  58586. facetCol.push(meshCol[i * 4], meshCol[i * 4 + 1], meshCol[i * 4 + 2], meshCol[i * 4 + 3]);
  58587. }
  58588. fi++;
  58589. }
  58590. // create a model shape for each single particle
  58591. var idx = this.nbParticles;
  58592. var shape = this._posToShape(facetPos);
  58593. var shapeUV = this._uvsToShapeUV(facetUV);
  58594. // compute the barycenter of the shape
  58595. var v;
  58596. for (v = 0; v < shape.length; v++) {
  58597. barycenter.addInPlace(shape[v]);
  58598. }
  58599. barycenter.scaleInPlace(1 / shape.length);
  58600. // shift the shape from its barycenter to the origin
  58601. for (v = 0; v < shape.length; v++) {
  58602. shape[v].subtractInPlace(barycenter);
  58603. }
  58604. var bInfo;
  58605. if (this._particlesIntersect) {
  58606. bInfo = new BABYLON.BoundingInfo(barycenter, barycenter);
  58607. }
  58608. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, size * 3, shapeUV, null, null);
  58609. // add the particle in the SPS
  58610. var currentPos = this._positions.length;
  58611. var currentInd = this._indices.length;
  58612. this._meshBuilder(this._index, shape, this._positions, facetInd, this._indices, facetUV, this._uvs, facetCol, this._colors, meshNor, this._normals, idx, 0, null);
  58613. this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, 0, bInfo);
  58614. // initialize the particle position
  58615. this.particles[this.nbParticles].position.addInPlace(barycenter);
  58616. this._index += shape.length;
  58617. idx++;
  58618. this.nbParticles++;
  58619. this._shapeCounter++;
  58620. f += size;
  58621. }
  58622. return this;
  58623. };
  58624. // unrotate the fixed normals in case the mesh was built with pre-rotated particles, ex : use of positionFunction in addShape()
  58625. SolidParticleSystem.prototype._unrotateFixedNormals = function () {
  58626. var index = 0;
  58627. var idx = 0;
  58628. for (var p = 0; p < this.particles.length; p++) {
  58629. this._particle = this.particles[p];
  58630. this._shape = this._particle._model._shape;
  58631. if (this._particle.rotationQuaternion) {
  58632. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  58633. }
  58634. else {
  58635. this._yaw = this._particle.rotation.y;
  58636. this._pitch = this._particle.rotation.x;
  58637. this._roll = this._particle.rotation.z;
  58638. this._quaternionRotationYPR();
  58639. }
  58640. this._quaternionToRotationMatrix();
  58641. this._rotMatrix.invertToRef(this._invertMatrix);
  58642. for (var pt = 0; pt < this._shape.length; pt++) {
  58643. idx = index + pt * 3;
  58644. BABYLON.Vector3.TransformNormalFromFloatsToRef(this._normals32[idx], this._normals32[idx + 1], this._normals32[idx + 2], this._invertMatrix, this._normal);
  58645. this._fixedNormal32[idx] = this._normal.x;
  58646. this._fixedNormal32[idx + 1] = this._normal.y;
  58647. this._fixedNormal32[idx + 2] = this._normal.z;
  58648. }
  58649. index = idx + 3;
  58650. }
  58651. };
  58652. //reset copy
  58653. SolidParticleSystem.prototype._resetCopy = function () {
  58654. this._copy.position.x = 0;
  58655. this._copy.position.y = 0;
  58656. this._copy.position.z = 0;
  58657. this._copy.rotation.x = 0;
  58658. this._copy.rotation.y = 0;
  58659. this._copy.rotation.z = 0;
  58660. this._copy.rotationQuaternion = null;
  58661. this._copy.scaling.x = 1.0;
  58662. this._copy.scaling.y = 1.0;
  58663. this._copy.scaling.z = 1.0;
  58664. this._copy.uvs.x = 0;
  58665. this._copy.uvs.y = 0;
  58666. this._copy.uvs.z = 1.0;
  58667. this._copy.uvs.w = 1.0;
  58668. this._copy.color = null;
  58669. this._copy.translateFromPivot = false;
  58670. };
  58671. // _meshBuilder : inserts the shape model in the global SPS mesh
  58672. SolidParticleSystem.prototype._meshBuilder = function (p, shape, positions, meshInd, indices, meshUV, uvs, meshCol, colors, meshNor, normals, idx, idxInShape, options) {
  58673. var i;
  58674. var u = 0;
  58675. var c = 0;
  58676. var n = 0;
  58677. this._resetCopy();
  58678. if (options && options.positionFunction) { // call to custom positionFunction
  58679. options.positionFunction(this._copy, idx, idxInShape);
  58680. this._mustUnrotateFixedNormals = true;
  58681. }
  58682. if (this._copy.rotationQuaternion) {
  58683. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58684. }
  58685. else {
  58686. this._yaw = this._copy.rotation.y;
  58687. this._pitch = this._copy.rotation.x;
  58688. this._roll = this._copy.rotation.z;
  58689. this._quaternionRotationYPR();
  58690. }
  58691. this._quaternionToRotationMatrix();
  58692. this._scaledPivot.x = this._copy.pivot.x * this._copy.scaling.x;
  58693. this._scaledPivot.y = this._copy.pivot.y * this._copy.scaling.y;
  58694. this._scaledPivot.z = this._copy.pivot.z * this._copy.scaling.z;
  58695. if (this._copy.translateFromPivot) {
  58696. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58697. }
  58698. else {
  58699. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58700. }
  58701. for (i = 0; i < shape.length; i++) {
  58702. this._vertex.x = shape[i].x;
  58703. this._vertex.y = shape[i].y;
  58704. this._vertex.z = shape[i].z;
  58705. if (options && options.vertexFunction) {
  58706. options.vertexFunction(this._copy, this._vertex, i);
  58707. }
  58708. this._vertex.x *= this._copy.scaling.x;
  58709. this._vertex.y *= this._copy.scaling.y;
  58710. this._vertex.z *= this._copy.scaling.z;
  58711. this._vertex.x -= this._scaledPivot.x;
  58712. this._vertex.y -= this._scaledPivot.y;
  58713. this._vertex.z -= this._scaledPivot.z;
  58714. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58715. this._rotated.addInPlace(this._pivotBackTranslation);
  58716. positions.push(this._copy.position.x + this._rotated.x, this._copy.position.y + this._rotated.y, this._copy.position.z + this._rotated.z);
  58717. if (meshUV) {
  58718. 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);
  58719. u += 2;
  58720. }
  58721. if (this._copy.color) {
  58722. this._color = this._copy.color;
  58723. }
  58724. else if (meshCol && meshCol[c] !== undefined) {
  58725. this._color.r = meshCol[c];
  58726. this._color.g = meshCol[c + 1];
  58727. this._color.b = meshCol[c + 2];
  58728. this._color.a = meshCol[c + 3];
  58729. }
  58730. else {
  58731. this._color.r = 1.0;
  58732. this._color.g = 1.0;
  58733. this._color.b = 1.0;
  58734. this._color.a = 1.0;
  58735. }
  58736. colors.push(this._color.r, this._color.g, this._color.b, this._color.a);
  58737. c += 4;
  58738. if (!this.recomputeNormals && meshNor) {
  58739. this._normal.x = meshNor[n];
  58740. this._normal.y = meshNor[n + 1];
  58741. this._normal.z = meshNor[n + 2];
  58742. BABYLON.Vector3.TransformNormalToRef(this._normal, this._rotMatrix, this._normal);
  58743. normals.push(this._normal.x, this._normal.y, this._normal.z);
  58744. n += 3;
  58745. }
  58746. }
  58747. for (i = 0; i < meshInd.length; i++) {
  58748. var current_ind = p + meshInd[i];
  58749. indices.push(current_ind);
  58750. if (current_ind > 65535) {
  58751. this._needs32Bits = true;
  58752. }
  58753. }
  58754. if (this._pickable) {
  58755. var nbfaces = meshInd.length / 3;
  58756. for (i = 0; i < nbfaces; i++) {
  58757. this.pickedParticles.push({ idx: idx, faceId: i });
  58758. }
  58759. }
  58760. if (this._depthSort) {
  58761. this.depthSortedParticles.push(new BABYLON.DepthSortedParticle());
  58762. }
  58763. return this._copy;
  58764. };
  58765. // returns a shape array from positions array
  58766. SolidParticleSystem.prototype._posToShape = function (positions) {
  58767. var shape = [];
  58768. for (var i = 0; i < positions.length; i += 3) {
  58769. shape.push(new BABYLON.Vector3(positions[i], positions[i + 1], positions[i + 2]));
  58770. }
  58771. return shape;
  58772. };
  58773. // returns a shapeUV array from a Vector4 uvs
  58774. SolidParticleSystem.prototype._uvsToShapeUV = function (uvs) {
  58775. var shapeUV = [];
  58776. if (uvs) {
  58777. for (var i = 0; i < uvs.length; i++)
  58778. shapeUV.push(uvs[i]);
  58779. }
  58780. return shapeUV;
  58781. };
  58782. // adds a new particle object in the particles array
  58783. SolidParticleSystem.prototype._addParticle = function (idx, idxpos, idxind, model, shapeId, idxInShape, bInfo) {
  58784. if (bInfo === void 0) { bInfo = null; }
  58785. var sp = new BABYLON.SolidParticle(idx, idxpos, idxind, model, shapeId, idxInShape, this, bInfo);
  58786. this.particles.push(sp);
  58787. return sp;
  58788. };
  58789. /**
  58790. * Adds some particles to the SPS from the model shape. Returns the shape id.
  58791. * Please read the doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#create-an-immutable-sps
  58792. * @param mesh is any Mesh object that will be used as a model for the solid particles.
  58793. * @param nb (positive integer) the number of particles to be created from this model
  58794. * @param options {positionFunction} is an optional javascript function to called for each particle on SPS creation.
  58795. * {vertexFunction} is an optional javascript function to called for each vertex of each particle on SPS creation
  58796. * @returns the number of shapes in the system
  58797. */
  58798. SolidParticleSystem.prototype.addShape = function (mesh, nb, options) {
  58799. var meshPos = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  58800. var meshInd = mesh.getIndices();
  58801. var meshUV = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  58802. var meshCol = mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  58803. var meshNor = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  58804. var bbInfo;
  58805. if (this._particlesIntersect) {
  58806. bbInfo = mesh.getBoundingInfo();
  58807. }
  58808. var shape = this._posToShape(meshPos);
  58809. var shapeUV = this._uvsToShapeUV(meshUV);
  58810. var posfunc = options ? options.positionFunction : null;
  58811. var vtxfunc = options ? options.vertexFunction : null;
  58812. var modelShape = new BABYLON.ModelShape(this._shapeCounter, shape, meshInd.length, shapeUV, posfunc, vtxfunc);
  58813. // particles
  58814. var sp;
  58815. var currentCopy;
  58816. var idx = this.nbParticles;
  58817. for (var i = 0; i < nb; i++) {
  58818. var currentPos = this._positions.length;
  58819. var currentInd = this._indices.length;
  58820. currentCopy = this._meshBuilder(this._index, shape, this._positions, meshInd, this._indices, meshUV, this._uvs, meshCol, this._colors, meshNor, this._normals, idx, i, options);
  58821. if (this._updatable) {
  58822. sp = this._addParticle(idx, currentPos, currentInd, modelShape, this._shapeCounter, i, bbInfo);
  58823. sp.position.copyFrom(currentCopy.position);
  58824. sp.rotation.copyFrom(currentCopy.rotation);
  58825. if (currentCopy.rotationQuaternion && sp.rotationQuaternion) {
  58826. sp.rotationQuaternion.copyFrom(currentCopy.rotationQuaternion);
  58827. }
  58828. if (currentCopy.color && sp.color) {
  58829. sp.color.copyFrom(currentCopy.color);
  58830. }
  58831. sp.scaling.copyFrom(currentCopy.scaling);
  58832. sp.uvs.copyFrom(currentCopy.uvs);
  58833. }
  58834. this._index += shape.length;
  58835. idx++;
  58836. }
  58837. this.nbParticles += nb;
  58838. this._shapeCounter++;
  58839. return this._shapeCounter - 1;
  58840. };
  58841. // rebuilds a particle back to its just built status : if needed, recomputes the custom positions and vertices
  58842. SolidParticleSystem.prototype._rebuildParticle = function (particle) {
  58843. this._resetCopy();
  58844. if (particle._model._positionFunction) { // recall to stored custom positionFunction
  58845. particle._model._positionFunction(this._copy, particle.idx, particle.idxInShape);
  58846. }
  58847. if (this._copy.rotationQuaternion) {
  58848. this._quaternion.copyFrom(this._copy.rotationQuaternion);
  58849. }
  58850. else {
  58851. this._yaw = this._copy.rotation.y;
  58852. this._pitch = this._copy.rotation.x;
  58853. this._roll = this._copy.rotation.z;
  58854. this._quaternionRotationYPR();
  58855. }
  58856. this._quaternionToRotationMatrix();
  58857. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  58858. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  58859. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  58860. if (this._copy.translateFromPivot) {
  58861. this._pivotBackTranslation.copyFromFloats(0.0, 0.0, 0.0);
  58862. }
  58863. else {
  58864. this._pivotBackTranslation.copyFrom(this._scaledPivot);
  58865. }
  58866. this._shape = particle._model._shape;
  58867. for (var pt = 0; pt < this._shape.length; pt++) {
  58868. this._vertex.x = this._shape[pt].x;
  58869. this._vertex.y = this._shape[pt].y;
  58870. this._vertex.z = this._shape[pt].z;
  58871. if (particle._model._vertexFunction) {
  58872. particle._model._vertexFunction(this._copy, this._vertex, pt); // recall to stored vertexFunction
  58873. }
  58874. this._vertex.x *= this._copy.scaling.x;
  58875. this._vertex.y *= this._copy.scaling.y;
  58876. this._vertex.z *= this._copy.scaling.z;
  58877. this._vertex.x -= this._scaledPivot.x;
  58878. this._vertex.y -= this._scaledPivot.y;
  58879. this._vertex.z -= this._scaledPivot.z;
  58880. BABYLON.Vector3.TransformCoordinatesToRef(this._vertex, this._rotMatrix, this._rotated);
  58881. this._rotated.addInPlace(this._pivotBackTranslation);
  58882. this._positions32[particle._pos + pt * 3] = this._copy.position.x + this._rotated.x;
  58883. this._positions32[particle._pos + pt * 3 + 1] = this._copy.position.y + this._rotated.y;
  58884. this._positions32[particle._pos + pt * 3 + 2] = this._copy.position.z + this._rotated.z;
  58885. }
  58886. particle.position.x = 0.0;
  58887. particle.position.y = 0.0;
  58888. particle.position.z = 0.0;
  58889. particle.rotation.x = 0.0;
  58890. particle.rotation.y = 0.0;
  58891. particle.rotation.z = 0.0;
  58892. particle.rotationQuaternion = null;
  58893. particle.scaling.x = 1.0;
  58894. particle.scaling.y = 1.0;
  58895. particle.scaling.z = 1.0;
  58896. particle.uvs.x = 0.0;
  58897. particle.uvs.y = 0.0;
  58898. particle.uvs.z = 1.0;
  58899. particle.uvs.w = 1.0;
  58900. particle.pivot.x = 0.0;
  58901. particle.pivot.y = 0.0;
  58902. particle.pivot.z = 0.0;
  58903. particle.translateFromPivot = false;
  58904. particle.parentId = null;
  58905. };
  58906. /**
  58907. * Rebuilds the whole mesh and updates the VBO : custom positions and vertices are recomputed if needed.
  58908. * @returns the SPS.
  58909. */
  58910. SolidParticleSystem.prototype.rebuildMesh = function () {
  58911. for (var p = 0; p < this.particles.length; p++) {
  58912. this._rebuildParticle(this.particles[p]);
  58913. }
  58914. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  58915. return this;
  58916. };
  58917. /**
  58918. * Sets all the particles : this method actually really updates the mesh according to the particle positions, rotations, colors, textures, etc.
  58919. * This method calls `updateParticle()` for each particle of the SPS.
  58920. * For an animated SPS, it is usually called within the render loop.
  58921. * @param start The particle index in the particle array where to start to compute the particle property values _(default 0)_
  58922. * @param end The particle index in the particle array where to stop to compute the particle property values _(default nbParticle - 1)_
  58923. * @param update If the mesh must be finally updated on this call after all the particle computations _(default true)_
  58924. * @returns the SPS.
  58925. */
  58926. SolidParticleSystem.prototype.setParticles = function (start, end, update) {
  58927. if (start === void 0) { start = 0; }
  58928. if (end === void 0) { end = this.nbParticles - 1; }
  58929. if (update === void 0) { update = true; }
  58930. if (!this._updatable) {
  58931. return this;
  58932. }
  58933. // custom beforeUpdate
  58934. this.beforeUpdateParticles(start, end, update);
  58935. this._cam_axisX.x = 1.0;
  58936. this._cam_axisX.y = 0.0;
  58937. this._cam_axisX.z = 0.0;
  58938. this._cam_axisY.x = 0.0;
  58939. this._cam_axisY.y = 1.0;
  58940. this._cam_axisY.z = 0.0;
  58941. this._cam_axisZ.x = 0.0;
  58942. this._cam_axisZ.y = 0.0;
  58943. this._cam_axisZ.z = 1.0;
  58944. // cases when the World Matrix is to be computed first
  58945. if (this.billboard || this._depthSort) {
  58946. this.mesh.computeWorldMatrix(true);
  58947. this.mesh._worldMatrix.invertToRef(this._invertMatrix);
  58948. }
  58949. // if the particles will always face the camera
  58950. if (this.billboard) {
  58951. // compute the camera position and un-rotate it by the current mesh rotation
  58952. this._camera.getDirectionToRef(this._axisZ, this._camDir);
  58953. BABYLON.Vector3.TransformNormalToRef(this._camDir, this._invertMatrix, this._cam_axisZ);
  58954. this._cam_axisZ.normalize();
  58955. // same for camera up vector extracted from the cam view matrix
  58956. var view = this._camera.getViewMatrix(true);
  58957. BABYLON.Vector3.TransformNormalFromFloatsToRef(view.m[1], view.m[5], view.m[9], this._invertMatrix, this._cam_axisY);
  58958. BABYLON.Vector3.CrossToRef(this._cam_axisY, this._cam_axisZ, this._cam_axisX);
  58959. this._cam_axisY.normalize();
  58960. this._cam_axisX.normalize();
  58961. }
  58962. // if depthSort, compute the camera global position in the mesh local system
  58963. if (this._depthSort) {
  58964. BABYLON.Vector3.TransformCoordinatesToRef(this._camera.globalPosition, this._invertMatrix, this._camInvertedPosition); // then un-rotate the camera
  58965. }
  58966. BABYLON.Matrix.IdentityToRef(this._rotMatrix);
  58967. var idx = 0; // current position index in the global array positions32
  58968. var index = 0; // position start index in the global array positions32 of the current particle
  58969. var colidx = 0; // current color index in the global array colors32
  58970. var colorIndex = 0; // color start index in the global array colors32 of the current particle
  58971. var uvidx = 0; // current uv index in the global array uvs32
  58972. var uvIndex = 0; // uv start index in the global array uvs32 of the current particle
  58973. var pt = 0; // current index in the particle model shape
  58974. if (this.mesh.isFacetDataEnabled) {
  58975. this._computeBoundingBox = true;
  58976. }
  58977. end = (end >= this.nbParticles) ? this.nbParticles - 1 : end;
  58978. if (this._computeBoundingBox) {
  58979. if (start == 0 && end == this.nbParticles - 1) { // all the particles are updated, then recompute the BBox from scratch
  58980. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, this._minimum);
  58981. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, this._maximum);
  58982. }
  58983. else { // only some particles are updated, then use the current existing BBox basis. Note : it can only increase.
  58984. if (this.mesh._boundingInfo) {
  58985. this._minimum.copyFrom(this.mesh._boundingInfo.boundingBox.minimum);
  58986. this._maximum.copyFrom(this.mesh._boundingInfo.boundingBox.maximum);
  58987. }
  58988. }
  58989. }
  58990. // particle loop
  58991. index = this.particles[start]._pos;
  58992. var vpos = (index / 3) | 0;
  58993. colorIndex = vpos * 4;
  58994. uvIndex = vpos * 2;
  58995. for (var p = start; p <= end; p++) {
  58996. this._particle = this.particles[p];
  58997. this._shape = this._particle._model._shape;
  58998. this._shapeUV = this._particle._model._shapeUV;
  58999. // call to custom user function to update the particle properties
  59000. this.updateParticle(this._particle);
  59001. // camera-particle distance for depth sorting
  59002. if (this._depthSort && this._depthSortParticles) {
  59003. var dsp = this.depthSortedParticles[p];
  59004. dsp.ind = this._particle._ind;
  59005. dsp.indicesLength = this._particle._model._indicesLength;
  59006. dsp.sqDistance = BABYLON.Vector3.DistanceSquared(this._particle.position, this._camInvertedPosition);
  59007. }
  59008. // skip the computations for inactive or already invisible particles
  59009. if (!this._particle.alive || (this._particle._stillInvisible && !this._particle.isVisible)) {
  59010. // increment indexes for the next particle
  59011. pt = this._shape.length;
  59012. index += pt * 3;
  59013. colorIndex += pt * 4;
  59014. uvIndex += pt * 2;
  59015. continue;
  59016. }
  59017. if (this._particle.isVisible) {
  59018. this._particle._stillInvisible = false; // un-mark permanent invisibility
  59019. this._particleHasParent = (this._particle.parentId !== null);
  59020. this._scaledPivot.x = this._particle.pivot.x * this._particle.scaling.x;
  59021. this._scaledPivot.y = this._particle.pivot.y * this._particle.scaling.y;
  59022. this._scaledPivot.z = this._particle.pivot.z * this._particle.scaling.z;
  59023. // particle rotation matrix
  59024. if (this.billboard) {
  59025. this._particle.rotation.x = 0.0;
  59026. this._particle.rotation.y = 0.0;
  59027. }
  59028. if (this._computeParticleRotation || this.billboard) {
  59029. if (this._particle.rotationQuaternion) {
  59030. this._quaternion.copyFrom(this._particle.rotationQuaternion);
  59031. }
  59032. else {
  59033. this._yaw = this._particle.rotation.y;
  59034. this._pitch = this._particle.rotation.x;
  59035. this._roll = this._particle.rotation.z;
  59036. this._quaternionRotationYPR();
  59037. }
  59038. this._quaternionToRotationMatrix();
  59039. }
  59040. if (this._particleHasParent) {
  59041. this._parent = this.particles[this._particle.parentId];
  59042. 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];
  59043. 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];
  59044. 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];
  59045. this._particle._globalPosition.x = this._parent._globalPosition.x + this._rotated.x;
  59046. this._particle._globalPosition.y = this._parent._globalPosition.y + this._rotated.y;
  59047. this._particle._globalPosition.z = this._parent._globalPosition.z + this._rotated.z;
  59048. if (this._computeParticleRotation || this.billboard) {
  59049. 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];
  59050. 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];
  59051. 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];
  59052. 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];
  59053. 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];
  59054. 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];
  59055. 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];
  59056. 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];
  59057. 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];
  59058. }
  59059. }
  59060. else {
  59061. this._particle._globalPosition.x = this._particle.position.x;
  59062. this._particle._globalPosition.y = this._particle.position.y;
  59063. this._particle._globalPosition.z = this._particle.position.z;
  59064. if (this._computeParticleRotation || this.billboard) {
  59065. this._particle._rotationMatrix[0] = this._rotMatrix.m[0];
  59066. this._particle._rotationMatrix[1] = this._rotMatrix.m[1];
  59067. this._particle._rotationMatrix[2] = this._rotMatrix.m[2];
  59068. this._particle._rotationMatrix[3] = this._rotMatrix.m[4];
  59069. this._particle._rotationMatrix[4] = this._rotMatrix.m[5];
  59070. this._particle._rotationMatrix[5] = this._rotMatrix.m[6];
  59071. this._particle._rotationMatrix[6] = this._rotMatrix.m[8];
  59072. this._particle._rotationMatrix[7] = this._rotMatrix.m[9];
  59073. this._particle._rotationMatrix[8] = this._rotMatrix.m[10];
  59074. }
  59075. }
  59076. if (this._particle.translateFromPivot) {
  59077. this._pivotBackTranslation.x = 0.0;
  59078. this._pivotBackTranslation.y = 0.0;
  59079. this._pivotBackTranslation.z = 0.0;
  59080. }
  59081. else {
  59082. this._pivotBackTranslation.x = this._scaledPivot.x;
  59083. this._pivotBackTranslation.y = this._scaledPivot.y;
  59084. this._pivotBackTranslation.z = this._scaledPivot.z;
  59085. }
  59086. // particle vertex loop
  59087. for (pt = 0; pt < this._shape.length; pt++) {
  59088. idx = index + pt * 3;
  59089. colidx = colorIndex + pt * 4;
  59090. uvidx = uvIndex + pt * 2;
  59091. this._vertex.x = this._shape[pt].x;
  59092. this._vertex.y = this._shape[pt].y;
  59093. this._vertex.z = this._shape[pt].z;
  59094. if (this._computeParticleVertex) {
  59095. this.updateParticleVertex(this._particle, this._vertex, pt);
  59096. }
  59097. // positions
  59098. this._vertex.x *= this._particle.scaling.x;
  59099. this._vertex.y *= this._particle.scaling.y;
  59100. this._vertex.z *= this._particle.scaling.z;
  59101. this._vertex.x -= this._scaledPivot.x;
  59102. this._vertex.y -= this._scaledPivot.y;
  59103. this._vertex.z -= this._scaledPivot.z;
  59104. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59105. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59106. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59107. this._rotated.x += this._pivotBackTranslation.x;
  59108. this._rotated.y += this._pivotBackTranslation.y;
  59109. this._rotated.z += this._pivotBackTranslation.z;
  59110. 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;
  59111. 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;
  59112. 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;
  59113. if (this._computeBoundingBox) {
  59114. if (this._positions32[idx] < this._minimum.x) {
  59115. this._minimum.x = this._positions32[idx];
  59116. }
  59117. if (this._positions32[idx] > this._maximum.x) {
  59118. this._maximum.x = this._positions32[idx];
  59119. }
  59120. if (this._positions32[idx + 1] < this._minimum.y) {
  59121. this._minimum.y = this._positions32[idx + 1];
  59122. }
  59123. if (this._positions32[idx + 1] > this._maximum.y) {
  59124. this._maximum.y = this._positions32[idx + 1];
  59125. }
  59126. if (this._positions32[idx + 2] < this._minimum.z) {
  59127. this._minimum.z = this._positions32[idx + 2];
  59128. }
  59129. if (this._positions32[idx + 2] > this._maximum.z) {
  59130. this._maximum.z = this._positions32[idx + 2];
  59131. }
  59132. }
  59133. // normals : if the particles can't be morphed then just rotate the normals, what is much more faster than ComputeNormals()
  59134. if (!this._computeParticleVertex) {
  59135. this._normal.x = this._fixedNormal32[idx];
  59136. this._normal.y = this._fixedNormal32[idx + 1];
  59137. this._normal.z = this._fixedNormal32[idx + 2];
  59138. this._rotated.x = this._normal.x * this._particle._rotationMatrix[0] + this._normal.y * this._particle._rotationMatrix[3] + this._normal.z * this._particle._rotationMatrix[6];
  59139. this._rotated.y = this._normal.x * this._particle._rotationMatrix[1] + this._normal.y * this._particle._rotationMatrix[4] + this._normal.z * this._particle._rotationMatrix[7];
  59140. this._rotated.z = this._normal.x * this._particle._rotationMatrix[2] + this._normal.y * this._particle._rotationMatrix[5] + this._normal.z * this._particle._rotationMatrix[8];
  59141. this._normals32[idx] = this._cam_axisX.x * this._rotated.x + this._cam_axisY.x * this._rotated.y + this._cam_axisZ.x * this._rotated.z;
  59142. 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;
  59143. 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;
  59144. }
  59145. if (this._computeParticleColor && this._particle.color) {
  59146. this._colors32[colidx] = this._particle.color.r;
  59147. this._colors32[colidx + 1] = this._particle.color.g;
  59148. this._colors32[colidx + 2] = this._particle.color.b;
  59149. this._colors32[colidx + 3] = this._particle.color.a;
  59150. }
  59151. if (this._computeParticleTexture) {
  59152. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59153. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59154. }
  59155. }
  59156. }
  59157. // particle just set invisible : scaled to zero and positioned at the origin
  59158. else {
  59159. this._particle._stillInvisible = true; // mark the particle as invisible
  59160. for (pt = 0; pt < this._shape.length; pt++) {
  59161. idx = index + pt * 3;
  59162. colidx = colorIndex + pt * 4;
  59163. uvidx = uvIndex + pt * 2;
  59164. this._positions32[idx] = 0.0;
  59165. this._positions32[idx + 1] = 0.0;
  59166. this._positions32[idx + 2] = 0.0;
  59167. this._normals32[idx] = 0.0;
  59168. this._normals32[idx + 1] = 0.0;
  59169. this._normals32[idx + 2] = 0.0;
  59170. if (this._computeParticleColor && this._particle.color) {
  59171. this._colors32[colidx] = this._particle.color.r;
  59172. this._colors32[colidx + 1] = this._particle.color.g;
  59173. this._colors32[colidx + 2] = this._particle.color.b;
  59174. this._colors32[colidx + 3] = this._particle.color.a;
  59175. }
  59176. if (this._computeParticleTexture) {
  59177. this._uvs32[uvidx] = this._shapeUV[pt * 2] * (this._particle.uvs.z - this._particle.uvs.x) + this._particle.uvs.x;
  59178. this._uvs32[uvidx + 1] = this._shapeUV[pt * 2 + 1] * (this._particle.uvs.w - this._particle.uvs.y) + this._particle.uvs.y;
  59179. }
  59180. }
  59181. }
  59182. // if the particle intersections must be computed : update the bbInfo
  59183. if (this._particlesIntersect) {
  59184. var bInfo = this._particle._boundingInfo;
  59185. var bBox = bInfo.boundingBox;
  59186. var bSphere = bInfo.boundingSphere;
  59187. if (!this._bSphereOnly) {
  59188. // place, scale and rotate the particle bbox within the SPS local system, then update it
  59189. for (var b = 0; b < bBox.vectors.length; b++) {
  59190. this._vertex.x = this._particle._modelBoundingInfo.boundingBox.vectors[b].x * this._particle.scaling.x;
  59191. this._vertex.y = this._particle._modelBoundingInfo.boundingBox.vectors[b].y * this._particle.scaling.y;
  59192. this._vertex.z = this._particle._modelBoundingInfo.boundingBox.vectors[b].z * this._particle.scaling.z;
  59193. this._rotated.x = this._vertex.x * this._particle._rotationMatrix[0] + this._vertex.y * this._particle._rotationMatrix[3] + this._vertex.z * this._particle._rotationMatrix[6];
  59194. this._rotated.y = this._vertex.x * this._particle._rotationMatrix[1] + this._vertex.y * this._particle._rotationMatrix[4] + this._vertex.z * this._particle._rotationMatrix[7];
  59195. this._rotated.z = this._vertex.x * this._particle._rotationMatrix[2] + this._vertex.y * this._particle._rotationMatrix[5] + this._vertex.z * this._particle._rotationMatrix[8];
  59196. 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;
  59197. 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;
  59198. 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;
  59199. }
  59200. bBox._update(this.mesh._worldMatrix);
  59201. }
  59202. // place and scale the particle bouding sphere in the SPS local system, then update it
  59203. this._minBbox.x = this._particle._modelBoundingInfo.minimum.x * this._particle.scaling.x;
  59204. this._minBbox.y = this._particle._modelBoundingInfo.minimum.y * this._particle.scaling.y;
  59205. this._minBbox.z = this._particle._modelBoundingInfo.minimum.z * this._particle.scaling.z;
  59206. this._maxBbox.x = this._particle._modelBoundingInfo.maximum.x * this._particle.scaling.x;
  59207. this._maxBbox.y = this._particle._modelBoundingInfo.maximum.y * this._particle.scaling.y;
  59208. this._maxBbox.z = this._particle._modelBoundingInfo.maximum.z * this._particle.scaling.z;
  59209. bSphere.center.x = this._particle._globalPosition.x + (this._minBbox.x + this._maxBbox.x) * 0.5;
  59210. bSphere.center.y = this._particle._globalPosition.y + (this._minBbox.y + this._maxBbox.y) * 0.5;
  59211. bSphere.center.z = this._particle._globalPosition.z + (this._minBbox.z + this._maxBbox.z) * 0.5;
  59212. 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));
  59213. bSphere._update(this.mesh._worldMatrix);
  59214. }
  59215. // increment indexes for the next particle
  59216. index = idx + 3;
  59217. colorIndex = colidx + 4;
  59218. uvIndex = uvidx + 2;
  59219. }
  59220. // if the VBO must be updated
  59221. if (update) {
  59222. if (this._computeParticleColor) {
  59223. this.mesh.updateVerticesData(BABYLON.VertexBuffer.ColorKind, this._colors32, false, false);
  59224. }
  59225. if (this._computeParticleTexture) {
  59226. this.mesh.updateVerticesData(BABYLON.VertexBuffer.UVKind, this._uvs32, false, false);
  59227. }
  59228. this.mesh.updateVerticesData(BABYLON.VertexBuffer.PositionKind, this._positions32, false, false);
  59229. if (!this.mesh.areNormalsFrozen || this.mesh.isFacetDataEnabled) {
  59230. if (this._computeParticleVertex || this.mesh.isFacetDataEnabled) {
  59231. // recompute the normals only if the particles can be morphed, update then also the normal reference array _fixedNormal32[]
  59232. var params = this.mesh.isFacetDataEnabled ? this.mesh.getFacetDataParameters() : null;
  59233. BABYLON.VertexData.ComputeNormals(this._positions32, this._indices32, this._normals32, params);
  59234. for (var i = 0; i < this._normals32.length; i++) {
  59235. this._fixedNormal32[i] = this._normals32[i];
  59236. }
  59237. }
  59238. if (!this.mesh.areNormalsFrozen) {
  59239. this.mesh.updateVerticesData(BABYLON.VertexBuffer.NormalKind, this._normals32, false, false);
  59240. }
  59241. }
  59242. if (this._depthSort && this._depthSortParticles) {
  59243. this.depthSortedParticles.sort(this._depthSortFunction);
  59244. var dspl = this.depthSortedParticles.length;
  59245. var sorted = 0;
  59246. var lind = 0;
  59247. var sind = 0;
  59248. var sid = 0;
  59249. for (sorted = 0; sorted < dspl; sorted++) {
  59250. lind = this.depthSortedParticles[sorted].indicesLength;
  59251. sind = this.depthSortedParticles[sorted].ind;
  59252. for (var i = 0; i < lind; i++) {
  59253. this._indices32[sid] = this._indices[sind + i];
  59254. sid++;
  59255. }
  59256. }
  59257. this.mesh.updateIndices(this._indices32);
  59258. }
  59259. }
  59260. if (this._computeBoundingBox) {
  59261. this.mesh._boundingInfo = new BABYLON.BoundingInfo(this._minimum, this._maximum);
  59262. this.mesh._boundingInfo.update(this.mesh._worldMatrix);
  59263. }
  59264. this.afterUpdateParticles(start, end, update);
  59265. return this;
  59266. };
  59267. SolidParticleSystem.prototype._quaternionRotationYPR = function () {
  59268. this._halfroll = this._roll * 0.5;
  59269. this._halfpitch = this._pitch * 0.5;
  59270. this._halfyaw = this._yaw * 0.5;
  59271. this._sinRoll = Math.sin(this._halfroll);
  59272. this._cosRoll = Math.cos(this._halfroll);
  59273. this._sinPitch = Math.sin(this._halfpitch);
  59274. this._cosPitch = Math.cos(this._halfpitch);
  59275. this._sinYaw = Math.sin(this._halfyaw);
  59276. this._cosYaw = Math.cos(this._halfyaw);
  59277. this._quaternion.x = this._cosYaw * this._sinPitch * this._cosRoll + this._sinYaw * this._cosPitch * this._sinRoll;
  59278. this._quaternion.y = this._sinYaw * this._cosPitch * this._cosRoll - this._cosYaw * this._sinPitch * this._sinRoll;
  59279. this._quaternion.z = this._cosYaw * this._cosPitch * this._sinRoll - this._sinYaw * this._sinPitch * this._cosRoll;
  59280. this._quaternion.w = this._cosYaw * this._cosPitch * this._cosRoll + this._sinYaw * this._sinPitch * this._sinRoll;
  59281. };
  59282. SolidParticleSystem.prototype._quaternionToRotationMatrix = function () {
  59283. this._rotMatrix.m[0] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.z * this._quaternion.z));
  59284. this._rotMatrix.m[1] = 2.0 * (this._quaternion.x * this._quaternion.y + this._quaternion.z * this._quaternion.w);
  59285. this._rotMatrix.m[2] = 2.0 * (this._quaternion.z * this._quaternion.x - this._quaternion.y * this._quaternion.w);
  59286. this._rotMatrix.m[3] = 0;
  59287. this._rotMatrix.m[4] = 2.0 * (this._quaternion.x * this._quaternion.y - this._quaternion.z * this._quaternion.w);
  59288. this._rotMatrix.m[5] = 1.0 - (2.0 * (this._quaternion.z * this._quaternion.z + this._quaternion.x * this._quaternion.x));
  59289. this._rotMatrix.m[6] = 2.0 * (this._quaternion.y * this._quaternion.z + this._quaternion.x * this._quaternion.w);
  59290. this._rotMatrix.m[7] = 0;
  59291. this._rotMatrix.m[8] = 2.0 * (this._quaternion.z * this._quaternion.x + this._quaternion.y * this._quaternion.w);
  59292. this._rotMatrix.m[9] = 2.0 * (this._quaternion.y * this._quaternion.z - this._quaternion.x * this._quaternion.w);
  59293. this._rotMatrix.m[10] = 1.0 - (2.0 * (this._quaternion.y * this._quaternion.y + this._quaternion.x * this._quaternion.x));
  59294. this._rotMatrix.m[11] = 0;
  59295. this._rotMatrix.m[12] = 0;
  59296. this._rotMatrix.m[13] = 0;
  59297. this._rotMatrix.m[14] = 0;
  59298. this._rotMatrix.m[15] = 1.0;
  59299. };
  59300. /**
  59301. * Disposes the SPS.
  59302. */
  59303. SolidParticleSystem.prototype.dispose = function () {
  59304. this.mesh.dispose();
  59305. this.vars = null;
  59306. // drop references to internal big arrays for the GC
  59307. this._positions = null;
  59308. this._indices = null;
  59309. this._normals = null;
  59310. this._uvs = null;
  59311. this._colors = null;
  59312. this._indices32 = null;
  59313. this._positions32 = null;
  59314. this._normals32 = null;
  59315. this._fixedNormal32 = null;
  59316. this._uvs32 = null;
  59317. this._colors32 = null;
  59318. this.pickedParticles = null;
  59319. };
  59320. /**
  59321. * Visibilty helper : Recomputes the visible size according to the mesh bounding box
  59322. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59323. * @returns the SPS.
  59324. */
  59325. SolidParticleSystem.prototype.refreshVisibleSize = function () {
  59326. if (!this._isVisibilityBoxLocked) {
  59327. this.mesh.refreshBoundingInfo();
  59328. }
  59329. return this;
  59330. };
  59331. /**
  59332. * Visibility helper : Sets the size of a visibility box, this sets the underlying mesh bounding box.
  59333. * @param size the size (float) of the visibility box
  59334. * note : this doesn't lock the SPS mesh bounding box.
  59335. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59336. */
  59337. SolidParticleSystem.prototype.setVisibilityBox = function (size) {
  59338. var vis = size / 2;
  59339. this.mesh._boundingInfo = new BABYLON.BoundingInfo(new BABYLON.Vector3(-vis, -vis, -vis), new BABYLON.Vector3(vis, vis, vis));
  59340. };
  59341. Object.defineProperty(SolidParticleSystem.prototype, "isAlwaysVisible", {
  59342. /**
  59343. * Gets whether the SPS as always visible or not
  59344. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59345. */
  59346. get: function () {
  59347. return this._alwaysVisible;
  59348. },
  59349. /**
  59350. * Sets the SPS as always visible or not
  59351. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59352. */
  59353. set: function (val) {
  59354. this._alwaysVisible = val;
  59355. this.mesh.alwaysSelectAsActiveMesh = val;
  59356. },
  59357. enumerable: true,
  59358. configurable: true
  59359. });
  59360. Object.defineProperty(SolidParticleSystem.prototype, "isVisibilityBoxLocked", {
  59361. /**
  59362. * Gets if the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59363. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59364. */
  59365. get: function () {
  59366. return this._isVisibilityBoxLocked;
  59367. },
  59368. /**
  59369. * Sets the SPS visibility box as locked or not. This enables/disables the underlying mesh bounding box updates.
  59370. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#sps-visibility
  59371. */
  59372. set: function (val) {
  59373. this._isVisibilityBoxLocked = val;
  59374. var boundingInfo = this.mesh.getBoundingInfo();
  59375. boundingInfo.isLocked = val;
  59376. },
  59377. enumerable: true,
  59378. configurable: true
  59379. });
  59380. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleRotation", {
  59381. /**
  59382. * Gets if `setParticles()` computes the particle rotations or not.
  59383. * Default value : true. The SPS is faster when it's set to false.
  59384. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59385. */
  59386. get: function () {
  59387. return this._computeParticleRotation;
  59388. },
  59389. /**
  59390. * Tells to `setParticles()` to compute the particle rotations or not.
  59391. * Default value : true. The SPS is faster when it's set to false.
  59392. * Note : the particle rotations aren't stored values, so setting `computeParticleRotation` to false will prevents the particle to rotate.
  59393. */
  59394. set: function (val) {
  59395. this._computeParticleRotation = val;
  59396. },
  59397. enumerable: true,
  59398. configurable: true
  59399. });
  59400. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleColor", {
  59401. /**
  59402. * Gets if `setParticles()` computes the particle colors or not.
  59403. * Default value : true. The SPS is faster when it's set to false.
  59404. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59405. */
  59406. get: function () {
  59407. return this._computeParticleColor;
  59408. },
  59409. /**
  59410. * Tells to `setParticles()` to compute the particle colors or not.
  59411. * Default value : true. The SPS is faster when it's set to false.
  59412. * Note : the particle colors are stored values, so setting `computeParticleColor` to false will keep yet the last colors set.
  59413. */
  59414. set: function (val) {
  59415. this._computeParticleColor = val;
  59416. },
  59417. enumerable: true,
  59418. configurable: true
  59419. });
  59420. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleTexture", {
  59421. /**
  59422. * Gets if `setParticles()` computes the particle textures or not.
  59423. * Default value : true. The SPS is faster when it's set to false.
  59424. * Note : the particle textures are stored values, so setting `computeParticleTexture` to false will keep yet the last colors set.
  59425. */
  59426. get: function () {
  59427. return this._computeParticleTexture;
  59428. },
  59429. set: function (val) {
  59430. this._computeParticleTexture = val;
  59431. },
  59432. enumerable: true,
  59433. configurable: true
  59434. });
  59435. Object.defineProperty(SolidParticleSystem.prototype, "computeParticleVertex", {
  59436. /**
  59437. * Gets if `setParticles()` calls the vertex function for each vertex of each particle, or not.
  59438. * Default value : false. The SPS is faster when it's set to false.
  59439. * Note : the particle custom vertex positions aren't stored values.
  59440. */
  59441. get: function () {
  59442. return this._computeParticleVertex;
  59443. },
  59444. /**
  59445. * Tells to `setParticles()` to call the vertex function for each vertex of each particle, or not.
  59446. * Default value : false. The SPS is faster when it's set to false.
  59447. * Note : the particle custom vertex positions aren't stored values.
  59448. */
  59449. set: function (val) {
  59450. this._computeParticleVertex = val;
  59451. },
  59452. enumerable: true,
  59453. configurable: true
  59454. });
  59455. Object.defineProperty(SolidParticleSystem.prototype, "computeBoundingBox", {
  59456. /**
  59457. * Gets if `setParticles()` computes or not the mesh bounding box when computing the particle positions.
  59458. */
  59459. get: function () {
  59460. return this._computeBoundingBox;
  59461. },
  59462. /**
  59463. * Tells to `setParticles()` to compute or not the mesh bounding box when computing the particle positions.
  59464. */
  59465. set: function (val) {
  59466. this._computeBoundingBox = val;
  59467. },
  59468. enumerable: true,
  59469. configurable: true
  59470. });
  59471. Object.defineProperty(SolidParticleSystem.prototype, "depthSortParticles", {
  59472. /**
  59473. * Gets if `setParticles()` sorts or not the distance between each particle and the camera.
  59474. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59475. * Default : `true`
  59476. */
  59477. get: function () {
  59478. return this._depthSortParticles;
  59479. },
  59480. /**
  59481. * Tells to `setParticles()` to sort or not the distance between each particle and the camera.
  59482. * Skipped when `enableDepthSort` is set to `false` (default) at construction time.
  59483. * Default : `true`
  59484. */
  59485. set: function (val) {
  59486. this._depthSortParticles = val;
  59487. },
  59488. enumerable: true,
  59489. configurable: true
  59490. });
  59491. // =======================================================================
  59492. // Particle behavior logic
  59493. // these following methods may be overwritten by the user to fit his needs
  59494. /**
  59495. * This function does nothing. It may be overwritten to set all the particle first values.
  59496. * The SPS doesn't call this function, you may have to call it by your own.
  59497. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59498. */
  59499. SolidParticleSystem.prototype.initParticles = function () {
  59500. };
  59501. /**
  59502. * This function does nothing. It may be overwritten to recycle a particle.
  59503. * The SPS doesn't call this function, you may have to call it by your own.
  59504. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59505. * @param particle The particle to recycle
  59506. * @returns the recycled particle
  59507. */
  59508. SolidParticleSystem.prototype.recycleParticle = function (particle) {
  59509. return particle;
  59510. };
  59511. /**
  59512. * Updates a particle : this function should be overwritten by the user.
  59513. * It is called on each particle by `setParticles()`. This is the place to code each particle behavior.
  59514. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#particle-management
  59515. * @example : just set a particle position or velocity and recycle conditions
  59516. * @param particle The particle to update
  59517. * @returns the updated particle
  59518. */
  59519. SolidParticleSystem.prototype.updateParticle = function (particle) {
  59520. return particle;
  59521. };
  59522. /**
  59523. * Updates a vertex of a particle : it can be overwritten by the user.
  59524. * This will be called on each vertex particle by `setParticles()` if `computeParticleVertex` is set to true only.
  59525. * @param particle the current particle
  59526. * @param vertex the current index of the current particle
  59527. * @param pt the index of the current vertex in the particle shape
  59528. * doc : http://doc.babylonjs.com/overviews/Solid_Particle_System#update-each-particle-shape
  59529. * @example : just set a vertex particle position
  59530. * @returns the updated vertex
  59531. */
  59532. SolidParticleSystem.prototype.updateParticleVertex = function (particle, vertex, pt) {
  59533. return vertex;
  59534. };
  59535. /**
  59536. * This will be called before any other treatment by `setParticles()` and will be passed three parameters.
  59537. * This does nothing and may be overwritten by the user.
  59538. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59539. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59540. * @param update the boolean update value actually passed to setParticles()
  59541. */
  59542. SolidParticleSystem.prototype.beforeUpdateParticles = function (start, stop, update) {
  59543. };
  59544. /**
  59545. * This will be called by `setParticles()` after all the other treatments and just before the actual mesh update.
  59546. * This will be passed three parameters.
  59547. * This does nothing and may be overwritten by the user.
  59548. * @param start the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59549. * @param stop the particle index in the particle array where to stop to iterate, same than the value passed to setParticle()
  59550. * @param update the boolean update value actually passed to setParticles()
  59551. */
  59552. SolidParticleSystem.prototype.afterUpdateParticles = function (start, stop, update) {
  59553. };
  59554. return SolidParticleSystem;
  59555. }());
  59556. BABYLON.SolidParticleSystem = SolidParticleSystem;
  59557. })(BABYLON || (BABYLON = {}));
  59558. //# sourceMappingURL=babylon.solidParticleSystem.js.map
  59559. var BABYLON;
  59560. (function (BABYLON) {
  59561. var ShaderMaterial = /** @class */ (function (_super) {
  59562. __extends(ShaderMaterial, _super);
  59563. function ShaderMaterial(name, scene, shaderPath, options) {
  59564. var _this = _super.call(this, name, scene) || this;
  59565. _this._textures = {};
  59566. _this._textureArrays = {};
  59567. _this._floats = {};
  59568. _this._ints = {};
  59569. _this._floatsArrays = {};
  59570. _this._colors3 = {};
  59571. _this._colors3Arrays = {};
  59572. _this._colors4 = {};
  59573. _this._vectors2 = {};
  59574. _this._vectors3 = {};
  59575. _this._vectors4 = {};
  59576. _this._matrices = {};
  59577. _this._matrices3x3 = {};
  59578. _this._matrices2x2 = {};
  59579. _this._vectors2Arrays = {};
  59580. _this._vectors3Arrays = {};
  59581. _this._cachedWorldViewMatrix = new BABYLON.Matrix();
  59582. _this._shaderPath = shaderPath;
  59583. options.needAlphaBlending = options.needAlphaBlending || false;
  59584. options.needAlphaTesting = options.needAlphaTesting || false;
  59585. options.attributes = options.attributes || ["position", "normal", "uv"];
  59586. options.uniforms = options.uniforms || ["worldViewProjection"];
  59587. options.uniformBuffers = options.uniformBuffers || [];
  59588. options.samplers = options.samplers || [];
  59589. options.defines = options.defines || [];
  59590. _this._options = options;
  59591. return _this;
  59592. }
  59593. ShaderMaterial.prototype.getClassName = function () {
  59594. return "ShaderMaterial";
  59595. };
  59596. ShaderMaterial.prototype.needAlphaBlending = function () {
  59597. return this._options.needAlphaBlending;
  59598. };
  59599. ShaderMaterial.prototype.needAlphaTesting = function () {
  59600. return this._options.needAlphaTesting;
  59601. };
  59602. ShaderMaterial.prototype._checkUniform = function (uniformName) {
  59603. if (this._options.uniforms.indexOf(uniformName) === -1) {
  59604. this._options.uniforms.push(uniformName);
  59605. }
  59606. };
  59607. ShaderMaterial.prototype.setTexture = function (name, texture) {
  59608. if (this._options.samplers.indexOf(name) === -1) {
  59609. this._options.samplers.push(name);
  59610. }
  59611. this._textures[name] = texture;
  59612. return this;
  59613. };
  59614. ShaderMaterial.prototype.setTextureArray = function (name, textures) {
  59615. if (this._options.samplers.indexOf(name) === -1) {
  59616. this._options.samplers.push(name);
  59617. }
  59618. this._checkUniform(name);
  59619. this._textureArrays[name] = textures;
  59620. return this;
  59621. };
  59622. ShaderMaterial.prototype.setFloat = function (name, value) {
  59623. this._checkUniform(name);
  59624. this._floats[name] = value;
  59625. return this;
  59626. };
  59627. ShaderMaterial.prototype.setInt = function (name, value) {
  59628. this._checkUniform(name);
  59629. this._ints[name] = value;
  59630. return this;
  59631. };
  59632. ShaderMaterial.prototype.setFloats = function (name, value) {
  59633. this._checkUniform(name);
  59634. this._floatsArrays[name] = value;
  59635. return this;
  59636. };
  59637. ShaderMaterial.prototype.setColor3 = function (name, value) {
  59638. this._checkUniform(name);
  59639. this._colors3[name] = value;
  59640. return this;
  59641. };
  59642. ShaderMaterial.prototype.setColor3Array = function (name, value) {
  59643. this._checkUniform(name);
  59644. this._colors3Arrays[name] = value.reduce(function (arr, color) {
  59645. color.toArray(arr, arr.length);
  59646. return arr;
  59647. }, []);
  59648. return this;
  59649. };
  59650. ShaderMaterial.prototype.setColor4 = function (name, value) {
  59651. this._checkUniform(name);
  59652. this._colors4[name] = value;
  59653. return this;
  59654. };
  59655. ShaderMaterial.prototype.setVector2 = function (name, value) {
  59656. this._checkUniform(name);
  59657. this._vectors2[name] = value;
  59658. return this;
  59659. };
  59660. ShaderMaterial.prototype.setVector3 = function (name, value) {
  59661. this._checkUniform(name);
  59662. this._vectors3[name] = value;
  59663. return this;
  59664. };
  59665. ShaderMaterial.prototype.setVector4 = function (name, value) {
  59666. this._checkUniform(name);
  59667. this._vectors4[name] = value;
  59668. return this;
  59669. };
  59670. ShaderMaterial.prototype.setMatrix = function (name, value) {
  59671. this._checkUniform(name);
  59672. this._matrices[name] = value;
  59673. return this;
  59674. };
  59675. ShaderMaterial.prototype.setMatrix3x3 = function (name, value) {
  59676. this._checkUniform(name);
  59677. this._matrices3x3[name] = value;
  59678. return this;
  59679. };
  59680. ShaderMaterial.prototype.setMatrix2x2 = function (name, value) {
  59681. this._checkUniform(name);
  59682. this._matrices2x2[name] = value;
  59683. return this;
  59684. };
  59685. ShaderMaterial.prototype.setArray2 = function (name, value) {
  59686. this._checkUniform(name);
  59687. this._vectors2Arrays[name] = value;
  59688. return this;
  59689. };
  59690. ShaderMaterial.prototype.setArray3 = function (name, value) {
  59691. this._checkUniform(name);
  59692. this._vectors3Arrays[name] = value;
  59693. return this;
  59694. };
  59695. ShaderMaterial.prototype._checkCache = function (scene, mesh, useInstances) {
  59696. if (!mesh) {
  59697. return true;
  59698. }
  59699. if (this._effect && (this._effect.defines.indexOf("#define INSTANCES") !== -1) !== useInstances) {
  59700. return false;
  59701. }
  59702. return false;
  59703. };
  59704. ShaderMaterial.prototype.isReady = function (mesh, useInstances) {
  59705. var scene = this.getScene();
  59706. var engine = scene.getEngine();
  59707. if (!this.checkReadyOnEveryCall) {
  59708. if (this._renderId === scene.getRenderId()) {
  59709. if (this._checkCache(scene, mesh, useInstances)) {
  59710. return true;
  59711. }
  59712. }
  59713. }
  59714. // Instances
  59715. var defines = [];
  59716. var attribs = [];
  59717. var fallbacks = new BABYLON.EffectFallbacks();
  59718. if (useInstances) {
  59719. defines.push("#define INSTANCES");
  59720. }
  59721. for (var index = 0; index < this._options.defines.length; index++) {
  59722. defines.push(this._options.defines[index]);
  59723. }
  59724. for (var index = 0; index < this._options.attributes.length; index++) {
  59725. attribs.push(this._options.attributes[index]);
  59726. }
  59727. if (mesh && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.ColorKind)) {
  59728. attribs.push(BABYLON.VertexBuffer.ColorKind);
  59729. defines.push("#define VERTEXCOLOR");
  59730. }
  59731. // Bones
  59732. if (mesh && mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  59733. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  59734. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  59735. if (mesh.numBoneInfluencers > 4) {
  59736. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  59737. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  59738. }
  59739. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  59740. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  59741. fallbacks.addCPUSkinningFallback(0, mesh);
  59742. if (this._options.uniforms.indexOf("mBones") === -1) {
  59743. this._options.uniforms.push("mBones");
  59744. }
  59745. }
  59746. else {
  59747. defines.push("#define NUM_BONE_INFLUENCERS 0");
  59748. }
  59749. // Textures
  59750. for (var name in this._textures) {
  59751. if (!this._textures[name].isReady()) {
  59752. return false;
  59753. }
  59754. }
  59755. // Alpha test
  59756. if (mesh && this._shouldTurnAlphaTestOn(mesh)) {
  59757. defines.push("#define ALPHATEST");
  59758. }
  59759. var previousEffect = this._effect;
  59760. var join = defines.join("\n");
  59761. this._effect = engine.createEffect(this._shaderPath, {
  59762. attributes: attribs,
  59763. uniformsNames: this._options.uniforms,
  59764. uniformBuffersNames: this._options.uniformBuffers,
  59765. samplers: this._options.samplers,
  59766. defines: join,
  59767. fallbacks: fallbacks,
  59768. onCompiled: this.onCompiled,
  59769. onError: this.onError
  59770. }, engine);
  59771. if (!this._effect.isReady()) {
  59772. return false;
  59773. }
  59774. if (previousEffect !== this._effect) {
  59775. scene.resetCachedMaterial();
  59776. }
  59777. this._renderId = scene.getRenderId();
  59778. return true;
  59779. };
  59780. ShaderMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  59781. var scene = this.getScene();
  59782. if (!this._effect) {
  59783. return;
  59784. }
  59785. if (this._options.uniforms.indexOf("world") !== -1) {
  59786. this._effect.setMatrix("world", world);
  59787. }
  59788. if (this._options.uniforms.indexOf("worldView") !== -1) {
  59789. world.multiplyToRef(scene.getViewMatrix(), this._cachedWorldViewMatrix);
  59790. this._effect.setMatrix("worldView", this._cachedWorldViewMatrix);
  59791. }
  59792. if (this._options.uniforms.indexOf("worldViewProjection") !== -1) {
  59793. this._effect.setMatrix("worldViewProjection", world.multiply(scene.getTransformMatrix()));
  59794. }
  59795. };
  59796. ShaderMaterial.prototype.bind = function (world, mesh) {
  59797. // Std values
  59798. this.bindOnlyWorldMatrix(world);
  59799. if (this._effect && this.getScene().getCachedMaterial() !== this) {
  59800. if (this._options.uniforms.indexOf("view") !== -1) {
  59801. this._effect.setMatrix("view", this.getScene().getViewMatrix());
  59802. }
  59803. if (this._options.uniforms.indexOf("projection") !== -1) {
  59804. this._effect.setMatrix("projection", this.getScene().getProjectionMatrix());
  59805. }
  59806. if (this._options.uniforms.indexOf("viewProjection") !== -1) {
  59807. this._effect.setMatrix("viewProjection", this.getScene().getTransformMatrix());
  59808. }
  59809. // Bones
  59810. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._effect);
  59811. var name;
  59812. // Texture
  59813. for (name in this._textures) {
  59814. this._effect.setTexture(name, this._textures[name]);
  59815. }
  59816. // Texture arrays
  59817. for (name in this._textureArrays) {
  59818. this._effect.setTextureArray(name, this._textureArrays[name]);
  59819. }
  59820. // Int
  59821. for (name in this._ints) {
  59822. this._effect.setInt(name, this._ints[name]);
  59823. }
  59824. // Float
  59825. for (name in this._floats) {
  59826. this._effect.setFloat(name, this._floats[name]);
  59827. }
  59828. // Floats
  59829. for (name in this._floatsArrays) {
  59830. this._effect.setArray(name, this._floatsArrays[name]);
  59831. }
  59832. // Color3
  59833. for (name in this._colors3) {
  59834. this._effect.setColor3(name, this._colors3[name]);
  59835. }
  59836. for (name in this._colors3Arrays) {
  59837. this._effect.setArray3(name, this._colors3Arrays[name]);
  59838. }
  59839. // Color4
  59840. for (name in this._colors4) {
  59841. var color = this._colors4[name];
  59842. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  59843. }
  59844. // Vector2
  59845. for (name in this._vectors2) {
  59846. this._effect.setVector2(name, this._vectors2[name]);
  59847. }
  59848. // Vector3
  59849. for (name in this._vectors3) {
  59850. this._effect.setVector3(name, this._vectors3[name]);
  59851. }
  59852. // Vector4
  59853. for (name in this._vectors4) {
  59854. this._effect.setVector4(name, this._vectors4[name]);
  59855. }
  59856. // Matrix
  59857. for (name in this._matrices) {
  59858. this._effect.setMatrix(name, this._matrices[name]);
  59859. }
  59860. // Matrix 3x3
  59861. for (name in this._matrices3x3) {
  59862. this._effect.setMatrix3x3(name, this._matrices3x3[name]);
  59863. }
  59864. // Matrix 2x2
  59865. for (name in this._matrices2x2) {
  59866. this._effect.setMatrix2x2(name, this._matrices2x2[name]);
  59867. }
  59868. // Vector2Array
  59869. for (name in this._vectors2Arrays) {
  59870. this._effect.setArray2(name, this._vectors2Arrays[name]);
  59871. }
  59872. // Vector3Array
  59873. for (name in this._vectors3Arrays) {
  59874. this._effect.setArray3(name, this._vectors3Arrays[name]);
  59875. }
  59876. }
  59877. this._afterBind(mesh);
  59878. };
  59879. ShaderMaterial.prototype.getActiveTextures = function () {
  59880. var activeTextures = _super.prototype.getActiveTextures.call(this);
  59881. for (var name in this._textures) {
  59882. activeTextures.push(this._textures[name]);
  59883. }
  59884. for (var name in this._textureArrays) {
  59885. var array = this._textureArrays[name];
  59886. for (var index = 0; index < array.length; index++) {
  59887. activeTextures.push(array[index]);
  59888. }
  59889. }
  59890. return activeTextures;
  59891. };
  59892. ShaderMaterial.prototype.hasTexture = function (texture) {
  59893. if (_super.prototype.hasTexture.call(this, texture)) {
  59894. return true;
  59895. }
  59896. for (var name in this._textures) {
  59897. if (this._textures[name] === texture) {
  59898. return true;
  59899. }
  59900. }
  59901. for (var name in this._textureArrays) {
  59902. var array = this._textureArrays[name];
  59903. for (var index = 0; index < array.length; index++) {
  59904. if (array[index] === texture) {
  59905. return true;
  59906. }
  59907. }
  59908. }
  59909. return false;
  59910. };
  59911. ShaderMaterial.prototype.clone = function (name) {
  59912. var newShaderMaterial = new ShaderMaterial(name, this.getScene(), this._shaderPath, this._options);
  59913. return newShaderMaterial;
  59914. };
  59915. ShaderMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  59916. if (forceDisposeTextures) {
  59917. var name;
  59918. for (name in this._textures) {
  59919. this._textures[name].dispose();
  59920. }
  59921. for (name in this._textureArrays) {
  59922. var array = this._textureArrays[name];
  59923. for (var index = 0; index < array.length; index++) {
  59924. array[index].dispose();
  59925. }
  59926. }
  59927. }
  59928. this._textures = {};
  59929. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  59930. };
  59931. ShaderMaterial.prototype.serialize = function () {
  59932. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  59933. serializationObject.customType = "BABYLON.ShaderMaterial";
  59934. serializationObject.options = this._options;
  59935. serializationObject.shaderPath = this._shaderPath;
  59936. var name;
  59937. // Texture
  59938. serializationObject.textures = {};
  59939. for (name in this._textures) {
  59940. serializationObject.textures[name] = this._textures[name].serialize();
  59941. }
  59942. // Texture arrays
  59943. serializationObject.textureArrays = {};
  59944. for (name in this._textureArrays) {
  59945. serializationObject.textureArrays[name] = [];
  59946. var array = this._textureArrays[name];
  59947. for (var index = 0; index < array.length; index++) {
  59948. serializationObject.textureArrays[name].push(array[index].serialize());
  59949. }
  59950. }
  59951. // Float
  59952. serializationObject.floats = {};
  59953. for (name in this._floats) {
  59954. serializationObject.floats[name] = this._floats[name];
  59955. }
  59956. // Float s
  59957. serializationObject.FloatArrays = {};
  59958. for (name in this._floatsArrays) {
  59959. serializationObject.FloatArrays[name] = this._floatsArrays[name];
  59960. }
  59961. // Color3
  59962. serializationObject.colors3 = {};
  59963. for (name in this._colors3) {
  59964. serializationObject.colors3[name] = this._colors3[name].asArray();
  59965. }
  59966. // Color3 array
  59967. serializationObject.colors3Arrays = {};
  59968. for (name in this._colors3Arrays) {
  59969. serializationObject.colors3Arrays[name] = this._colors3Arrays[name];
  59970. }
  59971. // Color4
  59972. serializationObject.colors4 = {};
  59973. for (name in this._colors4) {
  59974. serializationObject.colors4[name] = this._colors4[name].asArray();
  59975. }
  59976. // Vector2
  59977. serializationObject.vectors2 = {};
  59978. for (name in this._vectors2) {
  59979. serializationObject.vectors2[name] = this._vectors2[name].asArray();
  59980. }
  59981. // Vector3
  59982. serializationObject.vectors3 = {};
  59983. for (name in this._vectors3) {
  59984. serializationObject.vectors3[name] = this._vectors3[name].asArray();
  59985. }
  59986. // Vector4
  59987. serializationObject.vectors4 = {};
  59988. for (name in this._vectors4) {
  59989. serializationObject.vectors4[name] = this._vectors4[name].asArray();
  59990. }
  59991. // Matrix
  59992. serializationObject.matrices = {};
  59993. for (name in this._matrices) {
  59994. serializationObject.matrices[name] = this._matrices[name].asArray();
  59995. }
  59996. // Matrix 3x3
  59997. serializationObject.matrices3x3 = {};
  59998. for (name in this._matrices3x3) {
  59999. serializationObject.matrices3x3[name] = this._matrices3x3[name];
  60000. }
  60001. // Matrix 2x2
  60002. serializationObject.matrices2x2 = {};
  60003. for (name in this._matrices2x2) {
  60004. serializationObject.matrices2x2[name] = this._matrices2x2[name];
  60005. }
  60006. // Vector2Array
  60007. serializationObject.vectors2Arrays = {};
  60008. for (name in this._vectors2Arrays) {
  60009. serializationObject.vectors2Arrays[name] = this._vectors2Arrays[name];
  60010. }
  60011. // Vector3Array
  60012. serializationObject.vectors3Arrays = {};
  60013. for (name in this._vectors3Arrays) {
  60014. serializationObject.vectors3Arrays[name] = this._vectors3Arrays[name];
  60015. }
  60016. return serializationObject;
  60017. };
  60018. ShaderMaterial.Parse = function (source, scene, rootUrl) {
  60019. var material = BABYLON.SerializationHelper.Parse(function () { return new ShaderMaterial(source.name, scene, source.shaderPath, source.options); }, source, scene, rootUrl);
  60020. var name;
  60021. // Texture
  60022. for (name in source.textures) {
  60023. material.setTexture(name, BABYLON.Texture.Parse(source.textures[name], scene, rootUrl));
  60024. }
  60025. // Texture arrays
  60026. for (name in source.textureArrays) {
  60027. var array = source.textureArrays[name];
  60028. var textureArray = new Array();
  60029. for (var index = 0; index < array.length; index++) {
  60030. textureArray.push(BABYLON.Texture.Parse(array[index], scene, rootUrl));
  60031. }
  60032. material.setTextureArray(name, textureArray);
  60033. }
  60034. // Float
  60035. for (name in source.floats) {
  60036. material.setFloat(name, source.floats[name]);
  60037. }
  60038. // Float s
  60039. for (name in source.floatsArrays) {
  60040. material.setFloats(name, source.floatsArrays[name]);
  60041. }
  60042. // Color3
  60043. for (name in source.colors3) {
  60044. material.setColor3(name, BABYLON.Color3.FromArray(source.colors3[name]));
  60045. }
  60046. // Color3 arrays
  60047. for (name in source.colors3Arrays) {
  60048. var colors = source.colors3Arrays[name].reduce(function (arr, num, i) {
  60049. if (i % 3 === 0) {
  60050. arr.push([num]);
  60051. }
  60052. else {
  60053. arr[arr.length - 1].push(num);
  60054. }
  60055. return arr;
  60056. }, []).map(function (color) { return BABYLON.Color3.FromArray(color); });
  60057. material.setColor3Array(name, colors);
  60058. }
  60059. // Color4
  60060. for (name in source.colors4) {
  60061. material.setColor4(name, BABYLON.Color4.FromArray(source.colors4[name]));
  60062. }
  60063. // Vector2
  60064. for (name in source.vectors2) {
  60065. material.setVector2(name, BABYLON.Vector2.FromArray(source.vectors2[name]));
  60066. }
  60067. // Vector3
  60068. for (name in source.vectors3) {
  60069. material.setVector3(name, BABYLON.Vector3.FromArray(source.vectors3[name]));
  60070. }
  60071. // Vector4
  60072. for (name in source.vectors4) {
  60073. material.setVector4(name, BABYLON.Vector4.FromArray(source.vectors4[name]));
  60074. }
  60075. // Matrix
  60076. for (name in source.matrices) {
  60077. material.setMatrix(name, BABYLON.Matrix.FromArray(source.matrices[name]));
  60078. }
  60079. // Matrix 3x3
  60080. for (name in source.matrices3x3) {
  60081. material.setMatrix3x3(name, source.matrices3x3[name]);
  60082. }
  60083. // Matrix 2x2
  60084. for (name in source.matrices2x2) {
  60085. material.setMatrix2x2(name, source.matrices2x2[name]);
  60086. }
  60087. // Vector2Array
  60088. for (name in source.vectors2Arrays) {
  60089. material.setArray2(name, source.vectors2Arrays[name]);
  60090. }
  60091. // Vector3Array
  60092. for (name in source.vectors3Arrays) {
  60093. material.setArray3(name, source.vectors3Arrays[name]);
  60094. }
  60095. return material;
  60096. };
  60097. return ShaderMaterial;
  60098. }(BABYLON.Material));
  60099. BABYLON.ShaderMaterial = ShaderMaterial;
  60100. })(BABYLON || (BABYLON = {}));
  60101. //# sourceMappingURL=babylon.shaderMaterial.js.map
  60102. var BABYLON;
  60103. (function (BABYLON) {
  60104. var GroundMesh = /** @class */ (function (_super) {
  60105. __extends(GroundMesh, _super);
  60106. function GroundMesh(name, scene) {
  60107. var _this = _super.call(this, name, scene) || this;
  60108. _this.generateOctree = false;
  60109. return _this;
  60110. }
  60111. GroundMesh.prototype.getClassName = function () {
  60112. return "GroundMesh";
  60113. };
  60114. Object.defineProperty(GroundMesh.prototype, "subdivisions", {
  60115. get: function () {
  60116. return Math.min(this._subdivisionsX, this._subdivisionsY);
  60117. },
  60118. enumerable: true,
  60119. configurable: true
  60120. });
  60121. Object.defineProperty(GroundMesh.prototype, "subdivisionsX", {
  60122. get: function () {
  60123. return this._subdivisionsX;
  60124. },
  60125. enumerable: true,
  60126. configurable: true
  60127. });
  60128. Object.defineProperty(GroundMesh.prototype, "subdivisionsY", {
  60129. get: function () {
  60130. return this._subdivisionsY;
  60131. },
  60132. enumerable: true,
  60133. configurable: true
  60134. });
  60135. GroundMesh.prototype.optimize = function (chunksCount, octreeBlocksSize) {
  60136. if (octreeBlocksSize === void 0) { octreeBlocksSize = 32; }
  60137. this._subdivisionsX = chunksCount;
  60138. this._subdivisionsY = chunksCount;
  60139. this.subdivide(chunksCount);
  60140. this.createOrUpdateSubmeshesOctree(octreeBlocksSize);
  60141. };
  60142. /**
  60143. * Returns a height (y) value in the Worl system :
  60144. * the ground altitude at the coordinates (x, z) expressed in the World system.
  60145. * Returns the ground y position if (x, z) are outside the ground surface.
  60146. */
  60147. GroundMesh.prototype.getHeightAtCoordinates = function (x, z) {
  60148. var world = this.getWorldMatrix();
  60149. var invMat = BABYLON.Tmp.Matrix[5];
  60150. world.invertToRef(invMat);
  60151. var tmpVect = BABYLON.Tmp.Vector3[8];
  60152. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, invMat, tmpVect); // transform x,z in the mesh local space
  60153. x = tmpVect.x;
  60154. z = tmpVect.z;
  60155. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60156. return this.position.y;
  60157. }
  60158. if (!this._heightQuads || this._heightQuads.length == 0) {
  60159. this._initHeightQuads();
  60160. this._computeHeightQuads();
  60161. }
  60162. var facet = this._getFacetAt(x, z);
  60163. var y = -(facet.x * x + facet.z * z + facet.w) / facet.y;
  60164. // return y in the World system
  60165. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(0.0, y, 0.0, world, tmpVect);
  60166. return tmpVect.y;
  60167. };
  60168. /**
  60169. * Returns a normalized vector (Vector3) orthogonal to the ground
  60170. * at the ground coordinates (x, z) expressed in the World system.
  60171. * Returns Vector3(0.0, 1.0, 0.0) if (x, z) are outside the ground surface.
  60172. */
  60173. GroundMesh.prototype.getNormalAtCoordinates = function (x, z) {
  60174. var normal = new BABYLON.Vector3(0.0, 1.0, 0.0);
  60175. this.getNormalAtCoordinatesToRef(x, z, normal);
  60176. return normal;
  60177. };
  60178. /**
  60179. * Updates the Vector3 passed a reference with a normalized vector orthogonal to the ground
  60180. * at the ground coordinates (x, z) expressed in the World system.
  60181. * Doesn't uptade the reference Vector3 if (x, z) are outside the ground surface.
  60182. * Returns the GroundMesh.
  60183. */
  60184. GroundMesh.prototype.getNormalAtCoordinatesToRef = function (x, z, ref) {
  60185. var world = this.getWorldMatrix();
  60186. var tmpMat = BABYLON.Tmp.Matrix[5];
  60187. world.invertToRef(tmpMat);
  60188. var tmpVect = BABYLON.Tmp.Vector3[8];
  60189. BABYLON.Vector3.TransformCoordinatesFromFloatsToRef(x, 0.0, z, tmpMat, tmpVect); // transform x,z in the mesh local space
  60190. x = tmpVect.x;
  60191. z = tmpVect.z;
  60192. if (x < this._minX || x > this._maxX || z < this._minZ || z > this._maxZ) {
  60193. return this;
  60194. }
  60195. if (!this._heightQuads || this._heightQuads.length == 0) {
  60196. this._initHeightQuads();
  60197. this._computeHeightQuads();
  60198. }
  60199. var facet = this._getFacetAt(x, z);
  60200. BABYLON.Vector3.TransformNormalFromFloatsToRef(facet.x, facet.y, facet.z, world, ref);
  60201. return this;
  60202. };
  60203. /**
  60204. * Force the heights to be recomputed for getHeightAtCoordinates() or getNormalAtCoordinates()
  60205. * if the ground has been updated.
  60206. * This can be used in the render loop.
  60207. * Returns the GroundMesh.
  60208. */
  60209. GroundMesh.prototype.updateCoordinateHeights = function () {
  60210. if (!this._heightQuads || this._heightQuads.length == 0) {
  60211. this._initHeightQuads();
  60212. }
  60213. this._computeHeightQuads();
  60214. return this;
  60215. };
  60216. // Returns the element "facet" from the heightQuads array relative to (x, z) local coordinates
  60217. GroundMesh.prototype._getFacetAt = function (x, z) {
  60218. // retrieve col and row from x, z coordinates in the ground local system
  60219. var col = Math.floor((x + this._maxX) * this._subdivisionsX / this._width);
  60220. var row = Math.floor(-(z + this._maxZ) * this._subdivisionsY / this._height + this._subdivisionsY);
  60221. var quad = this._heightQuads[row * this._subdivisionsX + col];
  60222. var facet;
  60223. if (z < quad.slope.x * x + quad.slope.y) {
  60224. facet = quad.facet1;
  60225. }
  60226. else {
  60227. facet = quad.facet2;
  60228. }
  60229. return facet;
  60230. };
  60231. // Creates and populates the heightMap array with "facet" elements :
  60232. // a quad is two triangular facets separated by a slope, so a "facet" element is 1 slope + 2 facets
  60233. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60234. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60235. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60236. // Returns the GroundMesh.
  60237. GroundMesh.prototype._initHeightQuads = function () {
  60238. var subdivisionsX = this._subdivisionsX;
  60239. var subdivisionsY = this._subdivisionsY;
  60240. this._heightQuads = new Array();
  60241. for (var row = 0; row < subdivisionsY; row++) {
  60242. for (var col = 0; col < subdivisionsX; col++) {
  60243. 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) };
  60244. this._heightQuads[row * subdivisionsX + col] = quad;
  60245. }
  60246. }
  60247. return this;
  60248. };
  60249. // Compute each quad element values and update the the heightMap array :
  60250. // slope : Vector2(c, h) = 2D diagonal line equation setting appart two triangular facets in a quad : z = cx + h
  60251. // facet1 : Vector4(a, b, c, d) = first facet 3D plane equation : ax + by + cz + d = 0
  60252. // facet2 : Vector4(a, b, c, d) = second facet 3D plane equation : ax + by + cz + d = 0
  60253. // Returns the GroundMesh.
  60254. GroundMesh.prototype._computeHeightQuads = function () {
  60255. var positions = this.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60256. if (!positions) {
  60257. return this;
  60258. }
  60259. var v1 = BABYLON.Tmp.Vector3[3];
  60260. var v2 = BABYLON.Tmp.Vector3[2];
  60261. var v3 = BABYLON.Tmp.Vector3[1];
  60262. var v4 = BABYLON.Tmp.Vector3[0];
  60263. var v1v2 = BABYLON.Tmp.Vector3[4];
  60264. var v1v3 = BABYLON.Tmp.Vector3[5];
  60265. var v1v4 = BABYLON.Tmp.Vector3[6];
  60266. var norm1 = BABYLON.Tmp.Vector3[7];
  60267. var norm2 = BABYLON.Tmp.Vector3[8];
  60268. var i = 0;
  60269. var j = 0;
  60270. var k = 0;
  60271. var cd = 0; // 2D slope coefficient : z = cd * x + h
  60272. var h = 0;
  60273. var d1 = 0; // facet plane equation : ax + by + cz + d = 0
  60274. var d2 = 0;
  60275. var subdivisionsX = this._subdivisionsX;
  60276. var subdivisionsY = this._subdivisionsY;
  60277. for (var row = 0; row < subdivisionsY; row++) {
  60278. for (var col = 0; col < subdivisionsX; col++) {
  60279. i = col * 3;
  60280. j = row * (subdivisionsX + 1) * 3;
  60281. k = (row + 1) * (subdivisionsX + 1) * 3;
  60282. v1.x = positions[j + i];
  60283. v1.y = positions[j + i + 1];
  60284. v1.z = positions[j + i + 2];
  60285. v2.x = positions[j + i + 3];
  60286. v2.y = positions[j + i + 4];
  60287. v2.z = positions[j + i + 5];
  60288. v3.x = positions[k + i];
  60289. v3.y = positions[k + i + 1];
  60290. v3.z = positions[k + i + 2];
  60291. v4.x = positions[k + i + 3];
  60292. v4.y = positions[k + i + 4];
  60293. v4.z = positions[k + i + 5];
  60294. // 2D slope V1V4
  60295. cd = (v4.z - v1.z) / (v4.x - v1.x);
  60296. h = v1.z - cd * v1.x; // v1 belongs to the slope
  60297. // facet equations :
  60298. // we compute each facet normal vector
  60299. // the equation of the facet plane is : norm.x * x + norm.y * y + norm.z * z + d = 0
  60300. // we compute the value d by applying the equation to v1 which belongs to the plane
  60301. // then we store the facet equation in a Vector4
  60302. v2.subtractToRef(v1, v1v2);
  60303. v3.subtractToRef(v1, v1v3);
  60304. v4.subtractToRef(v1, v1v4);
  60305. BABYLON.Vector3.CrossToRef(v1v4, v1v3, norm1); // caution : CrossToRef uses the Tmp class
  60306. BABYLON.Vector3.CrossToRef(v1v2, v1v4, norm2);
  60307. norm1.normalize();
  60308. norm2.normalize();
  60309. d1 = -(norm1.x * v1.x + norm1.y * v1.y + norm1.z * v1.z);
  60310. d2 = -(norm2.x * v2.x + norm2.y * v2.y + norm2.z * v2.z);
  60311. var quad = this._heightQuads[row * subdivisionsX + col];
  60312. quad.slope.copyFromFloats(cd, h);
  60313. quad.facet1.copyFromFloats(norm1.x, norm1.y, norm1.z, d1);
  60314. quad.facet2.copyFromFloats(norm2.x, norm2.y, norm2.z, d2);
  60315. }
  60316. }
  60317. return this;
  60318. };
  60319. GroundMesh.prototype.serialize = function (serializationObject) {
  60320. _super.prototype.serialize.call(this, serializationObject);
  60321. serializationObject.subdivisionsX = this._subdivisionsX;
  60322. serializationObject.subdivisionsY = this._subdivisionsY;
  60323. serializationObject.minX = this._minX;
  60324. serializationObject.maxX = this._maxX;
  60325. serializationObject.minZ = this._minZ;
  60326. serializationObject.maxZ = this._maxZ;
  60327. serializationObject.width = this._width;
  60328. serializationObject.height = this._height;
  60329. };
  60330. GroundMesh.Parse = function (parsedMesh, scene) {
  60331. var result = new GroundMesh(parsedMesh.name, scene);
  60332. result._subdivisionsX = parsedMesh.subdivisionsX || 1;
  60333. result._subdivisionsY = parsedMesh.subdivisionsY || 1;
  60334. result._minX = parsedMesh.minX;
  60335. result._maxX = parsedMesh.maxX;
  60336. result._minZ = parsedMesh.minZ;
  60337. result._maxZ = parsedMesh.maxZ;
  60338. result._width = parsedMesh.width;
  60339. result._height = parsedMesh.height;
  60340. return result;
  60341. };
  60342. return GroundMesh;
  60343. }(BABYLON.Mesh));
  60344. BABYLON.GroundMesh = GroundMesh;
  60345. })(BABYLON || (BABYLON = {}));
  60346. //# sourceMappingURL=babylon.groundMesh.js.map
  60347. var BABYLON;
  60348. (function (BABYLON) {
  60349. /**
  60350. * Creates an instance based on a source mesh.
  60351. */
  60352. var InstancedMesh = /** @class */ (function (_super) {
  60353. __extends(InstancedMesh, _super);
  60354. function InstancedMesh(name, source) {
  60355. var _this = _super.call(this, name, source.getScene()) || this;
  60356. source.instances.push(_this);
  60357. _this._sourceMesh = source;
  60358. _this.position.copyFrom(source.position);
  60359. _this.rotation.copyFrom(source.rotation);
  60360. _this.scaling.copyFrom(source.scaling);
  60361. if (source.rotationQuaternion) {
  60362. _this.rotationQuaternion = source.rotationQuaternion.clone();
  60363. }
  60364. _this.infiniteDistance = source.infiniteDistance;
  60365. _this.setPivotMatrix(source.getPivotMatrix());
  60366. _this.refreshBoundingInfo();
  60367. _this._syncSubMeshes();
  60368. return _this;
  60369. }
  60370. /**
  60371. * Returns the string "InstancedMesh".
  60372. */
  60373. InstancedMesh.prototype.getClassName = function () {
  60374. return "InstancedMesh";
  60375. };
  60376. Object.defineProperty(InstancedMesh.prototype, "receiveShadows", {
  60377. // Methods
  60378. get: function () {
  60379. return this._sourceMesh.receiveShadows;
  60380. },
  60381. enumerable: true,
  60382. configurable: true
  60383. });
  60384. Object.defineProperty(InstancedMesh.prototype, "material", {
  60385. get: function () {
  60386. return this._sourceMesh.material;
  60387. },
  60388. enumerable: true,
  60389. configurable: true
  60390. });
  60391. Object.defineProperty(InstancedMesh.prototype, "visibility", {
  60392. get: function () {
  60393. return this._sourceMesh.visibility;
  60394. },
  60395. enumerable: true,
  60396. configurable: true
  60397. });
  60398. Object.defineProperty(InstancedMesh.prototype, "skeleton", {
  60399. get: function () {
  60400. return this._sourceMesh.skeleton;
  60401. },
  60402. enumerable: true,
  60403. configurable: true
  60404. });
  60405. Object.defineProperty(InstancedMesh.prototype, "renderingGroupId", {
  60406. get: function () {
  60407. return this._sourceMesh.renderingGroupId;
  60408. },
  60409. set: function (value) {
  60410. if (!this._sourceMesh || value === this._sourceMesh.renderingGroupId) {
  60411. return;
  60412. }
  60413. //no-op with warning
  60414. BABYLON.Tools.Warn("Note - setting renderingGroupId of an instanced mesh has no effect on the scene");
  60415. },
  60416. enumerable: true,
  60417. configurable: true
  60418. });
  60419. /**
  60420. * Returns the total number of vertices (integer).
  60421. */
  60422. InstancedMesh.prototype.getTotalVertices = function () {
  60423. return this._sourceMesh.getTotalVertices();
  60424. };
  60425. Object.defineProperty(InstancedMesh.prototype, "sourceMesh", {
  60426. get: function () {
  60427. return this._sourceMesh;
  60428. },
  60429. enumerable: true,
  60430. configurable: true
  60431. });
  60432. /**
  60433. * Is this node ready to be used/rendered
  60434. * @param completeCheck defines if a complete check (including materials and lights) has to be done (false by default)
  60435. * @return {boolean} is it ready
  60436. */
  60437. InstancedMesh.prototype.isReady = function (completeCheck) {
  60438. if (completeCheck === void 0) { completeCheck = false; }
  60439. return this._sourceMesh.isReady(completeCheck, true);
  60440. };
  60441. /**
  60442. * Returns a float array or a Float32Array of the requested kind of data : positons, normals, uvs, etc.
  60443. */
  60444. InstancedMesh.prototype.getVerticesData = function (kind, copyWhenShared) {
  60445. return this._sourceMesh.getVerticesData(kind, copyWhenShared);
  60446. };
  60447. /**
  60448. * Sets the vertex data of the mesh geometry for the requested `kind`.
  60449. * If the mesh has no geometry, a new Geometry object is set to the mesh and then passed this vertex data.
  60450. * The `data` are either a numeric array either a Float32Array.
  60451. * The parameter `updatable` is passed as is to the underlying Geometry object constructor (if initianilly none) or updater.
  60452. * 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).
  60453. * Note that a new underlying VertexBuffer object is created each call.
  60454. * If the `kind` is the `PositionKind`, the mesh BoundingInfo is renewed, so the bounding box and sphere, and the mesh World Matrix is recomputed.
  60455. *
  60456. * Possible `kind` values :
  60457. * - BABYLON.VertexBuffer.PositionKind
  60458. * - BABYLON.VertexBuffer.UVKind
  60459. * - BABYLON.VertexBuffer.UV2Kind
  60460. * - BABYLON.VertexBuffer.UV3Kind
  60461. * - BABYLON.VertexBuffer.UV4Kind
  60462. * - BABYLON.VertexBuffer.UV5Kind
  60463. * - BABYLON.VertexBuffer.UV6Kind
  60464. * - BABYLON.VertexBuffer.ColorKind
  60465. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60466. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60467. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60468. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60469. *
  60470. * Returns the Mesh.
  60471. */
  60472. InstancedMesh.prototype.setVerticesData = function (kind, data, updatable, stride) {
  60473. if (this.sourceMesh) {
  60474. this.sourceMesh.setVerticesData(kind, data, updatable, stride);
  60475. }
  60476. return this.sourceMesh;
  60477. };
  60478. /**
  60479. * Updates the existing vertex data of the mesh geometry for the requested `kind`.
  60480. * If the mesh has no geometry, it is simply returned as it is.
  60481. * The `data` are either a numeric array either a Float32Array.
  60482. * No new underlying VertexBuffer object is created.
  60483. * 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.
  60484. * If the parameter `makeItUnique` is true, a new global geometry is created from this positions and is set to the mesh.
  60485. *
  60486. * Possible `kind` values :
  60487. * - BABYLON.VertexBuffer.PositionKind
  60488. * - BABYLON.VertexBuffer.UVKind
  60489. * - BABYLON.VertexBuffer.UV2Kind
  60490. * - BABYLON.VertexBuffer.UV3Kind
  60491. * - BABYLON.VertexBuffer.UV4Kind
  60492. * - BABYLON.VertexBuffer.UV5Kind
  60493. * - BABYLON.VertexBuffer.UV6Kind
  60494. * - BABYLON.VertexBuffer.ColorKind
  60495. * - BABYLON.VertexBuffer.MatricesIndicesKind
  60496. * - BABYLON.VertexBuffer.MatricesIndicesExtraKind
  60497. * - BABYLON.VertexBuffer.MatricesWeightsKind
  60498. * - BABYLON.VertexBuffer.MatricesWeightsExtraKind
  60499. *
  60500. * Returns the Mesh.
  60501. */
  60502. InstancedMesh.prototype.updateVerticesData = function (kind, data, updateExtends, makeItUnique) {
  60503. if (this.sourceMesh) {
  60504. this.sourceMesh.updateVerticesData(kind, data, updateExtends, makeItUnique);
  60505. }
  60506. return this.sourceMesh;
  60507. };
  60508. /**
  60509. * Sets the mesh indices.
  60510. * Expects an array populated with integers or a typed array (Int32Array, Uint32Array, Uint16Array).
  60511. * If the mesh has no geometry, a new Geometry object is created and set to the mesh.
  60512. * This method creates a new index buffer each call.
  60513. * Returns the Mesh.
  60514. */
  60515. InstancedMesh.prototype.setIndices = function (indices, totalVertices) {
  60516. if (totalVertices === void 0) { totalVertices = null; }
  60517. if (this.sourceMesh) {
  60518. this.sourceMesh.setIndices(indices, totalVertices);
  60519. }
  60520. return this.sourceMesh;
  60521. };
  60522. /**
  60523. * Boolean : True if the mesh owns the requested kind of data.
  60524. */
  60525. InstancedMesh.prototype.isVerticesDataPresent = function (kind) {
  60526. return this._sourceMesh.isVerticesDataPresent(kind);
  60527. };
  60528. /**
  60529. * Returns an array of indices (IndicesArray).
  60530. */
  60531. InstancedMesh.prototype.getIndices = function () {
  60532. return this._sourceMesh.getIndices();
  60533. };
  60534. Object.defineProperty(InstancedMesh.prototype, "_positions", {
  60535. get: function () {
  60536. return this._sourceMesh._positions;
  60537. },
  60538. enumerable: true,
  60539. configurable: true
  60540. });
  60541. /**
  60542. * Sets a new updated BoundingInfo to the mesh.
  60543. * Returns the mesh.
  60544. */
  60545. InstancedMesh.prototype.refreshBoundingInfo = function () {
  60546. var meshBB = this._sourceMesh.getBoundingInfo();
  60547. this._boundingInfo = new BABYLON.BoundingInfo(meshBB.minimum.clone(), meshBB.maximum.clone());
  60548. this._updateBoundingInfo();
  60549. return this;
  60550. };
  60551. InstancedMesh.prototype._preActivate = function () {
  60552. if (this._currentLOD) {
  60553. this._currentLOD._preActivate();
  60554. }
  60555. return this;
  60556. };
  60557. InstancedMesh.prototype._activate = function (renderId) {
  60558. if (this._currentLOD) {
  60559. this._currentLOD._registerInstanceForRenderId(this, renderId);
  60560. }
  60561. return this;
  60562. };
  60563. /**
  60564. * Returns the current associated LOD AbstractMesh.
  60565. */
  60566. InstancedMesh.prototype.getLOD = function (camera) {
  60567. if (!camera) {
  60568. return this;
  60569. }
  60570. var boundingInfo = this.getBoundingInfo();
  60571. this._currentLOD = this.sourceMesh.getLOD(camera, boundingInfo.boundingSphere);
  60572. if (this._currentLOD === this.sourceMesh) {
  60573. return this;
  60574. }
  60575. return this._currentLOD;
  60576. };
  60577. InstancedMesh.prototype._syncSubMeshes = function () {
  60578. this.releaseSubMeshes();
  60579. if (this._sourceMesh.subMeshes) {
  60580. for (var index = 0; index < this._sourceMesh.subMeshes.length; index++) {
  60581. this._sourceMesh.subMeshes[index].clone(this, this._sourceMesh);
  60582. }
  60583. }
  60584. return this;
  60585. };
  60586. InstancedMesh.prototype._generatePointsArray = function () {
  60587. return this._sourceMesh._generatePointsArray();
  60588. };
  60589. /**
  60590. * Creates a new InstancedMesh from the current mesh.
  60591. * - name (string) : the cloned mesh name
  60592. * - newParent (optional Node) : the optional Node to parent the clone to.
  60593. * - doNotCloneChildren (optional boolean, default `false`) : if `true` the model children aren't cloned.
  60594. *
  60595. * Returns the clone.
  60596. */
  60597. InstancedMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60598. var result = this._sourceMesh.createInstance(name);
  60599. // Deep copy
  60600. BABYLON.Tools.DeepCopy(this, result, ["name", "subMeshes", "uniqueId"], []);
  60601. // Bounding info
  60602. this.refreshBoundingInfo();
  60603. // Parent
  60604. if (newParent) {
  60605. result.parent = newParent;
  60606. }
  60607. if (!doNotCloneChildren) {
  60608. // Children
  60609. for (var index = 0; index < this.getScene().meshes.length; index++) {
  60610. var mesh = this.getScene().meshes[index];
  60611. if (mesh.parent === this) {
  60612. mesh.clone(mesh.name, result);
  60613. }
  60614. }
  60615. }
  60616. result.computeWorldMatrix(true);
  60617. return result;
  60618. };
  60619. /**
  60620. * Disposes the InstancedMesh.
  60621. * Returns nothing.
  60622. */
  60623. InstancedMesh.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  60624. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  60625. // Remove from mesh
  60626. var index = this._sourceMesh.instances.indexOf(this);
  60627. this._sourceMesh.instances.splice(index, 1);
  60628. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  60629. };
  60630. return InstancedMesh;
  60631. }(BABYLON.AbstractMesh));
  60632. BABYLON.InstancedMesh = InstancedMesh;
  60633. })(BABYLON || (BABYLON = {}));
  60634. //# sourceMappingURL=babylon.instancedMesh.js.map
  60635. var BABYLON;
  60636. (function (BABYLON) {
  60637. var LinesMesh = /** @class */ (function (_super) {
  60638. __extends(LinesMesh, _super);
  60639. function LinesMesh(name, scene, parent, source, doNotCloneChildren, useVertexColor, useVertexAlpha) {
  60640. if (scene === void 0) { scene = null; }
  60641. if (parent === void 0) { parent = null; }
  60642. var _this = _super.call(this, name, scene, parent, source, doNotCloneChildren) || this;
  60643. _this.useVertexColor = useVertexColor;
  60644. _this.useVertexAlpha = useVertexAlpha;
  60645. _this.color = new BABYLON.Color3(1, 1, 1);
  60646. _this.alpha = 1;
  60647. if (source) {
  60648. _this.color = source.color.clone();
  60649. _this.alpha = source.alpha;
  60650. _this.useVertexColor = source.useVertexColor;
  60651. _this.useVertexAlpha = source.useVertexAlpha;
  60652. }
  60653. _this._intersectionThreshold = 0.1;
  60654. var defines = [];
  60655. var options = {
  60656. attributes: [BABYLON.VertexBuffer.PositionKind],
  60657. uniforms: ["world", "viewProjection"],
  60658. needAlphaBlending: true,
  60659. defines: defines
  60660. };
  60661. if (useVertexAlpha === false) {
  60662. options.needAlphaBlending = false;
  60663. }
  60664. if (!useVertexColor) {
  60665. options.uniforms.push("color");
  60666. }
  60667. else {
  60668. options.defines.push("#define VERTEXCOLOR");
  60669. options.attributes.push(BABYLON.VertexBuffer.ColorKind);
  60670. }
  60671. _this._colorShader = new BABYLON.ShaderMaterial("colorShader", _this.getScene(), "color", options);
  60672. return _this;
  60673. }
  60674. Object.defineProperty(LinesMesh.prototype, "intersectionThreshold", {
  60675. /**
  60676. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60677. * This margin is expressed in world space coordinates, so its value may vary.
  60678. * Default value is 0.1
  60679. * @returns the intersection Threshold value.
  60680. */
  60681. get: function () {
  60682. return this._intersectionThreshold;
  60683. },
  60684. /**
  60685. * The intersection Threshold is the margin applied when intersection a segment of the LinesMesh with a Ray.
  60686. * This margin is expressed in world space coordinates, so its value may vary.
  60687. * @param value the new threshold to apply
  60688. */
  60689. set: function (value) {
  60690. if (this._intersectionThreshold === value) {
  60691. return;
  60692. }
  60693. this._intersectionThreshold = value;
  60694. if (this.geometry) {
  60695. this.geometry.boundingBias = new BABYLON.Vector2(0, value);
  60696. }
  60697. },
  60698. enumerable: true,
  60699. configurable: true
  60700. });
  60701. /**
  60702. * Returns the string "LineMesh"
  60703. */
  60704. LinesMesh.prototype.getClassName = function () {
  60705. return "LinesMesh";
  60706. };
  60707. Object.defineProperty(LinesMesh.prototype, "material", {
  60708. get: function () {
  60709. return this._colorShader;
  60710. },
  60711. set: function (value) {
  60712. // Do nothing
  60713. },
  60714. enumerable: true,
  60715. configurable: true
  60716. });
  60717. Object.defineProperty(LinesMesh.prototype, "checkCollisions", {
  60718. get: function () {
  60719. return false;
  60720. },
  60721. enumerable: true,
  60722. configurable: true
  60723. });
  60724. LinesMesh.prototype.createInstance = function (name) {
  60725. throw new Error("LinesMeshes do not support createInstance.");
  60726. };
  60727. LinesMesh.prototype._bind = function (subMesh, effect, fillMode) {
  60728. if (!this._geometry) {
  60729. return this;
  60730. }
  60731. // VBOs
  60732. this._geometry._bind(this._colorShader.getEffect());
  60733. // Color
  60734. if (!this.useVertexColor) {
  60735. this._colorShader.setColor4("color", this.color.toColor4(this.alpha));
  60736. }
  60737. return this;
  60738. };
  60739. LinesMesh.prototype._draw = function (subMesh, fillMode, instancesCount) {
  60740. if (!this._geometry || !this._geometry.getVertexBuffers() || (!this._unIndexed && !this._geometry.getIndexBuffer())) {
  60741. return this;
  60742. }
  60743. var engine = this.getScene().getEngine();
  60744. // Draw order
  60745. engine.drawElementsType(BABYLON.Material.LineListDrawMode, subMesh.indexStart, subMesh.indexCount);
  60746. return this;
  60747. };
  60748. LinesMesh.prototype.dispose = function (doNotRecurse) {
  60749. this._colorShader.dispose();
  60750. _super.prototype.dispose.call(this, doNotRecurse);
  60751. };
  60752. /**
  60753. * Returns a new LineMesh object cloned from the current one.
  60754. */
  60755. LinesMesh.prototype.clone = function (name, newParent, doNotCloneChildren) {
  60756. return new LinesMesh(name, this.getScene(), newParent, this, doNotCloneChildren);
  60757. };
  60758. return LinesMesh;
  60759. }(BABYLON.Mesh));
  60760. BABYLON.LinesMesh = LinesMesh;
  60761. })(BABYLON || (BABYLON = {}));
  60762. //# sourceMappingURL=babylon.linesMesh.js.map
  60763. var BABYLON;
  60764. (function (BABYLON) {
  60765. /**
  60766. * Class containing static functions to help procedurally build meshes
  60767. */
  60768. var MeshBuilder = /** @class */ (function () {
  60769. function MeshBuilder() {
  60770. }
  60771. MeshBuilder.updateSideOrientation = function (orientation) {
  60772. if (orientation == BABYLON.Mesh.DOUBLESIDE) {
  60773. return BABYLON.Mesh.DOUBLESIDE;
  60774. }
  60775. if (orientation === undefined || orientation === null) {
  60776. return BABYLON.Mesh.FRONTSIDE;
  60777. }
  60778. return orientation;
  60779. };
  60780. /**
  60781. * Creates a box mesh
  60782. * * The parameter `size` sets the size (float) of each box side (default 1)
  60783. * * You can set some different box dimensions by using the parameters `width`, `height` and `depth` (all by default have the same value than `size`)
  60784. * * 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)
  60785. * * Please read this tutorial : http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  60786. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60787. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60788. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60789. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#box
  60790. * @param name defines the name of the mesh
  60791. * @param options defines the options used to create the mesh
  60792. * @param scene defines the hosting scene
  60793. * @returns the box mesh
  60794. */
  60795. MeshBuilder.CreateBox = function (name, options, scene) {
  60796. if (scene === void 0) { scene = null; }
  60797. var box = new BABYLON.Mesh(name, scene);
  60798. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60799. box._originalBuilderSideOrientation = options.sideOrientation;
  60800. var vertexData = BABYLON.VertexData.CreateBox(options);
  60801. vertexData.applyToMesh(box, options.updatable);
  60802. return box;
  60803. };
  60804. /**
  60805. * Creates a sphere mesh
  60806. * * The parameter `diameter` sets the diameter size (float) of the sphere (default 1)
  60807. * * 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`)
  60808. * * The parameter `segments` sets the sphere number of horizontal stripes (positive integer, default 32)
  60809. * * 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
  60810. * * 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)
  60811. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60812. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60813. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60814. * @param name defines the name of the mesh
  60815. * @param options defines the options used to create the mesh
  60816. * @param scene defines the hosting scene
  60817. * @returns the sphere mesh
  60818. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#sphere
  60819. */
  60820. MeshBuilder.CreateSphere = function (name, options, scene) {
  60821. var sphere = new BABYLON.Mesh(name, scene);
  60822. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60823. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60824. var vertexData = BABYLON.VertexData.CreateSphere(options);
  60825. vertexData.applyToMesh(sphere, options.updatable);
  60826. return sphere;
  60827. };
  60828. /**
  60829. * Creates a plane polygonal mesh. By default, this is a disc
  60830. * * The parameter `radius` sets the radius size (float) of the polygon (default 0.5)
  60831. * * 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
  60832. * * 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
  60833. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60834. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60835. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60836. * @param name defines the name of the mesh
  60837. * @param options defines the options used to create the mesh
  60838. * @param scene defines the hosting scene
  60839. * @returns the plane polygonal mesh
  60840. * @see http://doc.babylonjs.com/how_to/set_shapes#disc-or-regular-polygon
  60841. */
  60842. MeshBuilder.CreateDisc = function (name, options, scene) {
  60843. if (scene === void 0) { scene = null; }
  60844. var disc = new BABYLON.Mesh(name, scene);
  60845. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60846. disc._originalBuilderSideOrientation = options.sideOrientation;
  60847. var vertexData = BABYLON.VertexData.CreateDisc(options);
  60848. vertexData.applyToMesh(disc, options.updatable);
  60849. return disc;
  60850. };
  60851. /**
  60852. * Creates a sphere based upon an icosahedron with 20 triangular faces which can be subdivided
  60853. * * The parameter `radius` sets the radius size (float) of the icosphere (default 1)
  60854. * * 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`)
  60855. * * The parameter `subdivisions` sets the number of subdivisions (postive integer, default 4). The more subdivisions, the more faces on the icosphere whatever its size
  60856. * * 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
  60857. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60858. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60859. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60860. * @param name defines the name of the mesh
  60861. * @param options defines the options used to create the mesh
  60862. * @param scene defines the hosting scene
  60863. * @returns the icosahedron mesh
  60864. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes#icosphere
  60865. */
  60866. MeshBuilder.CreateIcoSphere = function (name, options, scene) {
  60867. var sphere = new BABYLON.Mesh(name, scene);
  60868. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60869. sphere._originalBuilderSideOrientation = options.sideOrientation;
  60870. var vertexData = BABYLON.VertexData.CreateIcoSphere(options);
  60871. vertexData.applyToMesh(sphere, options.updatable);
  60872. return sphere;
  60873. };
  60874. ;
  60875. /**
  60876. * Creates a ribbon mesh. The ribbon is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  60877. * * The parameter `pathArray` is a required array of paths, what are each an array of successive Vector3. The pathArray parameter depicts the ribbon geometry
  60878. * * The parameter `closeArray` (boolean, default false) creates a seam between the first and the last paths of the path array
  60879. * * The parameter `closePath` (boolean, default false) creates a seam between the first and the last points of each path of the path array
  60880. * * 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
  60881. * * 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
  60882. * * 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
  60883. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  60884. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  60885. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  60886. * * 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
  60887. * * The parameters `colors` is an optional flat array of `Color4` to set/update each ribbon vertex with its own custom color values
  60888. * * 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
  60889. * * Moreover, you can use the parameter `color` with `instance` (to update the ribbon), only if you previously used it at creation time
  60890. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  60891. * @param name defines the name of the mesh
  60892. * @param options defines the options used to create the mesh
  60893. * @param scene defines the hosting scene
  60894. * @returns the ribbon mesh
  60895. * @see http://doc.babylonjs.com/tutorials/Ribbon_Tutorial
  60896. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  60897. */
  60898. MeshBuilder.CreateRibbon = function (name, options, scene) {
  60899. if (scene === void 0) { scene = null; }
  60900. var pathArray = options.pathArray;
  60901. var closeArray = options.closeArray;
  60902. var closePath = options.closePath;
  60903. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  60904. var instance = options.instance;
  60905. var updatable = options.updatable;
  60906. if (instance) { // existing ribbon instance update
  60907. // positionFunction : ribbon case
  60908. // only pathArray and sideOrientation parameters are taken into account for positions update
  60909. BABYLON.Vector3.FromFloatsToRef(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE, BABYLON.Tmp.Vector3[0]); // minimum
  60910. BABYLON.Vector3.FromFloatsToRef(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE, BABYLON.Tmp.Vector3[1]);
  60911. var positionFunction = function (positions) {
  60912. var minlg = pathArray[0].length;
  60913. var i = 0;
  60914. var ns = (instance._originalBuilderSideOrientation === BABYLON.Mesh.DOUBLESIDE) ? 2 : 1;
  60915. for (var si = 1; si <= ns; si++) {
  60916. for (var p = 0; p < pathArray.length; p++) {
  60917. var path = pathArray[p];
  60918. var l = path.length;
  60919. minlg = (minlg < l) ? minlg : l;
  60920. var j = 0;
  60921. while (j < minlg) {
  60922. positions[i] = path[j].x;
  60923. positions[i + 1] = path[j].y;
  60924. positions[i + 2] = path[j].z;
  60925. if (path[j].x < BABYLON.Tmp.Vector3[0].x) {
  60926. BABYLON.Tmp.Vector3[0].x = path[j].x;
  60927. }
  60928. if (path[j].x > BABYLON.Tmp.Vector3[1].x) {
  60929. BABYLON.Tmp.Vector3[1].x = path[j].x;
  60930. }
  60931. if (path[j].y < BABYLON.Tmp.Vector3[0].y) {
  60932. BABYLON.Tmp.Vector3[0].y = path[j].y;
  60933. }
  60934. if (path[j].y > BABYLON.Tmp.Vector3[1].y) {
  60935. BABYLON.Tmp.Vector3[1].y = path[j].y;
  60936. }
  60937. if (path[j].z < BABYLON.Tmp.Vector3[0].z) {
  60938. BABYLON.Tmp.Vector3[0].z = path[j].z;
  60939. }
  60940. if (path[j].z > BABYLON.Tmp.Vector3[1].z) {
  60941. BABYLON.Tmp.Vector3[1].z = path[j].z;
  60942. }
  60943. j++;
  60944. i += 3;
  60945. }
  60946. if (instance._closePath) {
  60947. positions[i] = path[0].x;
  60948. positions[i + 1] = path[0].y;
  60949. positions[i + 2] = path[0].z;
  60950. i += 3;
  60951. }
  60952. }
  60953. }
  60954. };
  60955. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  60956. positionFunction(positions);
  60957. instance._boundingInfo = new BABYLON.BoundingInfo(BABYLON.Tmp.Vector3[0], BABYLON.Tmp.Vector3[1]);
  60958. instance._boundingInfo.update(instance._worldMatrix);
  60959. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  60960. if (options.colors) {
  60961. var colors = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  60962. for (var c = 0; c < options.colors.length; c++) {
  60963. colors[c * 4] = options.colors[c].r;
  60964. colors[c * 4 + 1] = options.colors[c].g;
  60965. colors[c * 4 + 2] = options.colors[c].b;
  60966. colors[c * 4 + 3] = options.colors[c].a;
  60967. }
  60968. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, colors, false, false);
  60969. }
  60970. if (options.uvs) {
  60971. var uvs = instance.getVerticesData(BABYLON.VertexBuffer.UVKind);
  60972. for (var i = 0; i < options.uvs.length; i++) {
  60973. uvs[i * 2] = options.uvs[i].x;
  60974. uvs[i * 2 + 1] = options.uvs[i].y;
  60975. }
  60976. instance.updateVerticesData(BABYLON.VertexBuffer.UVKind, uvs, false, false);
  60977. }
  60978. if (!instance.areNormalsFrozen || instance.isFacetDataEnabled) {
  60979. var indices = instance.getIndices();
  60980. var normals = instance.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  60981. var params = instance.isFacetDataEnabled ? instance.getFacetDataParameters() : null;
  60982. BABYLON.VertexData.ComputeNormals(positions, indices, normals, params);
  60983. if (instance._closePath) {
  60984. var indexFirst = 0;
  60985. var indexLast = 0;
  60986. for (var p = 0; p < pathArray.length; p++) {
  60987. indexFirst = instance._idx[p] * 3;
  60988. if (p + 1 < pathArray.length) {
  60989. indexLast = (instance._idx[p + 1] - 1) * 3;
  60990. }
  60991. else {
  60992. indexLast = normals.length - 3;
  60993. }
  60994. normals[indexFirst] = (normals[indexFirst] + normals[indexLast]) * 0.5;
  60995. normals[indexFirst + 1] = (normals[indexFirst + 1] + normals[indexLast + 1]) * 0.5;
  60996. normals[indexFirst + 2] = (normals[indexFirst + 2] + normals[indexLast + 2]) * 0.5;
  60997. normals[indexLast] = normals[indexFirst];
  60998. normals[indexLast + 1] = normals[indexFirst + 1];
  60999. normals[indexLast + 2] = normals[indexFirst + 2];
  61000. }
  61001. }
  61002. if (!(instance.areNormalsFrozen)) {
  61003. instance.updateVerticesData(BABYLON.VertexBuffer.NormalKind, normals, false, false);
  61004. }
  61005. }
  61006. return instance;
  61007. }
  61008. else { // new ribbon creation
  61009. var ribbon = new BABYLON.Mesh(name, scene);
  61010. ribbon._originalBuilderSideOrientation = sideOrientation;
  61011. var vertexData = BABYLON.VertexData.CreateRibbon(options);
  61012. if (closePath) {
  61013. ribbon._idx = vertexData._idx;
  61014. }
  61015. ribbon._closePath = closePath;
  61016. ribbon._closeArray = closeArray;
  61017. vertexData.applyToMesh(ribbon, updatable);
  61018. return ribbon;
  61019. }
  61020. };
  61021. /**
  61022. * Creates a cylinder or a cone mesh
  61023. * * The parameter `height` sets the height size (float) of the cylinder/cone (float, default 2).
  61024. * * The parameter `diameter` sets the diameter of the top and bottom cap at once (float, default 1).
  61025. * * 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.
  61026. * * The parameter `tessellation` sets the number of cylinder sides (positive integer, default 24). Set it to 3 to get a prism for instance.
  61027. * * The parameter `subdivisions` sets the number of rings along the cylinder height (positive integer, default 1).
  61028. * * The parameter `hasRings` (boolean, default false) makes the subdivisions independent from each other, so they become different faces.
  61029. * * The parameter `enclose` (boolean, default false) adds two extra faces per subdivision to a sliced cylinder to close it around its height axis.
  61030. * * The parameter `arc` (float, default 1) is the ratio (max 1) to apply to the circumference to slice the cylinder.
  61031. * * 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).
  61032. * * 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
  61033. * * Now, if the cylinder has 5 independent subdivisions (hasRings = true), n equals : top face + 5 stripe surfaces + bottom face = 2 + 5 = 7
  61034. * * 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
  61035. * * 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.
  61036. * * If `enclose` is false, a ring surface is one element.
  61037. * * If `enclose` is true, a ring surface is 3 successive elements in the array : the tubular surface, then the two closing faces.
  61038. * * 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
  61039. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61040. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61041. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61042. * @param name defines the name of the mesh
  61043. * @param options defines the options used to create the mesh
  61044. * @param scene defines the hosting scene
  61045. * @returns the cylinder mesh
  61046. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#cylinder-or-cone
  61047. */
  61048. MeshBuilder.CreateCylinder = function (name, options, scene) {
  61049. var cylinder = new BABYLON.Mesh(name, scene);
  61050. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61051. cylinder._originalBuilderSideOrientation = options.sideOrientation;
  61052. var vertexData = BABYLON.VertexData.CreateCylinder(options);
  61053. vertexData.applyToMesh(cylinder, options.updatable);
  61054. return cylinder;
  61055. };
  61056. /**
  61057. * Creates a torus mesh
  61058. * * The parameter `diameter` sets the diameter size (float) of the torus (default 1)
  61059. * * The parameter `thickness` sets the diameter size of the tube of the torus (float, default 0.5)
  61060. * * The parameter `tessellation` sets the number of torus sides (postive integer, default 16)
  61061. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61062. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61063. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61064. * @param name defines the name of the mesh
  61065. * @param options defines the options used to create the mesh
  61066. * @param scene defines the hosting scene
  61067. * @returns the torus mesh
  61068. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus
  61069. */
  61070. MeshBuilder.CreateTorus = function (name, options, scene) {
  61071. var torus = new BABYLON.Mesh(name, scene);
  61072. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61073. torus._originalBuilderSideOrientation = options.sideOrientation;
  61074. var vertexData = BABYLON.VertexData.CreateTorus(options);
  61075. vertexData.applyToMesh(torus, options.updatable);
  61076. return torus;
  61077. };
  61078. /**
  61079. * Creates a torus knot mesh
  61080. * * The parameter `radius` sets the global radius size (float) of the torus knot (default 2)
  61081. * * The parameter `radialSegments` sets the number of sides on each tube segments (positive integer, default 32)
  61082. * * The parameter `tubularSegments` sets the number of tubes to decompose the knot into (positive integer, default 32)
  61083. * * The parameters `p` and `q` are the number of windings on each axis (positive integers, default 2 and 3)
  61084. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61085. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61086. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61087. * @param name defines the name of the mesh
  61088. * @param options defines the options used to create the mesh
  61089. * @param scene defines the hosting scene
  61090. * @returns the torus knot mesh
  61091. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#torus-knot
  61092. */
  61093. MeshBuilder.CreateTorusKnot = function (name, options, scene) {
  61094. var torusKnot = new BABYLON.Mesh(name, scene);
  61095. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61096. torusKnot._originalBuilderSideOrientation = options.sideOrientation;
  61097. var vertexData = BABYLON.VertexData.CreateTorusKnot(options);
  61098. vertexData.applyToMesh(torusKnot, options.updatable);
  61099. return torusKnot;
  61100. };
  61101. /**
  61102. * Creates a line system mesh. A line system is a pool of many lines gathered in a single mesh
  61103. * * 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
  61104. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineSystem to this static function
  61105. * * The parameter `lines` is an array of lines, each line being an array of successive Vector3
  61106. * * The optional parameter `instance` is an instance of an existing LineSystem object to be updated with the passed `lines` parameter
  61107. * * The optional parameter `colors` is an array of line colors, each line colors being an array of successive Color4, one per line point
  61108. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need the alpha blending (faster)
  61109. * * 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
  61110. * * When updating an instance, remember that only line point positions can change, not the number of points, neither the number of lines
  61111. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61112. * @see http://doc.babylonjs.com/how_to/parametric_shapes#line-system
  61113. * @param name defines the name of the new line system
  61114. * @param options defines the options used to create the line system
  61115. * @param scene defines the hosting scene
  61116. * @returns a new line system mesh
  61117. */
  61118. MeshBuilder.CreateLineSystem = function (name, options, scene) {
  61119. var instance = options.instance;
  61120. var lines = options.lines;
  61121. var colors = options.colors;
  61122. if (instance) { // lines update
  61123. var positions = instance.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61124. var vertexColor;
  61125. var lineColors;
  61126. if (colors) {
  61127. vertexColor = instance.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  61128. }
  61129. var i = 0;
  61130. var c = 0;
  61131. for (var l = 0; l < lines.length; l++) {
  61132. var points = lines[l];
  61133. for (var p = 0; p < points.length; p++) {
  61134. positions[i] = points[p].x;
  61135. positions[i + 1] = points[p].y;
  61136. positions[i + 2] = points[p].z;
  61137. if (colors && vertexColor) {
  61138. lineColors = colors[l];
  61139. vertexColor[c] = lineColors[p].r;
  61140. vertexColor[c + 1] = lineColors[p].g;
  61141. vertexColor[c + 2] = lineColors[p].b;
  61142. vertexColor[c + 3] = lineColors[p].a;
  61143. c += 4;
  61144. }
  61145. i += 3;
  61146. }
  61147. }
  61148. instance.updateVerticesData(BABYLON.VertexBuffer.PositionKind, positions, false, false);
  61149. if (colors && vertexColor) {
  61150. instance.updateVerticesData(BABYLON.VertexBuffer.ColorKind, vertexColor, false, false);
  61151. }
  61152. return instance;
  61153. }
  61154. // line system creation
  61155. var useVertexColor = (colors) ? true : false;
  61156. var lineSystem = new BABYLON.LinesMesh(name, scene, null, undefined, undefined, useVertexColor, options.useVertexAlpha);
  61157. var vertexData = BABYLON.VertexData.CreateLineSystem(options);
  61158. vertexData.applyToMesh(lineSystem, options.updatable);
  61159. return lineSystem;
  61160. };
  61161. /**
  61162. * Creates a line mesh
  61163. * 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
  61164. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61165. * * The parameter `points` is an array successive Vector3
  61166. * * 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
  61167. * * The optional parameter `colors` is an array of successive Color4, one per line point
  61168. * * The optional parameter `useVertexAlpha` is to be set to `false` (default `true`) when you don't need alpha blending (faster)
  61169. * * When updating an instance, remember that only point positions can change, not the number of points
  61170. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61171. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lines
  61172. * @param name defines the name of the new line system
  61173. * @param options defines the options used to create the line system
  61174. * @param scene defines the hosting scene
  61175. * @returns a new line mesh
  61176. */
  61177. MeshBuilder.CreateLines = function (name, options, scene) {
  61178. if (scene === void 0) { scene = null; }
  61179. var colors = (options.colors) ? [options.colors] : null;
  61180. var lines = MeshBuilder.CreateLineSystem(name, { lines: [options.points], updatable: options.updatable, instance: options.instance, colors: colors, useVertexAlpha: options.useVertexAlpha }, scene);
  61181. return lines;
  61182. };
  61183. /**
  61184. * Creates a dashed line mesh
  61185. * * 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
  61186. * * Like every other parametric shape, it is dynamically updatable by passing an existing instance of LineMesh to this static function
  61187. * * The parameter `points` is an array successive Vector3
  61188. * * The parameter `dashNb` is the intended total number of dashes (positive integer, default 200)
  61189. * * The parameter `dashSize` is the size of the dashes relatively the dash number (positive float, default 3)
  61190. * * The parameter `gapSize` is the size of the gap between two successive dashes relatively the dash number (positive float, default 1)
  61191. * * 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
  61192. * * When updating an instance, remember that only point positions can change, not the number of points
  61193. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61194. * @param name defines the name of the mesh
  61195. * @param options defines the options used to create the mesh
  61196. * @param scene defines the hosting scene
  61197. * @returns the dashed line mesh
  61198. * @see http://doc.babylonjs.com/how_to/parametric_shapes#dashed-lines
  61199. */
  61200. MeshBuilder.CreateDashedLines = function (name, options, scene) {
  61201. if (scene === void 0) { scene = null; }
  61202. var points = options.points;
  61203. var instance = options.instance;
  61204. var gapSize = options.gapSize || 1;
  61205. var dashSize = options.dashSize || 3;
  61206. if (instance) { // dashed lines update
  61207. var positionFunction = function (positions) {
  61208. var curvect = BABYLON.Vector3.Zero();
  61209. var nbSeg = positions.length / 6;
  61210. var lg = 0;
  61211. var nb = 0;
  61212. var shft = 0;
  61213. var dashshft = 0;
  61214. var curshft = 0;
  61215. var p = 0;
  61216. var i = 0;
  61217. var j = 0;
  61218. for (i = 0; i < points.length - 1; i++) {
  61219. points[i + 1].subtractToRef(points[i], curvect);
  61220. lg += curvect.length();
  61221. }
  61222. shft = lg / nbSeg;
  61223. dashshft = instance.dashSize * shft / (instance.dashSize + instance.gapSize);
  61224. for (i = 0; i < points.length - 1; i++) {
  61225. points[i + 1].subtractToRef(points[i], curvect);
  61226. nb = Math.floor(curvect.length() / shft);
  61227. curvect.normalize();
  61228. j = 0;
  61229. while (j < nb && p < positions.length) {
  61230. curshft = shft * j;
  61231. positions[p] = points[i].x + curshft * curvect.x;
  61232. positions[p + 1] = points[i].y + curshft * curvect.y;
  61233. positions[p + 2] = points[i].z + curshft * curvect.z;
  61234. positions[p + 3] = points[i].x + (curshft + dashshft) * curvect.x;
  61235. positions[p + 4] = points[i].y + (curshft + dashshft) * curvect.y;
  61236. positions[p + 5] = points[i].z + (curshft + dashshft) * curvect.z;
  61237. p += 6;
  61238. j++;
  61239. }
  61240. }
  61241. while (p < positions.length) {
  61242. positions[p] = points[i].x;
  61243. positions[p + 1] = points[i].y;
  61244. positions[p + 2] = points[i].z;
  61245. p += 3;
  61246. }
  61247. };
  61248. instance.updateMeshPositions(positionFunction, false);
  61249. return instance;
  61250. }
  61251. // dashed lines creation
  61252. var dashedLines = new BABYLON.LinesMesh(name, scene);
  61253. var vertexData = BABYLON.VertexData.CreateDashedLines(options);
  61254. vertexData.applyToMesh(dashedLines, options.updatable);
  61255. dashedLines.dashSize = dashSize;
  61256. dashedLines.gapSize = gapSize;
  61257. return dashedLines;
  61258. };
  61259. /**
  61260. * 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.
  61261. * * 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.
  61262. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61263. * * 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.
  61264. * * The parameter `scale` (float, default 1) is the value to scale the shape.
  61265. * * 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
  61266. * * 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
  61267. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape.
  61268. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61269. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61270. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture.
  61271. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61272. * @param name defines the name of the mesh
  61273. * @param options defines the options used to create the mesh
  61274. * @param scene defines the hosting scene
  61275. * @returns the extruded shape mesh
  61276. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61277. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61278. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61279. */
  61280. MeshBuilder.ExtrudeShape = function (name, options, scene) {
  61281. if (scene === void 0) { scene = null; }
  61282. var path = options.path;
  61283. var shape = options.shape;
  61284. var scale = options.scale || 1;
  61285. var rotation = options.rotation || 0;
  61286. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61287. var updatable = options.updatable;
  61288. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61289. var instance = options.instance || null;
  61290. var invertUV = options.invertUV || false;
  61291. 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);
  61292. };
  61293. /**
  61294. * Creates an custom extruded shape mesh.
  61295. * The custom extrusion is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters.
  61296. * * 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.
  61297. * * The parameter `path` is a required array of successive Vector3. This is the axis curve the shape is extruded along.
  61298. * * 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
  61299. * * It must returns a float value that will be the rotation in radians applied to the shape on each path point.
  61300. * * 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
  61301. * * It must returns a float value that will be the scale value applied to the shape on each path point
  61302. * * The parameter `ribbonClosePath` (boolean, default false) forces the extrusion underlying ribbon to close all the paths in its `pathArray`
  61303. * * The parameter `ribbonCloseArray` (boolean, default false) forces the extrusion underlying ribbon to close its `pathArray`
  61304. * * 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
  61305. * * 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
  61306. * * Remember you can only change the shape or path point positions, not their number when updating an extruded shape
  61307. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61308. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61309. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61310. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61311. * @param name defines the name of the mesh
  61312. * @param options defines the options used to create the mesh
  61313. * @param scene defines the hosting scene
  61314. * @returns the custom extruded shape mesh
  61315. * @see http://doc.babylonjs.com/how_to/parametric_shapes#custom-extruded-shapes
  61316. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61317. * @see http://doc.babylonjs.com/how_to/parametric_shapes#extruded-shapes
  61318. */
  61319. MeshBuilder.ExtrudeShapeCustom = function (name, options, scene) {
  61320. var path = options.path;
  61321. var shape = options.shape;
  61322. var scaleFunction = options.scaleFunction || (function () { return 1; });
  61323. var rotationFunction = options.rotationFunction || (function () { return 0; });
  61324. var ribbonCloseArray = options.ribbonCloseArray || false;
  61325. var ribbonClosePath = options.ribbonClosePath || false;
  61326. var cap = (options.cap === 0) ? 0 : options.cap || BABYLON.Mesh.NO_CAP;
  61327. var updatable = options.updatable;
  61328. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61329. var instance = options.instance;
  61330. var invertUV = options.invertUV || false;
  61331. 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);
  61332. };
  61333. /**
  61334. * Creates lathe mesh.
  61335. * The lathe is a shape with a symetry axis : a 2D model shape is rotated around this axis to design the lathe
  61336. * * 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
  61337. * * The parameter `radius` (positive float, default 1) is the radius value of the lathe
  61338. * * The parameter `tessellation` (positive integer, default 64) is the side number of the lathe
  61339. * * 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
  61340. * * The parameter `closed` (boolean, default true) opens/closes the lathe circumference. This should be set to false when used with the parameter "arc"
  61341. * * 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
  61342. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61343. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61344. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61345. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61346. * @param name defines the name of the mesh
  61347. * @param options defines the options used to create the mesh
  61348. * @param scene defines the hosting scene
  61349. * @returns the lathe mesh
  61350. * @see http://doc.babylonjs.com/how_to/parametric_shapes#lathe
  61351. */
  61352. MeshBuilder.CreateLathe = function (name, options, scene) {
  61353. var arc = options.arc ? ((options.arc <= 0 || options.arc > 1) ? 1.0 : options.arc) : 1.0;
  61354. var closed = (options.closed === undefined) ? true : options.closed;
  61355. var shape = options.shape;
  61356. var radius = options.radius || 1;
  61357. var tessellation = options.tessellation || 64;
  61358. var updatable = options.updatable;
  61359. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61360. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61361. var pi2 = Math.PI * 2;
  61362. var paths = new Array();
  61363. var invertUV = options.invertUV || false;
  61364. var i = 0;
  61365. var p = 0;
  61366. var step = pi2 / tessellation * arc;
  61367. var rotated;
  61368. var path = new Array();
  61369. for (i = 0; i <= tessellation; i++) {
  61370. var path = [];
  61371. if (cap == BABYLON.Mesh.CAP_START || cap == BABYLON.Mesh.CAP_ALL) {
  61372. path.push(new BABYLON.Vector3(0, shape[0].y, 0));
  61373. path.push(new BABYLON.Vector3(Math.cos(i * step) * shape[0].x * radius, shape[0].y, Math.sin(i * step) * shape[0].x * radius));
  61374. }
  61375. for (p = 0; p < shape.length; p++) {
  61376. rotated = new BABYLON.Vector3(Math.cos(i * step) * shape[p].x * radius, shape[p].y, Math.sin(i * step) * shape[p].x * radius);
  61377. path.push(rotated);
  61378. }
  61379. if (cap == BABYLON.Mesh.CAP_END || cap == BABYLON.Mesh.CAP_ALL) {
  61380. 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));
  61381. path.push(new BABYLON.Vector3(0, shape[shape.length - 1].y, 0));
  61382. }
  61383. paths.push(path);
  61384. }
  61385. // lathe ribbon
  61386. var lathe = MeshBuilder.CreateRibbon(name, { pathArray: paths, closeArray: closed, sideOrientation: sideOrientation, updatable: updatable, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61387. return lathe;
  61388. };
  61389. /**
  61390. * Creates a plane mesh
  61391. * * The parameter `size` sets the size (float) of both sides of the plane at once (default 1)
  61392. * * You can set some different plane dimensions by using the parameters `width` and `height` (both by default have the same value than `size`)
  61393. * * The parameter `sourcePlane` is a Plane instance. It builds a mesh plane from a Math plane
  61394. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61395. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61396. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61397. * @param name defines the name of the mesh
  61398. * @param options defines the options used to create the mesh
  61399. * @param scene defines the hosting scene
  61400. * @returns the plane mesh
  61401. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61402. */
  61403. MeshBuilder.CreatePlane = function (name, options, scene) {
  61404. var plane = new BABYLON.Mesh(name, scene);
  61405. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61406. plane._originalBuilderSideOrientation = options.sideOrientation;
  61407. var vertexData = BABYLON.VertexData.CreatePlane(options);
  61408. vertexData.applyToMesh(plane, options.updatable);
  61409. if (options.sourcePlane) {
  61410. plane.translate(options.sourcePlane.normal, options.sourcePlane.d);
  61411. var product = Math.acos(BABYLON.Vector3.Dot(options.sourcePlane.normal, BABYLON.Axis.Z));
  61412. var vectorProduct = BABYLON.Vector3.Cross(BABYLON.Axis.Z, options.sourcePlane.normal);
  61413. plane.rotate(vectorProduct, product);
  61414. }
  61415. return plane;
  61416. };
  61417. /**
  61418. * Creates a ground mesh
  61419. * * The parameters `width` and `height` (floats, default 1) set the width and height sizes of the ground
  61420. * * The parameter `subdivisions` (positive integer) sets the number of subdivisions per side
  61421. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61422. * @param name defines the name of the mesh
  61423. * @param options defines the options used to create the mesh
  61424. * @param scene defines the hosting scene
  61425. * @returns the ground mesh
  61426. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#plane
  61427. */
  61428. MeshBuilder.CreateGround = function (name, options, scene) {
  61429. var ground = new BABYLON.GroundMesh(name, scene);
  61430. ground._setReady(false);
  61431. ground._subdivisionsX = options.subdivisionsX || options.subdivisions || 1;
  61432. ground._subdivisionsY = options.subdivisionsY || options.subdivisions || 1;
  61433. ground._width = options.width || 1;
  61434. ground._height = options.height || 1;
  61435. ground._maxX = ground._width / 2;
  61436. ground._maxZ = ground._height / 2;
  61437. ground._minX = -ground._maxX;
  61438. ground._minZ = -ground._maxZ;
  61439. var vertexData = BABYLON.VertexData.CreateGround(options);
  61440. vertexData.applyToMesh(ground, options.updatable);
  61441. ground._setReady(true);
  61442. return ground;
  61443. };
  61444. /**
  61445. * Creates a tiled ground mesh
  61446. * * The parameters `xmin` and `xmax` (floats, default -1 and 1) set the ground minimum and maximum X coordinates
  61447. * * The parameters `zmin` and `zmax` (floats, default -1 and 1) set the ground minimum and maximum Z coordinates
  61448. * * 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
  61449. * * 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
  61450. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61451. * @param name defines the name of the mesh
  61452. * @param options defines the options used to create the mesh
  61453. * @param scene defines the hosting scene
  61454. * @returns the tiled ground mesh
  61455. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tiled-ground
  61456. */
  61457. MeshBuilder.CreateTiledGround = function (name, options, scene) {
  61458. var tiledGround = new BABYLON.Mesh(name, scene);
  61459. var vertexData = BABYLON.VertexData.CreateTiledGround(options);
  61460. vertexData.applyToMesh(tiledGround, options.updatable);
  61461. return tiledGround;
  61462. };
  61463. /**
  61464. * Creates a ground mesh from a height map
  61465. * * The parameter `url` sets the URL of the height map image resource.
  61466. * * The parameters `width` and `height` (positive floats, default 10) set the ground width and height sizes.
  61467. * * The parameter `subdivisions` (positive integer, default 1) sets the number of subdivision per side.
  61468. * * The parameter `minHeight` (float, default 0) is the minimum altitude on the ground.
  61469. * * The parameter `maxHeight` (float, default 1) is the maximum altitude on the ground.
  61470. * * 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.
  61471. * * 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).
  61472. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created.
  61473. * @param name defines the name of the mesh
  61474. * @param url defines the url to the height map
  61475. * @param options defines the options used to create the mesh
  61476. * @param scene defines the hosting scene
  61477. * @returns the ground mesh
  61478. * @see http://doc.babylonjs.com/babylon101/height_map
  61479. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#ground-from-a-height-map
  61480. */
  61481. MeshBuilder.CreateGroundFromHeightMap = function (name, url, options, scene) {
  61482. var width = options.width || 10.0;
  61483. var height = options.height || 10.0;
  61484. var subdivisions = options.subdivisions || 1 | 0;
  61485. var minHeight = options.minHeight || 0.0;
  61486. var maxHeight = options.maxHeight || 1.0;
  61487. var filter = options.colorFilter || new BABYLON.Color3(0.3, 0.59, 0.11);
  61488. var updatable = options.updatable;
  61489. var onReady = options.onReady;
  61490. var ground = new BABYLON.GroundMesh(name, scene);
  61491. ground._subdivisionsX = subdivisions;
  61492. ground._subdivisionsY = subdivisions;
  61493. ground._width = width;
  61494. ground._height = height;
  61495. ground._maxX = ground._width / 2.0;
  61496. ground._maxZ = ground._height / 2.0;
  61497. ground._minX = -ground._maxX;
  61498. ground._minZ = -ground._maxZ;
  61499. ground._setReady(false);
  61500. var onload = function (img) {
  61501. // Getting height map data
  61502. var canvas = document.createElement("canvas");
  61503. var context = canvas.getContext("2d");
  61504. if (!context) {
  61505. throw new Error("Unable to get 2d context for CreateGroundFromHeightMap");
  61506. }
  61507. if (scene.isDisposed) {
  61508. return;
  61509. }
  61510. var bufferWidth = img.width;
  61511. var bufferHeight = img.height;
  61512. canvas.width = bufferWidth;
  61513. canvas.height = bufferHeight;
  61514. context.drawImage(img, 0, 0);
  61515. // Create VertexData from map data
  61516. // Cast is due to wrong definition in lib.d.ts from ts 1.3 - https://github.com/Microsoft/TypeScript/issues/949
  61517. var buffer = context.getImageData(0, 0, bufferWidth, bufferHeight).data;
  61518. var vertexData = BABYLON.VertexData.CreateGroundFromHeightMap({
  61519. width: width, height: height,
  61520. subdivisions: subdivisions,
  61521. minHeight: minHeight, maxHeight: maxHeight, colorFilter: filter,
  61522. buffer: buffer, bufferWidth: bufferWidth, bufferHeight: bufferHeight
  61523. });
  61524. vertexData.applyToMesh(ground, updatable);
  61525. //execute ready callback, if set
  61526. if (onReady) {
  61527. onReady(ground);
  61528. }
  61529. ground._setReady(true);
  61530. };
  61531. BABYLON.Tools.LoadImage(url, onload, function () { }, scene.database);
  61532. return ground;
  61533. };
  61534. /**
  61535. * Creates a polygon mesh
  61536. * The polygon's shape will depend on the input parameters and is constructed parallel to a ground mesh
  61537. * * 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
  61538. * * You can set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61539. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61540. * * 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)
  61541. * * Remember you can only change the shape positions, not their number when updating a polygon
  61542. * @param name defines the name of the mesh
  61543. * @param options defines the options used to create the mesh
  61544. * @param scene defines the hosting scene
  61545. * @returns the polygon mesh
  61546. */
  61547. MeshBuilder.CreatePolygon = function (name, options, scene) {
  61548. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61549. var shape = options.shape;
  61550. var holes = options.holes || [];
  61551. var depth = options.depth || 0;
  61552. var contours = [];
  61553. var hole = [];
  61554. for (var i = 0; i < shape.length; i++) {
  61555. contours[i] = new BABYLON.Vector2(shape[i].x, shape[i].z);
  61556. }
  61557. var epsilon = 0.00000001;
  61558. if (contours[0].equalsWithEpsilon(contours[contours.length - 1], epsilon)) {
  61559. contours.pop();
  61560. }
  61561. var polygonTriangulation = new BABYLON.PolygonMeshBuilder(name, contours, scene);
  61562. for (var hNb = 0; hNb < holes.length; hNb++) {
  61563. hole = [];
  61564. for (var hPoint = 0; hPoint < holes[hNb].length; hPoint++) {
  61565. hole.push(new BABYLON.Vector2(holes[hNb][hPoint].x, holes[hNb][hPoint].z));
  61566. }
  61567. polygonTriangulation.addHole(hole);
  61568. }
  61569. var polygon = polygonTriangulation.build(options.updatable, depth);
  61570. polygon._originalBuilderSideOrientation = options.sideOrientation;
  61571. var vertexData = BABYLON.VertexData.CreatePolygon(polygon, options.sideOrientation, options.faceUV, options.faceColors, options.frontUVs, options.backUVs);
  61572. vertexData.applyToMesh(polygon, options.updatable);
  61573. return polygon;
  61574. };
  61575. ;
  61576. /**
  61577. * Creates an extruded polygon mesh, with depth in the Y direction.
  61578. * * 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)
  61579. * @see http://doc.babylonjs.com/tutorials/CreateBox_Per_Face_Textures_And_Colors
  61580. * @param name defines the name of the mesh
  61581. * @param options defines the options used to create the mesh
  61582. * @param scene defines the hosting scene
  61583. * @returns the polygon mesh
  61584. */
  61585. MeshBuilder.ExtrudePolygon = function (name, options, scene) {
  61586. return MeshBuilder.CreatePolygon(name, options, scene);
  61587. };
  61588. ;
  61589. /**
  61590. * Creates a tube mesh.
  61591. * The tube is a parametric shape. It has no predefined shape. Its final shape will depend on the input parameters
  61592. * * The parameter `path` is a required array of successive Vector3. It is the curve used as the axis of the tube
  61593. * * The parameter `radius` (positive float, default 1) sets the tube radius size
  61594. * * The parameter `tessellation` (positive float, default 64) is the number of sides on the tubular surface
  61595. * * The parameter `radiusFunction` (javascript function, default null) is a vanilla javascript function. If it is not null, it overwrittes the parameter `radius`
  61596. * * 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)
  61597. * * The parameter `arc` (positive float, maximum 1, default 1) is the ratio to apply to the tube circumference : 2 x PI x arc
  61598. * * 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
  61599. * * 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
  61600. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61601. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61602. * * The optional parameter `invertUV` (boolean, default false) swaps in the geometry the U and V coordinates to apply a texture
  61603. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61604. * @param name defines the name of the mesh
  61605. * @param options defines the options used to create the mesh
  61606. * @param scene defines the hosting scene
  61607. * @returns the tube mesh
  61608. * @see http://doc.babylonjs.com/tutorials/Parametric_Shapes
  61609. * @see http://doc.babylonjs.com/tutorials/Mesh_CreateXXX_Methods_With_Options_Parameter#tube
  61610. */
  61611. MeshBuilder.CreateTube = function (name, options, scene) {
  61612. var path = options.path;
  61613. var instance = options.instance;
  61614. var radius = 1.0;
  61615. if (instance) {
  61616. radius = instance.radius;
  61617. }
  61618. if (options.radius !== undefined) {
  61619. radius = options.radius;
  61620. }
  61621. ;
  61622. var tessellation = options.tessellation || 64 | 0;
  61623. var radiusFunction = options.radiusFunction || null;
  61624. var cap = options.cap || BABYLON.Mesh.NO_CAP;
  61625. var invertUV = options.invertUV || false;
  61626. var updatable = options.updatable;
  61627. var sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61628. options.arc = options.arc && (options.arc <= 0.0 || options.arc > 1.0) ? 1.0 : options.arc || 1.0;
  61629. // tube geometry
  61630. var tubePathArray = function (path, path3D, circlePaths, radius, tessellation, radiusFunction, cap, arc) {
  61631. var tangents = path3D.getTangents();
  61632. var normals = path3D.getNormals();
  61633. var distances = path3D.getDistances();
  61634. var pi2 = Math.PI * 2;
  61635. var step = pi2 / tessellation * arc;
  61636. var returnRadius = function () { return radius; };
  61637. var radiusFunctionFinal = radiusFunction || returnRadius;
  61638. var circlePath;
  61639. var rad;
  61640. var normal;
  61641. var rotated;
  61642. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61643. var index = (cap === BABYLON.Mesh._NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61644. for (var i = 0; i < path.length; i++) {
  61645. rad = radiusFunctionFinal(i, distances[i]); // current radius
  61646. circlePath = Array(); // current circle array
  61647. normal = normals[i]; // current normal
  61648. for (var t = 0; t < tessellation; t++) {
  61649. BABYLON.Matrix.RotationAxisToRef(tangents[i], step * t, rotationMatrix);
  61650. rotated = circlePath[t] ? circlePath[t] : BABYLON.Vector3.Zero();
  61651. BABYLON.Vector3.TransformCoordinatesToRef(normal, rotationMatrix, rotated);
  61652. rotated.scaleInPlace(rad).addInPlace(path[i]);
  61653. circlePath[t] = rotated;
  61654. }
  61655. circlePaths[index] = circlePath;
  61656. index++;
  61657. }
  61658. // cap
  61659. var capPath = function (nbPoints, pathIndex) {
  61660. var pointCap = Array();
  61661. for (var i = 0; i < nbPoints; i++) {
  61662. pointCap.push(path[pathIndex]);
  61663. }
  61664. return pointCap;
  61665. };
  61666. switch (cap) {
  61667. case BABYLON.Mesh.NO_CAP:
  61668. break;
  61669. case BABYLON.Mesh.CAP_START:
  61670. circlePaths[0] = capPath(tessellation, 0);
  61671. circlePaths[1] = circlePaths[2].slice(0);
  61672. break;
  61673. case BABYLON.Mesh.CAP_END:
  61674. circlePaths[index] = circlePaths[index - 1].slice(0);
  61675. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61676. break;
  61677. case BABYLON.Mesh.CAP_ALL:
  61678. circlePaths[0] = capPath(tessellation, 0);
  61679. circlePaths[1] = circlePaths[2].slice(0);
  61680. circlePaths[index] = circlePaths[index - 1].slice(0);
  61681. circlePaths[index + 1] = capPath(tessellation, path.length - 1);
  61682. break;
  61683. default:
  61684. break;
  61685. }
  61686. return circlePaths;
  61687. };
  61688. var path3D;
  61689. var pathArray;
  61690. if (instance) { // tube update
  61691. var arc = options.arc || instance.arc;
  61692. path3D = (instance.path3D).update(path);
  61693. pathArray = tubePathArray(path, path3D, instance.pathArray, radius, instance.tessellation, radiusFunction, instance.cap, arc);
  61694. instance = MeshBuilder.CreateRibbon("", { pathArray: pathArray, instance: instance });
  61695. instance.path3D = path3D;
  61696. instance.pathArray = pathArray;
  61697. instance.arc = arc;
  61698. instance.radius = radius;
  61699. return instance;
  61700. }
  61701. // tube creation
  61702. path3D = new BABYLON.Path3D(path);
  61703. var newPathArray = new Array();
  61704. cap = (cap < 0 || cap > 3) ? 0 : cap;
  61705. pathArray = tubePathArray(path, path3D, newPathArray, radius, tessellation, radiusFunction, cap, options.arc);
  61706. var tube = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closePath: true, closeArray: false, updatable: updatable, sideOrientation: sideOrientation, invertUV: invertUV, frontUVs: options.frontUVs, backUVs: options.backUVs }, scene);
  61707. tube.pathArray = pathArray;
  61708. tube.path3D = path3D;
  61709. tube.tessellation = tessellation;
  61710. tube.cap = cap;
  61711. tube.arc = options.arc;
  61712. tube.radius = radius;
  61713. return tube;
  61714. };
  61715. /**
  61716. * Creates a polyhedron mesh
  61717. * * 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
  61718. * * The parameter `size` (positive float, default 1) sets the polygon size
  61719. * * You can overwrite the `size` on each dimension bu using the parameters `sizeX`, `sizeY` or `sizeZ` (positive floats, default to `size` value)
  61720. * * 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`
  61721. * * 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
  61722. * * 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)`)
  61723. * * 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
  61724. * * 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
  61725. * * You can also set the mesh side orientation with the values : BABYLON.Mesh.FRONTSIDE (default), BABYLON.Mesh.BACKSIDE or BABYLON.Mesh.DOUBLESIDE
  61726. * * If you create a double-sided mesh, you can choose what parts of the texture image to crop and stick respectively on the front and the back sides with the parameters `frontUVs` and `backUVs` (Vector4). Detail here : http://doc.babylonjs.com/babylon101/discover_basic_elements#side-orientation
  61727. * * The mesh can be set to updatable with the boolean parameter `updatable` (default false) if its internal geometry is supposed to change once created
  61728. * @param name defines the name of the mesh
  61729. * @param options defines the options used to create the mesh
  61730. * @param scene defines the hosting scene
  61731. * @returns the polyhedron mesh
  61732. * @see http://doc.babylonjs.com/how_to/polyhedra_shapes
  61733. */
  61734. MeshBuilder.CreatePolyhedron = function (name, options, scene) {
  61735. var polyhedron = new BABYLON.Mesh(name, scene);
  61736. options.sideOrientation = MeshBuilder.updateSideOrientation(options.sideOrientation);
  61737. polyhedron._originalBuilderSideOrientation = options.sideOrientation;
  61738. var vertexData = BABYLON.VertexData.CreatePolyhedron(options);
  61739. vertexData.applyToMesh(polyhedron, options.updatable);
  61740. return polyhedron;
  61741. };
  61742. /**
  61743. * Creates a decal mesh.
  61744. * 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
  61745. * * The parameter `position` (Vector3, default `(0, 0, 0)`) sets the position of the decal in World coordinates
  61746. * * The parameter `normal` (Vector3, default `Vector3.Up`) sets the normal of the mesh where the decal is applied onto in World coordinates
  61747. * * The parameter `size` (Vector3, default `(1, 1, 1)`) sets the decal scaling
  61748. * * The parameter `angle` (float in radian, default 0) sets the angle to rotate the decal
  61749. * @param name defines the name of the mesh
  61750. * @param sourceMesh defines the mesh where the decal must be applied
  61751. * @param options defines the options used to create the mesh
  61752. * @param scene defines the hosting scene
  61753. * @returns the decal mesh
  61754. * @see http://doc.babylonjs.com/how_to/decals
  61755. */
  61756. MeshBuilder.CreateDecal = function (name, sourceMesh, options) {
  61757. var indices = sourceMesh.getIndices();
  61758. var positions = sourceMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  61759. var normals = sourceMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  61760. var position = options.position || BABYLON.Vector3.Zero();
  61761. var normal = options.normal || BABYLON.Vector3.Up();
  61762. var size = options.size || BABYLON.Vector3.One();
  61763. var angle = options.angle || 0;
  61764. // Getting correct rotation
  61765. if (!normal) {
  61766. var target = new BABYLON.Vector3(0, 0, 1);
  61767. var camera = sourceMesh.getScene().activeCamera;
  61768. var cameraWorldTarget = BABYLON.Vector3.TransformCoordinates(target, camera.getWorldMatrix());
  61769. normal = camera.globalPosition.subtract(cameraWorldTarget);
  61770. }
  61771. var yaw = -Math.atan2(normal.z, normal.x) - Math.PI / 2;
  61772. var len = Math.sqrt(normal.x * normal.x + normal.z * normal.z);
  61773. var pitch = Math.atan2(normal.y, len);
  61774. // Matrix
  61775. var decalWorldMatrix = BABYLON.Matrix.RotationYawPitchRoll(yaw, pitch, angle).multiply(BABYLON.Matrix.Translation(position.x, position.y, position.z));
  61776. var inverseDecalWorldMatrix = BABYLON.Matrix.Invert(decalWorldMatrix);
  61777. var meshWorldMatrix = sourceMesh.getWorldMatrix();
  61778. var transformMatrix = meshWorldMatrix.multiply(inverseDecalWorldMatrix);
  61779. var vertexData = new BABYLON.VertexData();
  61780. vertexData.indices = [];
  61781. vertexData.positions = [];
  61782. vertexData.normals = [];
  61783. vertexData.uvs = [];
  61784. var currentVertexDataIndex = 0;
  61785. var extractDecalVector3 = function (indexId) {
  61786. var result = new BABYLON.PositionNormalVertex();
  61787. if (!indices || !positions || !normals) {
  61788. return result;
  61789. }
  61790. var vertexId = indices[indexId];
  61791. result.position = new BABYLON.Vector3(positions[vertexId * 3], positions[vertexId * 3 + 1], positions[vertexId * 3 + 2]);
  61792. // Send vector to decal local world
  61793. result.position = BABYLON.Vector3.TransformCoordinates(result.position, transformMatrix);
  61794. // Get normal
  61795. result.normal = new BABYLON.Vector3(normals[vertexId * 3], normals[vertexId * 3 + 1], normals[vertexId * 3 + 2]);
  61796. result.normal = BABYLON.Vector3.TransformNormal(result.normal, transformMatrix);
  61797. return result;
  61798. }; // Inspired by https://github.com/mrdoob/three.js/blob/eee231960882f6f3b6113405f524956145148146/examples/js/geometries/DecalGeometry.js
  61799. var clip = function (vertices, axis) {
  61800. if (vertices.length === 0) {
  61801. return vertices;
  61802. }
  61803. var clipSize = 0.5 * Math.abs(BABYLON.Vector3.Dot(size, axis));
  61804. var clipVertices = function (v0, v1) {
  61805. var clipFactor = BABYLON.Vector3.GetClipFactor(v0.position, v1.position, axis, clipSize);
  61806. return new BABYLON.PositionNormalVertex(BABYLON.Vector3.Lerp(v0.position, v1.position, clipFactor), BABYLON.Vector3.Lerp(v0.normal, v1.normal, clipFactor));
  61807. };
  61808. var result = new Array();
  61809. for (var index = 0; index < vertices.length; index += 3) {
  61810. var v1Out;
  61811. var v2Out;
  61812. var v3Out;
  61813. var total = 0;
  61814. var nV1 = null;
  61815. var nV2 = null;
  61816. var nV3 = null;
  61817. var nV4 = null;
  61818. var d1 = BABYLON.Vector3.Dot(vertices[index].position, axis) - clipSize;
  61819. var d2 = BABYLON.Vector3.Dot(vertices[index + 1].position, axis) - clipSize;
  61820. var d3 = BABYLON.Vector3.Dot(vertices[index + 2].position, axis) - clipSize;
  61821. v1Out = d1 > 0;
  61822. v2Out = d2 > 0;
  61823. v3Out = d3 > 0;
  61824. total = (v1Out ? 1 : 0) + (v2Out ? 1 : 0) + (v3Out ? 1 : 0);
  61825. switch (total) {
  61826. case 0:
  61827. result.push(vertices[index]);
  61828. result.push(vertices[index + 1]);
  61829. result.push(vertices[index + 2]);
  61830. break;
  61831. case 1:
  61832. if (v1Out) {
  61833. nV1 = vertices[index + 1];
  61834. nV2 = vertices[index + 2];
  61835. nV3 = clipVertices(vertices[index], nV1);
  61836. nV4 = clipVertices(vertices[index], nV2);
  61837. }
  61838. if (v2Out) {
  61839. nV1 = vertices[index];
  61840. nV2 = vertices[index + 2];
  61841. nV3 = clipVertices(vertices[index + 1], nV1);
  61842. nV4 = clipVertices(vertices[index + 1], nV2);
  61843. result.push(nV3);
  61844. result.push(nV2.clone());
  61845. result.push(nV1.clone());
  61846. result.push(nV2.clone());
  61847. result.push(nV3.clone());
  61848. result.push(nV4);
  61849. break;
  61850. }
  61851. if (v3Out) {
  61852. nV1 = vertices[index];
  61853. nV2 = vertices[index + 1];
  61854. nV3 = clipVertices(vertices[index + 2], nV1);
  61855. nV4 = clipVertices(vertices[index + 2], nV2);
  61856. }
  61857. if (nV1 && nV2 && nV3 && nV4) {
  61858. result.push(nV1.clone());
  61859. result.push(nV2.clone());
  61860. result.push(nV3);
  61861. result.push(nV4);
  61862. result.push(nV3.clone());
  61863. result.push(nV2.clone());
  61864. }
  61865. break;
  61866. case 2:
  61867. if (!v1Out) {
  61868. nV1 = vertices[index].clone();
  61869. nV2 = clipVertices(nV1, vertices[index + 1]);
  61870. nV3 = clipVertices(nV1, vertices[index + 2]);
  61871. result.push(nV1);
  61872. result.push(nV2);
  61873. result.push(nV3);
  61874. }
  61875. if (!v2Out) {
  61876. nV1 = vertices[index + 1].clone();
  61877. nV2 = clipVertices(nV1, vertices[index + 2]);
  61878. nV3 = clipVertices(nV1, vertices[index]);
  61879. result.push(nV1);
  61880. result.push(nV2);
  61881. result.push(nV3);
  61882. }
  61883. if (!v3Out) {
  61884. nV1 = vertices[index + 2].clone();
  61885. nV2 = clipVertices(nV1, vertices[index]);
  61886. nV3 = clipVertices(nV1, vertices[index + 1]);
  61887. result.push(nV1);
  61888. result.push(nV2);
  61889. result.push(nV3);
  61890. }
  61891. break;
  61892. case 3:
  61893. break;
  61894. }
  61895. }
  61896. return result;
  61897. };
  61898. for (var index = 0; index < indices.length; index += 3) {
  61899. var faceVertices = new Array();
  61900. faceVertices.push(extractDecalVector3(index));
  61901. faceVertices.push(extractDecalVector3(index + 1));
  61902. faceVertices.push(extractDecalVector3(index + 2));
  61903. // Clip
  61904. faceVertices = clip(faceVertices, new BABYLON.Vector3(1, 0, 0));
  61905. faceVertices = clip(faceVertices, new BABYLON.Vector3(-1, 0, 0));
  61906. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 1, 0));
  61907. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, -1, 0));
  61908. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, 1));
  61909. faceVertices = clip(faceVertices, new BABYLON.Vector3(0, 0, -1));
  61910. if (faceVertices.length === 0) {
  61911. continue;
  61912. }
  61913. // Add UVs and get back to world
  61914. for (var vIndex = 0; vIndex < faceVertices.length; vIndex++) {
  61915. var vertex = faceVertices[vIndex];
  61916. //TODO check for Int32Array | Uint32Array | Uint16Array
  61917. vertexData.indices.push(currentVertexDataIndex);
  61918. vertex.position.toArray(vertexData.positions, currentVertexDataIndex * 3);
  61919. vertex.normal.toArray(vertexData.normals, currentVertexDataIndex * 3);
  61920. vertexData.uvs.push(0.5 + vertex.position.x / size.x);
  61921. vertexData.uvs.push(0.5 + vertex.position.y / size.y);
  61922. currentVertexDataIndex++;
  61923. }
  61924. }
  61925. // Return mesh
  61926. var decal = new BABYLON.Mesh(name, sourceMesh.getScene());
  61927. vertexData.applyToMesh(decal);
  61928. decal.position = position.clone();
  61929. decal.rotation = new BABYLON.Vector3(pitch, yaw, angle);
  61930. return decal;
  61931. };
  61932. // Privates
  61933. MeshBuilder._ExtrudeShapeGeneric = function (name, shape, curve, scale, rotation, scaleFunction, rotateFunction, rbCA, rbCP, cap, custom, scene, updtbl, side, instance, invertUV, frontUVs, backUVs) {
  61934. // extrusion geometry
  61935. var extrusionPathArray = function (shape, curve, path3D, shapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom) {
  61936. var tangents = path3D.getTangents();
  61937. var normals = path3D.getNormals();
  61938. var binormals = path3D.getBinormals();
  61939. var distances = path3D.getDistances();
  61940. var angle = 0;
  61941. var returnScale = function () { return scale !== null ? scale : 1; };
  61942. var returnRotation = function () { return rotation !== null ? rotation : 0; };
  61943. var rotate = custom && rotateFunction ? rotateFunction : returnRotation;
  61944. var scl = custom && scaleFunction ? scaleFunction : returnScale;
  61945. var index = (cap === BABYLON.Mesh.NO_CAP || cap === BABYLON.Mesh.CAP_END) ? 0 : 2;
  61946. var rotationMatrix = BABYLON.Tmp.Matrix[0];
  61947. for (var i = 0; i < curve.length; i++) {
  61948. var shapePath = new Array();
  61949. var angleStep = rotate(i, distances[i]);
  61950. var scaleRatio = scl(i, distances[i]);
  61951. for (var p = 0; p < shape.length; p++) {
  61952. BABYLON.Matrix.RotationAxisToRef(tangents[i], angle, rotationMatrix);
  61953. var planed = ((tangents[i].scale(shape[p].z)).add(normals[i].scale(shape[p].x)).add(binormals[i].scale(shape[p].y)));
  61954. var rotated = shapePath[p] ? shapePath[p] : BABYLON.Vector3.Zero();
  61955. BABYLON.Vector3.TransformCoordinatesToRef(planed, rotationMatrix, rotated);
  61956. rotated.scaleInPlace(scaleRatio).addInPlace(curve[i]);
  61957. shapePath[p] = rotated;
  61958. }
  61959. shapePaths[index] = shapePath;
  61960. angle += angleStep;
  61961. index++;
  61962. }
  61963. // cap
  61964. var capPath = function (shapePath) {
  61965. var pointCap = Array();
  61966. var barycenter = BABYLON.Vector3.Zero();
  61967. var i;
  61968. for (i = 0; i < shapePath.length; i++) {
  61969. barycenter.addInPlace(shapePath[i]);
  61970. }
  61971. barycenter.scaleInPlace(1.0 / shapePath.length);
  61972. for (i = 0; i < shapePath.length; i++) {
  61973. pointCap.push(barycenter);
  61974. }
  61975. return pointCap;
  61976. };
  61977. switch (cap) {
  61978. case BABYLON.Mesh.NO_CAP:
  61979. break;
  61980. case BABYLON.Mesh.CAP_START:
  61981. shapePaths[0] = capPath(shapePaths[2]);
  61982. shapePaths[1] = shapePaths[2];
  61983. break;
  61984. case BABYLON.Mesh.CAP_END:
  61985. shapePaths[index] = shapePaths[index - 1];
  61986. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61987. break;
  61988. case BABYLON.Mesh.CAP_ALL:
  61989. shapePaths[0] = capPath(shapePaths[2]);
  61990. shapePaths[1] = shapePaths[2];
  61991. shapePaths[index] = shapePaths[index - 1];
  61992. shapePaths[index + 1] = capPath(shapePaths[index - 1]);
  61993. break;
  61994. default:
  61995. break;
  61996. }
  61997. return shapePaths;
  61998. };
  61999. var path3D;
  62000. var pathArray;
  62001. if (instance) { // instance update
  62002. path3D = (instance.path3D).update(curve);
  62003. pathArray = extrusionPathArray(shape, curve, instance.path3D, instance.pathArray, scale, rotation, scaleFunction, rotateFunction, instance.cap, custom);
  62004. instance = BABYLON.Mesh.CreateRibbon("", pathArray, false, false, 0, scene || undefined, false, 0, instance);
  62005. return instance;
  62006. }
  62007. // extruded shape creation
  62008. path3D = new BABYLON.Path3D(curve);
  62009. var newShapePaths = new Array();
  62010. cap = (cap < 0 || cap > 3) ? 0 : cap;
  62011. pathArray = extrusionPathArray(shape, curve, path3D, newShapePaths, scale, rotation, scaleFunction, rotateFunction, cap, custom);
  62012. var extrudedGeneric = MeshBuilder.CreateRibbon(name, { pathArray: pathArray, closeArray: rbCA, closePath: rbCP, updatable: updtbl, sideOrientation: side, invertUV: invertUV, frontUVs: frontUVs || undefined, backUVs: backUVs || undefined }, scene);
  62013. extrudedGeneric.pathArray = pathArray;
  62014. extrudedGeneric.path3D = path3D;
  62015. extrudedGeneric.cap = cap;
  62016. return extrudedGeneric;
  62017. };
  62018. return MeshBuilder;
  62019. }());
  62020. BABYLON.MeshBuilder = MeshBuilder;
  62021. })(BABYLON || (BABYLON = {}));
  62022. //# sourceMappingURL=babylon.meshBuilder.js.map
  62023. var BABYLON;
  62024. (function (BABYLON) {
  62025. /**
  62026. * Draco compression (https://google.github.io/draco/)
  62027. *
  62028. * This class wraps the Draco module.
  62029. *
  62030. * **Encoder**
  62031. *
  62032. * The encoder is not currently implemented.
  62033. *
  62034. * **Decoder**
  62035. *
  62036. * By default, the configuration points to a copy of the Draco decoder files for glTF from https://preview.babylonjs.com.
  62037. *
  62038. * To update the configuration, use the following code:
  62039. * ```javascript
  62040. * BABYLON.DracoCompression.Configuration = {
  62041. * decoder: {
  62042. * wasmUrl: "<url to the WebAssembly library>",
  62043. * wasmBinaryUrl: "<url to the WebAssembly binary>",
  62044. * fallbackUrl: "<url to the fallback JavaScript library>",
  62045. * }
  62046. * };
  62047. * ```
  62048. *
  62049. * Draco has two versions, one for WebAssembly and one for JavaScript. The decoder configuration can be set to only support Webssembly or only support the JavaScript version.
  62050. * Decoding will automatically fallback to the JavaScript version if WebAssembly version is not configured or if WebAssembly is not supported by the browser.
  62051. * Use `BABYLON.DracoCompression.DecoderAvailable` to determine if the decoder is available for the current session.
  62052. *
  62053. * To decode Draco compressed data, create a DracoCompression object and call decodeMeshAsync:
  62054. * ```javascript
  62055. * var dracoCompression = new BABYLON.DracoCompression();
  62056. * var vertexData = await dracoCompression.decodeMeshAsync(data, {
  62057. * [BABYLON.VertexBuffer.PositionKind]: 0
  62058. * });
  62059. * ```
  62060. *
  62061. * @see https://www.babylonjs-playground.com/#N3EK4B#0
  62062. */
  62063. var DracoCompression = /** @class */ (function () {
  62064. /**
  62065. * Constructor
  62066. */
  62067. function DracoCompression() {
  62068. }
  62069. Object.defineProperty(DracoCompression, "DecoderAvailable", {
  62070. /**
  62071. * Returns true if the decoder is available.
  62072. */
  62073. get: function () {
  62074. if (typeof DracoDecoderModule !== "undefined") {
  62075. return true;
  62076. }
  62077. var decoder = DracoCompression.Configuration.decoder;
  62078. if (decoder) {
  62079. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62080. return true;
  62081. }
  62082. if (decoder.fallbackUrl) {
  62083. return true;
  62084. }
  62085. }
  62086. return false;
  62087. },
  62088. enumerable: true,
  62089. configurable: true
  62090. });
  62091. /**
  62092. * Stop all async operations and release resources.
  62093. */
  62094. DracoCompression.prototype.dispose = function () {
  62095. };
  62096. /**
  62097. * Decode Draco compressed mesh data to vertex data.
  62098. * @param data The ArrayBuffer or ArrayBufferView for the Draco compression data
  62099. * @param attributes A map of attributes from vertex buffer kinds to Draco unique ids
  62100. * @returns A promise that resolves with the decoded vertex data
  62101. */
  62102. DracoCompression.prototype.decodeMeshAsync = function (data, attributes) {
  62103. var dataView = data instanceof ArrayBuffer ? new Uint8Array(data) : data;
  62104. return DracoCompression._GetDecoderModule().then(function (wrappedModule) {
  62105. var module = wrappedModule.module;
  62106. var vertexData = new BABYLON.VertexData();
  62107. var buffer = new module.DecoderBuffer();
  62108. buffer.Init(dataView, dataView.byteLength);
  62109. var decoder = new module.Decoder();
  62110. var geometry;
  62111. var status;
  62112. try {
  62113. var type = decoder.GetEncodedGeometryType(buffer);
  62114. switch (type) {
  62115. case module.TRIANGULAR_MESH:
  62116. geometry = new module.Mesh();
  62117. status = decoder.DecodeBufferToMesh(buffer, geometry);
  62118. break;
  62119. case module.POINT_CLOUD:
  62120. geometry = new module.PointCloud();
  62121. status = decoder.DecodeBufferToPointCloud(buffer, geometry);
  62122. break;
  62123. default:
  62124. throw new Error("Invalid geometry type " + type);
  62125. }
  62126. if (!status.ok() || !geometry.ptr) {
  62127. throw new Error(status.error_msg());
  62128. }
  62129. var numPoints = geometry.num_points();
  62130. if (type === module.TRIANGULAR_MESH) {
  62131. var numFaces = geometry.num_faces();
  62132. var faceIndices = new module.DracoInt32Array();
  62133. try {
  62134. var indices = new Uint32Array(numFaces * 3);
  62135. for (var i = 0; i < numFaces; i++) {
  62136. decoder.GetFaceFromMesh(geometry, i, faceIndices);
  62137. var offset = i * 3;
  62138. indices[offset + 0] = faceIndices.GetValue(0);
  62139. indices[offset + 1] = faceIndices.GetValue(1);
  62140. indices[offset + 2] = faceIndices.GetValue(2);
  62141. }
  62142. vertexData.indices = indices;
  62143. }
  62144. finally {
  62145. module.destroy(faceIndices);
  62146. }
  62147. }
  62148. for (var kind in attributes) {
  62149. var uniqueId = attributes[kind];
  62150. var attribute = decoder.GetAttributeByUniqueId(geometry, uniqueId);
  62151. var dracoData = new module.DracoFloat32Array();
  62152. try {
  62153. decoder.GetAttributeFloatForAllPoints(geometry, attribute, dracoData);
  62154. var babylonData = new Float32Array(numPoints * attribute.num_components());
  62155. for (var i = 0; i < babylonData.length; i++) {
  62156. babylonData[i] = dracoData.GetValue(i);
  62157. }
  62158. vertexData.set(babylonData, kind);
  62159. }
  62160. finally {
  62161. module.destroy(dracoData);
  62162. }
  62163. }
  62164. }
  62165. finally {
  62166. if (geometry) {
  62167. module.destroy(geometry);
  62168. }
  62169. module.destroy(decoder);
  62170. module.destroy(buffer);
  62171. }
  62172. return vertexData;
  62173. });
  62174. };
  62175. DracoCompression._GetDecoderModule = function () {
  62176. if (!DracoCompression._DecoderModulePromise) {
  62177. var promise = null;
  62178. var config_1 = {};
  62179. if (typeof DracoDecoderModule !== "undefined") {
  62180. promise = Promise.resolve();
  62181. }
  62182. else {
  62183. var decoder = DracoCompression.Configuration.decoder;
  62184. if (decoder) {
  62185. if (decoder.wasmUrl && decoder.wasmBinaryUrl && typeof WebAssembly === "object") {
  62186. promise = Promise.all([
  62187. DracoCompression._LoadScriptAsync(decoder.wasmUrl),
  62188. DracoCompression._LoadFileAsync(decoder.wasmBinaryUrl).then(function (data) {
  62189. config_1.wasmBinary = data;
  62190. })
  62191. ]);
  62192. }
  62193. else if (decoder.fallbackUrl) {
  62194. promise = DracoCompression._LoadScriptAsync(decoder.fallbackUrl);
  62195. }
  62196. }
  62197. }
  62198. if (!promise) {
  62199. throw new Error("Draco decoder module is not available");
  62200. }
  62201. DracoCompression._DecoderModulePromise = promise.then(function () {
  62202. return new Promise(function (resolve) {
  62203. config_1.onModuleLoaded = function (decoderModule) {
  62204. // decoderModule is Promise-like. Wrap before resolving to avoid loop.
  62205. resolve({ module: decoderModule });
  62206. };
  62207. DracoDecoderModule(config_1);
  62208. });
  62209. });
  62210. }
  62211. return DracoCompression._DecoderModulePromise;
  62212. };
  62213. DracoCompression._LoadScriptAsync = function (url) {
  62214. return new Promise(function (resolve, reject) {
  62215. BABYLON.Tools.LoadScript(url, function () {
  62216. resolve();
  62217. }, function (message) {
  62218. reject(new Error(message));
  62219. });
  62220. });
  62221. };
  62222. DracoCompression._LoadFileAsync = function (url) {
  62223. return new Promise(function (resolve, reject) {
  62224. BABYLON.Tools.LoadFile(url, function (data) {
  62225. resolve(data);
  62226. }, undefined, undefined, true, function (request, exception) {
  62227. reject(exception);
  62228. });
  62229. });
  62230. };
  62231. /**
  62232. * The configuration. Defaults to the following urls:
  62233. * - wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js"
  62234. * - wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm"
  62235. * - fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62236. */
  62237. DracoCompression.Configuration = {
  62238. decoder: {
  62239. wasmUrl: "https://preview.babylonjs.com/draco_wasm_wrapper_gltf.js",
  62240. wasmBinaryUrl: "https://preview.babylonjs.com/draco_decoder_gltf.wasm",
  62241. fallbackUrl: "https://preview.babylonjs.com/draco_decoder_gltf.js"
  62242. }
  62243. };
  62244. return DracoCompression;
  62245. }());
  62246. BABYLON.DracoCompression = DracoCompression;
  62247. })(BABYLON || (BABYLON = {}));
  62248. //# sourceMappingURL=babylon.dracoCompression.js.map
  62249. var BABYLON;
  62250. (function (BABYLON) {
  62251. var AudioEngine = /** @class */ (function () {
  62252. function AudioEngine() {
  62253. this._audioContext = null;
  62254. this._audioContextInitialized = false;
  62255. this.canUseWebAudio = false;
  62256. this.WarnedWebAudioUnsupported = false;
  62257. this.unlocked = false;
  62258. this.isMP3supported = false;
  62259. this.isOGGsupported = false;
  62260. if (typeof window.AudioContext !== 'undefined' || typeof window.webkitAudioContext !== 'undefined') {
  62261. window.AudioContext = window.AudioContext || window.webkitAudioContext;
  62262. this.canUseWebAudio = true;
  62263. }
  62264. var audioElem = document.createElement('audio');
  62265. try {
  62266. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/mpeg; codecs="mp3"').replace(/^no$/, '')) {
  62267. this.isMP3supported = true;
  62268. }
  62269. }
  62270. catch (e) {
  62271. // protect error during capability check.
  62272. }
  62273. try {
  62274. if (audioElem && !!audioElem.canPlayType && audioElem.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/, '')) {
  62275. this.isOGGsupported = true;
  62276. }
  62277. }
  62278. catch (e) {
  62279. // protect error during capability check.
  62280. }
  62281. if (/iPad|iPhone|iPod/.test(navigator.platform)) {
  62282. this._unlockiOSaudio();
  62283. }
  62284. else {
  62285. this.unlocked = true;
  62286. }
  62287. }
  62288. Object.defineProperty(AudioEngine.prototype, "audioContext", {
  62289. get: function () {
  62290. if (!this._audioContextInitialized) {
  62291. this._initializeAudioContext();
  62292. }
  62293. return this._audioContext;
  62294. },
  62295. enumerable: true,
  62296. configurable: true
  62297. });
  62298. AudioEngine.prototype._unlockiOSaudio = function () {
  62299. var _this = this;
  62300. var unlockaudio = function () {
  62301. if (!_this.audioContext) {
  62302. return;
  62303. }
  62304. var buffer = _this.audioContext.createBuffer(1, 1, 22050);
  62305. var source = _this.audioContext.createBufferSource();
  62306. source.buffer = buffer;
  62307. source.connect(_this.audioContext.destination);
  62308. source.start(0);
  62309. setTimeout(function () {
  62310. if ((source.playbackState === source.PLAYING_STATE || source.playbackState === source.FINISHED_STATE)) {
  62311. _this.unlocked = true;
  62312. window.removeEventListener('touchend', unlockaudio, false);
  62313. if (_this.onAudioUnlocked) {
  62314. _this.onAudioUnlocked();
  62315. }
  62316. }
  62317. }, 0);
  62318. };
  62319. window.addEventListener('touchend', unlockaudio, false);
  62320. };
  62321. AudioEngine.prototype._initializeAudioContext = function () {
  62322. try {
  62323. if (this.canUseWebAudio) {
  62324. this._audioContext = new AudioContext();
  62325. // create a global volume gain node
  62326. this.masterGain = this._audioContext.createGain();
  62327. this.masterGain.gain.value = 1;
  62328. this.masterGain.connect(this._audioContext.destination);
  62329. this._audioContextInitialized = true;
  62330. }
  62331. }
  62332. catch (e) {
  62333. this.canUseWebAudio = false;
  62334. BABYLON.Tools.Error("Web Audio: " + e.message);
  62335. }
  62336. };
  62337. AudioEngine.prototype.dispose = function () {
  62338. if (this.canUseWebAudio && this._audioContextInitialized) {
  62339. if (this._connectedAnalyser && this._audioContext) {
  62340. this._connectedAnalyser.stopDebugCanvas();
  62341. this._connectedAnalyser.dispose();
  62342. this.masterGain.disconnect();
  62343. this.masterGain.connect(this._audioContext.destination);
  62344. this._connectedAnalyser = null;
  62345. }
  62346. this.masterGain.gain.value = 1;
  62347. }
  62348. this.WarnedWebAudioUnsupported = false;
  62349. };
  62350. AudioEngine.prototype.getGlobalVolume = function () {
  62351. if (this.canUseWebAudio && this._audioContextInitialized) {
  62352. return this.masterGain.gain.value;
  62353. }
  62354. else {
  62355. return -1;
  62356. }
  62357. };
  62358. AudioEngine.prototype.setGlobalVolume = function (newVolume) {
  62359. if (this.canUseWebAudio && this._audioContextInitialized) {
  62360. this.masterGain.gain.value = newVolume;
  62361. }
  62362. };
  62363. AudioEngine.prototype.connectToAnalyser = function (analyser) {
  62364. if (this._connectedAnalyser) {
  62365. this._connectedAnalyser.stopDebugCanvas();
  62366. }
  62367. if (this.canUseWebAudio && this._audioContextInitialized && this._audioContext) {
  62368. this._connectedAnalyser = analyser;
  62369. this.masterGain.disconnect();
  62370. this._connectedAnalyser.connectAudioNodes(this.masterGain, this._audioContext.destination);
  62371. }
  62372. };
  62373. return AudioEngine;
  62374. }());
  62375. BABYLON.AudioEngine = AudioEngine;
  62376. })(BABYLON || (BABYLON = {}));
  62377. //# sourceMappingURL=babylon.audioEngine.js.map
  62378. var BABYLON;
  62379. (function (BABYLON) {
  62380. var Sound = /** @class */ (function () {
  62381. /**
  62382. * Create a sound and attach it to a scene
  62383. * @param name Name of your sound
  62384. * @param urlOrArrayBuffer Url to the sound to load async or ArrayBuffer, it also works with MediaStreams
  62385. * @param readyToPlayCallback Provide a callback function if you'd like to load your code once the sound is ready to be played
  62386. * @param options Objects to provide with the current available options: autoplay, loop, volume, spatialSound, maxDistance, rolloffFactor, refDistance, distanceModel, panningModel, streaming
  62387. */
  62388. function Sound(name, urlOrArrayBuffer, scene, readyToPlayCallback, options) {
  62389. if (readyToPlayCallback === void 0) { readyToPlayCallback = null; }
  62390. var _this = this;
  62391. this.autoplay = false;
  62392. this.loop = false;
  62393. this.useCustomAttenuation = false;
  62394. this.spatialSound = false;
  62395. this.refDistance = 1;
  62396. this.rolloffFactor = 1;
  62397. this.maxDistance = 100;
  62398. this.distanceModel = "linear";
  62399. this._panningModel = "equalpower";
  62400. this._playbackRate = 1;
  62401. this._streaming = false;
  62402. this._startTime = 0;
  62403. this._startOffset = 0;
  62404. this._position = BABYLON.Vector3.Zero();
  62405. this._localDirection = new BABYLON.Vector3(1, 0, 0);
  62406. this._volume = 1;
  62407. this._isReadyToPlay = false;
  62408. this.isPlaying = false;
  62409. this.isPaused = false;
  62410. this._isDirectional = false;
  62411. // Used if you'd like to create a directional sound.
  62412. // If not set, the sound will be omnidirectional
  62413. this._coneInnerAngle = 360;
  62414. this._coneOuterAngle = 360;
  62415. this._coneOuterGain = 0;
  62416. this._isOutputConnected = false;
  62417. this._urlType = "Unknown";
  62418. this.name = name;
  62419. this._scene = scene;
  62420. this._readyToPlayCallback = readyToPlayCallback;
  62421. // Default custom attenuation function is a linear attenuation
  62422. this._customAttenuationFunction = function (currentVolume, currentDistance, maxDistance, refDistance, rolloffFactor) {
  62423. if (currentDistance < maxDistance) {
  62424. return currentVolume * (1 - currentDistance / maxDistance);
  62425. }
  62426. else {
  62427. return 0;
  62428. }
  62429. };
  62430. if (options) {
  62431. this.autoplay = options.autoplay || false;
  62432. this.loop = options.loop || false;
  62433. // if volume === 0, we need another way to check this option
  62434. if (options.volume !== undefined) {
  62435. this._volume = options.volume;
  62436. }
  62437. this.spatialSound = options.spatialSound || false;
  62438. this.maxDistance = options.maxDistance || 100;
  62439. this.useCustomAttenuation = options.useCustomAttenuation || false;
  62440. this.rolloffFactor = options.rolloffFactor || 1;
  62441. this.refDistance = options.refDistance || 1;
  62442. this.distanceModel = options.distanceModel || "linear";
  62443. this._playbackRate = options.playbackRate || 1;
  62444. this._streaming = options.streaming || false;
  62445. }
  62446. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62447. this._soundGain = BABYLON.Engine.audioEngine.audioContext.createGain();
  62448. this._soundGain.gain.value = this._volume;
  62449. this._inputAudioNode = this._soundGain;
  62450. this._ouputAudioNode = this._soundGain;
  62451. if (this.spatialSound) {
  62452. this._createSpatialParameters();
  62453. }
  62454. this._scene.mainSoundTrack.AddSound(this);
  62455. var validParameter = true;
  62456. // if no parameter is passed, you need to call setAudioBuffer yourself to prepare the sound
  62457. if (urlOrArrayBuffer) {
  62458. try {
  62459. if (typeof (urlOrArrayBuffer) === "string") {
  62460. this._urlType = "String";
  62461. }
  62462. else if (urlOrArrayBuffer instanceof ArrayBuffer) {
  62463. this._urlType = "ArrayBuffer";
  62464. }
  62465. else if (urlOrArrayBuffer instanceof MediaStream) {
  62466. this._urlType = "MediaStream";
  62467. }
  62468. else if (Array.isArray(urlOrArrayBuffer)) {
  62469. this._urlType = "Array";
  62470. }
  62471. var urls = [];
  62472. var codecSupportedFound = false;
  62473. switch (this._urlType) {
  62474. case "MediaStream":
  62475. this._streaming = true;
  62476. this._isReadyToPlay = true;
  62477. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaStreamSource(urlOrArrayBuffer);
  62478. if (this.autoplay) {
  62479. this.play();
  62480. }
  62481. if (this._readyToPlayCallback) {
  62482. this._readyToPlayCallback();
  62483. }
  62484. break;
  62485. case "ArrayBuffer":
  62486. if (urlOrArrayBuffer.byteLength > 0) {
  62487. codecSupportedFound = true;
  62488. this._soundLoaded(urlOrArrayBuffer);
  62489. }
  62490. break;
  62491. case "String":
  62492. urls.push(urlOrArrayBuffer);
  62493. case "Array":
  62494. if (urls.length === 0)
  62495. urls = urlOrArrayBuffer;
  62496. // If we found a supported format, we load it immediately and stop the loop
  62497. for (var i = 0; i < urls.length; i++) {
  62498. var url = urls[i];
  62499. if (url.indexOf(".mp3", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isMP3supported) {
  62500. codecSupportedFound = true;
  62501. }
  62502. if (url.indexOf(".ogg", url.length - 4) !== -1 && BABYLON.Engine.audioEngine.isOGGsupported) {
  62503. codecSupportedFound = true;
  62504. }
  62505. if (url.indexOf(".wav", url.length - 4) !== -1) {
  62506. codecSupportedFound = true;
  62507. }
  62508. if (url.indexOf("blob:") !== -1) {
  62509. codecSupportedFound = true;
  62510. }
  62511. if (codecSupportedFound) {
  62512. // Loading sound using XHR2
  62513. if (!this._streaming) {
  62514. this._scene._loadFile(url, function (data) {
  62515. _this._soundLoaded(data);
  62516. }, undefined, true, true, function (exception) {
  62517. if (exception) {
  62518. BABYLON.Tools.Error("XHR " + exception.status + " error on: " + url + ".");
  62519. }
  62520. BABYLON.Tools.Error("Sound creation aborted.");
  62521. _this._scene.mainSoundTrack.RemoveSound(_this);
  62522. });
  62523. }
  62524. // Streaming sound using HTML5 Audio tag
  62525. else {
  62526. this._htmlAudioElement = new Audio(url);
  62527. this._htmlAudioElement.controls = false;
  62528. this._htmlAudioElement.loop = this.loop;
  62529. BABYLON.Tools.SetCorsBehavior(url, this._htmlAudioElement);
  62530. this._htmlAudioElement.preload = "auto";
  62531. this._htmlAudioElement.addEventListener("canplaythrough", function () {
  62532. _this._isReadyToPlay = true;
  62533. if (_this.autoplay) {
  62534. _this.play();
  62535. }
  62536. if (_this._readyToPlayCallback) {
  62537. _this._readyToPlayCallback();
  62538. }
  62539. });
  62540. document.body.appendChild(this._htmlAudioElement);
  62541. }
  62542. break;
  62543. }
  62544. }
  62545. break;
  62546. default:
  62547. validParameter = false;
  62548. break;
  62549. }
  62550. if (!validParameter) {
  62551. BABYLON.Tools.Error("Parameter must be a URL to the sound, an Array of URLs (.mp3 & .ogg) or an ArrayBuffer of the sound.");
  62552. }
  62553. else {
  62554. if (!codecSupportedFound) {
  62555. this._isReadyToPlay = true;
  62556. // Simulating a ready to play event to avoid breaking code path
  62557. if (this._readyToPlayCallback) {
  62558. window.setTimeout(function () {
  62559. if (_this._readyToPlayCallback) {
  62560. _this._readyToPlayCallback();
  62561. }
  62562. }, 1000);
  62563. }
  62564. }
  62565. }
  62566. }
  62567. catch (ex) {
  62568. BABYLON.Tools.Error("Unexpected error. Sound creation aborted.");
  62569. this._scene.mainSoundTrack.RemoveSound(this);
  62570. }
  62571. }
  62572. }
  62573. else {
  62574. // Adding an empty sound to avoid breaking audio calls for non Web Audio browsers
  62575. this._scene.mainSoundTrack.AddSound(this);
  62576. if (!BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported) {
  62577. BABYLON.Tools.Error("Web Audio is not supported by your browser.");
  62578. BABYLON.Engine.audioEngine.WarnedWebAudioUnsupported = true;
  62579. }
  62580. // Simulating a ready to play event to avoid breaking code for non web audio browsers
  62581. if (this._readyToPlayCallback) {
  62582. window.setTimeout(function () {
  62583. if (_this._readyToPlayCallback) {
  62584. _this._readyToPlayCallback();
  62585. }
  62586. }, 1000);
  62587. }
  62588. }
  62589. }
  62590. Sound.prototype.dispose = function () {
  62591. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62592. if (this.isPlaying) {
  62593. this.stop();
  62594. }
  62595. this._isReadyToPlay = false;
  62596. if (this.soundTrackId === -1) {
  62597. this._scene.mainSoundTrack.RemoveSound(this);
  62598. }
  62599. else {
  62600. this._scene.soundTracks[this.soundTrackId].RemoveSound(this);
  62601. }
  62602. if (this._soundGain) {
  62603. this._soundGain.disconnect();
  62604. this._soundGain = null;
  62605. }
  62606. if (this._soundPanner) {
  62607. this._soundPanner.disconnect();
  62608. this._soundPanner = null;
  62609. }
  62610. if (this._soundSource) {
  62611. this._soundSource.disconnect();
  62612. this._soundSource = null;
  62613. }
  62614. this._audioBuffer = null;
  62615. if (this._htmlAudioElement) {
  62616. this._htmlAudioElement.pause();
  62617. this._htmlAudioElement.src = "";
  62618. document.body.removeChild(this._htmlAudioElement);
  62619. }
  62620. if (this._streamingSource) {
  62621. this._streamingSource.disconnect();
  62622. }
  62623. if (this._connectedMesh && this._registerFunc) {
  62624. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62625. this._connectedMesh = null;
  62626. }
  62627. }
  62628. };
  62629. Sound.prototype.isReady = function () {
  62630. return this._isReadyToPlay;
  62631. };
  62632. Sound.prototype._soundLoaded = function (audioData) {
  62633. var _this = this;
  62634. if (!BABYLON.Engine.audioEngine.audioContext) {
  62635. return;
  62636. }
  62637. BABYLON.Engine.audioEngine.audioContext.decodeAudioData(audioData, function (buffer) {
  62638. _this._audioBuffer = buffer;
  62639. _this._isReadyToPlay = true;
  62640. if (_this.autoplay) {
  62641. _this.play();
  62642. }
  62643. if (_this._readyToPlayCallback) {
  62644. _this._readyToPlayCallback();
  62645. }
  62646. }, function (err) { BABYLON.Tools.Error("Error while decoding audio data for: " + _this.name + " / Error: " + err); });
  62647. };
  62648. Sound.prototype.setAudioBuffer = function (audioBuffer) {
  62649. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62650. this._audioBuffer = audioBuffer;
  62651. this._isReadyToPlay = true;
  62652. }
  62653. };
  62654. Sound.prototype.updateOptions = function (options) {
  62655. if (options) {
  62656. this.loop = options.loop || this.loop;
  62657. this.maxDistance = options.maxDistance || this.maxDistance;
  62658. this.useCustomAttenuation = options.useCustomAttenuation || this.useCustomAttenuation;
  62659. this.rolloffFactor = options.rolloffFactor || this.rolloffFactor;
  62660. this.refDistance = options.refDistance || this.refDistance;
  62661. this.distanceModel = options.distanceModel || this.distanceModel;
  62662. this._playbackRate = options.playbackRate || this._playbackRate;
  62663. this._updateSpatialParameters();
  62664. if (this.isPlaying) {
  62665. if (this._streaming && this._htmlAudioElement) {
  62666. this._htmlAudioElement.playbackRate = this._playbackRate;
  62667. }
  62668. else {
  62669. if (this._soundSource) {
  62670. this._soundSource.playbackRate.value = this._playbackRate;
  62671. }
  62672. }
  62673. }
  62674. }
  62675. };
  62676. Sound.prototype._createSpatialParameters = function () {
  62677. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  62678. if (this._scene.headphone) {
  62679. this._panningModel = "HRTF";
  62680. }
  62681. this._soundPanner = BABYLON.Engine.audioEngine.audioContext.createPanner();
  62682. this._updateSpatialParameters();
  62683. this._soundPanner.connect(this._ouputAudioNode);
  62684. this._inputAudioNode = this._soundPanner;
  62685. }
  62686. };
  62687. Sound.prototype._updateSpatialParameters = function () {
  62688. if (this.spatialSound && this._soundPanner) {
  62689. if (this.useCustomAttenuation) {
  62690. // Tricks to disable in a way embedded Web Audio attenuation
  62691. this._soundPanner.distanceModel = "linear";
  62692. this._soundPanner.maxDistance = Number.MAX_VALUE;
  62693. this._soundPanner.refDistance = 1;
  62694. this._soundPanner.rolloffFactor = 1;
  62695. this._soundPanner.panningModel = this._panningModel;
  62696. }
  62697. else {
  62698. this._soundPanner.distanceModel = this.distanceModel;
  62699. this._soundPanner.maxDistance = this.maxDistance;
  62700. this._soundPanner.refDistance = this.refDistance;
  62701. this._soundPanner.rolloffFactor = this.rolloffFactor;
  62702. this._soundPanner.panningModel = this._panningModel;
  62703. }
  62704. }
  62705. };
  62706. Sound.prototype.switchPanningModelToHRTF = function () {
  62707. this._panningModel = "HRTF";
  62708. this._switchPanningModel();
  62709. };
  62710. Sound.prototype.switchPanningModelToEqualPower = function () {
  62711. this._panningModel = "equalpower";
  62712. this._switchPanningModel();
  62713. };
  62714. Sound.prototype._switchPanningModel = function () {
  62715. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62716. this._soundPanner.panningModel = this._panningModel;
  62717. }
  62718. };
  62719. Sound.prototype.connectToSoundTrackAudioNode = function (soundTrackAudioNode) {
  62720. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  62721. if (this._isOutputConnected) {
  62722. this._ouputAudioNode.disconnect();
  62723. }
  62724. this._ouputAudioNode.connect(soundTrackAudioNode);
  62725. this._isOutputConnected = true;
  62726. }
  62727. };
  62728. /**
  62729. * Transform this sound into a directional source
  62730. * @param coneInnerAngle Size of the inner cone in degree
  62731. * @param coneOuterAngle Size of the outer cone in degree
  62732. * @param coneOuterGain Volume of the sound outside the outer cone (between 0.0 and 1.0)
  62733. */
  62734. Sound.prototype.setDirectionalCone = function (coneInnerAngle, coneOuterAngle, coneOuterGain) {
  62735. if (coneOuterAngle < coneInnerAngle) {
  62736. BABYLON.Tools.Error("setDirectionalCone(): outer angle of the cone must be superior or equal to the inner angle.");
  62737. return;
  62738. }
  62739. this._coneInnerAngle = coneInnerAngle;
  62740. this._coneOuterAngle = coneOuterAngle;
  62741. this._coneOuterGain = coneOuterGain;
  62742. this._isDirectional = true;
  62743. if (this.isPlaying && this.loop) {
  62744. this.stop();
  62745. this.play();
  62746. }
  62747. };
  62748. Sound.prototype.setPosition = function (newPosition) {
  62749. this._position = newPosition;
  62750. if (BABYLON.Engine.audioEngine.canUseWebAudio && this.spatialSound && this._soundPanner) {
  62751. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62752. }
  62753. };
  62754. Sound.prototype.setLocalDirectionToMesh = function (newLocalDirection) {
  62755. this._localDirection = newLocalDirection;
  62756. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.isPlaying) {
  62757. this._updateDirection();
  62758. }
  62759. };
  62760. Sound.prototype._updateDirection = function () {
  62761. if (!this._connectedMesh || !this._soundPanner) {
  62762. return;
  62763. }
  62764. var mat = this._connectedMesh.getWorldMatrix();
  62765. var direction = BABYLON.Vector3.TransformNormal(this._localDirection, mat);
  62766. direction.normalize();
  62767. this._soundPanner.setOrientation(direction.x, direction.y, direction.z);
  62768. };
  62769. Sound.prototype.updateDistanceFromListener = function () {
  62770. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._connectedMesh && this.useCustomAttenuation && this._soundGain && this._scene.activeCamera) {
  62771. var distance = this._connectedMesh.getDistanceToCamera(this._scene.activeCamera);
  62772. this._soundGain.gain.value = this._customAttenuationFunction(this._volume, distance, this.maxDistance, this.refDistance, this.rolloffFactor);
  62773. }
  62774. };
  62775. Sound.prototype.setAttenuationFunction = function (callback) {
  62776. this._customAttenuationFunction = callback;
  62777. };
  62778. /**
  62779. * Play the sound
  62780. * @param time (optional) Start the sound after X seconds. Start immediately (0) by default.
  62781. * @param offset (optional) Start the sound setting it at a specific time
  62782. */
  62783. Sound.prototype.play = function (time, offset) {
  62784. var _this = this;
  62785. if (this._isReadyToPlay && this._scene.audioEnabled && BABYLON.Engine.audioEngine.audioContext) {
  62786. try {
  62787. if (this._startOffset < 0) {
  62788. time = -this._startOffset;
  62789. this._startOffset = 0;
  62790. }
  62791. var startTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62792. if (!this._soundSource || !this._streamingSource) {
  62793. if (this.spatialSound && this._soundPanner) {
  62794. this._soundPanner.setPosition(this._position.x, this._position.y, this._position.z);
  62795. if (this._isDirectional) {
  62796. this._soundPanner.coneInnerAngle = this._coneInnerAngle;
  62797. this._soundPanner.coneOuterAngle = this._coneOuterAngle;
  62798. this._soundPanner.coneOuterGain = this._coneOuterGain;
  62799. if (this._connectedMesh) {
  62800. this._updateDirection();
  62801. }
  62802. else {
  62803. this._soundPanner.setOrientation(this._localDirection.x, this._localDirection.y, this._localDirection.z);
  62804. }
  62805. }
  62806. }
  62807. }
  62808. if (this._streaming) {
  62809. if (!this._streamingSource) {
  62810. this._streamingSource = BABYLON.Engine.audioEngine.audioContext.createMediaElementSource(this._htmlAudioElement);
  62811. this._htmlAudioElement.onended = function () { _this._onended(); };
  62812. this._htmlAudioElement.playbackRate = this._playbackRate;
  62813. }
  62814. this._streamingSource.disconnect();
  62815. this._streamingSource.connect(this._inputAudioNode);
  62816. if (this._htmlAudioElement) {
  62817. this._htmlAudioElement.play();
  62818. }
  62819. }
  62820. else {
  62821. this._soundSource = BABYLON.Engine.audioEngine.audioContext.createBufferSource();
  62822. this._soundSource.buffer = this._audioBuffer;
  62823. this._soundSource.connect(this._inputAudioNode);
  62824. this._soundSource.loop = this.loop;
  62825. this._soundSource.playbackRate.value = this._playbackRate;
  62826. this._soundSource.onended = function () { _this._onended(); };
  62827. if (this._soundSource.buffer) {
  62828. this._soundSource.start(startTime, this.isPaused ? this._startOffset % this._soundSource.buffer.duration : offset ? offset : 0);
  62829. }
  62830. }
  62831. this._startTime = startTime;
  62832. this.isPlaying = true;
  62833. this.isPaused = false;
  62834. }
  62835. catch (ex) {
  62836. BABYLON.Tools.Error("Error while trying to play audio: " + this.name + ", " + ex.message);
  62837. }
  62838. }
  62839. };
  62840. Sound.prototype._onended = function () {
  62841. this.isPlaying = false;
  62842. if (this.onended) {
  62843. this.onended();
  62844. }
  62845. };
  62846. /**
  62847. * Stop the sound
  62848. * @param time (optional) Stop the sound after X seconds. Stop immediately (0) by default.
  62849. */
  62850. Sound.prototype.stop = function (time) {
  62851. if (this.isPlaying) {
  62852. if (this._streaming) {
  62853. if (this._htmlAudioElement) {
  62854. this._htmlAudioElement.pause();
  62855. // Test needed for Firefox or it will generate an Invalid State Error
  62856. if (this._htmlAudioElement.currentTime > 0) {
  62857. this._htmlAudioElement.currentTime = 0;
  62858. }
  62859. }
  62860. else {
  62861. this._streamingSource.disconnect();
  62862. }
  62863. }
  62864. else if (BABYLON.Engine.audioEngine.audioContext && this._soundSource) {
  62865. var stopTime = time ? BABYLON.Engine.audioEngine.audioContext.currentTime + time : BABYLON.Engine.audioEngine.audioContext.currentTime;
  62866. this._soundSource.stop(stopTime);
  62867. this._soundSource.onended = function () { };
  62868. if (!this.isPaused) {
  62869. this._startOffset = 0;
  62870. }
  62871. }
  62872. this.isPlaying = false;
  62873. }
  62874. };
  62875. Sound.prototype.pause = function () {
  62876. if (this.isPlaying) {
  62877. this.isPaused = true;
  62878. if (this._streaming) {
  62879. if (this._htmlAudioElement) {
  62880. this._htmlAudioElement.pause();
  62881. }
  62882. else {
  62883. this._streamingSource.disconnect();
  62884. }
  62885. }
  62886. else if (BABYLON.Engine.audioEngine.audioContext) {
  62887. this.stop(0);
  62888. this._startOffset += BABYLON.Engine.audioEngine.audioContext.currentTime - this._startTime;
  62889. }
  62890. }
  62891. };
  62892. Sound.prototype.setVolume = function (newVolume, time) {
  62893. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._soundGain) {
  62894. if (time && BABYLON.Engine.audioEngine.audioContext) {
  62895. this._soundGain.gain.cancelScheduledValues(BABYLON.Engine.audioEngine.audioContext.currentTime);
  62896. this._soundGain.gain.setValueAtTime(this._soundGain.gain.value, BABYLON.Engine.audioEngine.audioContext.currentTime);
  62897. this._soundGain.gain.linearRampToValueAtTime(newVolume, BABYLON.Engine.audioEngine.audioContext.currentTime + time);
  62898. }
  62899. else {
  62900. this._soundGain.gain.value = newVolume;
  62901. }
  62902. }
  62903. this._volume = newVolume;
  62904. };
  62905. Sound.prototype.setPlaybackRate = function (newPlaybackRate) {
  62906. this._playbackRate = newPlaybackRate;
  62907. if (this.isPlaying) {
  62908. if (this._streaming && this._htmlAudioElement) {
  62909. this._htmlAudioElement.playbackRate = this._playbackRate;
  62910. }
  62911. else if (this._soundSource) {
  62912. this._soundSource.playbackRate.value = this._playbackRate;
  62913. }
  62914. }
  62915. };
  62916. Sound.prototype.getVolume = function () {
  62917. return this._volume;
  62918. };
  62919. Sound.prototype.attachToMesh = function (meshToConnectTo) {
  62920. var _this = this;
  62921. if (this._connectedMesh && this._registerFunc) {
  62922. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62923. this._registerFunc = null;
  62924. }
  62925. this._connectedMesh = meshToConnectTo;
  62926. if (!this.spatialSound) {
  62927. this.spatialSound = true;
  62928. this._createSpatialParameters();
  62929. if (this.isPlaying && this.loop) {
  62930. this.stop();
  62931. this.play();
  62932. }
  62933. }
  62934. this._onRegisterAfterWorldMatrixUpdate(this._connectedMesh);
  62935. this._registerFunc = function (connectedMesh) { return _this._onRegisterAfterWorldMatrixUpdate(connectedMesh); };
  62936. meshToConnectTo.registerAfterWorldMatrixUpdate(this._registerFunc);
  62937. };
  62938. Sound.prototype.detachFromMesh = function () {
  62939. if (this._connectedMesh && this._registerFunc) {
  62940. this._connectedMesh.unregisterAfterWorldMatrixUpdate(this._registerFunc);
  62941. this._registerFunc = null;
  62942. this._connectedMesh = null;
  62943. }
  62944. };
  62945. Sound.prototype._onRegisterAfterWorldMatrixUpdate = function (node) {
  62946. if (!node.getBoundingInfo) {
  62947. return;
  62948. }
  62949. var mesh = node;
  62950. var boundingInfo = mesh.getBoundingInfo();
  62951. this.setPosition(boundingInfo.boundingSphere.centerWorld);
  62952. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._isDirectional && this.isPlaying) {
  62953. this._updateDirection();
  62954. }
  62955. };
  62956. Sound.prototype.clone = function () {
  62957. var _this = this;
  62958. if (!this._streaming) {
  62959. var setBufferAndRun = function () {
  62960. if (_this._isReadyToPlay) {
  62961. clonedSound._audioBuffer = _this.getAudioBuffer();
  62962. clonedSound._isReadyToPlay = true;
  62963. if (clonedSound.autoplay) {
  62964. clonedSound.play();
  62965. }
  62966. }
  62967. else {
  62968. window.setTimeout(setBufferAndRun, 300);
  62969. }
  62970. };
  62971. var currentOptions = {
  62972. autoplay: this.autoplay, loop: this.loop,
  62973. volume: this._volume, spatialSound: this.spatialSound, maxDistance: this.maxDistance,
  62974. useCustomAttenuation: this.useCustomAttenuation, rolloffFactor: this.rolloffFactor,
  62975. refDistance: this.refDistance, distanceModel: this.distanceModel
  62976. };
  62977. var clonedSound = new Sound(this.name + "_cloned", new ArrayBuffer(0), this._scene, null, currentOptions);
  62978. if (this.useCustomAttenuation) {
  62979. clonedSound.setAttenuationFunction(this._customAttenuationFunction);
  62980. }
  62981. clonedSound.setPosition(this._position);
  62982. clonedSound.setPlaybackRate(this._playbackRate);
  62983. setBufferAndRun();
  62984. return clonedSound;
  62985. }
  62986. // Can't clone a streaming sound
  62987. else {
  62988. return null;
  62989. }
  62990. };
  62991. Sound.prototype.getAudioBuffer = function () {
  62992. return this._audioBuffer;
  62993. };
  62994. Sound.prototype.serialize = function () {
  62995. var serializationObject = {
  62996. name: this.name,
  62997. url: this.name,
  62998. autoplay: this.autoplay,
  62999. loop: this.loop,
  63000. volume: this._volume,
  63001. spatialSound: this.spatialSound,
  63002. maxDistance: this.maxDistance,
  63003. rolloffFactor: this.rolloffFactor,
  63004. refDistance: this.refDistance,
  63005. distanceModel: this.distanceModel,
  63006. playbackRate: this._playbackRate,
  63007. panningModel: this._panningModel,
  63008. soundTrackId: this.soundTrackId
  63009. };
  63010. if (this.spatialSound) {
  63011. if (this._connectedMesh)
  63012. serializationObject.connectedMeshId = this._connectedMesh.id;
  63013. serializationObject.position = this._position.asArray();
  63014. serializationObject.refDistance = this.refDistance;
  63015. serializationObject.distanceModel = this.distanceModel;
  63016. serializationObject.isDirectional = this._isDirectional;
  63017. serializationObject.localDirectionToMesh = this._localDirection.asArray();
  63018. serializationObject.coneInnerAngle = this._coneInnerAngle;
  63019. serializationObject.coneOuterAngle = this._coneOuterAngle;
  63020. serializationObject.coneOuterGain = this._coneOuterGain;
  63021. }
  63022. return serializationObject;
  63023. };
  63024. Sound.Parse = function (parsedSound, scene, rootUrl, sourceSound) {
  63025. var soundName = parsedSound.name;
  63026. var soundUrl;
  63027. if (parsedSound.url) {
  63028. soundUrl = rootUrl + parsedSound.url;
  63029. }
  63030. else {
  63031. soundUrl = rootUrl + soundName;
  63032. }
  63033. var options = {
  63034. autoplay: parsedSound.autoplay, loop: parsedSound.loop, volume: parsedSound.volume,
  63035. spatialSound: parsedSound.spatialSound, maxDistance: parsedSound.maxDistance,
  63036. rolloffFactor: parsedSound.rolloffFactor,
  63037. refDistance: parsedSound.refDistance,
  63038. distanceModel: parsedSound.distanceModel,
  63039. playbackRate: parsedSound.playbackRate
  63040. };
  63041. var newSound;
  63042. if (!sourceSound) {
  63043. newSound = new Sound(soundName, soundUrl, scene, function () { scene._removePendingData(newSound); }, options);
  63044. scene._addPendingData(newSound);
  63045. }
  63046. else {
  63047. var setBufferAndRun = function () {
  63048. if (sourceSound._isReadyToPlay) {
  63049. newSound._audioBuffer = sourceSound.getAudioBuffer();
  63050. newSound._isReadyToPlay = true;
  63051. if (newSound.autoplay) {
  63052. newSound.play();
  63053. }
  63054. }
  63055. else {
  63056. window.setTimeout(setBufferAndRun, 300);
  63057. }
  63058. };
  63059. newSound = new Sound(soundName, new ArrayBuffer(0), scene, null, options);
  63060. setBufferAndRun();
  63061. }
  63062. if (parsedSound.position) {
  63063. var soundPosition = BABYLON.Vector3.FromArray(parsedSound.position);
  63064. newSound.setPosition(soundPosition);
  63065. }
  63066. if (parsedSound.isDirectional) {
  63067. newSound.setDirectionalCone(parsedSound.coneInnerAngle || 360, parsedSound.coneOuterAngle || 360, parsedSound.coneOuterGain || 0);
  63068. if (parsedSound.localDirectionToMesh) {
  63069. var localDirectionToMesh = BABYLON.Vector3.FromArray(parsedSound.localDirectionToMesh);
  63070. newSound.setLocalDirectionToMesh(localDirectionToMesh);
  63071. }
  63072. }
  63073. if (parsedSound.connectedMeshId) {
  63074. var connectedMesh = scene.getMeshByID(parsedSound.connectedMeshId);
  63075. if (connectedMesh) {
  63076. newSound.attachToMesh(connectedMesh);
  63077. }
  63078. }
  63079. return newSound;
  63080. };
  63081. return Sound;
  63082. }());
  63083. BABYLON.Sound = Sound;
  63084. })(BABYLON || (BABYLON = {}));
  63085. //# sourceMappingURL=babylon.sound.js.map
  63086. var BABYLON;
  63087. (function (BABYLON) {
  63088. var SoundTrack = /** @class */ (function () {
  63089. function SoundTrack(scene, options) {
  63090. this.id = -1;
  63091. this._isMainTrack = false;
  63092. this._isInitialized = false;
  63093. this._scene = scene;
  63094. this.soundCollection = new Array();
  63095. this._options = options;
  63096. if (!this._isMainTrack) {
  63097. this._scene.soundTracks.push(this);
  63098. this.id = this._scene.soundTracks.length - 1;
  63099. }
  63100. }
  63101. SoundTrack.prototype._initializeSoundTrackAudioGraph = function () {
  63102. if (BABYLON.Engine.audioEngine.canUseWebAudio && BABYLON.Engine.audioEngine.audioContext) {
  63103. this._outputAudioNode = BABYLON.Engine.audioEngine.audioContext.createGain();
  63104. this._outputAudioNode.connect(BABYLON.Engine.audioEngine.masterGain);
  63105. if (this._options) {
  63106. if (this._options.volume) {
  63107. this._outputAudioNode.gain.value = this._options.volume;
  63108. }
  63109. if (this._options.mainTrack) {
  63110. this._isMainTrack = this._options.mainTrack;
  63111. }
  63112. }
  63113. this._isInitialized = true;
  63114. }
  63115. };
  63116. SoundTrack.prototype.dispose = function () {
  63117. if (BABYLON.Engine.audioEngine && BABYLON.Engine.audioEngine.canUseWebAudio) {
  63118. if (this._connectedAnalyser) {
  63119. this._connectedAnalyser.stopDebugCanvas();
  63120. }
  63121. while (this.soundCollection.length) {
  63122. this.soundCollection[0].dispose();
  63123. }
  63124. if (this._outputAudioNode) {
  63125. this._outputAudioNode.disconnect();
  63126. }
  63127. this._outputAudioNode = null;
  63128. }
  63129. };
  63130. SoundTrack.prototype.AddSound = function (sound) {
  63131. if (!this._isInitialized) {
  63132. this._initializeSoundTrackAudioGraph();
  63133. }
  63134. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63135. sound.connectToSoundTrackAudioNode(this._outputAudioNode);
  63136. }
  63137. if (sound.soundTrackId) {
  63138. if (sound.soundTrackId === -1) {
  63139. this._scene.mainSoundTrack.RemoveSound(sound);
  63140. }
  63141. else {
  63142. this._scene.soundTracks[sound.soundTrackId].RemoveSound(sound);
  63143. }
  63144. }
  63145. this.soundCollection.push(sound);
  63146. sound.soundTrackId = this.id;
  63147. };
  63148. SoundTrack.prototype.RemoveSound = function (sound) {
  63149. var index = this.soundCollection.indexOf(sound);
  63150. if (index !== -1) {
  63151. this.soundCollection.splice(index, 1);
  63152. }
  63153. };
  63154. SoundTrack.prototype.setVolume = function (newVolume) {
  63155. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63156. this._outputAudioNode.gain.value = newVolume;
  63157. }
  63158. };
  63159. SoundTrack.prototype.switchPanningModelToHRTF = function () {
  63160. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63161. for (var i = 0; i < this.soundCollection.length; i++) {
  63162. this.soundCollection[i].switchPanningModelToHRTF();
  63163. }
  63164. }
  63165. };
  63166. SoundTrack.prototype.switchPanningModelToEqualPower = function () {
  63167. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  63168. for (var i = 0; i < this.soundCollection.length; i++) {
  63169. this.soundCollection[i].switchPanningModelToEqualPower();
  63170. }
  63171. }
  63172. };
  63173. SoundTrack.prototype.connectToAnalyser = function (analyser) {
  63174. if (this._connectedAnalyser) {
  63175. this._connectedAnalyser.stopDebugCanvas();
  63176. }
  63177. this._connectedAnalyser = analyser;
  63178. if (BABYLON.Engine.audioEngine.canUseWebAudio && this._outputAudioNode) {
  63179. this._outputAudioNode.disconnect();
  63180. this._connectedAnalyser.connectAudioNodes(this._outputAudioNode, BABYLON.Engine.audioEngine.masterGain);
  63181. }
  63182. };
  63183. return SoundTrack;
  63184. }());
  63185. BABYLON.SoundTrack = SoundTrack;
  63186. })(BABYLON || (BABYLON = {}));
  63187. //# sourceMappingURL=babylon.soundtrack.js.map
  63188. var BABYLON;
  63189. (function (BABYLON) {
  63190. /**
  63191. * Class used to work with sound analyzer using fast fourier transform (FFT)
  63192. * @see http://doc.babylonjs.com/how_to/playing_sounds_and_music
  63193. */
  63194. var Analyser = /** @class */ (function () {
  63195. /**
  63196. * Creates a new analyser
  63197. * @param scene defines hosting scene
  63198. */
  63199. function Analyser(scene) {
  63200. /**
  63201. * Gets or sets the smoothing
  63202. * @ignorenaming
  63203. */
  63204. this.SMOOTHING = 0.75;
  63205. /**
  63206. * Gets or sets the FFT table size
  63207. * @ignorenaming
  63208. */
  63209. this.FFT_SIZE = 512;
  63210. /**
  63211. * Gets or sets the bar graph amplitude
  63212. * @ignorenaming
  63213. */
  63214. this.BARGRAPHAMPLITUDE = 256;
  63215. /**
  63216. * Gets or sets the position of the debug canvas
  63217. * @ignorenaming
  63218. */
  63219. this.DEBUGCANVASPOS = { x: 20, y: 20 };
  63220. /**
  63221. * Gets or sets the debug canvas size
  63222. * @ignorenaming
  63223. */
  63224. this.DEBUGCANVASSIZE = { width: 320, height: 200 };
  63225. this._scene = scene;
  63226. this._audioEngine = BABYLON.Engine.audioEngine;
  63227. if (this._audioEngine.canUseWebAudio && this._audioEngine.audioContext) {
  63228. this._webAudioAnalyser = this._audioEngine.audioContext.createAnalyser();
  63229. this._webAudioAnalyser.minDecibels = -140;
  63230. this._webAudioAnalyser.maxDecibels = 0;
  63231. this._byteFreqs = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63232. this._byteTime = new Uint8Array(this._webAudioAnalyser.frequencyBinCount);
  63233. this._floatFreqs = new Float32Array(this._webAudioAnalyser.frequencyBinCount);
  63234. }
  63235. }
  63236. /**
  63237. * Get the number of data values you will have to play with for the visualization
  63238. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/frequencyBinCount
  63239. * @returns a number
  63240. */
  63241. Analyser.prototype.getFrequencyBinCount = function () {
  63242. if (this._audioEngine.canUseWebAudio) {
  63243. return this._webAudioAnalyser.frequencyBinCount;
  63244. }
  63245. else {
  63246. return 0;
  63247. }
  63248. };
  63249. /**
  63250. * Gets the current frequency data as a byte array
  63251. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63252. * @returns a Uint8Array
  63253. */
  63254. Analyser.prototype.getByteFrequencyData = function () {
  63255. if (this._audioEngine.canUseWebAudio) {
  63256. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63257. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63258. this._webAudioAnalyser.getByteFrequencyData(this._byteFreqs);
  63259. }
  63260. return this._byteFreqs;
  63261. };
  63262. /**
  63263. * Gets the current waveform as a byte array
  63264. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteTimeDomainData
  63265. * @returns a Uint8Array
  63266. */
  63267. Analyser.prototype.getByteTimeDomainData = function () {
  63268. if (this._audioEngine.canUseWebAudio) {
  63269. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63270. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63271. this._webAudioAnalyser.getByteTimeDomainData(this._byteTime);
  63272. }
  63273. return this._byteTime;
  63274. };
  63275. /**
  63276. * Gets the current frequency data as a float array
  63277. * @see https://developer.mozilla.org/en-US/docs/Web/API/AnalyserNode/getByteFrequencyData
  63278. * @returns a Float32Array
  63279. */
  63280. Analyser.prototype.getFloatFrequencyData = function () {
  63281. if (this._audioEngine.canUseWebAudio) {
  63282. this._webAudioAnalyser.smoothingTimeConstant = this.SMOOTHING;
  63283. this._webAudioAnalyser.fftSize = this.FFT_SIZE;
  63284. this._webAudioAnalyser.getFloatFrequencyData(this._floatFreqs);
  63285. }
  63286. return this._floatFreqs;
  63287. };
  63288. /**
  63289. * Renders the debug canvas
  63290. */
  63291. Analyser.prototype.drawDebugCanvas = function () {
  63292. var _this = this;
  63293. if (this._audioEngine.canUseWebAudio) {
  63294. if (!this._debugCanvas) {
  63295. this._debugCanvas = document.createElement("canvas");
  63296. this._debugCanvas.width = this.DEBUGCANVASSIZE.width;
  63297. this._debugCanvas.height = this.DEBUGCANVASSIZE.height;
  63298. this._debugCanvas.style.position = "absolute";
  63299. this._debugCanvas.style.top = this.DEBUGCANVASPOS.y + "px";
  63300. this._debugCanvas.style.left = this.DEBUGCANVASPOS.x + "px";
  63301. this._debugCanvasContext = this._debugCanvas.getContext("2d");
  63302. document.body.appendChild(this._debugCanvas);
  63303. this._registerFunc = function () {
  63304. _this.drawDebugCanvas();
  63305. };
  63306. this._scene.registerBeforeRender(this._registerFunc);
  63307. }
  63308. if (this._registerFunc && this._debugCanvasContext) {
  63309. var workingArray = this.getByteFrequencyData();
  63310. this._debugCanvasContext.fillStyle = 'rgb(0, 0, 0)';
  63311. this._debugCanvasContext.fillRect(0, 0, this.DEBUGCANVASSIZE.width, this.DEBUGCANVASSIZE.height);
  63312. // Draw the frequency domain chart.
  63313. for (var i = 0; i < this.getFrequencyBinCount(); i++) {
  63314. var value = workingArray[i];
  63315. var percent = value / this.BARGRAPHAMPLITUDE;
  63316. var height = this.DEBUGCANVASSIZE.height * percent;
  63317. var offset = this.DEBUGCANVASSIZE.height - height - 1;
  63318. var barWidth = this.DEBUGCANVASSIZE.width / this.getFrequencyBinCount();
  63319. var hue = i / this.getFrequencyBinCount() * 360;
  63320. this._debugCanvasContext.fillStyle = 'hsl(' + hue + ', 100%, 50%)';
  63321. this._debugCanvasContext.fillRect(i * barWidth, offset, barWidth, height);
  63322. }
  63323. }
  63324. }
  63325. };
  63326. /**
  63327. * Stops rendering the debug canvas and removes it
  63328. */
  63329. Analyser.prototype.stopDebugCanvas = function () {
  63330. if (this._debugCanvas) {
  63331. if (this._registerFunc) {
  63332. this._scene.unregisterBeforeRender(this._registerFunc);
  63333. this._registerFunc = null;
  63334. }
  63335. document.body.removeChild(this._debugCanvas);
  63336. this._debugCanvas = null;
  63337. this._debugCanvasContext = null;
  63338. }
  63339. };
  63340. /**
  63341. * Connects two audio nodes
  63342. * @param inputAudioNode defines first node to connect
  63343. * @param outputAudioNode defines second node to connect
  63344. */
  63345. Analyser.prototype.connectAudioNodes = function (inputAudioNode, outputAudioNode) {
  63346. if (this._audioEngine.canUseWebAudio) {
  63347. inputAudioNode.connect(this._webAudioAnalyser);
  63348. this._webAudioAnalyser.connect(outputAudioNode);
  63349. }
  63350. };
  63351. /**
  63352. * Releases all associated resources
  63353. */
  63354. Analyser.prototype.dispose = function () {
  63355. if (this._audioEngine.canUseWebAudio) {
  63356. this._webAudioAnalyser.disconnect();
  63357. }
  63358. };
  63359. return Analyser;
  63360. }());
  63361. BABYLON.Analyser = Analyser;
  63362. })(BABYLON || (BABYLON = {}));
  63363. //# sourceMappingURL=babylon.analyser.js.map
  63364. var BABYLON;
  63365. (function (BABYLON) {
  63366. var CubeTexture = /** @class */ (function (_super) {
  63367. __extends(CubeTexture, _super);
  63368. /**
  63369. * Creates a cube texture to use with reflection for instance. It can be based upon dds or six images as well
  63370. * as prefiltered data.
  63371. * @param rootUrl defines the url of the texture or the root name of the six images
  63372. * @param scene defines the scene the texture is attached to
  63373. * @param extensions defines the suffixes add to the picture name in case six images are in use like _px.jpg...
  63374. * @param noMipmap defines if mipmaps should be created or not
  63375. * @param files defines the six files to load for the different faces
  63376. * @param onLoad defines a callback triggered at the end of the file load if no errors occured
  63377. * @param onError defines a callback triggered in case of error during load
  63378. * @param format defines the internal format to use for the texture once loaded
  63379. * @param prefiltered defines whether or not the texture is created from prefiltered data
  63380. * @param forcedExtension defines the extensions to use (force a special type of file to load) in case it is different from the file name
  63381. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63382. * @param lodScale defines the scale applied to environment texture. This manages the range of LOD level used for IBL according to the roughness
  63383. * @param lodOffset defines the offset applied to environment texture. This manages first LOD level used for IBL according to the roughness
  63384. * @return the cube texture
  63385. */
  63386. function CubeTexture(rootUrl, scene, extensions, noMipmap, files, onLoad, onError, format, prefiltered, forcedExtension, createPolynomials, lodScale, lodOffset) {
  63387. if (extensions === void 0) { extensions = null; }
  63388. if (noMipmap === void 0) { noMipmap = false; }
  63389. if (files === void 0) { files = null; }
  63390. if (onLoad === void 0) { onLoad = null; }
  63391. if (onError === void 0) { onError = null; }
  63392. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63393. if (prefiltered === void 0) { prefiltered = false; }
  63394. if (forcedExtension === void 0) { forcedExtension = null; }
  63395. if (createPolynomials === void 0) { createPolynomials = false; }
  63396. if (lodScale === void 0) { lodScale = 0.8; }
  63397. if (lodOffset === void 0) { lodOffset = 0; }
  63398. var _this = _super.call(this, scene) || this;
  63399. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  63400. /**
  63401. * Gets or sets the center of the bounding box associated with the cube texture
  63402. * It must define where the camera used to render the texture was set
  63403. */
  63404. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63405. _this._rotationY = 0;
  63406. /** @hidden */
  63407. _this._prefiltered = false;
  63408. _this.name = rootUrl;
  63409. _this.url = rootUrl;
  63410. _this._noMipmap = noMipmap;
  63411. _this.hasAlpha = false;
  63412. _this._format = format;
  63413. _this.isCube = true;
  63414. _this._textureMatrix = BABYLON.Matrix.Identity();
  63415. _this._createPolynomials = createPolynomials;
  63416. if (!rootUrl && !files) {
  63417. return _this;
  63418. }
  63419. var lastDot = rootUrl.lastIndexOf(".");
  63420. var extension = forcedExtension ? forcedExtension : (lastDot > -1 ? rootUrl.substring(lastDot).toLowerCase() : "");
  63421. var isDDS = (extension === ".dds");
  63422. var isEnv = (extension === ".env");
  63423. if (isEnv) {
  63424. _this.gammaSpace = false;
  63425. _this._prefiltered = false;
  63426. }
  63427. else {
  63428. _this._prefiltered = prefiltered;
  63429. if (prefiltered) {
  63430. _this.gammaSpace = false;
  63431. }
  63432. }
  63433. _this._texture = _this._getFromCache(rootUrl, noMipmap);
  63434. if (!files) {
  63435. if (!isEnv && !isDDS && !extensions) {
  63436. extensions = ["_px.jpg", "_py.jpg", "_pz.jpg", "_nx.jpg", "_ny.jpg", "_nz.jpg"];
  63437. }
  63438. files = [];
  63439. if (extensions) {
  63440. for (var index = 0; index < extensions.length; index++) {
  63441. files.push(rootUrl + extensions[index]);
  63442. }
  63443. }
  63444. }
  63445. _this._files = files;
  63446. if (!_this._texture) {
  63447. if (!scene.useDelayedTextureLoading) {
  63448. if (prefiltered) {
  63449. _this._texture = scene.getEngine().createPrefilteredCubeTexture(rootUrl, scene, lodScale, lodOffset, onLoad, onError, format, forcedExtension, _this._createPolynomials);
  63450. }
  63451. else {
  63452. _this._texture = scene.getEngine().createCubeTexture(rootUrl, scene, files, noMipmap, onLoad, onError, _this._format, forcedExtension, false, lodScale, lodOffset);
  63453. }
  63454. }
  63455. else {
  63456. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  63457. }
  63458. }
  63459. else if (onLoad) {
  63460. if (_this._texture.isReady) {
  63461. BABYLON.Tools.SetImmediate(function () { return onLoad(); });
  63462. }
  63463. else {
  63464. _this._texture.onLoadedObservable.add(onLoad);
  63465. }
  63466. }
  63467. return _this;
  63468. }
  63469. Object.defineProperty(CubeTexture.prototype, "boundingBoxSize", {
  63470. get: function () {
  63471. return this._boundingBoxSize;
  63472. },
  63473. /**
  63474. * Gets or sets the size of the bounding box associated with the cube texture
  63475. * When defined, the cubemap will switch to local mode
  63476. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63477. * @example https://www.babylonjs-playground.com/#RNASML
  63478. */
  63479. set: function (value) {
  63480. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63481. return;
  63482. }
  63483. this._boundingBoxSize = value;
  63484. var scene = this.getScene();
  63485. if (scene) {
  63486. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63487. }
  63488. },
  63489. enumerable: true,
  63490. configurable: true
  63491. });
  63492. Object.defineProperty(CubeTexture.prototype, "rotationY", {
  63493. /**
  63494. * Gets texture matrix rotation angle around Y axis radians.
  63495. */
  63496. get: function () {
  63497. return this._rotationY;
  63498. },
  63499. /**
  63500. * Sets texture matrix rotation angle around Y axis in radians.
  63501. */
  63502. set: function (value) {
  63503. this._rotationY = value;
  63504. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  63505. },
  63506. enumerable: true,
  63507. configurable: true
  63508. });
  63509. CubeTexture.CreateFromImages = function (files, scene, noMipmap) {
  63510. var rootUrlKey = "";
  63511. files.forEach(function (url) { return rootUrlKey += url; });
  63512. return new CubeTexture(rootUrlKey, scene, null, noMipmap, files);
  63513. };
  63514. /**
  63515. * Creates and return a texture created from prefilterd data by tools like IBL Baker or Lys.
  63516. * @param url defines the url of the prefiltered texture
  63517. * @param scene defines the scene the texture is attached to
  63518. * @param forcedExtension defines the extension of the file if different from the url
  63519. * @param createPolynomials defines whether or not to create polynomial harmonics from the texture data if necessary
  63520. * @return the prefiltered texture
  63521. */
  63522. CubeTexture.CreateFromPrefilteredData = function (url, scene, forcedExtension, createPolynomials) {
  63523. if (forcedExtension === void 0) { forcedExtension = null; }
  63524. if (createPolynomials === void 0) { createPolynomials = true; }
  63525. return new CubeTexture(url, scene, null, false, null, null, null, undefined, true, forcedExtension, createPolynomials);
  63526. };
  63527. // Methods
  63528. CubeTexture.prototype.delayLoad = function () {
  63529. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  63530. return;
  63531. }
  63532. var scene = this.getScene();
  63533. if (!scene) {
  63534. return;
  63535. }
  63536. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  63537. this._texture = this._getFromCache(this.url, this._noMipmap);
  63538. if (!this._texture) {
  63539. if (this._prefiltered) {
  63540. this._texture = scene.getEngine().createPrefilteredCubeTexture(this.url, scene, this.lodGenerationScale, this.lodGenerationOffset, undefined, undefined, this._format, undefined, this._createPolynomials);
  63541. }
  63542. else {
  63543. this._texture = scene.getEngine().createCubeTexture(this.url, scene, this._files, this._noMipmap, undefined, undefined, this._format);
  63544. }
  63545. }
  63546. };
  63547. CubeTexture.prototype.getReflectionTextureMatrix = function () {
  63548. return this._textureMatrix;
  63549. };
  63550. CubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  63551. this._textureMatrix = value;
  63552. };
  63553. CubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  63554. var texture = BABYLON.SerializationHelper.Parse(function () {
  63555. var prefiltered = false;
  63556. if (parsedTexture.prefiltered) {
  63557. prefiltered = parsedTexture.prefiltered;
  63558. }
  63559. return new CubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.extensions, false, null, null, null, undefined, prefiltered);
  63560. }, parsedTexture, scene);
  63561. // Local Cubemaps
  63562. if (parsedTexture.boundingBoxPosition) {
  63563. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  63564. }
  63565. if (parsedTexture.boundingBoxSize) {
  63566. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  63567. }
  63568. // Animations
  63569. if (parsedTexture.animations) {
  63570. for (var animationIndex = 0; animationIndex < parsedTexture.animations.length; animationIndex++) {
  63571. var parsedAnimation = parsedTexture.animations[animationIndex];
  63572. texture.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  63573. }
  63574. }
  63575. return texture;
  63576. };
  63577. CubeTexture.prototype.clone = function () {
  63578. var _this = this;
  63579. return BABYLON.SerializationHelper.Clone(function () {
  63580. var scene = _this.getScene();
  63581. if (!scene) {
  63582. return _this;
  63583. }
  63584. return new CubeTexture(_this.url, scene, _this._extensions, _this._noMipmap, _this._files);
  63585. }, this);
  63586. };
  63587. __decorate([
  63588. BABYLON.serialize("rotationY")
  63589. ], CubeTexture.prototype, "_rotationY", void 0);
  63590. return CubeTexture;
  63591. }(BABYLON.BaseTexture));
  63592. BABYLON.CubeTexture = CubeTexture;
  63593. })(BABYLON || (BABYLON = {}));
  63594. //# sourceMappingURL=babylon.cubeTexture.js.map
  63595. var BABYLON;
  63596. (function (BABYLON) {
  63597. var RenderTargetTexture = /** @class */ (function (_super) {
  63598. __extends(RenderTargetTexture, _super);
  63599. /**
  63600. * Instantiate a render target texture. This is mainly to render of screen the scene to for instance apply post processse
  63601. * or used a shadow, depth texture...
  63602. * @param name The friendly name of the texture
  63603. * @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)
  63604. * @param scene The scene the RTT belongs to. The latest created scene will be used if not precised.
  63605. * @param generateMipMaps True if mip maps need to be generated after render.
  63606. * @param doNotChangeAspectRatio True to not change the aspect ratio of the scene in the RTT
  63607. * @param type The type of the buffer in the RTT (int, half float, float...)
  63608. * @param isCube True if a cube texture needs to be created
  63609. * @param samplingMode The sampling mode to be usedwith the render target (Linear, Nearest...)
  63610. * @param generateDepthBuffer True to generate a depth buffer
  63611. * @param generateStencilBuffer True to generate a stencil buffer
  63612. * @param isMulti True if multiple textures need to be created (Draw Buffers)
  63613. * @param format The internal format of the buffer in the RTT (RED, RG, RGB, RGBA, ALPHA...)
  63614. */
  63615. function RenderTargetTexture(name, size, scene, generateMipMaps, doNotChangeAspectRatio, type, isCube, samplingMode, generateDepthBuffer, generateStencilBuffer, isMulti, format) {
  63616. if (doNotChangeAspectRatio === void 0) { doNotChangeAspectRatio = true; }
  63617. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  63618. if (isCube === void 0) { isCube = false; }
  63619. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  63620. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  63621. if (generateStencilBuffer === void 0) { generateStencilBuffer = false; }
  63622. if (isMulti === void 0) { isMulti = false; }
  63623. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  63624. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  63625. _this.isCube = isCube;
  63626. /**
  63627. * Use this list to define the list of mesh you want to render.
  63628. */
  63629. _this.renderList = new Array();
  63630. _this.renderParticles = true;
  63631. _this.renderSprites = false;
  63632. _this.coordinatesMode = BABYLON.Texture.PROJECTION_MODE;
  63633. _this.ignoreCameraViewport = false;
  63634. // Events
  63635. /**
  63636. * An event triggered when the texture is unbind.
  63637. */
  63638. _this.onBeforeBindObservable = new BABYLON.Observable();
  63639. /**
  63640. * An event triggered when the texture is unbind.
  63641. */
  63642. _this.onAfterUnbindObservable = new BABYLON.Observable();
  63643. /**
  63644. * An event triggered before rendering the texture
  63645. */
  63646. _this.onBeforeRenderObservable = new BABYLON.Observable();
  63647. /**
  63648. * An event triggered after rendering the texture
  63649. */
  63650. _this.onAfterRenderObservable = new BABYLON.Observable();
  63651. /**
  63652. * An event triggered after the texture clear
  63653. */
  63654. _this.onClearObservable = new BABYLON.Observable();
  63655. _this._currentRefreshId = -1;
  63656. _this._refreshRate = 1;
  63657. _this._samples = 1;
  63658. /**
  63659. * Gets or sets the center of the bounding box associated with the texture (when in cube mode)
  63660. * It must define where the camera used to render the texture is set
  63661. */
  63662. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  63663. scene = _this.getScene();
  63664. if (!scene) {
  63665. return _this;
  63666. }
  63667. _this._engine = scene.getEngine();
  63668. _this.name = name;
  63669. _this.isRenderTarget = true;
  63670. _this._initialSizeParameter = size;
  63671. _this._processSizeParameter(size);
  63672. _this._resizeObserver = _this.getScene().getEngine().onResizeObservable.add(function () {
  63673. });
  63674. _this._generateMipMaps = generateMipMaps ? true : false;
  63675. _this._doNotChangeAspectRatio = doNotChangeAspectRatio;
  63676. // Rendering groups
  63677. _this._renderingManager = new BABYLON.RenderingManager(scene);
  63678. if (isMulti) {
  63679. return _this;
  63680. }
  63681. _this._renderTargetOptions = {
  63682. generateMipMaps: generateMipMaps,
  63683. type: type,
  63684. format: format,
  63685. samplingMode: samplingMode,
  63686. generateDepthBuffer: generateDepthBuffer,
  63687. generateStencilBuffer: generateStencilBuffer
  63688. };
  63689. if (samplingMode === BABYLON.Texture.NEAREST_SAMPLINGMODE) {
  63690. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63691. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  63692. }
  63693. if (isCube) {
  63694. _this._texture = scene.getEngine().createRenderTargetCubeTexture(_this.getRenderSize(), _this._renderTargetOptions);
  63695. _this.coordinatesMode = BABYLON.Texture.INVCUBIC_MODE;
  63696. _this._textureMatrix = BABYLON.Matrix.Identity();
  63697. }
  63698. else {
  63699. _this._texture = scene.getEngine().createRenderTargetTexture(_this._size, _this._renderTargetOptions);
  63700. }
  63701. return _this;
  63702. }
  63703. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONCE", {
  63704. get: function () {
  63705. return RenderTargetTexture._REFRESHRATE_RENDER_ONCE;
  63706. },
  63707. enumerable: true,
  63708. configurable: true
  63709. });
  63710. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYFRAME", {
  63711. get: function () {
  63712. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME;
  63713. },
  63714. enumerable: true,
  63715. configurable: true
  63716. });
  63717. Object.defineProperty(RenderTargetTexture, "REFRESHRATE_RENDER_ONEVERYTWOFRAMES", {
  63718. get: function () {
  63719. return RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES;
  63720. },
  63721. enumerable: true,
  63722. configurable: true
  63723. });
  63724. Object.defineProperty(RenderTargetTexture.prototype, "onAfterUnbind", {
  63725. set: function (callback) {
  63726. if (this._onAfterUnbindObserver) {
  63727. this.onAfterUnbindObservable.remove(this._onAfterUnbindObserver);
  63728. }
  63729. this._onAfterUnbindObserver = this.onAfterUnbindObservable.add(callback);
  63730. },
  63731. enumerable: true,
  63732. configurable: true
  63733. });
  63734. Object.defineProperty(RenderTargetTexture.prototype, "onBeforeRender", {
  63735. set: function (callback) {
  63736. if (this._onBeforeRenderObserver) {
  63737. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  63738. }
  63739. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  63740. },
  63741. enumerable: true,
  63742. configurable: true
  63743. });
  63744. Object.defineProperty(RenderTargetTexture.prototype, "onAfterRender", {
  63745. set: function (callback) {
  63746. if (this._onAfterRenderObserver) {
  63747. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  63748. }
  63749. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  63750. },
  63751. enumerable: true,
  63752. configurable: true
  63753. });
  63754. Object.defineProperty(RenderTargetTexture.prototype, "onClear", {
  63755. set: function (callback) {
  63756. if (this._onClearObserver) {
  63757. this.onClearObservable.remove(this._onClearObserver);
  63758. }
  63759. this._onClearObserver = this.onClearObservable.add(callback);
  63760. },
  63761. enumerable: true,
  63762. configurable: true
  63763. });
  63764. Object.defineProperty(RenderTargetTexture.prototype, "renderTargetOptions", {
  63765. get: function () {
  63766. return this._renderTargetOptions;
  63767. },
  63768. enumerable: true,
  63769. configurable: true
  63770. });
  63771. RenderTargetTexture.prototype._onRatioRescale = function () {
  63772. if (this._sizeRatio) {
  63773. this.resize(this._initialSizeParameter);
  63774. }
  63775. };
  63776. Object.defineProperty(RenderTargetTexture.prototype, "boundingBoxSize", {
  63777. get: function () {
  63778. return this._boundingBoxSize;
  63779. },
  63780. /**
  63781. * Gets or sets the size of the bounding box associated with the texture (when in cube mode)
  63782. * When defined, the cubemap will switch to local mode
  63783. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  63784. * @example https://www.babylonjs-playground.com/#RNASML
  63785. */
  63786. set: function (value) {
  63787. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  63788. return;
  63789. }
  63790. this._boundingBoxSize = value;
  63791. var scene = this.getScene();
  63792. if (scene) {
  63793. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  63794. }
  63795. },
  63796. enumerable: true,
  63797. configurable: true
  63798. });
  63799. /**
  63800. * Creates a depth stencil texture.
  63801. * This is only available in WebGL 2 or with the depth texture extension available.
  63802. * @param comparisonFunction Specifies the comparison function to set on the texture. If 0 or undefined, the texture is not in comparison mode
  63803. * @param bilinearFiltering Specifies whether or not bilinear filtering is enable on the texture
  63804. * @param generateStencil Specifies whether or not a stencil should be allocated in the texture
  63805. */
  63806. RenderTargetTexture.prototype.createDepthStencilTexture = function (comparisonFunction, bilinearFiltering, generateStencil) {
  63807. if (comparisonFunction === void 0) { comparisonFunction = 0; }
  63808. if (bilinearFiltering === void 0) { bilinearFiltering = true; }
  63809. if (generateStencil === void 0) { generateStencil = false; }
  63810. if (!this.getScene()) {
  63811. return;
  63812. }
  63813. var engine = this.getScene().getEngine();
  63814. this.depthStencilTexture = engine.createDepthStencilTexture(this._size, {
  63815. bilinearFiltering: bilinearFiltering,
  63816. comparisonFunction: comparisonFunction,
  63817. generateStencil: generateStencil,
  63818. isCube: this.isCube
  63819. });
  63820. engine.setFrameBufferDepthStencilTexture(this);
  63821. };
  63822. RenderTargetTexture.prototype._processSizeParameter = function (size) {
  63823. if (size.ratio) {
  63824. this._sizeRatio = size.ratio;
  63825. this._size = {
  63826. width: this._bestReflectionRenderTargetDimension(this._engine.getRenderWidth(), this._sizeRatio),
  63827. height: this._bestReflectionRenderTargetDimension(this._engine.getRenderHeight(), this._sizeRatio)
  63828. };
  63829. }
  63830. else {
  63831. this._size = size;
  63832. }
  63833. };
  63834. Object.defineProperty(RenderTargetTexture.prototype, "samples", {
  63835. get: function () {
  63836. return this._samples;
  63837. },
  63838. set: function (value) {
  63839. if (this._samples === value) {
  63840. return;
  63841. }
  63842. var scene = this.getScene();
  63843. if (!scene) {
  63844. return;
  63845. }
  63846. this._samples = scene.getEngine().updateRenderTargetTextureSampleCount(this._texture, value);
  63847. },
  63848. enumerable: true,
  63849. configurable: true
  63850. });
  63851. RenderTargetTexture.prototype.resetRefreshCounter = function () {
  63852. this._currentRefreshId = -1;
  63853. };
  63854. Object.defineProperty(RenderTargetTexture.prototype, "refreshRate", {
  63855. get: function () {
  63856. return this._refreshRate;
  63857. },
  63858. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  63859. set: function (value) {
  63860. this._refreshRate = value;
  63861. this.resetRefreshCounter();
  63862. },
  63863. enumerable: true,
  63864. configurable: true
  63865. });
  63866. RenderTargetTexture.prototype.addPostProcess = function (postProcess) {
  63867. if (!this._postProcessManager) {
  63868. var scene = this.getScene();
  63869. if (!scene) {
  63870. return;
  63871. }
  63872. this._postProcessManager = new BABYLON.PostProcessManager(scene);
  63873. this._postProcesses = new Array();
  63874. }
  63875. this._postProcesses.push(postProcess);
  63876. this._postProcesses[0].autoClear = false;
  63877. };
  63878. RenderTargetTexture.prototype.clearPostProcesses = function (dispose) {
  63879. if (!this._postProcesses) {
  63880. return;
  63881. }
  63882. if (dispose) {
  63883. for (var _i = 0, _a = this._postProcesses; _i < _a.length; _i++) {
  63884. var postProcess = _a[_i];
  63885. postProcess.dispose();
  63886. }
  63887. }
  63888. this._postProcesses = [];
  63889. };
  63890. RenderTargetTexture.prototype.removePostProcess = function (postProcess) {
  63891. if (!this._postProcesses) {
  63892. return;
  63893. }
  63894. var index = this._postProcesses.indexOf(postProcess);
  63895. if (index === -1) {
  63896. return;
  63897. }
  63898. this._postProcesses.splice(index, 1);
  63899. if (this._postProcesses.length > 0) {
  63900. this._postProcesses[0].autoClear = false;
  63901. }
  63902. };
  63903. RenderTargetTexture.prototype._shouldRender = function () {
  63904. if (this._currentRefreshId === -1) { // At least render once
  63905. this._currentRefreshId = 1;
  63906. return true;
  63907. }
  63908. if (this.refreshRate === this._currentRefreshId) {
  63909. this._currentRefreshId = 1;
  63910. return true;
  63911. }
  63912. this._currentRefreshId++;
  63913. return false;
  63914. };
  63915. RenderTargetTexture.prototype.getRenderSize = function () {
  63916. if (this._size.width) {
  63917. return this._size.width;
  63918. }
  63919. return this._size;
  63920. };
  63921. RenderTargetTexture.prototype.getRenderWidth = function () {
  63922. if (this._size.width) {
  63923. return this._size.width;
  63924. }
  63925. return this._size;
  63926. };
  63927. RenderTargetTexture.prototype.getRenderHeight = function () {
  63928. if (this._size.width) {
  63929. return this._size.height;
  63930. }
  63931. return this._size;
  63932. };
  63933. Object.defineProperty(RenderTargetTexture.prototype, "canRescale", {
  63934. get: function () {
  63935. return true;
  63936. },
  63937. enumerable: true,
  63938. configurable: true
  63939. });
  63940. RenderTargetTexture.prototype.scale = function (ratio) {
  63941. var newSize = this.getRenderSize() * ratio;
  63942. this.resize(newSize);
  63943. };
  63944. RenderTargetTexture.prototype.getReflectionTextureMatrix = function () {
  63945. if (this.isCube) {
  63946. return this._textureMatrix;
  63947. }
  63948. return _super.prototype.getReflectionTextureMatrix.call(this);
  63949. };
  63950. RenderTargetTexture.prototype.resize = function (size) {
  63951. this.releaseInternalTexture();
  63952. var scene = this.getScene();
  63953. if (!scene) {
  63954. return;
  63955. }
  63956. this._processSizeParameter(size);
  63957. if (this.isCube) {
  63958. this._texture = scene.getEngine().createRenderTargetCubeTexture(this.getRenderSize(), this._renderTargetOptions);
  63959. }
  63960. else {
  63961. this._texture = scene.getEngine().createRenderTargetTexture(this._size, this._renderTargetOptions);
  63962. }
  63963. };
  63964. RenderTargetTexture.prototype.render = function (useCameraPostProcess, dumpForDebug) {
  63965. if (useCameraPostProcess === void 0) { useCameraPostProcess = false; }
  63966. if (dumpForDebug === void 0) { dumpForDebug = false; }
  63967. var scene = this.getScene();
  63968. if (!scene) {
  63969. return;
  63970. }
  63971. var engine = scene.getEngine();
  63972. if (this.useCameraPostProcesses !== undefined) {
  63973. useCameraPostProcess = this.useCameraPostProcesses;
  63974. }
  63975. if (this._waitingRenderList) {
  63976. this.renderList = [];
  63977. for (var index = 0; index < this._waitingRenderList.length; index++) {
  63978. var id = this._waitingRenderList[index];
  63979. var mesh_1 = scene.getMeshByID(id);
  63980. if (mesh_1) {
  63981. this.renderList.push(mesh_1);
  63982. }
  63983. }
  63984. delete this._waitingRenderList;
  63985. }
  63986. // Is predicate defined?
  63987. if (this.renderListPredicate) {
  63988. if (this.renderList) {
  63989. this.renderList.splice(0); // Clear previous renderList
  63990. }
  63991. else {
  63992. this.renderList = [];
  63993. }
  63994. var scene = this.getScene();
  63995. if (!scene) {
  63996. return;
  63997. }
  63998. var sceneMeshes = scene.meshes;
  63999. for (var index = 0; index < sceneMeshes.length; index++) {
  64000. var mesh = sceneMeshes[index];
  64001. if (this.renderListPredicate(mesh)) {
  64002. this.renderList.push(mesh);
  64003. }
  64004. }
  64005. }
  64006. this.onBeforeBindObservable.notifyObservers(this);
  64007. // Set custom projection.
  64008. // Needs to be before binding to prevent changing the aspect ratio.
  64009. var camera;
  64010. if (this.activeCamera) {
  64011. camera = this.activeCamera;
  64012. engine.setViewport(this.activeCamera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64013. if (this.activeCamera !== scene.activeCamera) {
  64014. scene.setTransformMatrix(this.activeCamera.getViewMatrix(), this.activeCamera.getProjectionMatrix(true));
  64015. }
  64016. }
  64017. else {
  64018. camera = scene.activeCamera;
  64019. if (camera) {
  64020. engine.setViewport(camera.viewport, this.getRenderWidth(), this.getRenderHeight());
  64021. }
  64022. }
  64023. // Prepare renderingManager
  64024. this._renderingManager.reset();
  64025. var currentRenderList = this.renderList ? this.renderList : scene.getActiveMeshes().data;
  64026. var currentRenderListLength = this.renderList ? this.renderList.length : scene.getActiveMeshes().length;
  64027. var sceneRenderId = scene.getRenderId();
  64028. for (var meshIndex = 0; meshIndex < currentRenderListLength; meshIndex++) {
  64029. var mesh = currentRenderList[meshIndex];
  64030. if (mesh) {
  64031. if (!mesh.isReady(this.refreshRate === 0)) {
  64032. this.resetRefreshCounter();
  64033. continue;
  64034. }
  64035. mesh._preActivateForIntermediateRendering(sceneRenderId);
  64036. var isMasked = void 0;
  64037. if (!this.renderList && camera) {
  64038. isMasked = ((mesh.layerMask & camera.layerMask) === 0);
  64039. }
  64040. else {
  64041. isMasked = false;
  64042. }
  64043. if (mesh.isEnabled() && mesh.isVisible && mesh.subMeshes && !isMasked) {
  64044. mesh._activate(sceneRenderId);
  64045. for (var subIndex = 0; subIndex < mesh.subMeshes.length; subIndex++) {
  64046. var subMesh = mesh.subMeshes[subIndex];
  64047. scene._activeIndices.addCount(subMesh.indexCount, false);
  64048. this._renderingManager.dispatch(subMesh, mesh);
  64049. }
  64050. }
  64051. }
  64052. }
  64053. for (var particleIndex = 0; particleIndex < scene.particleSystems.length; particleIndex++) {
  64054. var particleSystem = scene.particleSystems[particleIndex];
  64055. var emitter = particleSystem.emitter;
  64056. if (!particleSystem.isStarted() || !emitter || !emitter.position || !emitter.isEnabled()) {
  64057. continue;
  64058. }
  64059. if (currentRenderList.indexOf(emitter) >= 0) {
  64060. this._renderingManager.dispatchParticles(particleSystem);
  64061. }
  64062. }
  64063. if (this.isCube) {
  64064. for (var face = 0; face < 6; face++) {
  64065. this.renderToTarget(face, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64066. scene.incrementRenderId();
  64067. scene.resetCachedMaterial();
  64068. }
  64069. }
  64070. else {
  64071. this.renderToTarget(0, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug);
  64072. }
  64073. this.onAfterUnbindObservable.notifyObservers(this);
  64074. if (scene.activeCamera) {
  64075. if (this.activeCamera && this.activeCamera !== scene.activeCamera) {
  64076. scene.setTransformMatrix(scene.activeCamera.getViewMatrix(), scene.activeCamera.getProjectionMatrix(true));
  64077. }
  64078. engine.setViewport(scene.activeCamera.viewport);
  64079. }
  64080. scene.resetCachedMaterial();
  64081. };
  64082. RenderTargetTexture.prototype._bestReflectionRenderTargetDimension = function (renderDimension, scale) {
  64083. var minimum = 128;
  64084. var x = renderDimension * scale;
  64085. var curved = BABYLON.Tools.NearestPOT(x + (minimum * minimum / (minimum + x)));
  64086. // Ensure we don't exceed the render dimension (while staying POT)
  64087. return Math.min(BABYLON.Tools.FloorPOT(renderDimension), curved);
  64088. };
  64089. RenderTargetTexture.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64090. var _this = this;
  64091. if (!this._texture) {
  64092. return;
  64093. }
  64094. engine.unBindFramebuffer(this._texture, this.isCube, function () {
  64095. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64096. });
  64097. };
  64098. RenderTargetTexture.prototype.renderToTarget = function (faceIndex, currentRenderList, currentRenderListLength, useCameraPostProcess, dumpForDebug) {
  64099. var scene = this.getScene();
  64100. if (!scene) {
  64101. return;
  64102. }
  64103. var engine = scene.getEngine();
  64104. if (!this._texture) {
  64105. return;
  64106. }
  64107. // Bind
  64108. if (this._postProcessManager) {
  64109. this._postProcessManager._prepareFrame(this._texture, this._postProcesses);
  64110. }
  64111. else if (!useCameraPostProcess || !scene.postProcessManager._prepareFrame(this._texture)) {
  64112. if (this._texture) {
  64113. engine.bindFramebuffer(this._texture, this.isCube ? faceIndex : undefined, undefined, undefined, this.ignoreCameraViewport, this.depthStencilTexture ? this.depthStencilTexture : undefined);
  64114. }
  64115. }
  64116. this.onBeforeRenderObservable.notifyObservers(faceIndex);
  64117. // Clear
  64118. if (this.onClearObservable.hasObservers()) {
  64119. this.onClearObservable.notifyObservers(engine);
  64120. }
  64121. else {
  64122. engine.clear(this.clearColor || scene.clearColor, true, true, true);
  64123. }
  64124. if (!this._doNotChangeAspectRatio) {
  64125. scene.updateTransformMatrix(true);
  64126. }
  64127. // Render
  64128. this._renderingManager.render(this.customRenderFunction, currentRenderList, this.renderParticles, this.renderSprites);
  64129. if (this._postProcessManager) {
  64130. this._postProcessManager._finalizeFrame(false, this._texture, faceIndex, this._postProcesses, this.ignoreCameraViewport);
  64131. }
  64132. else if (useCameraPostProcess) {
  64133. scene.postProcessManager._finalizeFrame(false, this._texture, faceIndex);
  64134. }
  64135. if (!this._doNotChangeAspectRatio) {
  64136. scene.updateTransformMatrix(true);
  64137. }
  64138. // Dump ?
  64139. if (dumpForDebug) {
  64140. BABYLON.Tools.DumpFramebuffer(this.getRenderWidth(), this.getRenderHeight(), engine);
  64141. }
  64142. // Unbind
  64143. if (!this.isCube || faceIndex === 5) {
  64144. if (this.isCube) {
  64145. if (faceIndex === 5) {
  64146. engine.generateMipMapsForCubemap(this._texture);
  64147. }
  64148. }
  64149. this.unbindFrameBuffer(engine, faceIndex);
  64150. }
  64151. else {
  64152. this.onAfterRenderObservable.notifyObservers(faceIndex);
  64153. }
  64154. };
  64155. /**
  64156. * Overrides the default sort function applied in the renderging group to prepare the meshes.
  64157. * This allowed control for front to back rendering or reversly depending of the special needs.
  64158. *
  64159. * @param renderingGroupId The rendering group id corresponding to its index
  64160. * @param opaqueSortCompareFn The opaque queue comparison function use to sort.
  64161. * @param alphaTestSortCompareFn The alpha test queue comparison function use to sort.
  64162. * @param transparentSortCompareFn The transparent queue comparison function use to sort.
  64163. */
  64164. RenderTargetTexture.prototype.setRenderingOrder = function (renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn) {
  64165. if (opaqueSortCompareFn === void 0) { opaqueSortCompareFn = null; }
  64166. if (alphaTestSortCompareFn === void 0) { alphaTestSortCompareFn = null; }
  64167. if (transparentSortCompareFn === void 0) { transparentSortCompareFn = null; }
  64168. this._renderingManager.setRenderingOrder(renderingGroupId, opaqueSortCompareFn, alphaTestSortCompareFn, transparentSortCompareFn);
  64169. };
  64170. /**
  64171. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  64172. *
  64173. * @param renderingGroupId The rendering group id corresponding to its index
  64174. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  64175. */
  64176. RenderTargetTexture.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  64177. this._renderingManager.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  64178. };
  64179. RenderTargetTexture.prototype.clone = function () {
  64180. var textureSize = this.getSize();
  64181. 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);
  64182. // Base texture
  64183. newTexture.hasAlpha = this.hasAlpha;
  64184. newTexture.level = this.level;
  64185. // RenderTarget Texture
  64186. newTexture.coordinatesMode = this.coordinatesMode;
  64187. if (this.renderList) {
  64188. newTexture.renderList = this.renderList.slice(0);
  64189. }
  64190. return newTexture;
  64191. };
  64192. RenderTargetTexture.prototype.serialize = function () {
  64193. if (!this.name) {
  64194. return null;
  64195. }
  64196. var serializationObject = _super.prototype.serialize.call(this);
  64197. serializationObject.renderTargetSize = this.getRenderSize();
  64198. serializationObject.renderList = [];
  64199. if (this.renderList) {
  64200. for (var index = 0; index < this.renderList.length; index++) {
  64201. serializationObject.renderList.push(this.renderList[index].id);
  64202. }
  64203. }
  64204. return serializationObject;
  64205. };
  64206. // This will remove the attached framebuffer objects. The texture will not be able to be used as render target anymore
  64207. RenderTargetTexture.prototype.disposeFramebufferObjects = function () {
  64208. var objBuffer = this.getInternalTexture();
  64209. var scene = this.getScene();
  64210. if (objBuffer && scene) {
  64211. scene.getEngine()._releaseFramebufferObjects(objBuffer);
  64212. }
  64213. };
  64214. RenderTargetTexture.prototype.dispose = function () {
  64215. if (this._postProcessManager) {
  64216. this._postProcessManager.dispose();
  64217. this._postProcessManager = null;
  64218. }
  64219. this.clearPostProcesses(true);
  64220. if (this._resizeObserver) {
  64221. this.getScene().getEngine().onResizeObservable.remove(this._resizeObserver);
  64222. this._resizeObserver = null;
  64223. }
  64224. this.renderList = null;
  64225. // Remove from custom render targets
  64226. var scene = this.getScene();
  64227. if (!scene) {
  64228. return;
  64229. }
  64230. var index = scene.customRenderTargets.indexOf(this);
  64231. if (index >= 0) {
  64232. scene.customRenderTargets.splice(index, 1);
  64233. }
  64234. for (var _i = 0, _a = scene.cameras; _i < _a.length; _i++) {
  64235. var camera = _a[_i];
  64236. index = camera.customRenderTargets.indexOf(this);
  64237. if (index >= 0) {
  64238. camera.customRenderTargets.splice(index, 1);
  64239. }
  64240. }
  64241. _super.prototype.dispose.call(this);
  64242. };
  64243. RenderTargetTexture.prototype._rebuild = function () {
  64244. if (this.refreshRate === RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  64245. this.refreshRate = RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  64246. }
  64247. if (this._postProcessManager) {
  64248. this._postProcessManager._rebuild();
  64249. }
  64250. };
  64251. /**
  64252. * Clear the info related to rendering groups preventing retention point in material dispose.
  64253. */
  64254. RenderTargetTexture.prototype.freeRenderingGroups = function () {
  64255. if (this._renderingManager) {
  64256. this._renderingManager.freeRenderingGroups();
  64257. }
  64258. };
  64259. RenderTargetTexture._REFRESHRATE_RENDER_ONCE = 0;
  64260. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYFRAME = 1;
  64261. RenderTargetTexture._REFRESHRATE_RENDER_ONEVERYTWOFRAMES = 2;
  64262. return RenderTargetTexture;
  64263. }(BABYLON.Texture));
  64264. BABYLON.RenderTargetTexture = RenderTargetTexture;
  64265. })(BABYLON || (BABYLON = {}));
  64266. //# sourceMappingURL=babylon.renderTargetTexture.js.map
  64267. var BABYLON;
  64268. (function (BABYLON) {
  64269. ;
  64270. var MultiRenderTarget = /** @class */ (function (_super) {
  64271. __extends(MultiRenderTarget, _super);
  64272. function MultiRenderTarget(name, size, count, scene, options) {
  64273. var _this = this;
  64274. var generateMipMaps = options && options.generateMipMaps ? options.generateMipMaps : false;
  64275. var generateDepthTexture = options && options.generateDepthTexture ? options.generateDepthTexture : false;
  64276. var doNotChangeAspectRatio = !options || options.doNotChangeAspectRatio === undefined ? true : options.doNotChangeAspectRatio;
  64277. _this = _super.call(this, name, size, scene, generateMipMaps, doNotChangeAspectRatio) || this;
  64278. _this._engine = scene.getEngine();
  64279. if (!_this.isSupported) {
  64280. _this.dispose();
  64281. return;
  64282. }
  64283. var types = [];
  64284. var samplingModes = [];
  64285. for (var i = 0; i < count; i++) {
  64286. if (options && options.types && options.types[i] !== undefined) {
  64287. types.push(options.types[i]);
  64288. }
  64289. else {
  64290. types.push(options && options.defaultType ? options.defaultType : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  64291. }
  64292. if (options && options.samplingModes && options.samplingModes[i] !== undefined) {
  64293. samplingModes.push(options.samplingModes[i]);
  64294. }
  64295. else {
  64296. samplingModes.push(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  64297. }
  64298. }
  64299. var generateDepthBuffer = !options || options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  64300. var generateStencilBuffer = !options || options.generateStencilBuffer === undefined ? false : options.generateStencilBuffer;
  64301. _this._size = size;
  64302. _this._multiRenderTargetOptions = {
  64303. samplingModes: samplingModes,
  64304. generateMipMaps: generateMipMaps,
  64305. generateDepthBuffer: generateDepthBuffer,
  64306. generateStencilBuffer: generateStencilBuffer,
  64307. generateDepthTexture: generateDepthTexture,
  64308. types: types,
  64309. textureCount: count
  64310. };
  64311. _this._createInternalTextures();
  64312. _this._createTextures();
  64313. return _this;
  64314. }
  64315. Object.defineProperty(MultiRenderTarget.prototype, "isSupported", {
  64316. get: function () {
  64317. return this._engine.webGLVersion > 1 || this._engine.getCaps().drawBuffersExtension;
  64318. },
  64319. enumerable: true,
  64320. configurable: true
  64321. });
  64322. Object.defineProperty(MultiRenderTarget.prototype, "textures", {
  64323. get: function () {
  64324. return this._textures;
  64325. },
  64326. enumerable: true,
  64327. configurable: true
  64328. });
  64329. Object.defineProperty(MultiRenderTarget.prototype, "depthTexture", {
  64330. get: function () {
  64331. return this._textures[this._textures.length - 1];
  64332. },
  64333. enumerable: true,
  64334. configurable: true
  64335. });
  64336. Object.defineProperty(MultiRenderTarget.prototype, "wrapU", {
  64337. set: function (wrap) {
  64338. if (this._textures) {
  64339. for (var i = 0; i < this._textures.length; i++) {
  64340. this._textures[i].wrapU = wrap;
  64341. }
  64342. }
  64343. },
  64344. enumerable: true,
  64345. configurable: true
  64346. });
  64347. Object.defineProperty(MultiRenderTarget.prototype, "wrapV", {
  64348. set: function (wrap) {
  64349. if (this._textures) {
  64350. for (var i = 0; i < this._textures.length; i++) {
  64351. this._textures[i].wrapV = wrap;
  64352. }
  64353. }
  64354. },
  64355. enumerable: true,
  64356. configurable: true
  64357. });
  64358. MultiRenderTarget.prototype._rebuild = function () {
  64359. this.releaseInternalTextures();
  64360. this._createInternalTextures();
  64361. for (var i = 0; i < this._internalTextures.length; i++) {
  64362. var texture = this._textures[i];
  64363. texture._texture = this._internalTextures[i];
  64364. }
  64365. // Keeps references to frame buffer and stencil/depth buffer
  64366. this._texture = this._internalTextures[0];
  64367. };
  64368. MultiRenderTarget.prototype._createInternalTextures = function () {
  64369. this._internalTextures = this._engine.createMultipleRenderTarget(this._size, this._multiRenderTargetOptions);
  64370. };
  64371. MultiRenderTarget.prototype._createTextures = function () {
  64372. this._textures = [];
  64373. for (var i = 0; i < this._internalTextures.length; i++) {
  64374. var texture = new BABYLON.Texture(null, this.getScene());
  64375. texture._texture = this._internalTextures[i];
  64376. this._textures.push(texture);
  64377. }
  64378. // Keeps references to frame buffer and stencil/depth buffer
  64379. this._texture = this._internalTextures[0];
  64380. };
  64381. Object.defineProperty(MultiRenderTarget.prototype, "samples", {
  64382. get: function () {
  64383. return this._samples;
  64384. },
  64385. set: function (value) {
  64386. if (this._samples === value) {
  64387. return;
  64388. }
  64389. this._samples = this._engine.updateMultipleRenderTargetTextureSampleCount(this._internalTextures, value);
  64390. },
  64391. enumerable: true,
  64392. configurable: true
  64393. });
  64394. MultiRenderTarget.prototype.resize = function (size) {
  64395. this.releaseInternalTextures();
  64396. this._internalTextures = this._engine.createMultipleRenderTarget(size, this._multiRenderTargetOptions);
  64397. this._createInternalTextures();
  64398. };
  64399. MultiRenderTarget.prototype.unbindFrameBuffer = function (engine, faceIndex) {
  64400. var _this = this;
  64401. engine.unBindMultiColorAttachmentFramebuffer(this._internalTextures, this.isCube, function () {
  64402. _this.onAfterRenderObservable.notifyObservers(faceIndex);
  64403. });
  64404. };
  64405. MultiRenderTarget.prototype.dispose = function () {
  64406. this.releaseInternalTextures();
  64407. _super.prototype.dispose.call(this);
  64408. };
  64409. MultiRenderTarget.prototype.releaseInternalTextures = function () {
  64410. if (!this._internalTextures) {
  64411. return;
  64412. }
  64413. for (var i = this._internalTextures.length - 1; i >= 0; i--) {
  64414. if (this._internalTextures[i] !== undefined) {
  64415. this._internalTextures[i].dispose();
  64416. this._internalTextures.splice(i, 1);
  64417. }
  64418. }
  64419. };
  64420. return MultiRenderTarget;
  64421. }(BABYLON.RenderTargetTexture));
  64422. BABYLON.MultiRenderTarget = MultiRenderTarget;
  64423. })(BABYLON || (BABYLON = {}));
  64424. //# sourceMappingURL=babylon.multiRenderTarget.js.map
  64425. var BABYLON;
  64426. (function (BABYLON) {
  64427. var MirrorTexture = /** @class */ (function (_super) {
  64428. __extends(MirrorTexture, _super);
  64429. function MirrorTexture(name, size, scene, generateMipMaps, type, samplingMode, generateDepthBuffer) {
  64430. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  64431. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  64432. if (generateDepthBuffer === void 0) { generateDepthBuffer = true; }
  64433. var _this = _super.call(this, name, size, scene, generateMipMaps, true, type, false, samplingMode, generateDepthBuffer) || this;
  64434. _this.scene = scene;
  64435. _this.mirrorPlane = new BABYLON.Plane(0, 1, 0, 1);
  64436. _this._transformMatrix = BABYLON.Matrix.Zero();
  64437. _this._mirrorMatrix = BABYLON.Matrix.Zero();
  64438. _this._adaptiveBlurKernel = 0;
  64439. _this._blurKernelX = 0;
  64440. _this._blurKernelY = 0;
  64441. _this._blurRatio = 1.0;
  64442. _this.ignoreCameraViewport = true;
  64443. _this._updateGammaSpace();
  64444. _this._imageProcessingConfigChangeObserver = scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  64445. _this._updateGammaSpace;
  64446. });
  64447. _this.onBeforeRenderObservable.add(function () {
  64448. BABYLON.Matrix.ReflectionToRef(_this.mirrorPlane, _this._mirrorMatrix);
  64449. _this._savedViewMatrix = scene.getViewMatrix();
  64450. _this._mirrorMatrix.multiplyToRef(_this._savedViewMatrix, _this._transformMatrix);
  64451. scene.setTransformMatrix(_this._transformMatrix, scene.getProjectionMatrix());
  64452. scene.clipPlane = _this.mirrorPlane;
  64453. scene.getEngine().cullBackFaces = false;
  64454. scene._mirroredCameraPosition = BABYLON.Vector3.TransformCoordinates(scene.activeCamera.globalPosition, _this._mirrorMatrix);
  64455. });
  64456. _this.onAfterRenderObservable.add(function () {
  64457. scene.setTransformMatrix(_this._savedViewMatrix, scene.getProjectionMatrix());
  64458. scene.getEngine().cullBackFaces = true;
  64459. scene._mirroredCameraPosition = null;
  64460. delete scene.clipPlane;
  64461. });
  64462. return _this;
  64463. }
  64464. Object.defineProperty(MirrorTexture.prototype, "blurRatio", {
  64465. get: function () {
  64466. return this._blurRatio;
  64467. },
  64468. set: function (value) {
  64469. if (this._blurRatio === value) {
  64470. return;
  64471. }
  64472. this._blurRatio = value;
  64473. this._preparePostProcesses();
  64474. },
  64475. enumerable: true,
  64476. configurable: true
  64477. });
  64478. Object.defineProperty(MirrorTexture.prototype, "adaptiveBlurKernel", {
  64479. set: function (value) {
  64480. this._adaptiveBlurKernel = value;
  64481. this._autoComputeBlurKernel();
  64482. },
  64483. enumerable: true,
  64484. configurable: true
  64485. });
  64486. Object.defineProperty(MirrorTexture.prototype, "blurKernel", {
  64487. set: function (value) {
  64488. this.blurKernelX = value;
  64489. this.blurKernelY = value;
  64490. },
  64491. enumerable: true,
  64492. configurable: true
  64493. });
  64494. Object.defineProperty(MirrorTexture.prototype, "blurKernelX", {
  64495. get: function () {
  64496. return this._blurKernelX;
  64497. },
  64498. set: function (value) {
  64499. if (this._blurKernelX === value) {
  64500. return;
  64501. }
  64502. this._blurKernelX = value;
  64503. this._preparePostProcesses();
  64504. },
  64505. enumerable: true,
  64506. configurable: true
  64507. });
  64508. Object.defineProperty(MirrorTexture.prototype, "blurKernelY", {
  64509. get: function () {
  64510. return this._blurKernelY;
  64511. },
  64512. set: function (value) {
  64513. if (this._blurKernelY === value) {
  64514. return;
  64515. }
  64516. this._blurKernelY = value;
  64517. this._preparePostProcesses();
  64518. },
  64519. enumerable: true,
  64520. configurable: true
  64521. });
  64522. MirrorTexture.prototype._autoComputeBlurKernel = function () {
  64523. var engine = this.getScene().getEngine();
  64524. var dw = this.getRenderWidth() / engine.getRenderWidth();
  64525. var dh = this.getRenderHeight() / engine.getRenderHeight();
  64526. this.blurKernelX = this._adaptiveBlurKernel * dw;
  64527. this.blurKernelY = this._adaptiveBlurKernel * dh;
  64528. };
  64529. MirrorTexture.prototype._onRatioRescale = function () {
  64530. if (this._sizeRatio) {
  64531. this.resize(this._initialSizeParameter);
  64532. if (!this._adaptiveBlurKernel) {
  64533. this._preparePostProcesses();
  64534. }
  64535. }
  64536. if (this._adaptiveBlurKernel) {
  64537. this._autoComputeBlurKernel();
  64538. }
  64539. };
  64540. MirrorTexture.prototype._updateGammaSpace = function () {
  64541. this.gammaSpace = !this.scene.imageProcessingConfiguration.isEnabled || !this.scene.imageProcessingConfiguration.applyByPostProcess;
  64542. };
  64543. MirrorTexture.prototype._preparePostProcesses = function () {
  64544. this.clearPostProcesses(true);
  64545. if (this._blurKernelX && this._blurKernelY) {
  64546. var engine = this.getScene().getEngine();
  64547. var textureType = engine.getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  64548. 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);
  64549. this._blurX.autoClear = false;
  64550. if (this._blurRatio === 1 && this.samples < 2 && this._texture) {
  64551. this._blurX.inputTexture = this._texture;
  64552. }
  64553. else {
  64554. this._blurX.alwaysForcePOT = true;
  64555. }
  64556. 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);
  64557. this._blurY.autoClear = false;
  64558. this._blurY.alwaysForcePOT = this._blurRatio !== 1;
  64559. this.addPostProcess(this._blurX);
  64560. this.addPostProcess(this._blurY);
  64561. }
  64562. else {
  64563. if (this._blurY) {
  64564. this.removePostProcess(this._blurY);
  64565. this._blurY.dispose();
  64566. this._blurY = null;
  64567. }
  64568. if (this._blurX) {
  64569. this.removePostProcess(this._blurX);
  64570. this._blurX.dispose();
  64571. this._blurX = null;
  64572. }
  64573. }
  64574. };
  64575. MirrorTexture.prototype.clone = function () {
  64576. var scene = this.getScene();
  64577. if (!scene) {
  64578. return this;
  64579. }
  64580. var textureSize = this.getSize();
  64581. var newTexture = new MirrorTexture(this.name, textureSize.width, scene, this._renderTargetOptions.generateMipMaps, this._renderTargetOptions.type, this._renderTargetOptions.samplingMode, this._renderTargetOptions.generateDepthBuffer);
  64582. // Base texture
  64583. newTexture.hasAlpha = this.hasAlpha;
  64584. newTexture.level = this.level;
  64585. // Mirror Texture
  64586. newTexture.mirrorPlane = this.mirrorPlane.clone();
  64587. if (this.renderList) {
  64588. newTexture.renderList = this.renderList.slice(0);
  64589. }
  64590. return newTexture;
  64591. };
  64592. MirrorTexture.prototype.serialize = function () {
  64593. if (!this.name) {
  64594. return null;
  64595. }
  64596. var serializationObject = _super.prototype.serialize.call(this);
  64597. serializationObject.mirrorPlane = this.mirrorPlane.asArray();
  64598. return serializationObject;
  64599. };
  64600. MirrorTexture.prototype.dispose = function () {
  64601. _super.prototype.dispose.call(this);
  64602. this.scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigChangeObserver);
  64603. };
  64604. return MirrorTexture;
  64605. }(BABYLON.RenderTargetTexture));
  64606. BABYLON.MirrorTexture = MirrorTexture;
  64607. })(BABYLON || (BABYLON = {}));
  64608. //# sourceMappingURL=babylon.mirrorTexture.js.map
  64609. var BABYLON;
  64610. (function (BABYLON) {
  64611. /**
  64612. * Creates a refraction texture used by refraction channel of the standard material.
  64613. * @param name the texture name
  64614. * @param size size of the underlying texture
  64615. * @param scene root scene
  64616. */
  64617. var RefractionTexture = /** @class */ (function (_super) {
  64618. __extends(RefractionTexture, _super);
  64619. function RefractionTexture(name, size, scene, generateMipMaps) {
  64620. var _this = _super.call(this, name, size, scene, generateMipMaps, true) || this;
  64621. _this.refractionPlane = new BABYLON.Plane(0, 1, 0, 1);
  64622. _this.depth = 2.0;
  64623. _this.onBeforeRenderObservable.add(function () {
  64624. scene.clipPlane = _this.refractionPlane;
  64625. });
  64626. _this.onAfterRenderObservable.add(function () {
  64627. delete scene.clipPlane;
  64628. });
  64629. return _this;
  64630. }
  64631. RefractionTexture.prototype.clone = function () {
  64632. var scene = this.getScene();
  64633. if (!scene) {
  64634. return this;
  64635. }
  64636. var textureSize = this.getSize();
  64637. var newTexture = new RefractionTexture(this.name, textureSize.width, scene, this._generateMipMaps);
  64638. // Base texture
  64639. newTexture.hasAlpha = this.hasAlpha;
  64640. newTexture.level = this.level;
  64641. // Refraction Texture
  64642. newTexture.refractionPlane = this.refractionPlane.clone();
  64643. if (this.renderList) {
  64644. newTexture.renderList = this.renderList.slice(0);
  64645. }
  64646. newTexture.depth = this.depth;
  64647. return newTexture;
  64648. };
  64649. RefractionTexture.prototype.serialize = function () {
  64650. if (!this.name) {
  64651. return null;
  64652. }
  64653. var serializationObject = _super.prototype.serialize.call(this);
  64654. serializationObject.mirrorPlane = this.refractionPlane.asArray();
  64655. serializationObject.depth = this.depth;
  64656. return serializationObject;
  64657. };
  64658. return RefractionTexture;
  64659. }(BABYLON.RenderTargetTexture));
  64660. BABYLON.RefractionTexture = RefractionTexture;
  64661. })(BABYLON || (BABYLON = {}));
  64662. //# sourceMappingURL=babylon.refractionTexture.js.map
  64663. var BABYLON;
  64664. (function (BABYLON) {
  64665. /**
  64666. * A class extending {BABYLON.Texture} allowing drawing on a texture
  64667. * @see http://doc.babylonjs.com/how_to/dynamictexture
  64668. */
  64669. var DynamicTexture = /** @class */ (function (_super) {
  64670. __extends(DynamicTexture, _super);
  64671. /**
  64672. * Creates a {BABYLON.DynamicTexture}
  64673. * @param name defines the name of the texture
  64674. * @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
  64675. * @param scene defines the scene where you want the texture
  64676. * @param generateMipMaps defines the use of MinMaps or not (default is false)
  64677. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  64678. * @param format defines the texture format to use (default is BABYLON.Engine.TEXTUREFORMAT_RGBA)
  64679. */
  64680. function DynamicTexture(name, options, scene, generateMipMaps, samplingMode, format) {
  64681. if (scene === void 0) { scene = null; }
  64682. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64683. if (format === void 0) { format = BABYLON.Engine.TEXTUREFORMAT_RGBA; }
  64684. var _this = _super.call(this, null, scene, !generateMipMaps, undefined, samplingMode, undefined, undefined, undefined, undefined, format) || this;
  64685. _this.name = name;
  64686. _this._engine = _this.getScene().getEngine();
  64687. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64688. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64689. _this._generateMipMaps = generateMipMaps;
  64690. if (options.getContext) {
  64691. _this._canvas = options;
  64692. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64693. }
  64694. else {
  64695. _this._canvas = document.createElement("canvas");
  64696. if (options.width || options.width === 0) {
  64697. _this._texture = _this._engine.createDynamicTexture(options.width, options.height, generateMipMaps, samplingMode);
  64698. }
  64699. else {
  64700. _this._texture = _this._engine.createDynamicTexture(options, options, generateMipMaps, samplingMode);
  64701. }
  64702. }
  64703. var textureSize = _this.getSize();
  64704. _this._canvas.width = textureSize.width;
  64705. _this._canvas.height = textureSize.height;
  64706. _this._context = _this._canvas.getContext("2d");
  64707. return _this;
  64708. }
  64709. Object.defineProperty(DynamicTexture.prototype, "canRescale", {
  64710. /**
  64711. * Gets the current state of canRescale
  64712. */
  64713. get: function () {
  64714. return true;
  64715. },
  64716. enumerable: true,
  64717. configurable: true
  64718. });
  64719. DynamicTexture.prototype._recreate = function (textureSize) {
  64720. this._canvas.width = textureSize.width;
  64721. this._canvas.height = textureSize.height;
  64722. this.releaseInternalTexture();
  64723. this._texture = this._engine.createDynamicTexture(textureSize.width, textureSize.height, this._generateMipMaps, this._samplingMode);
  64724. };
  64725. /**
  64726. * Scales the texture
  64727. * @param ratio the scale factor to apply to both width and height
  64728. */
  64729. DynamicTexture.prototype.scale = function (ratio) {
  64730. var textureSize = this.getSize();
  64731. textureSize.width *= ratio;
  64732. textureSize.height *= ratio;
  64733. this._recreate(textureSize);
  64734. };
  64735. /**
  64736. * Resizes the texture
  64737. * @param width the new width
  64738. * @param height the new height
  64739. */
  64740. DynamicTexture.prototype.scaleTo = function (width, height) {
  64741. var textureSize = this.getSize();
  64742. textureSize.width = width;
  64743. textureSize.height = height;
  64744. this._recreate(textureSize);
  64745. };
  64746. /**
  64747. * Gets the context of the canvas used by the texture
  64748. * @returns the canvas context of the dynamic texture
  64749. */
  64750. DynamicTexture.prototype.getContext = function () {
  64751. return this._context;
  64752. };
  64753. /**
  64754. * Clears the texture
  64755. */
  64756. DynamicTexture.prototype.clear = function () {
  64757. var size = this.getSize();
  64758. this._context.fillRect(0, 0, size.width, size.height);
  64759. };
  64760. /**
  64761. * Updates the texture
  64762. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64763. * @param premulAlpha defines if alpha is stored as premultiplied (default is false)
  64764. */
  64765. DynamicTexture.prototype.update = function (invertY, premulAlpha) {
  64766. if (premulAlpha === void 0) { premulAlpha = false; }
  64767. this._engine.updateDynamicTexture(this._texture, this._canvas, invertY === undefined ? true : invertY, premulAlpha, this._format || undefined);
  64768. };
  64769. /**
  64770. * Draws text onto the texture
  64771. * @param text defines the text to be drawn
  64772. * @param x defines the placement of the text from the left
  64773. * @param y defines the placement of the text from the top when invertY is true and from the bottom when false
  64774. * @param font defines the font to be used with font-style, font-size, font-name
  64775. * @param color defines the color used for the text
  64776. * @param clearColor defines the color for the canvas, use null to not overwrite canvas
  64777. * @param invertY defines the direction for the Y axis (default is true - y increases downwards)
  64778. * @param update defines whether texture is immediately update (default is true)
  64779. */
  64780. DynamicTexture.prototype.drawText = function (text, x, y, font, color, clearColor, invertY, update) {
  64781. if (update === void 0) { update = true; }
  64782. var size = this.getSize();
  64783. if (clearColor) {
  64784. this._context.fillStyle = clearColor;
  64785. this._context.fillRect(0, 0, size.width, size.height);
  64786. }
  64787. this._context.font = font;
  64788. if (x === null || x === undefined) {
  64789. var textSize = this._context.measureText(text);
  64790. x = (size.width - textSize.width) / 2;
  64791. }
  64792. if (y === null || y === undefined) {
  64793. var fontSize = parseInt((font.replace(/\D/g, '')));
  64794. y = (size.height / 2) + (fontSize / 3.65);
  64795. }
  64796. this._context.fillStyle = color;
  64797. this._context.fillText(text, x, y);
  64798. if (update) {
  64799. this.update(invertY);
  64800. }
  64801. };
  64802. /**
  64803. * Clones the texture
  64804. * @returns the clone of the texture.
  64805. */
  64806. DynamicTexture.prototype.clone = function () {
  64807. var scene = this.getScene();
  64808. if (!scene) {
  64809. return this;
  64810. }
  64811. var textureSize = this.getSize();
  64812. var newTexture = new DynamicTexture(this.name, textureSize, scene, this._generateMipMaps);
  64813. // Base texture
  64814. newTexture.hasAlpha = this.hasAlpha;
  64815. newTexture.level = this.level;
  64816. // Dynamic Texture
  64817. newTexture.wrapU = this.wrapU;
  64818. newTexture.wrapV = this.wrapV;
  64819. return newTexture;
  64820. };
  64821. /** @hidden */
  64822. DynamicTexture.prototype._rebuild = function () {
  64823. this.update();
  64824. };
  64825. return DynamicTexture;
  64826. }(BABYLON.Texture));
  64827. BABYLON.DynamicTexture = DynamicTexture;
  64828. })(BABYLON || (BABYLON = {}));
  64829. //# sourceMappingURL=babylon.dynamicTexture.js.map
  64830. var BABYLON;
  64831. (function (BABYLON) {
  64832. var VideoTexture = /** @class */ (function (_super) {
  64833. __extends(VideoTexture, _super);
  64834. /**
  64835. * Creates a video texture.
  64836. * Sample : https://doc.babylonjs.com/how_to/video_texture
  64837. * @param {string | null} name optional name, will detect from video source, if not defined
  64838. * @param {(string | string[] | HTMLVideoElement)} src can be used to provide an url, array of urls or an already setup HTML video element.
  64839. * @param {BABYLON.Scene} scene is obviously the current scene.
  64840. * @param {boolean} generateMipMaps can be used to turn on mipmaps (Can be expensive for videoTextures because they are often updated).
  64841. * @param {boolean} invertY is false by default but can be used to invert video on Y axis
  64842. * @param {number} samplingMode controls the sampling method and is set to TRILINEAR_SAMPLINGMODE by default
  64843. * @param {VideoTextureSettings} [settings] allows finer control over video usage
  64844. */
  64845. function VideoTexture(name, src, scene, generateMipMaps, invertY, samplingMode, settings) {
  64846. if (generateMipMaps === void 0) { generateMipMaps = false; }
  64847. if (invertY === void 0) { invertY = false; }
  64848. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  64849. if (settings === void 0) { settings = {
  64850. autoPlay: true,
  64851. loop: true,
  64852. autoUpdateTexture: true,
  64853. }; }
  64854. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  64855. _this._onUserActionRequestedObservable = null;
  64856. _this._stillImageCaptured = false;
  64857. _this._createInternalTexture = function () {
  64858. if (_this._texture != null) {
  64859. return;
  64860. }
  64861. if (!_this._engine.needPOTTextures ||
  64862. (BABYLON.Tools.IsExponentOfTwo(_this.video.videoWidth) && BABYLON.Tools.IsExponentOfTwo(_this.video.videoHeight))) {
  64863. _this.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  64864. _this.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  64865. }
  64866. else {
  64867. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64868. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  64869. _this._generateMipMaps = false;
  64870. }
  64871. _this._texture = _this._engine.createDynamicTexture(_this.video.videoWidth, _this.video.videoHeight, _this._generateMipMaps, _this._samplingMode);
  64872. if (!_this.video.autoplay) {
  64873. var oldHandler_1 = _this.video.onplaying;
  64874. var error_1 = false;
  64875. _this.video.onplaying = function () {
  64876. _this.video.onplaying = oldHandler_1;
  64877. _this._texture.isReady = true;
  64878. _this._updateInternalTexture();
  64879. if (!error_1) {
  64880. _this.video.pause();
  64881. }
  64882. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64883. _this.onLoadObservable.notifyObservers(_this);
  64884. }
  64885. };
  64886. var playing = _this.video.play();
  64887. if (playing) {
  64888. playing.then(function () {
  64889. // Everything is good.
  64890. })
  64891. .catch(function () {
  64892. error_1 = true;
  64893. // On Chrome for instance, new policies might prevent playing without user interaction.
  64894. if (_this._onUserActionRequestedObservable && _this._onUserActionRequestedObservable.hasObservers()) {
  64895. _this._onUserActionRequestedObservable.notifyObservers(_this);
  64896. }
  64897. });
  64898. }
  64899. else {
  64900. _this.video.onplaying = oldHandler_1;
  64901. _this._texture.isReady = true;
  64902. _this._updateInternalTexture();
  64903. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64904. _this.onLoadObservable.notifyObservers(_this);
  64905. }
  64906. }
  64907. }
  64908. else {
  64909. _this._texture.isReady = true;
  64910. _this._updateInternalTexture();
  64911. if (_this._onLoadObservable && _this._onLoadObservable.hasObservers()) {
  64912. _this.onLoadObservable.notifyObservers(_this);
  64913. }
  64914. }
  64915. };
  64916. _this.reset = function () {
  64917. if (_this._texture == null) {
  64918. return;
  64919. }
  64920. _this._texture.dispose();
  64921. _this._texture = null;
  64922. };
  64923. _this._updateInternalTexture = function (e) {
  64924. if (_this._texture == null || !_this._texture.isReady) {
  64925. return;
  64926. }
  64927. if (_this.video.readyState < _this.video.HAVE_CURRENT_DATA) {
  64928. return;
  64929. }
  64930. _this._engine.updateVideoTexture(_this._texture, _this.video, _this._invertY);
  64931. };
  64932. _this._engine = _this.getScene().getEngine();
  64933. _this._generateMipMaps = generateMipMaps;
  64934. _this._samplingMode = samplingMode;
  64935. _this.autoUpdateTexture = settings.autoUpdateTexture;
  64936. _this.name = name || _this._getName(src);
  64937. _this.video = _this._getVideo(src);
  64938. if (settings.poster) {
  64939. _this.video.poster = settings.poster;
  64940. }
  64941. if (settings.autoPlay !== undefined) {
  64942. _this.video.autoplay = settings.autoPlay;
  64943. }
  64944. if (settings.loop !== undefined) {
  64945. _this.video.loop = settings.loop;
  64946. }
  64947. _this.video.setAttribute("playsinline", "");
  64948. _this.video.addEventListener("canplay", _this._createInternalTexture);
  64949. _this.video.addEventListener("paused", _this._updateInternalTexture);
  64950. _this.video.addEventListener("seeked", _this._updateInternalTexture);
  64951. _this.video.addEventListener("emptied", _this.reset);
  64952. if (_this.video.readyState >= _this.video.HAVE_CURRENT_DATA) {
  64953. _this._createInternalTexture();
  64954. }
  64955. return _this;
  64956. }
  64957. Object.defineProperty(VideoTexture.prototype, "onUserActionRequestedObservable", {
  64958. get: function () {
  64959. if (!this._onUserActionRequestedObservable) {
  64960. this._onUserActionRequestedObservable = new BABYLON.Observable();
  64961. }
  64962. return this._onUserActionRequestedObservable;
  64963. },
  64964. enumerable: true,
  64965. configurable: true
  64966. });
  64967. VideoTexture.prototype._getName = function (src) {
  64968. if (src instanceof HTMLVideoElement) {
  64969. return src.currentSrc;
  64970. }
  64971. if (typeof src === "object") {
  64972. return src.toString();
  64973. }
  64974. return src;
  64975. };
  64976. ;
  64977. VideoTexture.prototype._getVideo = function (src) {
  64978. if (src instanceof HTMLVideoElement) {
  64979. BABYLON.Tools.SetCorsBehavior(src.currentSrc, src);
  64980. return src;
  64981. }
  64982. var video = document.createElement("video");
  64983. if (typeof src === "string") {
  64984. BABYLON.Tools.SetCorsBehavior(src, video);
  64985. video.src = src;
  64986. }
  64987. else {
  64988. BABYLON.Tools.SetCorsBehavior(src[0], video);
  64989. src.forEach(function (url) {
  64990. var source = document.createElement("source");
  64991. source.src = url;
  64992. video.appendChild(source);
  64993. });
  64994. }
  64995. return video;
  64996. };
  64997. ;
  64998. /**
  64999. * Internal method to initiate `update`.
  65000. */
  65001. VideoTexture.prototype._rebuild = function () {
  65002. this.update();
  65003. };
  65004. /**
  65005. * Update Texture in the `auto` mode. Does not do anything if `settings.autoUpdateTexture` is false.
  65006. */
  65007. VideoTexture.prototype.update = function () {
  65008. if (!this.autoUpdateTexture) {
  65009. // Expecting user to call `updateTexture` manually
  65010. return;
  65011. }
  65012. this.updateTexture(true);
  65013. };
  65014. /**
  65015. * Update Texture in `manual` mode. Does not do anything if not visible or paused.
  65016. * @param isVisible Visibility state, detected by user using `scene.getActiveMeshes()` or othervise.
  65017. */
  65018. VideoTexture.prototype.updateTexture = function (isVisible) {
  65019. if (!isVisible) {
  65020. return;
  65021. }
  65022. if (this.video.paused && this._stillImageCaptured) {
  65023. return;
  65024. }
  65025. this._stillImageCaptured = true;
  65026. this._updateInternalTexture();
  65027. };
  65028. /**
  65029. * Change video content. Changing video instance or setting multiple urls (as in constructor) is not supported.
  65030. * @param url New url.
  65031. */
  65032. VideoTexture.prototype.updateURL = function (url) {
  65033. this.video.src = url;
  65034. };
  65035. VideoTexture.prototype.dispose = function () {
  65036. _super.prototype.dispose.call(this);
  65037. if (this._onUserActionRequestedObservable) {
  65038. this._onUserActionRequestedObservable.clear();
  65039. this._onUserActionRequestedObservable = null;
  65040. }
  65041. this.video.removeEventListener("canplay", this._createInternalTexture);
  65042. this.video.removeEventListener("paused", this._updateInternalTexture);
  65043. this.video.removeEventListener("seeked", this._updateInternalTexture);
  65044. this.video.removeEventListener("emptied", this.reset);
  65045. this.video.pause();
  65046. };
  65047. VideoTexture.CreateFromWebCam = function (scene, onReady, constraints) {
  65048. var video = document.createElement("video");
  65049. video.setAttribute('autoplay', '');
  65050. video.setAttribute('muted', '');
  65051. video.setAttribute('playsinline', '');
  65052. var constraintsDeviceId;
  65053. if (constraints && constraints.deviceId) {
  65054. constraintsDeviceId = {
  65055. exact: constraints.deviceId,
  65056. };
  65057. }
  65058. window.URL = window.URL || window.webkitURL || window.mozURL || window.msURL;
  65059. if (navigator.mediaDevices) {
  65060. navigator.mediaDevices.getUserMedia({ video: constraints })
  65061. .then(function (stream) {
  65062. if (video.mozSrcObject !== undefined) {
  65063. // hack for Firefox < 19
  65064. video.mozSrcObject = stream;
  65065. }
  65066. else {
  65067. video.srcObject = stream;
  65068. }
  65069. var onPlaying = function () {
  65070. if (onReady) {
  65071. onReady(new VideoTexture("video", video, scene, true, true));
  65072. }
  65073. video.removeEventListener("playing", onPlaying);
  65074. };
  65075. video.addEventListener("playing", onPlaying);
  65076. video.play();
  65077. })
  65078. .catch(function (err) {
  65079. BABYLON.Tools.Error(err.name);
  65080. });
  65081. }
  65082. else {
  65083. navigator.getUserMedia =
  65084. navigator.getUserMedia ||
  65085. navigator.webkitGetUserMedia ||
  65086. navigator.mozGetUserMedia ||
  65087. navigator.msGetUserMedia;
  65088. if (navigator.getUserMedia) {
  65089. navigator.getUserMedia({
  65090. video: {
  65091. deviceId: constraintsDeviceId,
  65092. width: {
  65093. min: (constraints && constraints.minWidth) || 256,
  65094. max: (constraints && constraints.maxWidth) || 640,
  65095. },
  65096. height: {
  65097. min: (constraints && constraints.minHeight) || 256,
  65098. max: (constraints && constraints.maxHeight) || 480,
  65099. },
  65100. },
  65101. }, function (stream) {
  65102. if (video.mozSrcObject !== undefined) {
  65103. // hack for Firefox < 19
  65104. video.mozSrcObject = stream;
  65105. }
  65106. else {
  65107. video.src = (window.URL && window.URL.createObjectURL(stream)) || stream;
  65108. }
  65109. video.play();
  65110. if (onReady) {
  65111. onReady(new VideoTexture("video", video, scene, true, true));
  65112. }
  65113. }, function (e) {
  65114. BABYLON.Tools.Error(e.name);
  65115. });
  65116. }
  65117. }
  65118. };
  65119. return VideoTexture;
  65120. }(BABYLON.Texture));
  65121. BABYLON.VideoTexture = VideoTexture;
  65122. })(BABYLON || (BABYLON = {}));
  65123. //# sourceMappingURL=babylon.videoTexture.js.map
  65124. var BABYLON;
  65125. (function (BABYLON) {
  65126. var RawTexture = /** @class */ (function (_super) {
  65127. __extends(RawTexture, _super);
  65128. function RawTexture(data, width, height, format, scene, generateMipMaps, invertY, samplingMode, type) {
  65129. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65130. if (invertY === void 0) { invertY = false; }
  65131. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65132. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65133. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65134. _this.format = format;
  65135. _this._engine = scene.getEngine();
  65136. _this._texture = scene.getEngine().createRawTexture(data, width, height, format, generateMipMaps, invertY, samplingMode, null, type);
  65137. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65138. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  65139. return _this;
  65140. }
  65141. RawTexture.prototype.update = function (data) {
  65142. this._engine.updateRawTexture(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65143. };
  65144. // Statics
  65145. RawTexture.CreateLuminanceTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65146. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65147. if (invertY === void 0) { invertY = false; }
  65148. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65149. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE, scene, generateMipMaps, invertY, samplingMode);
  65150. };
  65151. RawTexture.CreateLuminanceAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65152. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65153. if (invertY === void 0) { invertY = false; }
  65154. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65155. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_LUMINANCE_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65156. };
  65157. RawTexture.CreateAlphaTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode) {
  65158. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65159. if (invertY === void 0) { invertY = false; }
  65160. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65161. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_ALPHA, scene, generateMipMaps, invertY, samplingMode);
  65162. };
  65163. RawTexture.CreateRGBTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65164. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65165. if (invertY === void 0) { invertY = false; }
  65166. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65167. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65168. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGB, scene, generateMipMaps, invertY, samplingMode, type);
  65169. };
  65170. RawTexture.CreateRGBATexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65171. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65172. if (invertY === void 0) { invertY = false; }
  65173. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65174. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65175. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_RGBA, scene, generateMipMaps, invertY, samplingMode, type);
  65176. };
  65177. RawTexture.CreateRTexture = function (data, width, height, scene, generateMipMaps, invertY, samplingMode, type) {
  65178. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65179. if (invertY === void 0) { invertY = false; }
  65180. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65181. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  65182. return new RawTexture(data, width, height, BABYLON.Engine.TEXTUREFORMAT_R, scene, generateMipMaps, invertY, samplingMode, type);
  65183. };
  65184. return RawTexture;
  65185. }(BABYLON.Texture));
  65186. BABYLON.RawTexture = RawTexture;
  65187. })(BABYLON || (BABYLON = {}));
  65188. //# sourceMappingURL=babylon.rawTexture.js.map
  65189. var BABYLON;
  65190. (function (BABYLON) {
  65191. /**
  65192. * Class used to store 3D textures containing user data
  65193. */
  65194. var RawTexture3D = /** @class */ (function (_super) {
  65195. __extends(RawTexture3D, _super);
  65196. /**
  65197. * Create a new RawTexture3D
  65198. * @param data defines the data of the texture
  65199. * @param width defines the width of the texture
  65200. * @param height defines the height of the texture
  65201. * @param depth defines the depth of the texture
  65202. * @param format defines the texture format to use
  65203. * @param scene defines the hosting scene
  65204. * @param generateMipMaps defines a boolean indicating if mip levels should be generated (true by default)
  65205. * @param invertY defines if texture must be stored with Y axis inverted
  65206. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  65207. * @param textureType defines the texture Type (Engine.TEXTURETYPE_UNSIGNED_INT, Engine.TEXTURETYPE_FLOAT...)
  65208. */
  65209. function RawTexture3D(data, width, height, depth,
  65210. /** Gets or sets the texture format to use */
  65211. format, scene, generateMipMaps, invertY, samplingMode, textureType) {
  65212. if (generateMipMaps === void 0) { generateMipMaps = true; }
  65213. if (invertY === void 0) { invertY = false; }
  65214. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  65215. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65216. var _this = _super.call(this, null, scene, !generateMipMaps, invertY) || this;
  65217. _this.format = format;
  65218. _this._engine = scene.getEngine();
  65219. _this._texture = scene.getEngine().createRawTexture3D(data, width, height, depth, format, generateMipMaps, invertY, samplingMode, undefined, textureType);
  65220. _this.is3D = true;
  65221. return _this;
  65222. }
  65223. /**
  65224. * Update the texture with new data
  65225. * @param data defines the data to store in the texture
  65226. */
  65227. RawTexture3D.prototype.update = function (data) {
  65228. if (!this._texture) {
  65229. return;
  65230. }
  65231. this._engine.updateRawTexture3D(this._texture, data, this._texture.format, this._texture.invertY, undefined, this._texture.type);
  65232. };
  65233. return RawTexture3D;
  65234. }(BABYLON.Texture));
  65235. BABYLON.RawTexture3D = RawTexture3D;
  65236. })(BABYLON || (BABYLON = {}));
  65237. //# sourceMappingURL=babylon.rawTexture3D.js.map
  65238. var BABYLON;
  65239. (function (BABYLON) {
  65240. /**
  65241. * PostProcessManager is used to manage one or more post processes or post process pipelines
  65242. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65243. */
  65244. var PostProcessManager = /** @class */ (function () {
  65245. /**
  65246. * Creates a new instance PostProcess
  65247. * @param scene The scene that the post process is associated with.
  65248. */
  65249. function PostProcessManager(scene) {
  65250. this._vertexBuffers = {};
  65251. this._scene = scene;
  65252. }
  65253. PostProcessManager.prototype._prepareBuffers = function () {
  65254. if (this._vertexBuffers[BABYLON.VertexBuffer.PositionKind]) {
  65255. return;
  65256. }
  65257. // VBO
  65258. var vertices = [];
  65259. vertices.push(1, 1);
  65260. vertices.push(-1, 1);
  65261. vertices.push(-1, -1);
  65262. vertices.push(1, -1);
  65263. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(this._scene.getEngine(), vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  65264. this._buildIndexBuffer();
  65265. };
  65266. PostProcessManager.prototype._buildIndexBuffer = function () {
  65267. // Indices
  65268. var indices = [];
  65269. indices.push(0);
  65270. indices.push(1);
  65271. indices.push(2);
  65272. indices.push(0);
  65273. indices.push(2);
  65274. indices.push(3);
  65275. this._indexBuffer = this._scene.getEngine().createIndexBuffer(indices);
  65276. };
  65277. /**
  65278. * Rebuilds the vertex buffers of the manager.
  65279. */
  65280. PostProcessManager.prototype._rebuild = function () {
  65281. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65282. if (!vb) {
  65283. return;
  65284. }
  65285. vb._rebuild();
  65286. this._buildIndexBuffer();
  65287. };
  65288. // Methods
  65289. /**
  65290. * Prepares a frame to be run through a post process.
  65291. * @param sourceTexture The input texture to the post procesess. (default: null)
  65292. * @param postProcesses An array of post processes to be run. (default: null)
  65293. * @returns True if the post processes were able to be run.
  65294. */
  65295. PostProcessManager.prototype._prepareFrame = function (sourceTexture, postProcesses) {
  65296. if (sourceTexture === void 0) { sourceTexture = null; }
  65297. if (postProcesses === void 0) { postProcesses = null; }
  65298. var camera = this._scene.activeCamera;
  65299. if (!camera) {
  65300. return false;
  65301. }
  65302. var postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65303. if (!postProcesses || postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65304. return false;
  65305. }
  65306. postProcesses[0].activate(camera, sourceTexture, postProcesses !== null && postProcesses !== undefined);
  65307. return true;
  65308. };
  65309. /**
  65310. * Manually render a set of post processes to a texture.
  65311. * @param postProcesses An array of post processes to be run.
  65312. * @param targetTexture The target texture to render to.
  65313. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight
  65314. * @param faceIndex defines the face to render to if a cubemap is defined as the target
  65315. * @param lodLevel defines which lod of the texture to render to
  65316. */
  65317. PostProcessManager.prototype.directRender = function (postProcesses, targetTexture, forceFullscreenViewport, faceIndex, lodLevel) {
  65318. if (targetTexture === void 0) { targetTexture = null; }
  65319. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65320. if (faceIndex === void 0) { faceIndex = 0; }
  65321. if (lodLevel === void 0) { lodLevel = 0; }
  65322. var engine = this._scene.getEngine();
  65323. for (var index = 0; index < postProcesses.length; index++) {
  65324. if (index < postProcesses.length - 1) {
  65325. postProcesses[index + 1].activate(this._scene.activeCamera, targetTexture);
  65326. }
  65327. else {
  65328. if (targetTexture) {
  65329. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport, undefined, lodLevel);
  65330. }
  65331. else {
  65332. engine.restoreDefaultFramebuffer();
  65333. }
  65334. }
  65335. var pp = postProcesses[index];
  65336. var effect = pp.apply();
  65337. if (effect) {
  65338. pp.onBeforeRenderObservable.notifyObservers(effect);
  65339. // VBOs
  65340. this._prepareBuffers();
  65341. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65342. // Draw order
  65343. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65344. pp.onAfterRenderObservable.notifyObservers(effect);
  65345. }
  65346. }
  65347. // Restore depth buffer
  65348. engine.setDepthBuffer(true);
  65349. engine.setDepthWrite(true);
  65350. };
  65351. /**
  65352. * Finalize the result of the output of the postprocesses.
  65353. * @param doNotPresent If true the result will not be displayed to the screen.
  65354. * @param targetTexture The target texture to render to.
  65355. * @param faceIndex The index of the face to bind the target texture to.
  65356. * @param postProcesses The array of post processes to render.
  65357. * @param forceFullscreenViewport force gl.viewport to be full screen eg. 0,0,textureWidth,textureHeight (default: false)
  65358. */
  65359. PostProcessManager.prototype._finalizeFrame = function (doNotPresent, targetTexture, faceIndex, postProcesses, forceFullscreenViewport) {
  65360. if (forceFullscreenViewport === void 0) { forceFullscreenViewport = false; }
  65361. var camera = this._scene.activeCamera;
  65362. if (!camera) {
  65363. return;
  65364. }
  65365. postProcesses = postProcesses || camera._postProcesses.filter(function (pp) { return pp != null; });
  65366. if (postProcesses.length === 0 || !this._scene.postProcessesEnabled) {
  65367. return;
  65368. }
  65369. var engine = this._scene.getEngine();
  65370. for (var index = 0, len = postProcesses.length; index < len; index++) {
  65371. var pp = postProcesses[index];
  65372. if (index < len - 1) {
  65373. pp._outputTexture = postProcesses[index + 1].activate(camera, targetTexture);
  65374. }
  65375. else {
  65376. if (targetTexture) {
  65377. engine.bindFramebuffer(targetTexture, faceIndex, undefined, undefined, forceFullscreenViewport);
  65378. pp._outputTexture = targetTexture;
  65379. }
  65380. else {
  65381. engine.restoreDefaultFramebuffer();
  65382. pp._outputTexture = null;
  65383. }
  65384. }
  65385. if (doNotPresent) {
  65386. break;
  65387. }
  65388. var effect = pp.apply();
  65389. if (effect) {
  65390. pp.onBeforeRenderObservable.notifyObservers(effect);
  65391. // VBOs
  65392. this._prepareBuffers();
  65393. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, effect);
  65394. // Draw order
  65395. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  65396. pp.onAfterRenderObservable.notifyObservers(effect);
  65397. }
  65398. }
  65399. // Restore states
  65400. engine.setDepthBuffer(true);
  65401. engine.setDepthWrite(true);
  65402. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  65403. };
  65404. /**
  65405. * Disposes of the post process manager.
  65406. */
  65407. PostProcessManager.prototype.dispose = function () {
  65408. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  65409. if (buffer) {
  65410. buffer.dispose();
  65411. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  65412. }
  65413. if (this._indexBuffer) {
  65414. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  65415. this._indexBuffer = null;
  65416. }
  65417. };
  65418. return PostProcessManager;
  65419. }());
  65420. BABYLON.PostProcessManager = PostProcessManager;
  65421. })(BABYLON || (BABYLON = {}));
  65422. //# sourceMappingURL=babylon.postProcessManager.js.map
  65423. var BABYLON;
  65424. (function (BABYLON) {
  65425. /**
  65426. * PostProcess can be used to apply a shader to a texture after it has been rendered
  65427. * See https://doc.babylonjs.com/how_to/how_to_use_postprocesses
  65428. */
  65429. var PostProcess = /** @class */ (function () {
  65430. /**
  65431. * Creates a new instance PostProcess
  65432. * @param name The name of the PostProcess.
  65433. * @param fragmentUrl The url of the fragment shader to be used.
  65434. * @param parameters Array of the names of uniform non-sampler2D variables that will be passed to the shader.
  65435. * @param samplers Array of the names of uniform sampler2D variables that will be passed to the shader.
  65436. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  65437. * @param camera The camera to apply the render pass to.
  65438. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  65439. * @param engine The engine which the post process will be applied. (default: current engine)
  65440. * @param reusable If the post process can be reused on the same frame. (default: false)
  65441. * @param defines String of defines that will be set when running the fragment shader. (default: null)
  65442. * @param textureType Type of textures used when performing the post process. (default: 0)
  65443. * @param vertexUrl The url of the vertex shader to be used. (default: "postprocess")
  65444. * @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
  65445. * @param blockCompilation If the shader should not be compiled imediatly. (default: false)
  65446. */
  65447. function PostProcess(/** Name of the PostProcess. */ name, fragmentUrl, parameters, samplers, options, camera, samplingMode, engine, reusable, defines, textureType, vertexUrl, indexParameters, blockCompilation) {
  65448. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.NEAREST_SAMPLINGMODE; }
  65449. if (defines === void 0) { defines = null; }
  65450. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65451. if (vertexUrl === void 0) { vertexUrl = "postprocess"; }
  65452. if (blockCompilation === void 0) { blockCompilation = false; }
  65453. this.name = name;
  65454. /**
  65455. * Width of the texture to apply the post process on
  65456. */
  65457. this.width = -1;
  65458. /**
  65459. * Height of the texture to apply the post process on
  65460. */
  65461. this.height = -1;
  65462. /**
  65463. * Internal, reference to the location where this postprocess was output to. (Typically the texture on the next postprocess in the chain)
  65464. */
  65465. this._outputTexture = null;
  65466. /**
  65467. * If the buffer needs to be cleared before applying the post process. (default: true)
  65468. * Should be set to false if shader will overwrite all previous pixels.
  65469. */
  65470. this.autoClear = true;
  65471. /**
  65472. * Type of alpha mode to use when performing the post process (default: Engine.ALPHA_DISABLE)
  65473. */
  65474. this.alphaMode = BABYLON.Engine.ALPHA_DISABLE;
  65475. /**
  65476. * Animations to be used for the post processing
  65477. */
  65478. this.animations = new Array();
  65479. /**
  65480. * Enable Pixel Perfect mode where texture is not scaled to be power of 2.
  65481. * Can only be used on a single postprocess or on the last one of a chain. (default: false)
  65482. */
  65483. this.enablePixelPerfectMode = false;
  65484. /**
  65485. * Force the postprocess to be applied without taking in account viewport
  65486. */
  65487. this.forceFullscreenViewport = true;
  65488. /**
  65489. * Scale mode for the post process (default: Engine.SCALEMODE_FLOOR)
  65490. *
  65491. * | Value | Type | Description |
  65492. * | ----- | ----------------------------------- | ----------- |
  65493. * | 1 | SCALEMODE_FLOOR | [engine.scalemode_floor](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_floor) |
  65494. * | 2 | SCALEMODE_NEAREST | [engine.scalemode_nearest](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_nearest) |
  65495. * | 3 | SCALEMODE_CEILING | [engine.scalemode_ceiling](http://doc.babylonjs.com/api/classes/babylon.engine#scalemode_ceiling) |
  65496. *
  65497. */
  65498. this.scaleMode = BABYLON.Engine.SCALEMODE_FLOOR;
  65499. /**
  65500. * Force textures to be a power of two (default: false)
  65501. */
  65502. this.alwaysForcePOT = false;
  65503. /**
  65504. * Number of sample textures (default: 1)
  65505. */
  65506. this.samples = 1;
  65507. /**
  65508. * Modify the scale of the post process to be the same as the viewport (default: false)
  65509. */
  65510. this.adaptScaleToCurrentViewport = false;
  65511. this._reusable = false;
  65512. /**
  65513. * Smart array of input and output textures for the post process.
  65514. */
  65515. this._textures = new BABYLON.SmartArray(2);
  65516. /**
  65517. * The index in _textures that corresponds to the output texture.
  65518. */
  65519. this._currentRenderTextureInd = 0;
  65520. this._scaleRatio = new BABYLON.Vector2(1, 1);
  65521. this._texelSize = BABYLON.Vector2.Zero();
  65522. // Events
  65523. /**
  65524. * An event triggered when the postprocess is activated.
  65525. */
  65526. this.onActivateObservable = new BABYLON.Observable();
  65527. /**
  65528. * An event triggered when the postprocess changes its size.
  65529. */
  65530. this.onSizeChangedObservable = new BABYLON.Observable();
  65531. /**
  65532. * An event triggered when the postprocess applies its effect.
  65533. */
  65534. this.onApplyObservable = new BABYLON.Observable();
  65535. /**
  65536. * An event triggered before rendering the postprocess
  65537. */
  65538. this.onBeforeRenderObservable = new BABYLON.Observable();
  65539. /**
  65540. * An event triggered after rendering the postprocess
  65541. */
  65542. this.onAfterRenderObservable = new BABYLON.Observable();
  65543. if (camera != null) {
  65544. this._camera = camera;
  65545. this._scene = camera.getScene();
  65546. camera.attachPostProcess(this);
  65547. this._engine = this._scene.getEngine();
  65548. this._scene.postProcesses.push(this);
  65549. }
  65550. else if (engine) {
  65551. this._engine = engine;
  65552. this._engine.postProcesses.push(this);
  65553. }
  65554. this._options = options;
  65555. this.renderTargetSamplingMode = samplingMode ? samplingMode : BABYLON.Texture.NEAREST_SAMPLINGMODE;
  65556. this._reusable = reusable || false;
  65557. this._textureType = textureType;
  65558. this._samplers = samplers || [];
  65559. this._samplers.push("textureSampler");
  65560. this._fragmentUrl = fragmentUrl;
  65561. this._vertexUrl = vertexUrl;
  65562. this._parameters = parameters || [];
  65563. this._parameters.push("scale");
  65564. this._indexParameters = indexParameters;
  65565. if (!blockCompilation) {
  65566. this.updateEffect(defines);
  65567. }
  65568. }
  65569. Object.defineProperty(PostProcess.prototype, "onActivate", {
  65570. /**
  65571. * A function that is added to the onActivateObservable
  65572. */
  65573. set: function (callback) {
  65574. if (this._onActivateObserver) {
  65575. this.onActivateObservable.remove(this._onActivateObserver);
  65576. }
  65577. if (callback) {
  65578. this._onActivateObserver = this.onActivateObservable.add(callback);
  65579. }
  65580. },
  65581. enumerable: true,
  65582. configurable: true
  65583. });
  65584. Object.defineProperty(PostProcess.prototype, "onSizeChanged", {
  65585. /**
  65586. * A function that is added to the onSizeChangedObservable
  65587. */
  65588. set: function (callback) {
  65589. if (this._onSizeChangedObserver) {
  65590. this.onSizeChangedObservable.remove(this._onSizeChangedObserver);
  65591. }
  65592. this._onSizeChangedObserver = this.onSizeChangedObservable.add(callback);
  65593. },
  65594. enumerable: true,
  65595. configurable: true
  65596. });
  65597. Object.defineProperty(PostProcess.prototype, "onApply", {
  65598. /**
  65599. * A function that is added to the onApplyObservable
  65600. */
  65601. set: function (callback) {
  65602. if (this._onApplyObserver) {
  65603. this.onApplyObservable.remove(this._onApplyObserver);
  65604. }
  65605. this._onApplyObserver = this.onApplyObservable.add(callback);
  65606. },
  65607. enumerable: true,
  65608. configurable: true
  65609. });
  65610. Object.defineProperty(PostProcess.prototype, "onBeforeRender", {
  65611. /**
  65612. * A function that is added to the onBeforeRenderObservable
  65613. */
  65614. set: function (callback) {
  65615. if (this._onBeforeRenderObserver) {
  65616. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  65617. }
  65618. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  65619. },
  65620. enumerable: true,
  65621. configurable: true
  65622. });
  65623. Object.defineProperty(PostProcess.prototype, "onAfterRender", {
  65624. /**
  65625. * A function that is added to the onAfterRenderObservable
  65626. */
  65627. set: function (callback) {
  65628. if (this._onAfterRenderObserver) {
  65629. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  65630. }
  65631. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  65632. },
  65633. enumerable: true,
  65634. configurable: true
  65635. });
  65636. Object.defineProperty(PostProcess.prototype, "inputTexture", {
  65637. /**
  65638. * 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
  65639. * render it's output into this texture and this texture will be used as textureSampler in the fragment shader of this post process.
  65640. */
  65641. get: function () {
  65642. return this._textures.data[this._currentRenderTextureInd];
  65643. },
  65644. set: function (value) {
  65645. this._forcedOutputTexture = value;
  65646. },
  65647. enumerable: true,
  65648. configurable: true
  65649. });
  65650. /**
  65651. * Gets the camera which post process is applied to.
  65652. * @returns The camera the post process is applied to.
  65653. */
  65654. PostProcess.prototype.getCamera = function () {
  65655. return this._camera;
  65656. };
  65657. Object.defineProperty(PostProcess.prototype, "texelSize", {
  65658. /**
  65659. * Gets the texel size of the postprocess.
  65660. * See https://en.wikipedia.org/wiki/Texel_(graphics)
  65661. */
  65662. get: function () {
  65663. if (this._shareOutputWithPostProcess) {
  65664. return this._shareOutputWithPostProcess.texelSize;
  65665. }
  65666. if (this._forcedOutputTexture) {
  65667. this._texelSize.copyFromFloats(1.0 / this._forcedOutputTexture.width, 1.0 / this._forcedOutputTexture.height);
  65668. }
  65669. return this._texelSize;
  65670. },
  65671. enumerable: true,
  65672. configurable: true
  65673. });
  65674. /**
  65675. * Gets the engine which this post process belongs to.
  65676. * @returns The engine the post process was enabled with.
  65677. */
  65678. PostProcess.prototype.getEngine = function () {
  65679. return this._engine;
  65680. };
  65681. /**
  65682. * The effect that is created when initializing the post process.
  65683. * @returns The created effect corrisponding the the postprocess.
  65684. */
  65685. PostProcess.prototype.getEffect = function () {
  65686. return this._effect;
  65687. };
  65688. /**
  65689. * To avoid multiple redundant textures for multiple post process, the output the output texture for this post process can be shared with another.
  65690. * @param postProcess The post process to share the output with.
  65691. * @returns This post process.
  65692. */
  65693. PostProcess.prototype.shareOutputWith = function (postProcess) {
  65694. this._disposeTextures();
  65695. this._shareOutputWithPostProcess = postProcess;
  65696. return this;
  65697. };
  65698. /**
  65699. * Reverses the effect of calling shareOutputWith and returns the post process back to its original state.
  65700. * This should be called if the post process that shares output with this post process is disabled/disposed.
  65701. */
  65702. PostProcess.prototype.useOwnOutput = function () {
  65703. if (this._textures.length == 0) {
  65704. this._textures = new BABYLON.SmartArray(2);
  65705. }
  65706. this._shareOutputWithPostProcess = null;
  65707. };
  65708. /**
  65709. * Updates the effect with the current post process compile time values and recompiles the shader.
  65710. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  65711. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  65712. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  65713. * @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
  65714. * @param onCompiled Called when the shader has been compiled.
  65715. * @param onError Called if there is an error when compiling a shader.
  65716. */
  65717. PostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  65718. if (defines === void 0) { defines = null; }
  65719. if (uniforms === void 0) { uniforms = null; }
  65720. if (samplers === void 0) { samplers = null; }
  65721. 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);
  65722. };
  65723. /**
  65724. * The post process is reusable if it can be used multiple times within one frame.
  65725. * @returns If the post process is reusable
  65726. */
  65727. PostProcess.prototype.isReusable = function () {
  65728. return this._reusable;
  65729. };
  65730. /** invalidate frameBuffer to hint the postprocess to create a depth buffer */
  65731. PostProcess.prototype.markTextureDirty = function () {
  65732. this.width = -1;
  65733. };
  65734. /**
  65735. * Activates the post process by intializing the textures to be used when executed. Notifies onActivateObservable.
  65736. * 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.
  65737. * @param camera The camera that will be used in the post process. This camera will be used when calling onActivateObservable.
  65738. * @param sourceTexture The source texture to be inspected to get the width and height if not specified in the post process constructor. (default: null)
  65739. * @param forceDepthStencil If true, a depth and stencil buffer will be generated. (default: false)
  65740. * @returns The target texture that was bound to be written to.
  65741. */
  65742. PostProcess.prototype.activate = function (camera, sourceTexture, forceDepthStencil) {
  65743. var _this = this;
  65744. if (sourceTexture === void 0) { sourceTexture = null; }
  65745. camera = camera || this._camera;
  65746. var scene = camera.getScene();
  65747. var engine = scene.getEngine();
  65748. var maxSize = engine.getCaps().maxTextureSize;
  65749. var requiredWidth = ((sourceTexture ? sourceTexture.width : this._engine.getRenderWidth(true)) * this._options) | 0;
  65750. var requiredHeight = ((sourceTexture ? sourceTexture.height : this._engine.getRenderHeight(true)) * this._options) | 0;
  65751. // 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
  65752. var webVRCamera = camera.parent;
  65753. if (webVRCamera && (webVRCamera.leftCamera == camera || webVRCamera.rightCamera == camera)) {
  65754. requiredWidth /= 2;
  65755. }
  65756. var desiredWidth = (this._options.width || requiredWidth);
  65757. var desiredHeight = this._options.height || requiredHeight;
  65758. if (!this._shareOutputWithPostProcess && !this._forcedOutputTexture) {
  65759. if (this.adaptScaleToCurrentViewport) {
  65760. var currentViewport = engine.currentViewport;
  65761. if (currentViewport) {
  65762. desiredWidth *= currentViewport.width;
  65763. desiredHeight *= currentViewport.height;
  65764. }
  65765. }
  65766. if (this.renderTargetSamplingMode === BABYLON.Texture.TRILINEAR_SAMPLINGMODE || this.alwaysForcePOT) {
  65767. if (!this._options.width) {
  65768. desiredWidth = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredWidth, maxSize, this.scaleMode) : desiredWidth;
  65769. }
  65770. if (!this._options.height) {
  65771. desiredHeight = engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(desiredHeight, maxSize, this.scaleMode) : desiredHeight;
  65772. }
  65773. }
  65774. if (this.width !== desiredWidth || this.height !== desiredHeight) {
  65775. if (this._textures.length > 0) {
  65776. for (var i = 0; i < this._textures.length; i++) {
  65777. this._engine._releaseTexture(this._textures.data[i]);
  65778. }
  65779. this._textures.reset();
  65780. }
  65781. this.width = desiredWidth;
  65782. this.height = desiredHeight;
  65783. var textureSize = { width: this.width, height: this.height };
  65784. var textureOptions = {
  65785. generateMipMaps: false,
  65786. generateDepthBuffer: forceDepthStencil || camera._postProcesses.indexOf(this) === 0,
  65787. generateStencilBuffer: (forceDepthStencil || camera._postProcesses.indexOf(this) === 0) && this._engine.isStencilEnable,
  65788. samplingMode: this.renderTargetSamplingMode,
  65789. type: this._textureType
  65790. };
  65791. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65792. if (this._reusable) {
  65793. this._textures.push(this._engine.createRenderTargetTexture(textureSize, textureOptions));
  65794. }
  65795. this._texelSize.copyFromFloats(1.0 / this.width, 1.0 / this.height);
  65796. this.onSizeChangedObservable.notifyObservers(this);
  65797. }
  65798. this._textures.forEach(function (texture) {
  65799. if (texture.samples !== _this.samples) {
  65800. _this._engine.updateRenderTargetTextureSampleCount(texture, _this.samples);
  65801. }
  65802. });
  65803. }
  65804. var target;
  65805. if (this._shareOutputWithPostProcess) {
  65806. target = this._shareOutputWithPostProcess.inputTexture;
  65807. }
  65808. else if (this._forcedOutputTexture) {
  65809. target = this._forcedOutputTexture;
  65810. this.width = this._forcedOutputTexture.width;
  65811. this.height = this._forcedOutputTexture.height;
  65812. }
  65813. else {
  65814. target = this.inputTexture;
  65815. }
  65816. // Bind the input of this post process to be used as the output of the previous post process.
  65817. if (this.enablePixelPerfectMode) {
  65818. this._scaleRatio.copyFromFloats(requiredWidth / desiredWidth, requiredHeight / desiredHeight);
  65819. this._engine.bindFramebuffer(target, 0, requiredWidth, requiredHeight, this.forceFullscreenViewport);
  65820. }
  65821. else {
  65822. this._scaleRatio.copyFromFloats(1, 1);
  65823. this._engine.bindFramebuffer(target, 0, undefined, undefined, this.forceFullscreenViewport);
  65824. }
  65825. this.onActivateObservable.notifyObservers(camera);
  65826. // Clear
  65827. if (this.autoClear && this.alphaMode === BABYLON.Engine.ALPHA_DISABLE) {
  65828. this._engine.clear(this.clearColor ? this.clearColor : scene.clearColor, true, true, true);
  65829. }
  65830. if (this._reusable) {
  65831. this._currentRenderTextureInd = (this._currentRenderTextureInd + 1) % 2;
  65832. }
  65833. return target;
  65834. };
  65835. Object.defineProperty(PostProcess.prototype, "isSupported", {
  65836. /**
  65837. * If the post process is supported.
  65838. */
  65839. get: function () {
  65840. return this._effect.isSupported;
  65841. },
  65842. enumerable: true,
  65843. configurable: true
  65844. });
  65845. Object.defineProperty(PostProcess.prototype, "aspectRatio", {
  65846. /**
  65847. * The aspect ratio of the output texture.
  65848. */
  65849. get: function () {
  65850. if (this._shareOutputWithPostProcess) {
  65851. return this._shareOutputWithPostProcess.aspectRatio;
  65852. }
  65853. if (this._forcedOutputTexture) {
  65854. return this._forcedOutputTexture.width / this._forcedOutputTexture.height;
  65855. }
  65856. return this.width / this.height;
  65857. },
  65858. enumerable: true,
  65859. configurable: true
  65860. });
  65861. /**
  65862. * Get a value indicating if the post-process is ready to be used
  65863. * @returns true if the post-process is ready (shader is compiled)
  65864. */
  65865. PostProcess.prototype.isReady = function () {
  65866. return this._effect && this._effect.isReady();
  65867. };
  65868. /**
  65869. * Binds all textures and uniforms to the shader, this will be run on every pass.
  65870. * @returns the effect corrisponding to this post process. Null if not compiled or not ready.
  65871. */
  65872. PostProcess.prototype.apply = function () {
  65873. // Check
  65874. if (!this._effect || !this._effect.isReady())
  65875. return null;
  65876. // States
  65877. this._engine.enableEffect(this._effect);
  65878. this._engine.setState(false);
  65879. this._engine.setDepthBuffer(false);
  65880. this._engine.setDepthWrite(false);
  65881. // Alpha
  65882. this._engine.setAlphaMode(this.alphaMode);
  65883. if (this.alphaConstants) {
  65884. this.getEngine().setAlphaConstants(this.alphaConstants.r, this.alphaConstants.g, this.alphaConstants.b, this.alphaConstants.a);
  65885. }
  65886. // Bind the output texture of the preivous post process as the input to this post process.
  65887. var source;
  65888. if (this._shareOutputWithPostProcess) {
  65889. source = this._shareOutputWithPostProcess.inputTexture;
  65890. }
  65891. else if (this._forcedOutputTexture) {
  65892. source = this._forcedOutputTexture;
  65893. }
  65894. else {
  65895. source = this.inputTexture;
  65896. }
  65897. this._effect._bindTexture("textureSampler", source);
  65898. // Parameters
  65899. this._effect.setVector2("scale", this._scaleRatio);
  65900. this.onApplyObservable.notifyObservers(this._effect);
  65901. return this._effect;
  65902. };
  65903. PostProcess.prototype._disposeTextures = function () {
  65904. if (this._shareOutputWithPostProcess || this._forcedOutputTexture) {
  65905. return;
  65906. }
  65907. if (this._textures.length > 0) {
  65908. for (var i = 0; i < this._textures.length; i++) {
  65909. this._engine._releaseTexture(this._textures.data[i]);
  65910. }
  65911. }
  65912. this._textures.dispose();
  65913. };
  65914. /**
  65915. * Disposes the post process.
  65916. * @param camera The camera to dispose the post process on.
  65917. */
  65918. PostProcess.prototype.dispose = function (camera) {
  65919. camera = camera || this._camera;
  65920. this._disposeTextures();
  65921. if (this._scene) {
  65922. var index_1 = this._scene.postProcesses.indexOf(this);
  65923. if (index_1 !== -1) {
  65924. this._scene.postProcesses.splice(index_1, 1);
  65925. }
  65926. }
  65927. else {
  65928. var index_2 = this._engine.postProcesses.indexOf(this);
  65929. if (index_2 !== -1) {
  65930. this._engine.postProcesses.splice(index_2, 1);
  65931. }
  65932. }
  65933. if (!camera) {
  65934. return;
  65935. }
  65936. camera.detachPostProcess(this);
  65937. var index = camera._postProcesses.indexOf(this);
  65938. if (index === 0 && camera._postProcesses.length > 0) {
  65939. var firstPostProcess = this._camera._getFirstPostProcess();
  65940. if (firstPostProcess) {
  65941. firstPostProcess.markTextureDirty();
  65942. }
  65943. }
  65944. this.onActivateObservable.clear();
  65945. this.onAfterRenderObservable.clear();
  65946. this.onApplyObservable.clear();
  65947. this.onBeforeRenderObservable.clear();
  65948. this.onSizeChangedObservable.clear();
  65949. };
  65950. return PostProcess;
  65951. }());
  65952. BABYLON.PostProcess = PostProcess;
  65953. })(BABYLON || (BABYLON = {}));
  65954. //# sourceMappingURL=babylon.postProcess.js.map
  65955. var BABYLON;
  65956. (function (BABYLON) {
  65957. var PassPostProcess = /** @class */ (function (_super) {
  65958. __extends(PassPostProcess, _super);
  65959. function PassPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  65960. if (camera === void 0) { camera = null; }
  65961. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  65962. if (blockCompilation === void 0) { blockCompilation = false; }
  65963. return _super.call(this, name, "pass", null, null, options, camera, samplingMode, engine, reusable, undefined, textureType, undefined, null, blockCompilation) || this;
  65964. }
  65965. return PassPostProcess;
  65966. }(BABYLON.PostProcess));
  65967. BABYLON.PassPostProcess = PassPostProcess;
  65968. })(BABYLON || (BABYLON = {}));
  65969. //# sourceMappingURL=babylon.passPostProcess.js.map
  65970. var __assign = (this && this.__assign) || Object.assign || function(t) {
  65971. for (var s, i = 1, n = arguments.length; i < n; i++) {
  65972. s = arguments[i];
  65973. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  65974. t[p] = s[p];
  65975. }
  65976. return t;
  65977. };
  65978. var BABYLON;
  65979. (function (BABYLON) {
  65980. /**
  65981. * Default implementation IShadowGenerator.
  65982. * This is the main object responsible of generating shadows in the framework.
  65983. * Documentation: https://doc.babylonjs.com/babylon101/shadows
  65984. */
  65985. var ShadowGenerator = /** @class */ (function () {
  65986. /**
  65987. * Creates a ShadowGenerator object.
  65988. * A ShadowGenerator is the required tool to use the shadows.
  65989. * Each light casting shadows needs to use its own ShadowGenerator.
  65990. * Documentation : http://doc.babylonjs.com/tutorials/shadows
  65991. * @param mapSize The size of the texture what stores the shadows. Example : 1024.
  65992. * @param light The light object generating the shadows.
  65993. * @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.
  65994. */
  65995. function ShadowGenerator(mapSize, light, useFullFloatFirst) {
  65996. this._bias = 0.00005;
  65997. this._normalBias = 0;
  65998. this._blurBoxOffset = 1;
  65999. this._blurScale = 2;
  66000. this._blurKernel = 1;
  66001. this._useKernelBlur = false;
  66002. this._filter = ShadowGenerator.FILTER_NONE;
  66003. this._filteringQuality = ShadowGenerator.QUALITY_HIGH;
  66004. this._contactHardeningLightSizeUVRatio = 0.1;
  66005. this._darkness = 0;
  66006. this._transparencyShadow = false;
  66007. /**
  66008. * Controls the extent to which the shadows fade out at the edge of the frustum
  66009. * Used only by directionals and spots
  66010. */
  66011. this.frustumEdgeFalloff = 0;
  66012. /**
  66013. * If true the shadow map is generated by rendering the back face of the mesh instead of the front face.
  66014. * This can help with self-shadowing as the geometry making up the back of objects is slightly offset.
  66015. * It might on the other hand introduce peter panning.
  66016. */
  66017. this.forceBackFacesOnly = false;
  66018. this._lightDirection = BABYLON.Vector3.Zero();
  66019. this._viewMatrix = BABYLON.Matrix.Zero();
  66020. this._projectionMatrix = BABYLON.Matrix.Zero();
  66021. this._transformMatrix = BABYLON.Matrix.Zero();
  66022. this._cachedPosition = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66023. this._cachedDirection = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  66024. this._currentFaceIndex = 0;
  66025. this._currentFaceIndexCache = 0;
  66026. this._defaultTextureMatrix = BABYLON.Matrix.Identity();
  66027. this._mapSize = mapSize;
  66028. this._light = light;
  66029. this._scene = light.getScene();
  66030. light._shadowGenerator = this;
  66031. // Texture type fallback from float to int if not supported.
  66032. var caps = this._scene.getEngine().getCaps();
  66033. if (!useFullFloatFirst) {
  66034. if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66035. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66036. }
  66037. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66038. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66039. }
  66040. else {
  66041. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66042. }
  66043. }
  66044. else {
  66045. if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  66046. this._textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  66047. }
  66048. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  66049. this._textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  66050. }
  66051. else {
  66052. this._textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  66053. }
  66054. }
  66055. this._initializeGenerator();
  66056. this._applyFilterValues();
  66057. }
  66058. Object.defineProperty(ShadowGenerator.prototype, "bias", {
  66059. /**
  66060. * Gets the bias: offset applied on the depth preventing acnea (in light direction).
  66061. */
  66062. get: function () {
  66063. return this._bias;
  66064. },
  66065. /**
  66066. * Sets the bias: offset applied on the depth preventing acnea (in light direction).
  66067. */
  66068. set: function (bias) {
  66069. this._bias = bias;
  66070. },
  66071. enumerable: true,
  66072. configurable: true
  66073. });
  66074. Object.defineProperty(ShadowGenerator.prototype, "normalBias", {
  66075. /**
  66076. * Gets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66077. */
  66078. get: function () {
  66079. return this._normalBias;
  66080. },
  66081. /**
  66082. * Sets the normalBias: offset applied on the depth preventing acnea (along side the normal direction and proportinal to the light/normal angle).
  66083. */
  66084. set: function (normalBias) {
  66085. this._normalBias = normalBias;
  66086. },
  66087. enumerable: true,
  66088. configurable: true
  66089. });
  66090. Object.defineProperty(ShadowGenerator.prototype, "blurBoxOffset", {
  66091. /**
  66092. * Gets the blur box offset: offset applied during the blur pass.
  66093. * Only usefull if useKernelBlur = false
  66094. */
  66095. get: function () {
  66096. return this._blurBoxOffset;
  66097. },
  66098. /**
  66099. * Sets the blur box offset: offset applied during the blur pass.
  66100. * Only usefull if useKernelBlur = false
  66101. */
  66102. set: function (value) {
  66103. if (this._blurBoxOffset === value) {
  66104. return;
  66105. }
  66106. this._blurBoxOffset = value;
  66107. this._disposeBlurPostProcesses();
  66108. },
  66109. enumerable: true,
  66110. configurable: true
  66111. });
  66112. Object.defineProperty(ShadowGenerator.prototype, "blurScale", {
  66113. /**
  66114. * Gets the blur scale: scale of the blurred texture compared to the main shadow map.
  66115. * 2 means half of the size.
  66116. */
  66117. get: function () {
  66118. return this._blurScale;
  66119. },
  66120. /**
  66121. * Sets the blur scale: scale of the blurred texture compared to the main shadow map.
  66122. * 2 means half of the size.
  66123. */
  66124. set: function (value) {
  66125. if (this._blurScale === value) {
  66126. return;
  66127. }
  66128. this._blurScale = value;
  66129. this._disposeBlurPostProcesses();
  66130. },
  66131. enumerable: true,
  66132. configurable: true
  66133. });
  66134. Object.defineProperty(ShadowGenerator.prototype, "blurKernel", {
  66135. /**
  66136. * Gets the blur kernel: kernel size of the blur pass.
  66137. * Only usefull if useKernelBlur = true
  66138. */
  66139. get: function () {
  66140. return this._blurKernel;
  66141. },
  66142. /**
  66143. * Sets the blur kernel: kernel size of the blur pass.
  66144. * Only usefull if useKernelBlur = true
  66145. */
  66146. set: function (value) {
  66147. if (this._blurKernel === value) {
  66148. return;
  66149. }
  66150. this._blurKernel = value;
  66151. this._disposeBlurPostProcesses();
  66152. },
  66153. enumerable: true,
  66154. configurable: true
  66155. });
  66156. Object.defineProperty(ShadowGenerator.prototype, "useKernelBlur", {
  66157. /**
  66158. * Gets whether the blur pass is a kernel blur (if true) or box blur.
  66159. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66160. */
  66161. get: function () {
  66162. return this._useKernelBlur;
  66163. },
  66164. /**
  66165. * Sets whether the blur pass is a kernel blur (if true) or box blur.
  66166. * Only usefull in filtered mode (useBlurExponentialShadowMap...)
  66167. */
  66168. set: function (value) {
  66169. if (this._useKernelBlur === value) {
  66170. return;
  66171. }
  66172. this._useKernelBlur = value;
  66173. this._disposeBlurPostProcesses();
  66174. },
  66175. enumerable: true,
  66176. configurable: true
  66177. });
  66178. Object.defineProperty(ShadowGenerator.prototype, "depthScale", {
  66179. /**
  66180. * Gets the depth scale used in ESM mode.
  66181. */
  66182. get: function () {
  66183. return this._depthScale !== undefined ? this._depthScale : this._light.getDepthScale();
  66184. },
  66185. /**
  66186. * Sets the depth scale used in ESM mode.
  66187. * This can override the scale stored on the light.
  66188. */
  66189. set: function (value) {
  66190. this._depthScale = value;
  66191. },
  66192. enumerable: true,
  66193. configurable: true
  66194. });
  66195. Object.defineProperty(ShadowGenerator.prototype, "filter", {
  66196. /**
  66197. * Gets the current mode of the shadow generator (normal, PCF, ESM...).
  66198. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66199. */
  66200. get: function () {
  66201. return this._filter;
  66202. },
  66203. /**
  66204. * Sets the current mode of the shadow generator (normal, PCF, ESM...).
  66205. * The returned value is a number equal to one of the available mode defined in ShadowMap.FILTER_x like _FILTER_NONE
  66206. */
  66207. set: function (value) {
  66208. // Blurring the cubemap is going to be too expensive. Reverting to unblurred version
  66209. if (this._light.needCube()) {
  66210. if (value === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66211. this.useExponentialShadowMap = true;
  66212. return;
  66213. }
  66214. else if (value === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66215. this.useCloseExponentialShadowMap = true;
  66216. return;
  66217. }
  66218. // PCF on cubemap would also be expensive
  66219. else if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66220. this.usePoissonSampling = true;
  66221. return;
  66222. }
  66223. }
  66224. // Weblg1 fallback for PCF.
  66225. if (value === ShadowGenerator.FILTER_PCF || value === ShadowGenerator.FILTER_PCSS) {
  66226. if (this._scene.getEngine().webGLVersion === 1) {
  66227. this.usePoissonSampling = true;
  66228. return;
  66229. }
  66230. }
  66231. if (this._filter === value) {
  66232. return;
  66233. }
  66234. this._filter = value;
  66235. this._disposeBlurPostProcesses();
  66236. this._applyFilterValues();
  66237. this._light._markMeshesAsLightDirty();
  66238. },
  66239. enumerable: true,
  66240. configurable: true
  66241. });
  66242. Object.defineProperty(ShadowGenerator.prototype, "usePoissonSampling", {
  66243. /**
  66244. * Gets if the current filter is set to Poisson Sampling.
  66245. */
  66246. get: function () {
  66247. return this.filter === ShadowGenerator.FILTER_POISSONSAMPLING;
  66248. },
  66249. /**
  66250. * Sets the current filter to Poisson Sampling.
  66251. */
  66252. set: function (value) {
  66253. if (!value && this.filter !== ShadowGenerator.FILTER_POISSONSAMPLING) {
  66254. return;
  66255. }
  66256. this.filter = (value ? ShadowGenerator.FILTER_POISSONSAMPLING : ShadowGenerator.FILTER_NONE);
  66257. },
  66258. enumerable: true,
  66259. configurable: true
  66260. });
  66261. Object.defineProperty(ShadowGenerator.prototype, "useVarianceShadowMap", {
  66262. /**
  66263. * Gets if the current filter is set to VSM.
  66264. * DEPRECATED. Should use useExponentialShadowMap instead.
  66265. */
  66266. get: function () {
  66267. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66268. return this.useExponentialShadowMap;
  66269. },
  66270. /**
  66271. * Sets the current filter is to VSM.
  66272. * DEPRECATED. Should use useExponentialShadowMap instead.
  66273. */
  66274. set: function (value) {
  66275. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useExponentialShadowMap instead.");
  66276. this.useExponentialShadowMap = value;
  66277. },
  66278. enumerable: true,
  66279. configurable: true
  66280. });
  66281. Object.defineProperty(ShadowGenerator.prototype, "useBlurVarianceShadowMap", {
  66282. /**
  66283. * Gets if the current filter is set to blurred VSM.
  66284. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66285. */
  66286. get: function () {
  66287. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66288. return this.useBlurExponentialShadowMap;
  66289. },
  66290. /**
  66291. * Sets the current filter is to blurred VSM.
  66292. * DEPRECATED. Should use useBlurExponentialShadowMap instead.
  66293. */
  66294. set: function (value) {
  66295. BABYLON.Tools.Warn("VSM are now replaced by ESM. Please use useBlurExponentialShadowMap instead.");
  66296. this.useBlurExponentialShadowMap = value;
  66297. },
  66298. enumerable: true,
  66299. configurable: true
  66300. });
  66301. Object.defineProperty(ShadowGenerator.prototype, "useExponentialShadowMap", {
  66302. /**
  66303. * Gets if the current filter is set to ESM.
  66304. */
  66305. get: function () {
  66306. return this.filter === ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP;
  66307. },
  66308. /**
  66309. * Sets the current filter is to ESM.
  66310. */
  66311. set: function (value) {
  66312. if (!value && this.filter !== ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP) {
  66313. return;
  66314. }
  66315. this.filter = (value ? ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66316. },
  66317. enumerable: true,
  66318. configurable: true
  66319. });
  66320. Object.defineProperty(ShadowGenerator.prototype, "useBlurExponentialShadowMap", {
  66321. /**
  66322. * Gets if the current filter is set to filtered ESM.
  66323. */
  66324. get: function () {
  66325. return this.filter === ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP;
  66326. },
  66327. /**
  66328. * Gets if the current filter is set to filtered ESM.
  66329. */
  66330. set: function (value) {
  66331. if (!value && this.filter !== ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP) {
  66332. return;
  66333. }
  66334. this.filter = (value ? ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66335. },
  66336. enumerable: true,
  66337. configurable: true
  66338. });
  66339. Object.defineProperty(ShadowGenerator.prototype, "useCloseExponentialShadowMap", {
  66340. /**
  66341. * Gets if the current filter is set to "close ESM" (using the inverse of the
  66342. * exponential to prevent steep falloff artifacts).
  66343. */
  66344. get: function () {
  66345. return this.filter === ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP;
  66346. },
  66347. /**
  66348. * Sets the current filter to "close ESM" (using the inverse of the
  66349. * exponential to prevent steep falloff artifacts).
  66350. */
  66351. set: function (value) {
  66352. if (!value && this.filter !== ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP) {
  66353. return;
  66354. }
  66355. this.filter = (value ? ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66356. },
  66357. enumerable: true,
  66358. configurable: true
  66359. });
  66360. Object.defineProperty(ShadowGenerator.prototype, "useBlurCloseExponentialShadowMap", {
  66361. /**
  66362. * Gets if the current filter is set to filtered "close ESM" (using the inverse of the
  66363. * exponential to prevent steep falloff artifacts).
  66364. */
  66365. get: function () {
  66366. return this.filter === ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP;
  66367. },
  66368. /**
  66369. * Sets the current filter to filtered "close ESM" (using the inverse of the
  66370. * exponential to prevent steep falloff artifacts).
  66371. */
  66372. set: function (value) {
  66373. if (!value && this.filter !== ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP) {
  66374. return;
  66375. }
  66376. this.filter = (value ? ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP : ShadowGenerator.FILTER_NONE);
  66377. },
  66378. enumerable: true,
  66379. configurable: true
  66380. });
  66381. Object.defineProperty(ShadowGenerator.prototype, "usePercentageCloserFiltering", {
  66382. /**
  66383. * Gets if the current filter is set to "PCF" (percentage closer filtering).
  66384. */
  66385. get: function () {
  66386. return this.filter === ShadowGenerator.FILTER_PCF;
  66387. },
  66388. /**
  66389. * Sets the current filter to "PCF" (percentage closer filtering).
  66390. */
  66391. set: function (value) {
  66392. if (!value && this.filter !== ShadowGenerator.FILTER_PCF) {
  66393. return;
  66394. }
  66395. this.filter = (value ? ShadowGenerator.FILTER_PCF : ShadowGenerator.FILTER_NONE);
  66396. },
  66397. enumerable: true,
  66398. configurable: true
  66399. });
  66400. Object.defineProperty(ShadowGenerator.prototype, "filteringQuality", {
  66401. /**
  66402. * Gets the PCF or PCSS Quality.
  66403. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66404. */
  66405. get: function () {
  66406. return this._filteringQuality;
  66407. },
  66408. /**
  66409. * Sets the PCF or PCSS Quality.
  66410. * Only valid if usePercentageCloserFiltering or usePercentageCloserFiltering is true.
  66411. */
  66412. set: function (filteringQuality) {
  66413. this._filteringQuality = filteringQuality;
  66414. },
  66415. enumerable: true,
  66416. configurable: true
  66417. });
  66418. Object.defineProperty(ShadowGenerator.prototype, "useContactHardeningShadow", {
  66419. /**
  66420. * Gets if the current filter is set to "PCSS" (contact hardening).
  66421. */
  66422. get: function () {
  66423. return this.filter === ShadowGenerator.FILTER_PCSS;
  66424. },
  66425. /**
  66426. * Sets the current filter to "PCSS" (contact hardening).
  66427. */
  66428. set: function (value) {
  66429. if (!value && this.filter !== ShadowGenerator.FILTER_PCSS) {
  66430. return;
  66431. }
  66432. this.filter = (value ? ShadowGenerator.FILTER_PCSS : ShadowGenerator.FILTER_NONE);
  66433. },
  66434. enumerable: true,
  66435. configurable: true
  66436. });
  66437. Object.defineProperty(ShadowGenerator.prototype, "contactHardeningLightSizeUVRatio", {
  66438. /**
  66439. * Gets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66440. * Using a ratio helps keeping shape stability independently of the map size.
  66441. *
  66442. * It does not account for the light projection as it was having too much
  66443. * instability during the light setup or during light position changes.
  66444. *
  66445. * Only valid if useContactHardeningShadow is true.
  66446. */
  66447. get: function () {
  66448. return this._contactHardeningLightSizeUVRatio;
  66449. },
  66450. /**
  66451. * Sets the Light Size (in shadow map uv unit) used in PCSS to determine the blocker search area and the penumbra size.
  66452. * Using a ratio helps keeping shape stability independently of the map size.
  66453. *
  66454. * It does not account for the light projection as it was having too much
  66455. * instability during the light setup or during light position changes.
  66456. *
  66457. * Only valid if useContactHardeningShadow is true.
  66458. */
  66459. set: function (contactHardeningLightSizeUVRatio) {
  66460. this._contactHardeningLightSizeUVRatio = contactHardeningLightSizeUVRatio;
  66461. },
  66462. enumerable: true,
  66463. configurable: true
  66464. });
  66465. /**
  66466. * Returns the darkness value (float). This can only decrease the actual darkness of a shadow.
  66467. * 0 means strongest and 1 would means no shadow.
  66468. * @returns the darkness.
  66469. */
  66470. ShadowGenerator.prototype.getDarkness = function () {
  66471. return this._darkness;
  66472. };
  66473. /**
  66474. * Sets the darkness value (float). This can only decrease the actual darkness of a shadow.
  66475. * @param darkness The darkness value 0 means strongest and 1 would means no shadow.
  66476. * @returns the shadow generator allowing fluent coding.
  66477. */
  66478. ShadowGenerator.prototype.setDarkness = function (darkness) {
  66479. if (darkness >= 1.0)
  66480. this._darkness = 1.0;
  66481. else if (darkness <= 0.0)
  66482. this._darkness = 0.0;
  66483. else
  66484. this._darkness = darkness;
  66485. return this;
  66486. };
  66487. /**
  66488. * Sets the ability to have transparent shadow (boolean).
  66489. * @param transparent True if transparent else False
  66490. * @returns the shadow generator allowing fluent coding
  66491. */
  66492. ShadowGenerator.prototype.setTransparencyShadow = function (transparent) {
  66493. this._transparencyShadow = transparent;
  66494. return this;
  66495. };
  66496. /**
  66497. * Gets the main RTT containing the shadow map (usually storing depth from the light point of view).
  66498. * @returns The render target texture if present otherwise, null
  66499. */
  66500. ShadowGenerator.prototype.getShadowMap = function () {
  66501. return this._shadowMap;
  66502. };
  66503. /**
  66504. * Gets the RTT used during rendering (can be a blurred version of the shadow map or the shadow map itself).
  66505. * @returns The render target texture if the shadow map is present otherwise, null
  66506. */
  66507. ShadowGenerator.prototype.getShadowMapForRendering = function () {
  66508. if (this._shadowMap2) {
  66509. return this._shadowMap2;
  66510. }
  66511. return this._shadowMap;
  66512. };
  66513. /**
  66514. * Helper function to add a mesh and its descendants to the list of shadow casters.
  66515. * @param mesh Mesh to add
  66516. * @param includeDescendants boolean indicating if the descendants should be added. Default to true
  66517. * @returns the Shadow Generator itself
  66518. */
  66519. ShadowGenerator.prototype.addShadowCaster = function (mesh, includeDescendants) {
  66520. if (includeDescendants === void 0) { includeDescendants = true; }
  66521. if (!this._shadowMap) {
  66522. return this;
  66523. }
  66524. if (!this._shadowMap.renderList) {
  66525. this._shadowMap.renderList = [];
  66526. }
  66527. this._shadowMap.renderList.push(mesh);
  66528. if (includeDescendants) {
  66529. (_a = this._shadowMap.renderList).push.apply(_a, mesh.getChildMeshes());
  66530. }
  66531. return this;
  66532. var _a;
  66533. };
  66534. /**
  66535. * Helper function to remove a mesh and its descendants from the list of shadow casters
  66536. * @param mesh Mesh to remove
  66537. * @param includeDescendants boolean indicating if the descendants should be removed. Default to true
  66538. * @returns the Shadow Generator itself
  66539. */
  66540. ShadowGenerator.prototype.removeShadowCaster = function (mesh, includeDescendants) {
  66541. if (includeDescendants === void 0) { includeDescendants = true; }
  66542. if (!this._shadowMap || !this._shadowMap.renderList) {
  66543. return this;
  66544. }
  66545. var index = this._shadowMap.renderList.indexOf(mesh);
  66546. if (index !== -1) {
  66547. this._shadowMap.renderList.splice(index, 1);
  66548. }
  66549. if (includeDescendants) {
  66550. for (var _i = 0, _a = mesh.getChildren(); _i < _a.length; _i++) {
  66551. var child = _a[_i];
  66552. this.removeShadowCaster(child);
  66553. }
  66554. }
  66555. return this;
  66556. };
  66557. /**
  66558. * Returns the associated light object.
  66559. * @returns the light generating the shadow
  66560. */
  66561. ShadowGenerator.prototype.getLight = function () {
  66562. return this._light;
  66563. };
  66564. ShadowGenerator.prototype._initializeGenerator = function () {
  66565. this._light._markMeshesAsLightDirty();
  66566. this._initializeShadowMap();
  66567. };
  66568. ShadowGenerator.prototype._initializeShadowMap = function () {
  66569. var _this = this;
  66570. // Render target
  66571. var engine = this._scene.getEngine();
  66572. if (engine.webGLVersion > 1) {
  66573. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube(), undefined, false, false);
  66574. this._shadowMap.createDepthStencilTexture(BABYLON.Engine.LESS, true);
  66575. }
  66576. else {
  66577. this._shadowMap = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap", this._mapSize, this._scene, false, true, this._textureType, this._light.needCube());
  66578. }
  66579. this._shadowMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66580. this._shadowMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66581. this._shadowMap.anisotropicFilteringLevel = 1;
  66582. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66583. this._shadowMap.renderParticles = false;
  66584. this._shadowMap.ignoreCameraViewport = true;
  66585. // Record Face Index before render.
  66586. this._shadowMap.onBeforeRenderObservable.add(function (faceIndex) {
  66587. _this._currentFaceIndex = faceIndex;
  66588. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66589. engine.setColorWrite(false);
  66590. }
  66591. });
  66592. // Custom render function.
  66593. this._shadowMap.customRenderFunction = this._renderForShadowMap.bind(this);
  66594. // Blur if required afer render.
  66595. this._shadowMap.onAfterUnbindObservable.add(function () {
  66596. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66597. engine.setColorWrite(true);
  66598. }
  66599. if (!_this.useBlurExponentialShadowMap && !_this.useBlurCloseExponentialShadowMap) {
  66600. return;
  66601. }
  66602. var shadowMap = _this.getShadowMapForRendering();
  66603. if (shadowMap) {
  66604. _this._scene.postProcessManager.directRender(_this._blurPostProcesses, shadowMap.getInternalTexture(), true);
  66605. }
  66606. });
  66607. // Clear according to the chosen filter.
  66608. var clearZero = new BABYLON.Color4(0, 0, 0, 0);
  66609. var clearOne = new BABYLON.Color4(1.0, 1.0, 1.0, 1.0);
  66610. this._shadowMap.onClearObservable.add(function (engine) {
  66611. if (_this._filter === ShadowGenerator.FILTER_PCF) {
  66612. engine.clear(clearOne, false, true, false);
  66613. }
  66614. else if (_this.useExponentialShadowMap || _this.useBlurExponentialShadowMap) {
  66615. engine.clear(clearZero, true, true, false);
  66616. }
  66617. else {
  66618. engine.clear(clearOne, true, true, false);
  66619. }
  66620. });
  66621. };
  66622. ShadowGenerator.prototype._initializeBlurRTTAndPostProcesses = function () {
  66623. var _this = this;
  66624. var engine = this._scene.getEngine();
  66625. var targetSize = this._mapSize / this.blurScale;
  66626. if (!this.useKernelBlur || this.blurScale !== 1.0) {
  66627. this._shadowMap2 = new BABYLON.RenderTargetTexture(this._light.name + "_shadowMap2", targetSize, this._scene, false, true, this._textureType);
  66628. this._shadowMap2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66629. this._shadowMap2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  66630. this._shadowMap2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66631. }
  66632. if (this.useKernelBlur) {
  66633. 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);
  66634. this._kernelBlurXPostprocess.width = targetSize;
  66635. this._kernelBlurXPostprocess.height = targetSize;
  66636. this._kernelBlurXPostprocess.onApplyObservable.add(function (effect) {
  66637. effect.setTexture("textureSampler", _this._shadowMap);
  66638. });
  66639. 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);
  66640. this._kernelBlurXPostprocess.autoClear = false;
  66641. this._kernelBlurYPostprocess.autoClear = false;
  66642. if (this._textureType === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66643. this._kernelBlurXPostprocess.packedFloat = true;
  66644. this._kernelBlurYPostprocess.packedFloat = true;
  66645. }
  66646. this._blurPostProcesses = [this._kernelBlurXPostprocess, this._kernelBlurYPostprocess];
  66647. }
  66648. else {
  66649. 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);
  66650. this._boxBlurPostprocess.onApplyObservable.add(function (effect) {
  66651. effect.setFloat2("screenSize", targetSize, targetSize);
  66652. effect.setTexture("textureSampler", _this._shadowMap);
  66653. });
  66654. this._boxBlurPostprocess.autoClear = false;
  66655. this._blurPostProcesses = [this._boxBlurPostprocess];
  66656. }
  66657. };
  66658. ShadowGenerator.prototype._renderForShadowMap = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  66659. var index;
  66660. var engine = this._scene.getEngine();
  66661. if (depthOnlySubMeshes.length) {
  66662. engine.setColorWrite(false);
  66663. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  66664. this._renderSubMeshForShadowMap(depthOnlySubMeshes.data[index]);
  66665. }
  66666. engine.setColorWrite(true);
  66667. }
  66668. for (index = 0; index < opaqueSubMeshes.length; index++) {
  66669. this._renderSubMeshForShadowMap(opaqueSubMeshes.data[index]);
  66670. }
  66671. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  66672. this._renderSubMeshForShadowMap(alphaTestSubMeshes.data[index]);
  66673. }
  66674. if (this._transparencyShadow) {
  66675. for (index = 0; index < transparentSubMeshes.length; index++) {
  66676. this._renderSubMeshForShadowMap(transparentSubMeshes.data[index]);
  66677. }
  66678. }
  66679. };
  66680. ShadowGenerator.prototype._renderSubMeshForShadowMap = function (subMesh) {
  66681. var _this = this;
  66682. var mesh = subMesh.getRenderingMesh();
  66683. var scene = this._scene;
  66684. var engine = scene.getEngine();
  66685. var material = subMesh.getMaterial();
  66686. if (!material) {
  66687. return;
  66688. }
  66689. // Culling
  66690. engine.setState(material.backFaceCulling);
  66691. // Managing instances
  66692. var batch = mesh._getInstancesRenderList(subMesh._id);
  66693. if (batch.mustReturn) {
  66694. return;
  66695. }
  66696. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  66697. if (this.isReady(subMesh, hardwareInstancedRendering)) {
  66698. engine.enableEffect(this._effect);
  66699. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  66700. this._effect.setFloat3("biasAndScale", this.bias, this.normalBias, this.depthScale);
  66701. this._effect.setMatrix("viewProjection", this.getTransformMatrix());
  66702. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66703. this._effect.setVector3("lightData", this._cachedDirection);
  66704. }
  66705. else {
  66706. this._effect.setVector3("lightData", this._cachedPosition);
  66707. }
  66708. if (scene.activeCamera) {
  66709. this._effect.setFloat2("depthValues", this.getLight().getDepthMinZ(scene.activeCamera), this.getLight().getDepthMinZ(scene.activeCamera) + this.getLight().getDepthMaxZ(scene.activeCamera));
  66710. }
  66711. // Alpha test
  66712. if (material && material.needAlphaTesting()) {
  66713. var alphaTexture = material.getAlphaTestTexture();
  66714. if (alphaTexture) {
  66715. this._effect.setTexture("diffuseSampler", alphaTexture);
  66716. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix() || this._defaultTextureMatrix);
  66717. }
  66718. }
  66719. // Bones
  66720. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66721. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices((mesh)));
  66722. }
  66723. // Morph targets
  66724. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effect);
  66725. if (this.forceBackFacesOnly) {
  66726. engine.setState(true, 0, false, true);
  66727. }
  66728. // Draw
  66729. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  66730. if (this.forceBackFacesOnly) {
  66731. engine.setState(true, 0, false, false);
  66732. }
  66733. }
  66734. else {
  66735. // Need to reset refresh rate of the shadowMap
  66736. if (this._shadowMap) {
  66737. this._shadowMap.resetRefreshCounter();
  66738. }
  66739. }
  66740. };
  66741. ShadowGenerator.prototype._applyFilterValues = function () {
  66742. if (!this._shadowMap) {
  66743. return;
  66744. }
  66745. if (this.filter === ShadowGenerator.FILTER_NONE || this.filter === ShadowGenerator.FILTER_PCSS) {
  66746. this._shadowMap.updateSamplingMode(BABYLON.Texture.NEAREST_SAMPLINGMODE);
  66747. }
  66748. else {
  66749. this._shadowMap.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  66750. }
  66751. };
  66752. /**
  66753. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66754. * @param onCompiled Callback triggered at the and of the effects compilation
  66755. * @param options Sets of optional options forcing the compilation with different modes
  66756. */
  66757. ShadowGenerator.prototype.forceCompilation = function (onCompiled, options) {
  66758. var _this = this;
  66759. var localOptions = __assign({ useInstances: false }, options);
  66760. var shadowMap = this.getShadowMap();
  66761. if (!shadowMap) {
  66762. if (onCompiled) {
  66763. onCompiled(this);
  66764. }
  66765. return;
  66766. }
  66767. var renderList = shadowMap.renderList;
  66768. if (!renderList) {
  66769. if (onCompiled) {
  66770. onCompiled(this);
  66771. }
  66772. return;
  66773. }
  66774. var subMeshes = new Array();
  66775. for (var _i = 0, renderList_1 = renderList; _i < renderList_1.length; _i++) {
  66776. var mesh = renderList_1[_i];
  66777. subMeshes.push.apply(subMeshes, mesh.subMeshes);
  66778. }
  66779. if (subMeshes.length === 0) {
  66780. if (onCompiled) {
  66781. onCompiled(this);
  66782. }
  66783. return;
  66784. }
  66785. var currentIndex = 0;
  66786. var checkReady = function () {
  66787. if (!_this._scene || !_this._scene.getEngine()) {
  66788. return;
  66789. }
  66790. while (_this.isReady(subMeshes[currentIndex], localOptions.useInstances)) {
  66791. currentIndex++;
  66792. if (currentIndex >= subMeshes.length) {
  66793. if (onCompiled) {
  66794. onCompiled(_this);
  66795. }
  66796. return;
  66797. }
  66798. }
  66799. setTimeout(checkReady, 16);
  66800. };
  66801. checkReady();
  66802. };
  66803. /**
  66804. * Forces all the attached effect to compile to enable rendering only once ready vs. lazyly compiling effects.
  66805. * @param options Sets of optional options forcing the compilation with different modes
  66806. * @returns A promise that resolves when the compilation completes
  66807. */
  66808. ShadowGenerator.prototype.forceCompilationAsync = function (options) {
  66809. var _this = this;
  66810. return new Promise(function (resolve) {
  66811. _this.forceCompilation(function () {
  66812. resolve();
  66813. }, options);
  66814. });
  66815. };
  66816. /**
  66817. * Determine wheter the shadow generator is ready or not (mainly all effects and related post processes needs to be ready).
  66818. * @param subMesh The submesh we want to render in the shadow map
  66819. * @param useInstances Defines wether will draw in the map using instances
  66820. * @returns true if ready otherwise, false
  66821. */
  66822. ShadowGenerator.prototype.isReady = function (subMesh, useInstances) {
  66823. var defines = [];
  66824. if (this._textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  66825. defines.push("#define FLOAT");
  66826. }
  66827. if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66828. defines.push("#define ESM");
  66829. }
  66830. else if (this.usePercentageCloserFiltering || this.useContactHardeningShadow) {
  66831. defines.push("#define DEPTHTEXTURE");
  66832. }
  66833. var attribs = [BABYLON.VertexBuffer.PositionKind];
  66834. var mesh = subMesh.getMesh();
  66835. var material = subMesh.getMaterial();
  66836. // Normal bias.
  66837. if (this.normalBias && mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  66838. attribs.push(BABYLON.VertexBuffer.NormalKind);
  66839. defines.push("#define NORMAL");
  66840. if (mesh.nonUniformScaling) {
  66841. defines.push("#define NONUNIFORMSCALING");
  66842. }
  66843. if (this.getLight().getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  66844. defines.push("#define DIRECTIONINLIGHTDATA");
  66845. }
  66846. }
  66847. // Alpha test
  66848. if (material && material.needAlphaTesting()) {
  66849. var alphaTexture = material.getAlphaTestTexture();
  66850. if (alphaTexture) {
  66851. defines.push("#define ALPHATEST");
  66852. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  66853. attribs.push(BABYLON.VertexBuffer.UVKind);
  66854. defines.push("#define UV1");
  66855. }
  66856. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  66857. if (alphaTexture.coordinatesIndex === 1) {
  66858. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  66859. defines.push("#define UV2");
  66860. }
  66861. }
  66862. }
  66863. }
  66864. // Bones
  66865. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  66866. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  66867. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  66868. if (mesh.numBoneInfluencers > 4) {
  66869. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  66870. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  66871. }
  66872. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  66873. defines.push("#define BonesPerMesh " + (mesh.skeleton.bones.length + 1));
  66874. }
  66875. else {
  66876. defines.push("#define NUM_BONE_INFLUENCERS 0");
  66877. }
  66878. // Morph targets
  66879. var manager = mesh.morphTargetManager;
  66880. var morphInfluencers = 0;
  66881. if (manager) {
  66882. if (manager.numInfluencers > 0) {
  66883. defines.push("#define MORPHTARGETS");
  66884. morphInfluencers = manager.numInfluencers;
  66885. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  66886. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  66887. }
  66888. }
  66889. // Instances
  66890. if (useInstances) {
  66891. defines.push("#define INSTANCES");
  66892. attribs.push("world0");
  66893. attribs.push("world1");
  66894. attribs.push("world2");
  66895. attribs.push("world3");
  66896. }
  66897. // Get correct effect
  66898. var join = defines.join("\n");
  66899. if (this._cachedDefines !== join) {
  66900. this._cachedDefines = join;
  66901. this._effect = this._scene.getEngine().createEffect("shadowMap", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "lightData", "depthValues", "biasAndScale", "morphTargetInfluences"], ["diffuseSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  66902. }
  66903. if (!this._effect.isReady()) {
  66904. return false;
  66905. }
  66906. if (this.useBlurExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66907. if (!this._blurPostProcesses || !this._blurPostProcesses.length) {
  66908. this._initializeBlurRTTAndPostProcesses();
  66909. }
  66910. }
  66911. if (this._kernelBlurXPostprocess && !this._kernelBlurXPostprocess.isReady()) {
  66912. return false;
  66913. }
  66914. if (this._kernelBlurYPostprocess && !this._kernelBlurYPostprocess.isReady()) {
  66915. return false;
  66916. }
  66917. if (this._boxBlurPostprocess && !this._boxBlurPostprocess.isReady()) {
  66918. return false;
  66919. }
  66920. return true;
  66921. };
  66922. /**
  66923. * Prepare all the defines in a material relying on a shadow map at the specified light index.
  66924. * @param defines Defines of the material we want to update
  66925. * @param lightIndex Index of the light in the enabled light list of the material
  66926. */
  66927. ShadowGenerator.prototype.prepareDefines = function (defines, lightIndex) {
  66928. var scene = this._scene;
  66929. var light = this._light;
  66930. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66931. return;
  66932. }
  66933. defines["SHADOW" + lightIndex] = true;
  66934. if (this.useContactHardeningShadow) {
  66935. defines["SHADOWPCSS" + lightIndex] = true;
  66936. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66937. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66938. }
  66939. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66940. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66941. }
  66942. // else default to high.
  66943. }
  66944. if (this.usePercentageCloserFiltering) {
  66945. defines["SHADOWPCF" + lightIndex] = true;
  66946. if (this._filteringQuality === ShadowGenerator.QUALITY_LOW) {
  66947. defines["SHADOWLOWQUALITY" + lightIndex] = true;
  66948. }
  66949. else if (this._filteringQuality === ShadowGenerator.QUALITY_MEDIUM) {
  66950. defines["SHADOWMEDIUMQUALITY" + lightIndex] = true;
  66951. }
  66952. // else default to high.
  66953. }
  66954. else if (this.usePoissonSampling) {
  66955. defines["SHADOWPOISSON" + lightIndex] = true;
  66956. }
  66957. else if (this.useExponentialShadowMap || this.useBlurExponentialShadowMap) {
  66958. defines["SHADOWESM" + lightIndex] = true;
  66959. }
  66960. else if (this.useCloseExponentialShadowMap || this.useBlurCloseExponentialShadowMap) {
  66961. defines["SHADOWCLOSEESM" + lightIndex] = true;
  66962. }
  66963. if (light.needCube()) {
  66964. defines["SHADOWCUBE" + lightIndex] = true;
  66965. }
  66966. };
  66967. /**
  66968. * Binds the shadow related information inside of an effect (information like near, far, darkness...
  66969. * defined in the generator but impacting the effect).
  66970. * @param lightIndex Index of the light in the enabled light list of the material owning the effect
  66971. * @param effect The effect we are binfing the information for
  66972. */
  66973. ShadowGenerator.prototype.bindShadowLight = function (lightIndex, effect) {
  66974. var light = this._light;
  66975. var scene = this._scene;
  66976. if (!scene.shadowsEnabled || !light.shadowEnabled) {
  66977. return;
  66978. }
  66979. var camera = scene.activeCamera;
  66980. if (!camera) {
  66981. return;
  66982. }
  66983. var shadowMap = this.getShadowMap();
  66984. if (!shadowMap) {
  66985. return;
  66986. }
  66987. if (!light.needCube()) {
  66988. effect.setMatrix("lightMatrix" + lightIndex, this.getTransformMatrix());
  66989. }
  66990. // Only PCF uses depth stencil texture.
  66991. if (this._filter === ShadowGenerator.FILTER_PCF) {
  66992. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66993. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), shadowMap.getSize().width, 1 / shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66994. }
  66995. else if (this._filter === ShadowGenerator.FILTER_PCSS) {
  66996. effect.setDepthStencilTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  66997. effect.setTexture("depthSampler" + lightIndex, this.getShadowMapForRendering());
  66998. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), 1 / shadowMap.getSize().width, this._contactHardeningLightSizeUVRatio * shadowMap.getSize().width, this.frustumEdgeFalloff, lightIndex);
  66999. }
  67000. else {
  67001. effect.setTexture("shadowSampler" + lightIndex, this.getShadowMapForRendering());
  67002. light._uniformBuffer.updateFloat4("shadowsInfo", this.getDarkness(), this.blurScale / shadowMap.getSize().width, this.depthScale, this.frustumEdgeFalloff, lightIndex);
  67003. }
  67004. light._uniformBuffer.updateFloat2("depthValues", this.getLight().getDepthMinZ(camera), this.getLight().getDepthMinZ(camera) + this.getLight().getDepthMaxZ(camera), lightIndex);
  67005. };
  67006. /**
  67007. * Gets the transformation matrix used to project the meshes into the map from the light point of view.
  67008. * (eq to shadow prjection matrix * light transform matrix)
  67009. * @returns The transform matrix used to create the shadow map
  67010. */
  67011. ShadowGenerator.prototype.getTransformMatrix = function () {
  67012. var scene = this._scene;
  67013. if (this._currentRenderID === scene.getRenderId() && this._currentFaceIndexCache === this._currentFaceIndex) {
  67014. return this._transformMatrix;
  67015. }
  67016. this._currentRenderID = scene.getRenderId();
  67017. this._currentFaceIndexCache = this._currentFaceIndex;
  67018. var lightPosition = this._light.position;
  67019. if (this._light.computeTransformedInformation()) {
  67020. lightPosition = this._light.transformedPosition;
  67021. }
  67022. BABYLON.Vector3.NormalizeToRef(this._light.getShadowDirection(this._currentFaceIndex), this._lightDirection);
  67023. if (Math.abs(BABYLON.Vector3.Dot(this._lightDirection, BABYLON.Vector3.Up())) === 1.0) {
  67024. this._lightDirection.z = 0.0000000000001; // Required to avoid perfectly perpendicular light
  67025. }
  67026. if (this._light.needProjectionMatrixCompute() || !this._cachedPosition || !this._cachedDirection || !lightPosition.equals(this._cachedPosition) || !this._lightDirection.equals(this._cachedDirection)) {
  67027. this._cachedPosition.copyFrom(lightPosition);
  67028. this._cachedDirection.copyFrom(this._lightDirection);
  67029. BABYLON.Matrix.LookAtLHToRef(lightPosition, lightPosition.add(this._lightDirection), BABYLON.Vector3.Up(), this._viewMatrix);
  67030. var shadowMap = this.getShadowMap();
  67031. if (shadowMap) {
  67032. var renderList = shadowMap.renderList;
  67033. if (renderList) {
  67034. this._light.setShadowProjectionMatrix(this._projectionMatrix, this._viewMatrix, renderList);
  67035. }
  67036. }
  67037. this._viewMatrix.multiplyToRef(this._projectionMatrix, this._transformMatrix);
  67038. }
  67039. return this._transformMatrix;
  67040. };
  67041. /**
  67042. * Recreates the shadow map dependencies like RTT and post processes. This can be used during the switch between
  67043. * Cube and 2D textures for instance.
  67044. */
  67045. ShadowGenerator.prototype.recreateShadowMap = function () {
  67046. var shadowMap = this._shadowMap;
  67047. if (!shadowMap) {
  67048. return;
  67049. }
  67050. // Track render list.
  67051. var renderList = shadowMap.renderList;
  67052. // Clean up existing data.
  67053. this._disposeRTTandPostProcesses();
  67054. // Reinitializes.
  67055. this._initializeGenerator();
  67056. // Reaffect the filter to ensure a correct fallback if necessary.
  67057. this.filter = this.filter;
  67058. // Reaffect the filter.
  67059. this._applyFilterValues();
  67060. // Reaffect Render List.
  67061. this._shadowMap.renderList = renderList;
  67062. };
  67063. ShadowGenerator.prototype._disposeBlurPostProcesses = function () {
  67064. if (this._shadowMap2) {
  67065. this._shadowMap2.dispose();
  67066. this._shadowMap2 = null;
  67067. }
  67068. if (this._boxBlurPostprocess) {
  67069. this._boxBlurPostprocess.dispose();
  67070. this._boxBlurPostprocess = null;
  67071. }
  67072. if (this._kernelBlurXPostprocess) {
  67073. this._kernelBlurXPostprocess.dispose();
  67074. this._kernelBlurXPostprocess = null;
  67075. }
  67076. if (this._kernelBlurYPostprocess) {
  67077. this._kernelBlurYPostprocess.dispose();
  67078. this._kernelBlurYPostprocess = null;
  67079. }
  67080. this._blurPostProcesses = [];
  67081. };
  67082. ShadowGenerator.prototype._disposeRTTandPostProcesses = function () {
  67083. if (this._shadowMap) {
  67084. this._shadowMap.dispose();
  67085. this._shadowMap = null;
  67086. }
  67087. this._disposeBlurPostProcesses();
  67088. };
  67089. /**
  67090. * Disposes the ShadowGenerator.
  67091. * Returns nothing.
  67092. */
  67093. ShadowGenerator.prototype.dispose = function () {
  67094. this._disposeRTTandPostProcesses();
  67095. if (this._light) {
  67096. this._light._shadowGenerator = null;
  67097. this._light._markMeshesAsLightDirty();
  67098. }
  67099. };
  67100. /**
  67101. * Serializes the shadow generator setup to a json object.
  67102. * @returns The serialized JSON object
  67103. */
  67104. ShadowGenerator.prototype.serialize = function () {
  67105. var serializationObject = {};
  67106. var shadowMap = this.getShadowMap();
  67107. if (!shadowMap) {
  67108. return serializationObject;
  67109. }
  67110. serializationObject.lightId = this._light.id;
  67111. serializationObject.mapSize = shadowMap.getRenderSize();
  67112. serializationObject.useExponentialShadowMap = this.useExponentialShadowMap;
  67113. serializationObject.useBlurExponentialShadowMap = this.useBlurExponentialShadowMap;
  67114. serializationObject.useCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67115. serializationObject.useBlurCloseExponentialShadowMap = this.useBlurExponentialShadowMap;
  67116. serializationObject.usePoissonSampling = this.usePoissonSampling;
  67117. serializationObject.forceBackFacesOnly = this.forceBackFacesOnly;
  67118. serializationObject.depthScale = this.depthScale;
  67119. serializationObject.darkness = this.getDarkness();
  67120. serializationObject.blurBoxOffset = this.blurBoxOffset;
  67121. serializationObject.blurKernel = this.blurKernel;
  67122. serializationObject.blurScale = this.blurScale;
  67123. serializationObject.useKernelBlur = this.useKernelBlur;
  67124. serializationObject.transparencyShadow = this._transparencyShadow;
  67125. serializationObject.frustumEdgeFalloff = this.frustumEdgeFalloff;
  67126. serializationObject.bias = this.bias;
  67127. serializationObject.normalBias = this.normalBias;
  67128. serializationObject.usePercentageCloserFiltering = this.usePercentageCloserFiltering;
  67129. serializationObject.useContactHardeningShadow = this.useContactHardeningShadow;
  67130. serializationObject.filteringQuality = this.filteringQuality;
  67131. serializationObject.contactHardeningLightSizeUVRatio = this.contactHardeningLightSizeUVRatio;
  67132. serializationObject.renderList = [];
  67133. if (shadowMap.renderList) {
  67134. for (var meshIndex = 0; meshIndex < shadowMap.renderList.length; meshIndex++) {
  67135. var mesh = shadowMap.renderList[meshIndex];
  67136. serializationObject.renderList.push(mesh.id);
  67137. }
  67138. }
  67139. return serializationObject;
  67140. };
  67141. /**
  67142. * Parses a serialized ShadowGenerator and returns a new ShadowGenerator.
  67143. * @param parsedShadowGenerator The JSON object to parse
  67144. * @param scene The scene to create the shadow map for
  67145. * @returns The parsed shadow generator
  67146. */
  67147. ShadowGenerator.Parse = function (parsedShadowGenerator, scene) {
  67148. //casting to point light, as light is missing the position attr and typescript complains.
  67149. var light = scene.getLightByID(parsedShadowGenerator.lightId);
  67150. var shadowGenerator = new ShadowGenerator(parsedShadowGenerator.mapSize, light);
  67151. var shadowMap = shadowGenerator.getShadowMap();
  67152. for (var meshIndex = 0; meshIndex < parsedShadowGenerator.renderList.length; meshIndex++) {
  67153. var meshes = scene.getMeshesByID(parsedShadowGenerator.renderList[meshIndex]);
  67154. meshes.forEach(function (mesh) {
  67155. if (!shadowMap) {
  67156. return;
  67157. }
  67158. if (!shadowMap.renderList) {
  67159. shadowMap.renderList = [];
  67160. }
  67161. shadowMap.renderList.push(mesh);
  67162. });
  67163. }
  67164. if (parsedShadowGenerator.usePoissonSampling) {
  67165. shadowGenerator.usePoissonSampling = true;
  67166. }
  67167. else if (parsedShadowGenerator.useExponentialShadowMap) {
  67168. shadowGenerator.useExponentialShadowMap = true;
  67169. }
  67170. else if (parsedShadowGenerator.useBlurExponentialShadowMap) {
  67171. shadowGenerator.useBlurExponentialShadowMap = true;
  67172. }
  67173. else if (parsedShadowGenerator.useCloseExponentialShadowMap) {
  67174. shadowGenerator.useCloseExponentialShadowMap = true;
  67175. }
  67176. else if (parsedShadowGenerator.useBlurCloseExponentialShadowMap) {
  67177. shadowGenerator.useBlurCloseExponentialShadowMap = true;
  67178. }
  67179. else if (parsedShadowGenerator.usePercentageCloserFiltering) {
  67180. shadowGenerator.usePercentageCloserFiltering = true;
  67181. }
  67182. else if (parsedShadowGenerator.useContactHardeningShadow) {
  67183. shadowGenerator.useContactHardeningShadow = true;
  67184. }
  67185. if (parsedShadowGenerator.filteringQuality) {
  67186. shadowGenerator.filteringQuality = parsedShadowGenerator.filteringQuality;
  67187. }
  67188. if (parsedShadowGenerator.contactHardeningLightSizeUVRatio) {
  67189. shadowGenerator.contactHardeningLightSizeUVRatio = parsedShadowGenerator.contactHardeningLightSizeUVRatio;
  67190. }
  67191. // Backward compat
  67192. else if (parsedShadowGenerator.useVarianceShadowMap) {
  67193. shadowGenerator.useExponentialShadowMap = true;
  67194. }
  67195. else if (parsedShadowGenerator.useBlurVarianceShadowMap) {
  67196. shadowGenerator.useBlurExponentialShadowMap = true;
  67197. }
  67198. if (parsedShadowGenerator.depthScale) {
  67199. shadowGenerator.depthScale = parsedShadowGenerator.depthScale;
  67200. }
  67201. if (parsedShadowGenerator.blurScale) {
  67202. shadowGenerator.blurScale = parsedShadowGenerator.blurScale;
  67203. }
  67204. if (parsedShadowGenerator.blurBoxOffset) {
  67205. shadowGenerator.blurBoxOffset = parsedShadowGenerator.blurBoxOffset;
  67206. }
  67207. if (parsedShadowGenerator.useKernelBlur) {
  67208. shadowGenerator.useKernelBlur = parsedShadowGenerator.useKernelBlur;
  67209. }
  67210. if (parsedShadowGenerator.blurKernel) {
  67211. shadowGenerator.blurKernel = parsedShadowGenerator.blurKernel;
  67212. }
  67213. if (parsedShadowGenerator.bias !== undefined) {
  67214. shadowGenerator.bias = parsedShadowGenerator.bias;
  67215. }
  67216. if (parsedShadowGenerator.normalBias !== undefined) {
  67217. shadowGenerator.normalBias = parsedShadowGenerator.normalBias;
  67218. }
  67219. if (parsedShadowGenerator.frustumEdgeFalloff !== undefined) {
  67220. shadowGenerator.frustumEdgeFalloff = parsedShadowGenerator.frustumEdgeFalloff;
  67221. }
  67222. if (parsedShadowGenerator.darkness) {
  67223. shadowGenerator.setDarkness(parsedShadowGenerator.darkness);
  67224. }
  67225. if (parsedShadowGenerator.transparencyShadow) {
  67226. shadowGenerator.setTransparencyShadow(true);
  67227. }
  67228. shadowGenerator.forceBackFacesOnly = parsedShadowGenerator.forceBackFacesOnly;
  67229. return shadowGenerator;
  67230. };
  67231. /**
  67232. * Shadow generator mode None: no filtering applied.
  67233. */
  67234. ShadowGenerator.FILTER_NONE = 0;
  67235. /**
  67236. * Shadow generator mode ESM: Exponential Shadow Mapping.
  67237. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67238. */
  67239. ShadowGenerator.FILTER_EXPONENTIALSHADOWMAP = 1;
  67240. /**
  67241. * Shadow generator mode Poisson Sampling: Percentage Closer Filtering.
  67242. * (Multiple Tap around evenly distributed around the pixel are used to evaluate the shadow strength)
  67243. */
  67244. ShadowGenerator.FILTER_POISSONSAMPLING = 2;
  67245. /**
  67246. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping.
  67247. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67248. */
  67249. ShadowGenerator.FILTER_BLUREXPONENTIALSHADOWMAP = 3;
  67250. /**
  67251. * Shadow generator mode ESM: Exponential Shadow Mapping using the inverse of the exponential preventing
  67252. * edge artifacts on steep falloff.
  67253. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67254. */
  67255. ShadowGenerator.FILTER_CLOSEEXPONENTIALSHADOWMAP = 4;
  67256. /**
  67257. * Shadow generator mode ESM: Blurred Exponential Shadow Mapping using the inverse of the exponential preventing
  67258. * edge artifacts on steep falloff.
  67259. * (http://developer.download.nvidia.com/presentations/2008/GDC/GDC08_SoftShadowMapping.pdf)
  67260. */
  67261. ShadowGenerator.FILTER_BLURCLOSEEXPONENTIALSHADOWMAP = 5;
  67262. /**
  67263. * Shadow generator mode PCF: Percentage Closer Filtering
  67264. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67265. * (https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch11.html)
  67266. */
  67267. ShadowGenerator.FILTER_PCF = 6;
  67268. /**
  67269. * Shadow generator mode PCSS: Percentage Closering Soft Shadow.
  67270. * benefits from Webgl 2 shadow samplers. Fallback to Poisson Sampling in Webgl 1
  67271. * Contact Hardening
  67272. */
  67273. ShadowGenerator.FILTER_PCSS = 7;
  67274. /**
  67275. * Reserved for PCF and PCSS
  67276. * Highest Quality.
  67277. *
  67278. * Execute PCF on a 5*5 kernel improving a lot the shadow aliasing artifacts.
  67279. *
  67280. * Execute PCSS with 32 taps blocker search and 64 taps PCF.
  67281. */
  67282. ShadowGenerator.QUALITY_HIGH = 0;
  67283. /**
  67284. * Reserved for PCF and PCSS
  67285. * Good tradeoff for quality/perf cross devices
  67286. *
  67287. * Execute PCF on a 3*3 kernel.
  67288. *
  67289. * Execute PCSS with 16 taps blocker search and 32 taps PCF.
  67290. */
  67291. ShadowGenerator.QUALITY_MEDIUM = 1;
  67292. /**
  67293. * Reserved for PCF and PCSS
  67294. * The lowest quality but the fastest.
  67295. *
  67296. * Execute PCF on a 1*1 kernel.
  67297. *
  67298. * Execute PCSS with 16 taps blocker search and 16 taps PCF.
  67299. */
  67300. ShadowGenerator.QUALITY_LOW = 2;
  67301. return ShadowGenerator;
  67302. }());
  67303. BABYLON.ShadowGenerator = ShadowGenerator;
  67304. })(BABYLON || (BABYLON = {}));
  67305. //# sourceMappingURL=babylon.shadowGenerator.js.map
  67306. var BABYLON;
  67307. (function (BABYLON) {
  67308. var DefaultLoadingScreen = /** @class */ (function () {
  67309. function DefaultLoadingScreen(_renderingCanvas, _loadingText, _loadingDivBackgroundColor) {
  67310. if (_loadingText === void 0) { _loadingText = ""; }
  67311. if (_loadingDivBackgroundColor === void 0) { _loadingDivBackgroundColor = "black"; }
  67312. var _this = this;
  67313. this._renderingCanvas = _renderingCanvas;
  67314. this._loadingText = _loadingText;
  67315. this._loadingDivBackgroundColor = _loadingDivBackgroundColor;
  67316. // Resize
  67317. this._resizeLoadingUI = function () {
  67318. var canvasRect = _this._renderingCanvas.getBoundingClientRect();
  67319. var canvasPositioning = window.getComputedStyle(_this._renderingCanvas).position;
  67320. if (!_this._loadingDiv) {
  67321. return;
  67322. }
  67323. _this._loadingDiv.style.position = (canvasPositioning === "fixed") ? "fixed" : "absolute";
  67324. _this._loadingDiv.style.left = canvasRect.left + "px";
  67325. _this._loadingDiv.style.top = canvasRect.top + "px";
  67326. _this._loadingDiv.style.width = canvasRect.width + "px";
  67327. _this._loadingDiv.style.height = canvasRect.height + "px";
  67328. };
  67329. }
  67330. DefaultLoadingScreen.prototype.displayLoadingUI = function () {
  67331. if (this._loadingDiv) {
  67332. // Do not add a loading screen if there is already one
  67333. return;
  67334. }
  67335. this._loadingDiv = document.createElement("div");
  67336. this._loadingDiv.id = "babylonjsLoadingDiv";
  67337. this._loadingDiv.style.opacity = "0";
  67338. this._loadingDiv.style.transition = "opacity 1.5s ease";
  67339. this._loadingDiv.style.pointerEvents = "none";
  67340. // Loading text
  67341. this._loadingTextDiv = document.createElement("div");
  67342. this._loadingTextDiv.style.position = "absolute";
  67343. this._loadingTextDiv.style.left = "0";
  67344. this._loadingTextDiv.style.top = "50%";
  67345. this._loadingTextDiv.style.marginTop = "80px";
  67346. this._loadingTextDiv.style.width = "100%";
  67347. this._loadingTextDiv.style.height = "20px";
  67348. this._loadingTextDiv.style.fontFamily = "Arial";
  67349. this._loadingTextDiv.style.fontSize = "14px";
  67350. this._loadingTextDiv.style.color = "white";
  67351. this._loadingTextDiv.style.textAlign = "center";
  67352. this._loadingTextDiv.innerHTML = "Loading";
  67353. this._loadingDiv.appendChild(this._loadingTextDiv);
  67354. //set the predefined text
  67355. this._loadingTextDiv.innerHTML = this._loadingText;
  67356. // Generating keyframes
  67357. var style = document.createElement('style');
  67358. style.type = 'text/css';
  67359. 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 }";
  67360. style.innerHTML = keyFrames;
  67361. document.getElementsByTagName('head')[0].appendChild(style);
  67362. // Loading img
  67363. var imgBack = new Image();
  67364. imgBack.src = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAYAAAA5ZDbSAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAJcEhZcwAADsMAAA7DAcdvqGQAAAAZdEVYdFNvZnR3YXJlAHBhaW50Lm5ldCA0LjAuMTZEaa/1AAAYq0lEQVR4Xu2dCZRcVZnHScAJUZSwjSOIbAJmEAZwQCCMoAInYRGIg8AwegQx7AFzUBBmzAFlE4EAwxz2GRk2w7AnAURZBiEOZgyEQDAQAjmEJqTpNd3V1V3Vmd+/6utKV7/1vnpVXd2p/zn3vOV+27vfu/fd/W3QQAPrBZqbm7fJZrN79vf3T+/r67uf4wO9vb37WXQDIwWtra0Tenp6voQTv5XP56/BkfcR3iLk1g6B7hEeI+zP5V+ZiAbqBZ2dnZ8lV+6Gg87CobfhpOc4byf0FjwYE9DneBkWcXrM2tmzNzTxDdQKJPyETCazI46YgiMuI9zJuXJltuChFIHsP/PSfIfTjU19A2mira1tcxy3ey6XO5vEnkV4kes11XBmENDVj97XOT2O03FmWgMuoNLzGRJva8IUnPkzjjcT/kLoKCZzfQB7XiX8M2G8md7AUJgzJ+Z6e88gZ1xGuj3HsY17PcVkrG9gp7CUF/F8PUvxqdZDrFq1ahNVfKjwTCYxZuDE2wjKlc2WViMePM+HPNsFPOdf22OPblD5OZ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ze6OaY0KU1ogfTUgUJMK0lBIL06dS/F/LJeRe0k2kAAk7BgSWN2GVW/aCOjRuPCbBHVGBG6J3ECKIN3VlfjroguqA+RrMsFvCNqisf5mRox2qPlB4s8vuiMdIE/fVjVvLlRnhKlqYLig7QIpOiva40PAqR2E22neJFrN10AVgWMOIDgPuMOjmRFa+HVaR0fHliaugXoEOe80nBWrZg2dZkZoYffuaW5u1kCVkadmbT70AGdqJodWOhxHqP2eFg1UDvsLatnSFq41M+KKnp6eXbhsdB2OdGiCeX8+/2ecqgnmk/VXNYtqYLSAnNposzpjgw3+H/belpVa8J7TAAAAAElFTkSuQmCC";
  67365. imgBack.style.position = "absolute";
  67366. imgBack.style.left = "50%";
  67367. imgBack.style.top = "50%";
  67368. imgBack.style.marginLeft = "-60px";
  67369. imgBack.style.marginTop = "-60px";
  67370. imgBack.style.animation = "spin1 2s infinite ease-in-out";
  67371. imgBack.style.webkitAnimation = "spin1 2s infinite ease-in-out";
  67372. imgBack.style.transformOrigin = "50% 50%";
  67373. imgBack.style.webkitTransformOrigin = "50% 50%";
  67374. this._loadingDiv.appendChild(imgBack);
  67375. this._resizeLoadingUI();
  67376. window.addEventListener("resize", this._resizeLoadingUI);
  67377. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67378. document.body.appendChild(this._loadingDiv);
  67379. this._loadingDiv.style.opacity = "1";
  67380. };
  67381. DefaultLoadingScreen.prototype.hideLoadingUI = function () {
  67382. var _this = this;
  67383. if (!this._loadingDiv) {
  67384. return;
  67385. }
  67386. var onTransitionEnd = function () {
  67387. if (!_this._loadingDiv) {
  67388. return;
  67389. }
  67390. document.body.removeChild(_this._loadingDiv);
  67391. window.removeEventListener("resize", _this._resizeLoadingUI);
  67392. _this._loadingDiv = null;
  67393. };
  67394. this._loadingDiv.style.opacity = "0";
  67395. this._loadingDiv.addEventListener("transitionend", onTransitionEnd);
  67396. };
  67397. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIText", {
  67398. set: function (text) {
  67399. this._loadingText = text;
  67400. if (this._loadingTextDiv) {
  67401. this._loadingTextDiv.innerHTML = this._loadingText;
  67402. }
  67403. },
  67404. enumerable: true,
  67405. configurable: true
  67406. });
  67407. Object.defineProperty(DefaultLoadingScreen.prototype, "loadingUIBackgroundColor", {
  67408. get: function () {
  67409. return this._loadingDivBackgroundColor;
  67410. },
  67411. set: function (color) {
  67412. this._loadingDivBackgroundColor = color;
  67413. if (!this._loadingDiv) {
  67414. return;
  67415. }
  67416. this._loadingDiv.style.backgroundColor = this._loadingDivBackgroundColor;
  67417. },
  67418. enumerable: true,
  67419. configurable: true
  67420. });
  67421. return DefaultLoadingScreen;
  67422. }());
  67423. BABYLON.DefaultLoadingScreen = DefaultLoadingScreen;
  67424. })(BABYLON || (BABYLON = {}));
  67425. //# sourceMappingURL=babylon.loadingScreen.js.map
  67426. var BABYLON;
  67427. (function (BABYLON) {
  67428. var SceneLoaderProgressEvent = /** @class */ (function () {
  67429. function SceneLoaderProgressEvent(lengthComputable, loaded, total) {
  67430. this.lengthComputable = lengthComputable;
  67431. this.loaded = loaded;
  67432. this.total = total;
  67433. }
  67434. SceneLoaderProgressEvent.FromProgressEvent = function (event) {
  67435. return new SceneLoaderProgressEvent(event.lengthComputable, event.loaded, event.total);
  67436. };
  67437. return SceneLoaderProgressEvent;
  67438. }());
  67439. BABYLON.SceneLoaderProgressEvent = SceneLoaderProgressEvent;
  67440. var SceneLoader = /** @class */ (function () {
  67441. function SceneLoader() {
  67442. }
  67443. Object.defineProperty(SceneLoader, "NO_LOGGING", {
  67444. get: function () {
  67445. return 0;
  67446. },
  67447. enumerable: true,
  67448. configurable: true
  67449. });
  67450. Object.defineProperty(SceneLoader, "MINIMAL_LOGGING", {
  67451. get: function () {
  67452. return 1;
  67453. },
  67454. enumerable: true,
  67455. configurable: true
  67456. });
  67457. Object.defineProperty(SceneLoader, "SUMMARY_LOGGING", {
  67458. get: function () {
  67459. return 2;
  67460. },
  67461. enumerable: true,
  67462. configurable: true
  67463. });
  67464. Object.defineProperty(SceneLoader, "DETAILED_LOGGING", {
  67465. get: function () {
  67466. return 3;
  67467. },
  67468. enumerable: true,
  67469. configurable: true
  67470. });
  67471. Object.defineProperty(SceneLoader, "ForceFullSceneLoadingForIncremental", {
  67472. get: function () {
  67473. return SceneLoader._ForceFullSceneLoadingForIncremental;
  67474. },
  67475. set: function (value) {
  67476. SceneLoader._ForceFullSceneLoadingForIncremental = value;
  67477. },
  67478. enumerable: true,
  67479. configurable: true
  67480. });
  67481. Object.defineProperty(SceneLoader, "ShowLoadingScreen", {
  67482. get: function () {
  67483. return SceneLoader._ShowLoadingScreen;
  67484. },
  67485. set: function (value) {
  67486. SceneLoader._ShowLoadingScreen = value;
  67487. },
  67488. enumerable: true,
  67489. configurable: true
  67490. });
  67491. Object.defineProperty(SceneLoader, "loggingLevel", {
  67492. get: function () {
  67493. return SceneLoader._loggingLevel;
  67494. },
  67495. set: function (value) {
  67496. SceneLoader._loggingLevel = value;
  67497. },
  67498. enumerable: true,
  67499. configurable: true
  67500. });
  67501. Object.defineProperty(SceneLoader, "CleanBoneMatrixWeights", {
  67502. get: function () {
  67503. return SceneLoader._CleanBoneMatrixWeights;
  67504. },
  67505. set: function (value) {
  67506. SceneLoader._CleanBoneMatrixWeights = value;
  67507. },
  67508. enumerable: true,
  67509. configurable: true
  67510. });
  67511. SceneLoader._getDefaultPlugin = function () {
  67512. return SceneLoader._registeredPlugins[".babylon"];
  67513. };
  67514. SceneLoader._getPluginForExtension = function (extension) {
  67515. var registeredPlugin = SceneLoader._registeredPlugins[extension];
  67516. if (registeredPlugin) {
  67517. return registeredPlugin;
  67518. }
  67519. BABYLON.Tools.Warn("Unable to find a plugin to load " + extension + " files. Trying to use .babylon default plugin. To load from a specific filetype (eg. gltf) see: http://doc.babylonjs.com/how_to/load_from_any_file_type");
  67520. return SceneLoader._getDefaultPlugin();
  67521. };
  67522. SceneLoader._getPluginForDirectLoad = function (data) {
  67523. for (var extension in SceneLoader._registeredPlugins) {
  67524. var plugin = SceneLoader._registeredPlugins[extension].plugin;
  67525. if (plugin.canDirectLoad && plugin.canDirectLoad(data)) {
  67526. return SceneLoader._registeredPlugins[extension];
  67527. }
  67528. }
  67529. return SceneLoader._getDefaultPlugin();
  67530. };
  67531. SceneLoader._getPluginForFilename = function (sceneFilename) {
  67532. if (sceneFilename.name) {
  67533. sceneFilename = sceneFilename.name;
  67534. }
  67535. var queryStringPosition = sceneFilename.indexOf("?");
  67536. if (queryStringPosition !== -1) {
  67537. sceneFilename = sceneFilename.substring(0, queryStringPosition);
  67538. }
  67539. var dotPosition = sceneFilename.lastIndexOf(".");
  67540. var extension = sceneFilename.substring(dotPosition, sceneFilename.length).toLowerCase();
  67541. return SceneLoader._getPluginForExtension(extension);
  67542. };
  67543. // use babylon file loader directly if sceneFilename is prefixed with "data:"
  67544. SceneLoader._getDirectLoad = function (sceneFilename) {
  67545. if (sceneFilename.substr && sceneFilename.substr(0, 5) === "data:") {
  67546. return sceneFilename.substr(5);
  67547. }
  67548. return null;
  67549. };
  67550. SceneLoader._loadData = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, onDispose, pluginExtension) {
  67551. var directLoad = SceneLoader._getDirectLoad(sceneFilename);
  67552. var registeredPlugin = pluginExtension ? SceneLoader._getPluginForExtension(pluginExtension) : (directLoad ? SceneLoader._getPluginForDirectLoad(sceneFilename) : SceneLoader._getPluginForFilename(sceneFilename));
  67553. var plugin;
  67554. if (registeredPlugin.plugin.createPlugin) {
  67555. plugin = registeredPlugin.plugin.createPlugin();
  67556. }
  67557. else {
  67558. plugin = registeredPlugin.plugin;
  67559. }
  67560. var useArrayBuffer = registeredPlugin.isBinary;
  67561. var database;
  67562. SceneLoader.OnPluginActivatedObservable.notifyObservers(plugin);
  67563. var dataCallback = function (data, responseURL) {
  67564. if (scene.isDisposed) {
  67565. onError("Scene has been disposed");
  67566. return;
  67567. }
  67568. scene.database = database;
  67569. onSuccess(plugin, data, responseURL);
  67570. };
  67571. var request = null;
  67572. var pluginDisposed = false;
  67573. var onDisposeObservable = plugin.onDisposeObservable;
  67574. if (onDisposeObservable) {
  67575. onDisposeObservable.add(function () {
  67576. pluginDisposed = true;
  67577. if (request) {
  67578. request.abort();
  67579. request = null;
  67580. }
  67581. onDispose();
  67582. });
  67583. }
  67584. var manifestChecked = function () {
  67585. if (pluginDisposed) {
  67586. return;
  67587. }
  67588. var url = rootUrl + sceneFilename;
  67589. request = BABYLON.Tools.LoadFile(url, dataCallback, onProgress ? function (event) {
  67590. onProgress(SceneLoaderProgressEvent.FromProgressEvent(event));
  67591. } : undefined, database, useArrayBuffer, function (request, exception) {
  67592. onError("Failed to load scene." + (exception ? "" : " " + exception.message), exception);
  67593. });
  67594. };
  67595. if (directLoad) {
  67596. dataCallback(directLoad);
  67597. return plugin;
  67598. }
  67599. if (rootUrl.indexOf("file:") === -1) {
  67600. var engine = scene.getEngine();
  67601. var canUseOfflineSupport = engine.enableOfflineSupport;
  67602. if (canUseOfflineSupport) {
  67603. // Also check for exceptions
  67604. var exceptionFound = false;
  67605. for (var _i = 0, _a = scene.disableOfflineSupportExceptionRules; _i < _a.length; _i++) {
  67606. var regex = _a[_i];
  67607. if (regex.test(rootUrl + sceneFilename)) {
  67608. exceptionFound = true;
  67609. break;
  67610. }
  67611. }
  67612. canUseOfflineSupport = !exceptionFound;
  67613. }
  67614. if (canUseOfflineSupport) {
  67615. // Checking if a manifest file has been set for this scene and if offline mode has been requested
  67616. database = new BABYLON.Database(rootUrl + sceneFilename, manifestChecked, engine.disableManifestCheck);
  67617. }
  67618. else {
  67619. manifestChecked();
  67620. }
  67621. }
  67622. // Loading file from disk via input file or drag'n'drop
  67623. else {
  67624. var fileOrString = sceneFilename;
  67625. if (fileOrString.name) { // File
  67626. request = BABYLON.Tools.ReadFile(fileOrString, dataCallback, onProgress, useArrayBuffer);
  67627. }
  67628. else if (BABYLON.FilesInput.FilesToLoad[sceneFilename]) {
  67629. request = BABYLON.Tools.ReadFile(BABYLON.FilesInput.FilesToLoad[sceneFilename], dataCallback, onProgress, useArrayBuffer);
  67630. }
  67631. else {
  67632. onError("Unable to find file named " + sceneFilename);
  67633. }
  67634. }
  67635. return plugin;
  67636. };
  67637. // Public functions
  67638. SceneLoader.GetPluginForExtension = function (extension) {
  67639. return SceneLoader._getPluginForExtension(extension).plugin;
  67640. };
  67641. SceneLoader.IsPluginForExtensionAvailable = function (extension) {
  67642. return !!SceneLoader._registeredPlugins[extension];
  67643. };
  67644. SceneLoader.RegisterPlugin = function (plugin) {
  67645. if (typeof plugin.extensions === "string") {
  67646. var extension = plugin.extensions;
  67647. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67648. plugin: plugin,
  67649. isBinary: false
  67650. };
  67651. }
  67652. else {
  67653. var extensions = plugin.extensions;
  67654. Object.keys(extensions).forEach(function (extension) {
  67655. SceneLoader._registeredPlugins[extension.toLowerCase()] = {
  67656. plugin: plugin,
  67657. isBinary: extensions[extension].isBinary
  67658. };
  67659. });
  67660. }
  67661. };
  67662. /**
  67663. * Import meshes into a scene
  67664. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67665. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67666. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67667. * @param scene the instance of BABYLON.Scene to append to
  67668. * @param onSuccess a callback with a list of imported meshes, particleSystems, and skeletons when import succeeds
  67669. * @param onProgress a callback with a progress event for each file being loaded
  67670. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67671. * @param pluginExtension the extension used to determine the plugin
  67672. * @returns The loaded plugin
  67673. */
  67674. SceneLoader.ImportMesh = function (meshNames, rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67675. if (sceneFilename === void 0) { sceneFilename = ""; }
  67676. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67677. if (onSuccess === void 0) { onSuccess = null; }
  67678. if (onProgress === void 0) { onProgress = null; }
  67679. if (onError === void 0) { onError = null; }
  67680. if (pluginExtension === void 0) { pluginExtension = null; }
  67681. if (!scene) {
  67682. BABYLON.Tools.Error("No scene available to import mesh to");
  67683. return null;
  67684. }
  67685. if (!sceneFilename) {
  67686. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67687. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67688. }
  67689. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67690. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67691. return null;
  67692. }
  67693. var loadingToken = {};
  67694. scene._addPendingData(loadingToken);
  67695. var disposeHandler = function () {
  67696. scene._removePendingData(loadingToken);
  67697. };
  67698. var errorHandler = function (message, exception) {
  67699. var errorMessage = "Unable to import meshes from " + rootUrl + sceneFilename + ": " + message;
  67700. if (onError) {
  67701. onError(scene, errorMessage, exception);
  67702. }
  67703. else {
  67704. BABYLON.Tools.Error(errorMessage);
  67705. // should the exception be thrown?
  67706. }
  67707. disposeHandler();
  67708. };
  67709. var progressHandler = onProgress ? function (event) {
  67710. try {
  67711. onProgress(event);
  67712. }
  67713. catch (e) {
  67714. errorHandler("Error in onProgress callback", e);
  67715. }
  67716. } : undefined;
  67717. var successHandler = function (meshes, particleSystems, skeletons, animationGroups) {
  67718. scene.importedMeshesFiles.push(rootUrl + sceneFilename);
  67719. if (onSuccess) {
  67720. try {
  67721. onSuccess(meshes, particleSystems, skeletons, animationGroups);
  67722. }
  67723. catch (e) {
  67724. errorHandler("Error in onSuccess callback", e);
  67725. }
  67726. }
  67727. scene._removePendingData(loadingToken);
  67728. };
  67729. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67730. if (plugin.rewriteRootURL) {
  67731. rootUrl = plugin.rewriteRootURL(rootUrl, responseURL);
  67732. }
  67733. if (sceneFilename === "") {
  67734. if (sceneFilename === "") {
  67735. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67736. }
  67737. }
  67738. if (plugin.importMesh) {
  67739. var syncedPlugin = plugin;
  67740. var meshes = new Array();
  67741. var particleSystems = new Array();
  67742. var skeletons = new Array();
  67743. if (!syncedPlugin.importMesh(meshNames, scene, data, rootUrl, meshes, particleSystems, skeletons, errorHandler)) {
  67744. return;
  67745. }
  67746. scene.loadingPluginName = plugin.name;
  67747. successHandler(meshes, particleSystems, skeletons, []);
  67748. }
  67749. else {
  67750. var asyncedPlugin = plugin;
  67751. asyncedPlugin.importMeshAsync(meshNames, scene, data, rootUrl, progressHandler).then(function (result) {
  67752. scene.loadingPluginName = plugin.name;
  67753. successHandler(result.meshes, result.particleSystems, result.skeletons, result.animationGroups);
  67754. }).catch(function (error) {
  67755. errorHandler(error.message, error);
  67756. });
  67757. }
  67758. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67759. };
  67760. /**
  67761. * Import meshes into a scene
  67762. * @param meshNames an array of mesh names, a single mesh name, or empty string for all meshes that filter what meshes are imported
  67763. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67764. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67765. * @param scene the instance of BABYLON.Scene to append to
  67766. * @param onProgress a callback with a progress event for each file being loaded
  67767. * @param pluginExtension the extension used to determine the plugin
  67768. * @returns The loaded list of imported meshes, particle systems, skeletons, and animation groups
  67769. */
  67770. SceneLoader.ImportMeshAsync = function (meshNames, rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67771. if (sceneFilename === void 0) { sceneFilename = ""; }
  67772. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67773. if (onProgress === void 0) { onProgress = null; }
  67774. if (pluginExtension === void 0) { pluginExtension = null; }
  67775. return new Promise(function (resolve, reject) {
  67776. SceneLoader.ImportMesh(meshNames, rootUrl, sceneFilename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  67777. resolve({
  67778. meshes: meshes,
  67779. particleSystems: particleSystems,
  67780. skeletons: skeletons,
  67781. animationGroups: animationGroups
  67782. });
  67783. }, onProgress, function (scene, message, exception) {
  67784. reject(exception || new Error(message));
  67785. }, pluginExtension);
  67786. });
  67787. };
  67788. /**
  67789. * Load a scene
  67790. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67791. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67792. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67793. * @param onSuccess a callback with the scene when import succeeds
  67794. * @param onProgress a callback with a progress event for each file being loaded
  67795. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67796. * @param pluginExtension the extension used to determine the plugin
  67797. * @returns The loaded plugin
  67798. */
  67799. SceneLoader.Load = function (rootUrl, sceneFilename, engine, onSuccess, onProgress, onError, pluginExtension) {
  67800. if (onSuccess === void 0) { onSuccess = null; }
  67801. if (onProgress === void 0) { onProgress = null; }
  67802. if (onError === void 0) { onError = null; }
  67803. if (pluginExtension === void 0) { pluginExtension = null; }
  67804. return SceneLoader.Append(rootUrl, sceneFilename, new BABYLON.Scene(engine), onSuccess, onProgress, onError, pluginExtension);
  67805. };
  67806. /**
  67807. * Load a scene
  67808. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67809. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67810. * @param engine is the instance of BABYLON.Engine to use to create the scene
  67811. * @param onProgress a callback with a progress event for each file being loaded
  67812. * @param pluginExtension the extension used to determine the plugin
  67813. * @returns The loaded scene
  67814. */
  67815. SceneLoader.LoadAsync = function (rootUrl, sceneFilename, engine, onProgress, pluginExtension) {
  67816. if (onProgress === void 0) { onProgress = null; }
  67817. if (pluginExtension === void 0) { pluginExtension = null; }
  67818. return new Promise(function (resolve, reject) {
  67819. SceneLoader.Load(rootUrl, sceneFilename, engine, function (scene) {
  67820. resolve(scene);
  67821. }, onProgress, function (scene, message, exception) {
  67822. reject(exception || new Error(message));
  67823. }, pluginExtension);
  67824. });
  67825. };
  67826. /**
  67827. * Append a scene
  67828. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67829. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67830. * @param scene is the instance of BABYLON.Scene to append to
  67831. * @param onSuccess a callback with the scene when import succeeds
  67832. * @param onProgress a callback with a progress event for each file being loaded
  67833. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67834. * @param pluginExtension the extension used to determine the plugin
  67835. * @returns The loaded plugin
  67836. */
  67837. SceneLoader.Append = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67838. if (sceneFilename === void 0) { sceneFilename = ""; }
  67839. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67840. if (onSuccess === void 0) { onSuccess = null; }
  67841. if (onProgress === void 0) { onProgress = null; }
  67842. if (onError === void 0) { onError = null; }
  67843. if (pluginExtension === void 0) { pluginExtension = null; }
  67844. if (!scene) {
  67845. BABYLON.Tools.Error("No scene available to append to");
  67846. return null;
  67847. }
  67848. if (!sceneFilename) {
  67849. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67850. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67851. }
  67852. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67853. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67854. return null;
  67855. }
  67856. if (SceneLoader.ShowLoadingScreen) {
  67857. scene.getEngine().displayLoadingUI();
  67858. }
  67859. var loadingToken = {};
  67860. scene._addPendingData(loadingToken);
  67861. var disposeHandler = function () {
  67862. scene._removePendingData(loadingToken);
  67863. scene.getEngine().hideLoadingUI();
  67864. };
  67865. var errorHandler = function (message, exception) {
  67866. var errorMessage = "Unable to load from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67867. if (onError) {
  67868. onError(scene, errorMessage, exception);
  67869. }
  67870. else {
  67871. BABYLON.Tools.Error(errorMessage);
  67872. // should the exception be thrown?
  67873. }
  67874. disposeHandler();
  67875. };
  67876. var progressHandler = onProgress ? function (event) {
  67877. try {
  67878. onProgress(event);
  67879. }
  67880. catch (e) {
  67881. errorHandler("Error in onProgress callback", e);
  67882. }
  67883. } : undefined;
  67884. var successHandler = function () {
  67885. if (onSuccess) {
  67886. try {
  67887. onSuccess(scene);
  67888. }
  67889. catch (e) {
  67890. errorHandler("Error in onSuccess callback", e);
  67891. }
  67892. }
  67893. scene._removePendingData(loadingToken);
  67894. };
  67895. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  67896. if (sceneFilename === "") {
  67897. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl, true);
  67898. }
  67899. if (plugin.load) {
  67900. var syncedPlugin = plugin;
  67901. if (!syncedPlugin.load(scene, data, rootUrl, errorHandler)) {
  67902. return;
  67903. }
  67904. scene.loadingPluginName = plugin.name;
  67905. successHandler();
  67906. }
  67907. else {
  67908. var asyncedPlugin = plugin;
  67909. asyncedPlugin.loadAsync(scene, data, rootUrl, progressHandler).then(function () {
  67910. scene.loadingPluginName = plugin.name;
  67911. successHandler();
  67912. }).catch(function (error) {
  67913. errorHandler(error.message, error);
  67914. });
  67915. }
  67916. if (SceneLoader.ShowLoadingScreen) {
  67917. scene.executeWhenReady(function () {
  67918. scene.getEngine().hideLoadingUI();
  67919. });
  67920. }
  67921. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  67922. };
  67923. /**
  67924. * Append a scene
  67925. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67926. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67927. * @param scene is the instance of BABYLON.Scene to append to
  67928. * @param onProgress a callback with a progress event for each file being loaded
  67929. * @param pluginExtension the extension used to determine the plugin
  67930. * @returns The given scene
  67931. */
  67932. SceneLoader.AppendAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  67933. if (sceneFilename === void 0) { sceneFilename = ""; }
  67934. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67935. if (onProgress === void 0) { onProgress = null; }
  67936. if (pluginExtension === void 0) { pluginExtension = null; }
  67937. return new Promise(function (resolve, reject) {
  67938. SceneLoader.Append(rootUrl, sceneFilename, scene, function (scene) {
  67939. resolve(scene);
  67940. }, onProgress, function (scene, message, exception) {
  67941. reject(exception || new Error(message));
  67942. }, pluginExtension);
  67943. });
  67944. };
  67945. /**
  67946. * Load a scene into an asset container
  67947. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  67948. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  67949. * @param scene is the instance of BABYLON.Scene to append to (default: last created scene)
  67950. * @param onSuccess a callback with the scene when import succeeds
  67951. * @param onProgress a callback with a progress event for each file being loaded
  67952. * @param onError a callback with the scene, a message, and possibly an exception when import fails
  67953. * @param pluginExtension the extension used to determine the plugin
  67954. * @returns The loaded plugin
  67955. */
  67956. SceneLoader.LoadAssetContainer = function (rootUrl, sceneFilename, scene, onSuccess, onProgress, onError, pluginExtension) {
  67957. if (sceneFilename === void 0) { sceneFilename = ""; }
  67958. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  67959. if (onSuccess === void 0) { onSuccess = null; }
  67960. if (onProgress === void 0) { onProgress = null; }
  67961. if (onError === void 0) { onError = null; }
  67962. if (pluginExtension === void 0) { pluginExtension = null; }
  67963. if (!scene) {
  67964. BABYLON.Tools.Error("No scene available to load asset container to");
  67965. return null;
  67966. }
  67967. if (!sceneFilename) {
  67968. sceneFilename = BABYLON.Tools.GetFilename(rootUrl);
  67969. rootUrl = BABYLON.Tools.GetFolderPath(rootUrl);
  67970. }
  67971. if (sceneFilename.substr && sceneFilename.substr(0, 1) === "/") {
  67972. BABYLON.Tools.Error("Wrong sceneFilename parameter");
  67973. return null;
  67974. }
  67975. var loadingToken = {};
  67976. scene._addPendingData(loadingToken);
  67977. var disposeHandler = function () {
  67978. scene._removePendingData(loadingToken);
  67979. };
  67980. var errorHandler = function (message, exception) {
  67981. var errorMessage = "Unable to load assets from " + rootUrl + sceneFilename + (message ? ": " + message : "");
  67982. if (onError) {
  67983. onError(scene, errorMessage, exception);
  67984. }
  67985. else {
  67986. BABYLON.Tools.Error(errorMessage);
  67987. // should the exception be thrown?
  67988. }
  67989. disposeHandler();
  67990. };
  67991. var progressHandler = onProgress ? function (event) {
  67992. try {
  67993. onProgress(event);
  67994. }
  67995. catch (e) {
  67996. errorHandler("Error in onProgress callback", e);
  67997. }
  67998. } : undefined;
  67999. var successHandler = function (assets) {
  68000. if (onSuccess) {
  68001. try {
  68002. onSuccess(assets);
  68003. }
  68004. catch (e) {
  68005. errorHandler("Error in onSuccess callback", e);
  68006. }
  68007. }
  68008. scene._removePendingData(loadingToken);
  68009. };
  68010. return SceneLoader._loadData(rootUrl, sceneFilename, scene, function (plugin, data, responseURL) {
  68011. if (plugin.loadAssetContainer) {
  68012. var syncedPlugin = plugin;
  68013. var assetContainer = syncedPlugin.loadAssetContainer(scene, data, rootUrl, errorHandler);
  68014. if (!assetContainer) {
  68015. return;
  68016. }
  68017. scene.loadingPluginName = plugin.name;
  68018. successHandler(assetContainer);
  68019. }
  68020. else if (plugin.loadAssetContainerAsync) {
  68021. var asyncedPlugin = plugin;
  68022. asyncedPlugin.loadAssetContainerAsync(scene, data, rootUrl, progressHandler).then(function (assetContainer) {
  68023. scene.loadingPluginName = plugin.name;
  68024. successHandler(assetContainer);
  68025. }).catch(function (error) {
  68026. errorHandler(error.message, error);
  68027. });
  68028. }
  68029. else {
  68030. errorHandler("LoadAssetContainer is not supported by this plugin. Plugin did not provide a loadAssetContainer or loadAssetContainerAsync method.");
  68031. }
  68032. if (SceneLoader.ShowLoadingScreen) {
  68033. scene.executeWhenReady(function () {
  68034. scene.getEngine().hideLoadingUI();
  68035. });
  68036. }
  68037. }, progressHandler, errorHandler, disposeHandler, pluginExtension);
  68038. };
  68039. /**
  68040. * Load a scene into an asset container
  68041. * @param rootUrl a string that defines the root url for scene and resources OR the concatenation of rootURL and filename (eg. http://example.com/test.glb)
  68042. * @param sceneFilename a string that defines the name of the scene file. can start with "data:" following by the stringified version of the scene (default: empty string)
  68043. * @param scene is the instance of BABYLON.Scene to append to
  68044. * @param onProgress a callback with a progress event for each file being loaded
  68045. * @param pluginExtension the extension used to determine the plugin
  68046. * @returns The loaded asset container
  68047. */
  68048. SceneLoader.LoadAssetContainerAsync = function (rootUrl, sceneFilename, scene, onProgress, pluginExtension) {
  68049. if (sceneFilename === void 0) { sceneFilename = ""; }
  68050. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  68051. if (onProgress === void 0) { onProgress = null; }
  68052. if (pluginExtension === void 0) { pluginExtension = null; }
  68053. return new Promise(function (resolve, reject) {
  68054. SceneLoader.LoadAssetContainer(rootUrl, sceneFilename, scene, function (assetContainer) {
  68055. resolve(assetContainer);
  68056. }, onProgress, function (scene, message, exception) {
  68057. reject(exception || new Error(message));
  68058. }, pluginExtension);
  68059. });
  68060. };
  68061. // Flags
  68062. SceneLoader._ForceFullSceneLoadingForIncremental = false;
  68063. SceneLoader._ShowLoadingScreen = true;
  68064. SceneLoader._CleanBoneMatrixWeights = false;
  68065. SceneLoader._loggingLevel = SceneLoader.NO_LOGGING;
  68066. // Members
  68067. SceneLoader.OnPluginActivatedObservable = new BABYLON.Observable();
  68068. SceneLoader._registeredPlugins = {};
  68069. return SceneLoader;
  68070. }());
  68071. BABYLON.SceneLoader = SceneLoader;
  68072. ;
  68073. })(BABYLON || (BABYLON = {}));
  68074. //# sourceMappingURL=babylon.sceneLoader.js.map
  68075. var BABYLON;
  68076. (function (BABYLON) {
  68077. var parseMaterialById = function (id, parsedData, scene, rootUrl) {
  68078. for (var index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68079. var parsedMaterial = parsedData.materials[index];
  68080. if (parsedMaterial.id === id) {
  68081. return BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68082. }
  68083. }
  68084. return null;
  68085. };
  68086. var isDescendantOf = function (mesh, names, hierarchyIds) {
  68087. for (var i in names) {
  68088. if (mesh.name === names[i]) {
  68089. hierarchyIds.push(mesh.id);
  68090. return true;
  68091. }
  68092. }
  68093. if (mesh.parentId && hierarchyIds.indexOf(mesh.parentId) !== -1) {
  68094. hierarchyIds.push(mesh.id);
  68095. return true;
  68096. }
  68097. return false;
  68098. };
  68099. var logOperation = function (operation, producer) {
  68100. return operation + " of " + (producer ? producer.file + " from " + producer.name + " version: " + producer.version + ", exporter version: " + producer.exporter_version : "unknown");
  68101. };
  68102. var loadAssetContainer = function (scene, data, rootUrl, onError, addToScene) {
  68103. if (addToScene === void 0) { addToScene = false; }
  68104. var container = new BABYLON.AssetContainer(scene);
  68105. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68106. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68107. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68108. // and avoid problems with multiple concurrent .babylon loads.
  68109. var log = "importScene has failed JSON parse";
  68110. try {
  68111. var parsedData = JSON.parse(data);
  68112. log = "";
  68113. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68114. var index;
  68115. var cache;
  68116. // Lights
  68117. if (parsedData.lights !== undefined && parsedData.lights !== null) {
  68118. for (index = 0, cache = parsedData.lights.length; index < cache; index++) {
  68119. var parsedLight = parsedData.lights[index];
  68120. var light = BABYLON.Light.Parse(parsedLight, scene);
  68121. if (light) {
  68122. container.lights.push(light);
  68123. log += (index === 0 ? "\n\tLights:" : "");
  68124. log += "\n\t\t" + light.toString(fullDetails);
  68125. }
  68126. }
  68127. }
  68128. // Animations
  68129. if (parsedData.animations !== undefined && parsedData.animations !== null) {
  68130. for (index = 0, cache = parsedData.animations.length; index < cache; index++) {
  68131. var parsedAnimation = parsedData.animations[index];
  68132. var animation = BABYLON.Animation.Parse(parsedAnimation);
  68133. scene.animations.push(animation);
  68134. container.animations.push(animation);
  68135. log += (index === 0 ? "\n\tAnimations:" : "");
  68136. log += "\n\t\t" + animation.toString(fullDetails);
  68137. }
  68138. }
  68139. // Materials
  68140. if (parsedData.materials !== undefined && parsedData.materials !== null) {
  68141. for (index = 0, cache = parsedData.materials.length; index < cache; index++) {
  68142. var parsedMaterial = parsedData.materials[index];
  68143. var mat = BABYLON.Material.Parse(parsedMaterial, scene, rootUrl);
  68144. container.materials.push(mat);
  68145. log += (index === 0 ? "\n\tMaterials:" : "");
  68146. log += "\n\t\t" + mat.toString(fullDetails);
  68147. }
  68148. }
  68149. if (parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68150. for (index = 0, cache = parsedData.multiMaterials.length; index < cache; index++) {
  68151. var parsedMultiMaterial = parsedData.multiMaterials[index];
  68152. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68153. container.multiMaterials.push(mmat);
  68154. log += (index === 0 ? "\n\tMultiMaterials:" : "");
  68155. log += "\n\t\t" + mmat.toString(fullDetails);
  68156. }
  68157. }
  68158. // Morph targets
  68159. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68160. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68161. var managerData = _a[_i];
  68162. container.morphTargetManagers.push(BABYLON.MorphTargetManager.Parse(managerData, scene));
  68163. }
  68164. }
  68165. // Skeletons
  68166. if (parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68167. for (index = 0, cache = parsedData.skeletons.length; index < cache; index++) {
  68168. var parsedSkeleton = parsedData.skeletons[index];
  68169. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68170. container.skeletons.push(skeleton);
  68171. log += (index === 0 ? "\n\tSkeletons:" : "");
  68172. log += "\n\t\t" + skeleton.toString(fullDetails);
  68173. }
  68174. }
  68175. // Geometries
  68176. var geometries = parsedData.geometries;
  68177. if (geometries !== undefined && geometries !== null) {
  68178. var addedGeometry = new Array();
  68179. // Boxes
  68180. var boxes = geometries.boxes;
  68181. if (boxes !== undefined && boxes !== null) {
  68182. for (index = 0, cache = boxes.length; index < cache; index++) {
  68183. var parsedBox = boxes[index];
  68184. addedGeometry.push(BABYLON.BoxGeometry.Parse(parsedBox, scene));
  68185. }
  68186. }
  68187. // Spheres
  68188. var spheres = geometries.spheres;
  68189. if (spheres !== undefined && spheres !== null) {
  68190. for (index = 0, cache = spheres.length; index < cache; index++) {
  68191. var parsedSphere = spheres[index];
  68192. addedGeometry.push(BABYLON.SphereGeometry.Parse(parsedSphere, scene));
  68193. }
  68194. }
  68195. // Cylinders
  68196. var cylinders = geometries.cylinders;
  68197. if (cylinders !== undefined && cylinders !== null) {
  68198. for (index = 0, cache = cylinders.length; index < cache; index++) {
  68199. var parsedCylinder = cylinders[index];
  68200. addedGeometry.push(BABYLON.CylinderGeometry.Parse(parsedCylinder, scene));
  68201. }
  68202. }
  68203. // Toruses
  68204. var toruses = geometries.toruses;
  68205. if (toruses !== undefined && toruses !== null) {
  68206. for (index = 0, cache = toruses.length; index < cache; index++) {
  68207. var parsedTorus = toruses[index];
  68208. addedGeometry.push(BABYLON.TorusGeometry.Parse(parsedTorus, scene));
  68209. }
  68210. }
  68211. // Grounds
  68212. var grounds = geometries.grounds;
  68213. if (grounds !== undefined && grounds !== null) {
  68214. for (index = 0, cache = grounds.length; index < cache; index++) {
  68215. var parsedGround = grounds[index];
  68216. addedGeometry.push(BABYLON.GroundGeometry.Parse(parsedGround, scene));
  68217. }
  68218. }
  68219. // Planes
  68220. var planes = geometries.planes;
  68221. if (planes !== undefined && planes !== null) {
  68222. for (index = 0, cache = planes.length; index < cache; index++) {
  68223. var parsedPlane = planes[index];
  68224. addedGeometry.push(BABYLON.PlaneGeometry.Parse(parsedPlane, scene));
  68225. }
  68226. }
  68227. // TorusKnots
  68228. var torusKnots = geometries.torusKnots;
  68229. if (torusKnots !== undefined && torusKnots !== null) {
  68230. for (index = 0, cache = torusKnots.length; index < cache; index++) {
  68231. var parsedTorusKnot = torusKnots[index];
  68232. addedGeometry.push(BABYLON.TorusKnotGeometry.Parse(parsedTorusKnot, scene));
  68233. }
  68234. }
  68235. // VertexData
  68236. var vertexData = geometries.vertexData;
  68237. if (vertexData !== undefined && vertexData !== null) {
  68238. for (index = 0, cache = vertexData.length; index < cache; index++) {
  68239. var parsedVertexData = vertexData[index];
  68240. addedGeometry.push(BABYLON.Geometry.Parse(parsedVertexData, scene, rootUrl));
  68241. }
  68242. }
  68243. addedGeometry.forEach(function (g) {
  68244. if (g) {
  68245. container.geometries.push(g);
  68246. }
  68247. });
  68248. }
  68249. // Transform nodes
  68250. if (parsedData.transformNodes !== undefined && parsedData.transformNodes !== null) {
  68251. for (index = 0, cache = parsedData.transformNodes.length; index < cache; index++) {
  68252. var parsedTransformNode = parsedData.transformNodes[index];
  68253. var node = BABYLON.TransformNode.Parse(parsedTransformNode, scene, rootUrl);
  68254. container.transformNodes.push(node);
  68255. }
  68256. }
  68257. // Meshes
  68258. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68259. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68260. var parsedMesh = parsedData.meshes[index];
  68261. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68262. container.meshes.push(mesh);
  68263. log += (index === 0 ? "\n\tMeshes:" : "");
  68264. log += "\n\t\t" + mesh.toString(fullDetails);
  68265. }
  68266. }
  68267. // Cameras
  68268. if (parsedData.cameras !== undefined && parsedData.cameras !== null) {
  68269. for (index = 0, cache = parsedData.cameras.length; index < cache; index++) {
  68270. var parsedCamera = parsedData.cameras[index];
  68271. var camera = BABYLON.Camera.Parse(parsedCamera, scene);
  68272. container.cameras.push(camera);
  68273. log += (index === 0 ? "\n\tCameras:" : "");
  68274. log += "\n\t\t" + camera.toString(fullDetails);
  68275. }
  68276. }
  68277. // Browsing all the graph to connect the dots
  68278. for (index = 0, cache = scene.cameras.length; index < cache; index++) {
  68279. var camera = scene.cameras[index];
  68280. if (camera._waitingParentId) {
  68281. camera.parent = scene.getLastEntryByID(camera._waitingParentId);
  68282. camera._waitingParentId = null;
  68283. }
  68284. }
  68285. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68286. var light_1 = scene.lights[index];
  68287. if (light_1 && light_1._waitingParentId) {
  68288. light_1.parent = scene.getLastEntryByID(light_1._waitingParentId);
  68289. light_1._waitingParentId = null;
  68290. }
  68291. }
  68292. // Sounds
  68293. // TODO: add sound
  68294. var loadedSounds = [];
  68295. var loadedSound;
  68296. if (BABYLON.AudioEngine && parsedData.sounds !== undefined && parsedData.sounds !== null) {
  68297. for (index = 0, cache = parsedData.sounds.length; index < cache; index++) {
  68298. var parsedSound = parsedData.sounds[index];
  68299. if (BABYLON.Engine.audioEngine.canUseWebAudio) {
  68300. if (!parsedSound.url)
  68301. parsedSound.url = parsedSound.name;
  68302. if (!loadedSounds[parsedSound.url]) {
  68303. loadedSound = BABYLON.Sound.Parse(parsedSound, scene, rootUrl);
  68304. loadedSounds[parsedSound.url] = loadedSound;
  68305. container.sounds.push(loadedSound);
  68306. }
  68307. else {
  68308. container.sounds.push(BABYLON.Sound.Parse(parsedSound, scene, rootUrl, loadedSounds[parsedSound.url]));
  68309. }
  68310. }
  68311. else {
  68312. container.sounds.push(new BABYLON.Sound(parsedSound.name, null, scene));
  68313. }
  68314. }
  68315. }
  68316. loadedSounds = [];
  68317. // Connect parents & children and parse actions
  68318. for (index = 0, cache = scene.transformNodes.length; index < cache; index++) {
  68319. var transformNode = scene.transformNodes[index];
  68320. if (transformNode._waitingParentId) {
  68321. transformNode.parent = scene.getLastEntryByID(transformNode._waitingParentId);
  68322. transformNode._waitingParentId = null;
  68323. }
  68324. }
  68325. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68326. var mesh = scene.meshes[index];
  68327. if (mesh._waitingParentId) {
  68328. mesh.parent = scene.getLastEntryByID(mesh._waitingParentId);
  68329. mesh._waitingParentId = null;
  68330. }
  68331. if (mesh._waitingActions) {
  68332. BABYLON.ActionManager.Parse(mesh._waitingActions, mesh, scene);
  68333. mesh._waitingActions = null;
  68334. }
  68335. }
  68336. // freeze world matrix application
  68337. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68338. var currentMesh = scene.meshes[index];
  68339. if (currentMesh._waitingFreezeWorldMatrix) {
  68340. currentMesh.freezeWorldMatrix();
  68341. currentMesh._waitingFreezeWorldMatrix = null;
  68342. }
  68343. else {
  68344. currentMesh.computeWorldMatrix(true);
  68345. }
  68346. }
  68347. // Particles Systems
  68348. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68349. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68350. var parsedParticleSystem = parsedData.particleSystems[index];
  68351. if (parsedParticleSystem.activeParticleCount) {
  68352. var ps = BABYLON.GPUParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68353. container.particleSystems.push(ps);
  68354. }
  68355. else {
  68356. var ps = BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl);
  68357. container.particleSystems.push(ps);
  68358. }
  68359. }
  68360. }
  68361. // Lens flares
  68362. if (parsedData.lensFlareSystems !== undefined && parsedData.lensFlareSystems !== null) {
  68363. for (index = 0, cache = parsedData.lensFlareSystems.length; index < cache; index++) {
  68364. var parsedLensFlareSystem = parsedData.lensFlareSystems[index];
  68365. var lf = BABYLON.LensFlareSystem.Parse(parsedLensFlareSystem, scene, rootUrl);
  68366. container.lensFlareSystems.push(lf);
  68367. }
  68368. }
  68369. // Shadows
  68370. if (parsedData.shadowGenerators !== undefined && parsedData.shadowGenerators !== null) {
  68371. for (index = 0, cache = parsedData.shadowGenerators.length; index < cache; index++) {
  68372. var parsedShadowGenerator = parsedData.shadowGenerators[index];
  68373. var sg = BABYLON.ShadowGenerator.Parse(parsedShadowGenerator, scene);
  68374. container.shadowGenerators.push(sg);
  68375. }
  68376. }
  68377. // Lights exclusions / inclusions
  68378. for (index = 0, cache = scene.lights.length; index < cache; index++) {
  68379. var light_2 = scene.lights[index];
  68380. // Excluded check
  68381. if (light_2._excludedMeshesIds.length > 0) {
  68382. for (var excludedIndex = 0; excludedIndex < light_2._excludedMeshesIds.length; excludedIndex++) {
  68383. var excludedMesh = scene.getMeshByID(light_2._excludedMeshesIds[excludedIndex]);
  68384. if (excludedMesh) {
  68385. light_2.excludedMeshes.push(excludedMesh);
  68386. }
  68387. }
  68388. light_2._excludedMeshesIds = [];
  68389. }
  68390. // Included check
  68391. if (light_2._includedOnlyMeshesIds.length > 0) {
  68392. for (var includedOnlyIndex = 0; includedOnlyIndex < light_2._includedOnlyMeshesIds.length; includedOnlyIndex++) {
  68393. var includedOnlyMesh = scene.getMeshByID(light_2._includedOnlyMeshesIds[includedOnlyIndex]);
  68394. if (includedOnlyMesh) {
  68395. light_2.includedOnlyMeshes.push(includedOnlyMesh);
  68396. }
  68397. }
  68398. light_2._includedOnlyMeshesIds = [];
  68399. }
  68400. }
  68401. // Effect layers
  68402. if (parsedData.effectLayers) {
  68403. for (index = 0; index < parsedData.effectLayers.length; index++) {
  68404. var effectLayer = BABYLON.EffectLayer.Parse(parsedData.effectLayers[index], scene, rootUrl);
  68405. container.effectLayers.push(effectLayer);
  68406. }
  68407. }
  68408. // Actions (scene)
  68409. if (parsedData.actions !== undefined && parsedData.actions !== null) {
  68410. BABYLON.ActionManager.Parse(parsedData.actions, null, scene);
  68411. }
  68412. if (!addToScene) {
  68413. container.removeAllFromScene();
  68414. }
  68415. }
  68416. catch (err) {
  68417. var msg = logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + log;
  68418. if (onError) {
  68419. onError(msg, err);
  68420. }
  68421. else {
  68422. BABYLON.Tools.Log(msg);
  68423. throw err;
  68424. }
  68425. }
  68426. finally {
  68427. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68428. BABYLON.Tools.Log(logOperation("loadAssts", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68429. }
  68430. }
  68431. return container;
  68432. };
  68433. BABYLON.SceneLoader.RegisterPlugin({
  68434. name: "babylon.js",
  68435. extensions: ".babylon",
  68436. canDirectLoad: function (data) {
  68437. if (data.indexOf("babylon") !== -1) { // We consider that the producer string is filled
  68438. return true;
  68439. }
  68440. return false;
  68441. },
  68442. importMesh: function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons, onError) {
  68443. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68444. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68445. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68446. // and avoid problems with multiple concurrent .babylon loads.
  68447. var log = "importMesh has failed JSON parse";
  68448. try {
  68449. var parsedData = JSON.parse(data);
  68450. log = "";
  68451. var fullDetails = BABYLON.SceneLoader.loggingLevel === BABYLON.SceneLoader.DETAILED_LOGGING;
  68452. if (!meshesNames) {
  68453. meshesNames = null;
  68454. }
  68455. else if (!Array.isArray(meshesNames)) {
  68456. meshesNames = [meshesNames];
  68457. }
  68458. var hierarchyIds = new Array();
  68459. if (parsedData.meshes !== undefined && parsedData.meshes !== null) {
  68460. var loadedSkeletonsIds = [];
  68461. var loadedMaterialsIds = [];
  68462. var index;
  68463. var cache;
  68464. for (index = 0, cache = parsedData.meshes.length; index < cache; index++) {
  68465. var parsedMesh = parsedData.meshes[index];
  68466. if (meshesNames === null || isDescendantOf(parsedMesh, meshesNames, hierarchyIds)) {
  68467. if (meshesNames !== null) {
  68468. // Remove found mesh name from list.
  68469. delete meshesNames[meshesNames.indexOf(parsedMesh.name)];
  68470. }
  68471. //Geometry?
  68472. if (parsedMesh.geometryId !== undefined && parsedMesh.geometryId !== null) {
  68473. //does the file contain geometries?
  68474. if (parsedData.geometries !== undefined && parsedData.geometries !== null) {
  68475. //find the correct geometry and add it to the scene
  68476. var found = false;
  68477. ["boxes", "spheres", "cylinders", "toruses", "grounds", "planes", "torusKnots", "vertexData"].forEach(function (geometryType) {
  68478. if (found === true || !parsedData.geometries[geometryType] || !(Array.isArray(parsedData.geometries[geometryType]))) {
  68479. return;
  68480. }
  68481. else {
  68482. parsedData.geometries[geometryType].forEach(function (parsedGeometryData) {
  68483. if (parsedGeometryData.id === parsedMesh.geometryId) {
  68484. switch (geometryType) {
  68485. case "boxes":
  68486. BABYLON.BoxGeometry.Parse(parsedGeometryData, scene);
  68487. break;
  68488. case "spheres":
  68489. BABYLON.SphereGeometry.Parse(parsedGeometryData, scene);
  68490. break;
  68491. case "cylinders":
  68492. BABYLON.CylinderGeometry.Parse(parsedGeometryData, scene);
  68493. break;
  68494. case "toruses":
  68495. BABYLON.TorusGeometry.Parse(parsedGeometryData, scene);
  68496. break;
  68497. case "grounds":
  68498. BABYLON.GroundGeometry.Parse(parsedGeometryData, scene);
  68499. break;
  68500. case "planes":
  68501. BABYLON.PlaneGeometry.Parse(parsedGeometryData, scene);
  68502. break;
  68503. case "torusKnots":
  68504. BABYLON.TorusKnotGeometry.Parse(parsedGeometryData, scene);
  68505. break;
  68506. case "vertexData":
  68507. BABYLON.Geometry.Parse(parsedGeometryData, scene, rootUrl);
  68508. break;
  68509. }
  68510. found = true;
  68511. }
  68512. });
  68513. }
  68514. });
  68515. if (found === false) {
  68516. BABYLON.Tools.Warn("Geometry not found for mesh " + parsedMesh.id);
  68517. }
  68518. }
  68519. }
  68520. // Material ?
  68521. if (parsedMesh.materialId) {
  68522. var materialFound = (loadedMaterialsIds.indexOf(parsedMesh.materialId) !== -1);
  68523. if (materialFound === false && parsedData.multiMaterials !== undefined && parsedData.multiMaterials !== null) {
  68524. for (var multimatIndex = 0, multimatCache = parsedData.multiMaterials.length; multimatIndex < multimatCache; multimatIndex++) {
  68525. var parsedMultiMaterial = parsedData.multiMaterials[multimatIndex];
  68526. if (parsedMultiMaterial.id === parsedMesh.materialId) {
  68527. for (var matIndex = 0, matCache = parsedMultiMaterial.materials.length; matIndex < matCache; matIndex++) {
  68528. var subMatId = parsedMultiMaterial.materials[matIndex];
  68529. loadedMaterialsIds.push(subMatId);
  68530. var mat = parseMaterialById(subMatId, parsedData, scene, rootUrl);
  68531. if (mat) {
  68532. log += "\n\tMaterial " + mat.toString(fullDetails);
  68533. }
  68534. }
  68535. loadedMaterialsIds.push(parsedMultiMaterial.id);
  68536. var mmat = BABYLON.Material.ParseMultiMaterial(parsedMultiMaterial, scene);
  68537. if (mmat) {
  68538. materialFound = true;
  68539. log += "\n\tMulti-Material " + mmat.toString(fullDetails);
  68540. }
  68541. break;
  68542. }
  68543. }
  68544. }
  68545. if (materialFound === false) {
  68546. loadedMaterialsIds.push(parsedMesh.materialId);
  68547. var mat = parseMaterialById(parsedMesh.materialId, parsedData, scene, rootUrl);
  68548. if (!mat) {
  68549. BABYLON.Tools.Warn("Material not found for mesh " + parsedMesh.id);
  68550. }
  68551. else {
  68552. log += "\n\tMaterial " + mat.toString(fullDetails);
  68553. }
  68554. }
  68555. }
  68556. // Skeleton ?
  68557. if (parsedMesh.skeletonId > -1 && parsedData.skeletons !== undefined && parsedData.skeletons !== null) {
  68558. var skeletonAlreadyLoaded = (loadedSkeletonsIds.indexOf(parsedMesh.skeletonId) > -1);
  68559. if (skeletonAlreadyLoaded === false) {
  68560. for (var skeletonIndex = 0, skeletonCache = parsedData.skeletons.length; skeletonIndex < skeletonCache; skeletonIndex++) {
  68561. var parsedSkeleton = parsedData.skeletons[skeletonIndex];
  68562. if (parsedSkeleton.id === parsedMesh.skeletonId) {
  68563. var skeleton = BABYLON.Skeleton.Parse(parsedSkeleton, scene);
  68564. skeletons.push(skeleton);
  68565. loadedSkeletonsIds.push(parsedSkeleton.id);
  68566. log += "\n\tSkeleton " + skeleton.toString(fullDetails);
  68567. }
  68568. }
  68569. }
  68570. }
  68571. // Morph targets ?
  68572. if (parsedData.morphTargetManagers !== undefined && parsedData.morphTargetManagers !== null) {
  68573. for (var _i = 0, _a = parsedData.morphTargetManagers; _i < _a.length; _i++) {
  68574. var managerData = _a[_i];
  68575. BABYLON.MorphTargetManager.Parse(managerData, scene);
  68576. }
  68577. }
  68578. var mesh = BABYLON.Mesh.Parse(parsedMesh, scene, rootUrl);
  68579. meshes.push(mesh);
  68580. log += "\n\tMesh " + mesh.toString(fullDetails);
  68581. }
  68582. }
  68583. // Connecting parents
  68584. var currentMesh;
  68585. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68586. currentMesh = scene.meshes[index];
  68587. if (currentMesh._waitingParentId) {
  68588. currentMesh.parent = scene.getLastEntryByID(currentMesh._waitingParentId);
  68589. currentMesh._waitingParentId = null;
  68590. }
  68591. }
  68592. // freeze and compute world matrix application
  68593. for (index = 0, cache = scene.meshes.length; index < cache; index++) {
  68594. currentMesh = scene.meshes[index];
  68595. if (currentMesh._waitingFreezeWorldMatrix) {
  68596. currentMesh.freezeWorldMatrix();
  68597. currentMesh._waitingFreezeWorldMatrix = null;
  68598. }
  68599. else {
  68600. currentMesh.computeWorldMatrix(true);
  68601. }
  68602. }
  68603. }
  68604. // Particles
  68605. if (parsedData.particleSystems !== undefined && parsedData.particleSystems !== null) {
  68606. for (index = 0, cache = parsedData.particleSystems.length; index < cache; index++) {
  68607. var parsedParticleSystem = parsedData.particleSystems[index];
  68608. if (hierarchyIds.indexOf(parsedParticleSystem.emitterId) !== -1) {
  68609. particleSystems.push(BABYLON.ParticleSystem.Parse(parsedParticleSystem, scene, rootUrl));
  68610. }
  68611. }
  68612. }
  68613. return true;
  68614. }
  68615. catch (err) {
  68616. var msg = logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + log;
  68617. if (onError) {
  68618. onError(msg, err);
  68619. }
  68620. else {
  68621. BABYLON.Tools.Log(msg);
  68622. throw err;
  68623. }
  68624. }
  68625. finally {
  68626. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68627. BABYLON.Tools.Log(logOperation("importMesh", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68628. }
  68629. }
  68630. return false;
  68631. },
  68632. load: function (scene, data, rootUrl, onError) {
  68633. // Entire method running in try block, so ALWAYS logs as far as it got, only actually writes details
  68634. // when SceneLoader.debugLogging = true (default), or exception encountered.
  68635. // Everything stored in var log instead of writing separate lines to support only writing in exception,
  68636. // and avoid problems with multiple concurrent .babylon loads.
  68637. var log = "importScene has failed JSON parse";
  68638. try {
  68639. var parsedData = JSON.parse(data);
  68640. log = "";
  68641. // Scene
  68642. if (parsedData.useDelayedTextureLoading !== undefined && parsedData.useDelayedTextureLoading !== null) {
  68643. scene.useDelayedTextureLoading = parsedData.useDelayedTextureLoading && !BABYLON.SceneLoader.ForceFullSceneLoadingForIncremental;
  68644. }
  68645. if (parsedData.autoClear !== undefined && parsedData.autoClear !== null) {
  68646. scene.autoClear = parsedData.autoClear;
  68647. }
  68648. if (parsedData.clearColor !== undefined && parsedData.clearColor !== null) {
  68649. scene.clearColor = BABYLON.Color4.FromArray(parsedData.clearColor);
  68650. }
  68651. if (parsedData.ambientColor !== undefined && parsedData.ambientColor !== null) {
  68652. scene.ambientColor = BABYLON.Color3.FromArray(parsedData.ambientColor);
  68653. }
  68654. if (parsedData.gravity !== undefined && parsedData.gravity !== null) {
  68655. scene.gravity = BABYLON.Vector3.FromArray(parsedData.gravity);
  68656. }
  68657. // Fog
  68658. if (parsedData.fogMode && parsedData.fogMode !== 0) {
  68659. scene.fogMode = parsedData.fogMode;
  68660. scene.fogColor = BABYLON.Color3.FromArray(parsedData.fogColor);
  68661. scene.fogStart = parsedData.fogStart;
  68662. scene.fogEnd = parsedData.fogEnd;
  68663. scene.fogDensity = parsedData.fogDensity;
  68664. log += "\tFog mode for scene: ";
  68665. switch (scene.fogMode) {
  68666. // getters not compiling, so using hardcoded
  68667. case 1:
  68668. log += "exp\n";
  68669. break;
  68670. case 2:
  68671. log += "exp2\n";
  68672. break;
  68673. case 3:
  68674. log += "linear\n";
  68675. break;
  68676. }
  68677. }
  68678. //Physics
  68679. if (parsedData.physicsEnabled) {
  68680. var physicsPlugin;
  68681. if (parsedData.physicsEngine === "cannon") {
  68682. physicsPlugin = new BABYLON.CannonJSPlugin();
  68683. }
  68684. else if (parsedData.physicsEngine === "oimo") {
  68685. physicsPlugin = new BABYLON.OimoJSPlugin();
  68686. }
  68687. log = "\tPhysics engine " + (parsedData.physicsEngine ? parsedData.physicsEngine : "oimo") + " enabled\n";
  68688. //else - default engine, which is currently oimo
  68689. var physicsGravity = parsedData.physicsGravity ? BABYLON.Vector3.FromArray(parsedData.physicsGravity) : null;
  68690. scene.enablePhysics(physicsGravity, physicsPlugin);
  68691. }
  68692. // Metadata
  68693. if (parsedData.metadata !== undefined && parsedData.metadata !== null) {
  68694. scene.metadata = parsedData.metadata;
  68695. }
  68696. //collisions, if defined. otherwise, default is true
  68697. if (parsedData.collisionsEnabled !== undefined && parsedData.collisionsEnabled !== null) {
  68698. scene.collisionsEnabled = parsedData.collisionsEnabled;
  68699. }
  68700. scene.workerCollisions = !!parsedData.workerCollisions;
  68701. var container = loadAssetContainer(scene, data, rootUrl, onError, true);
  68702. if (!container) {
  68703. return false;
  68704. }
  68705. if (parsedData.autoAnimate) {
  68706. scene.beginAnimation(scene, parsedData.autoAnimateFrom, parsedData.autoAnimateTo, parsedData.autoAnimateLoop, parsedData.autoAnimateSpeed || 1.0);
  68707. }
  68708. if (parsedData.activeCameraID !== undefined && parsedData.activeCameraID !== null) {
  68709. scene.setActiveCameraByID(parsedData.activeCameraID);
  68710. }
  68711. // Environment texture
  68712. if (parsedData.environmentTexture !== undefined && parsedData.environmentTexture !== null) {
  68713. if (parsedData.environmentTextureType && parsedData.environmentTextureType === "BABYLON.HDRCubeTexture") {
  68714. var hdrSize = (parsedData.environmentTextureSize) ? parsedData.environmentTextureSize : 128;
  68715. var hdrTexture = new BABYLON.HDRCubeTexture(rootUrl + parsedData.environmentTexture, scene, hdrSize);
  68716. if (parsedData.environmentTextureRotationY) {
  68717. hdrTexture.rotationY = parsedData.environmentTextureRotationY;
  68718. }
  68719. scene.environmentTexture = hdrTexture;
  68720. }
  68721. else {
  68722. var cubeTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(rootUrl + parsedData.environmentTexture, scene);
  68723. if (parsedData.environmentTextureRotationY) {
  68724. cubeTexture.rotationY = parsedData.environmentTextureRotationY;
  68725. }
  68726. scene.environmentTexture = cubeTexture;
  68727. }
  68728. if (parsedData.createDefaultSkybox === true) {
  68729. var skyboxScale = (scene.activeCamera !== undefined && scene.activeCamera !== null) ? (scene.activeCamera.maxZ - scene.activeCamera.minZ) / 2 : 1000;
  68730. var skyboxBlurLevel = parsedData.skyboxBlurLevel || 0;
  68731. scene.createDefaultSkybox(undefined, true, skyboxScale, skyboxBlurLevel);
  68732. }
  68733. }
  68734. // Finish
  68735. return true;
  68736. }
  68737. catch (err) {
  68738. var msg = logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + log;
  68739. if (onError) {
  68740. onError(msg, err);
  68741. }
  68742. else {
  68743. BABYLON.Tools.Log(msg);
  68744. throw err;
  68745. }
  68746. }
  68747. finally {
  68748. if (log !== null && BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.NO_LOGGING) {
  68749. BABYLON.Tools.Log(logOperation("importScene", parsedData ? parsedData.producer : "Unknown") + (BABYLON.SceneLoader.loggingLevel !== BABYLON.SceneLoader.MINIMAL_LOGGING ? log : ""));
  68750. }
  68751. }
  68752. return false;
  68753. },
  68754. loadAssetContainer: function (scene, data, rootUrl, onError) {
  68755. var container = loadAssetContainer(scene, data, rootUrl, onError);
  68756. return container;
  68757. }
  68758. });
  68759. })(BABYLON || (BABYLON = {}));
  68760. //# sourceMappingURL=babylon.babylonFileLoader.js.map
  68761. var BABYLON;
  68762. (function (BABYLON) {
  68763. var FilesInput = /** @class */ (function () {
  68764. function FilesInput(engine, scene, sceneLoadedCallback, progressCallback, additionalRenderLoopLogicCallback, textureLoadingCallback, startingProcessingFilesCallback, onReloadCallback, errorCallback) {
  68765. this.onProcessFileCallback = function () { return true; };
  68766. this._engine = engine;
  68767. this._currentScene = scene;
  68768. this._sceneLoadedCallback = sceneLoadedCallback;
  68769. this._progressCallback = progressCallback;
  68770. this._additionalRenderLoopLogicCallback = additionalRenderLoopLogicCallback;
  68771. this._textureLoadingCallback = textureLoadingCallback;
  68772. this._startingProcessingFilesCallback = startingProcessingFilesCallback;
  68773. this._onReloadCallback = onReloadCallback;
  68774. this._errorCallback = errorCallback;
  68775. }
  68776. FilesInput.prototype.monitorElementForDragNDrop = function (elementToMonitor) {
  68777. var _this = this;
  68778. if (elementToMonitor) {
  68779. this._elementToMonitor = elementToMonitor;
  68780. this._dragEnterHandler = function (e) { _this.drag(e); };
  68781. this._dragOverHandler = function (e) { _this.drag(e); };
  68782. this._dropHandler = function (e) { _this.drop(e); };
  68783. this._elementToMonitor.addEventListener("dragenter", this._dragEnterHandler, false);
  68784. this._elementToMonitor.addEventListener("dragover", this._dragOverHandler, false);
  68785. this._elementToMonitor.addEventListener("drop", this._dropHandler, false);
  68786. }
  68787. };
  68788. FilesInput.prototype.dispose = function () {
  68789. if (!this._elementToMonitor) {
  68790. return;
  68791. }
  68792. this._elementToMonitor.removeEventListener("dragenter", this._dragEnterHandler);
  68793. this._elementToMonitor.removeEventListener("dragover", this._dragOverHandler);
  68794. this._elementToMonitor.removeEventListener("drop", this._dropHandler);
  68795. };
  68796. FilesInput.prototype.renderFunction = function () {
  68797. if (this._additionalRenderLoopLogicCallback) {
  68798. this._additionalRenderLoopLogicCallback();
  68799. }
  68800. if (this._currentScene) {
  68801. if (this._textureLoadingCallback) {
  68802. var remaining = this._currentScene.getWaitingItemsCount();
  68803. if (remaining > 0) {
  68804. this._textureLoadingCallback(remaining);
  68805. }
  68806. }
  68807. this._currentScene.render();
  68808. }
  68809. };
  68810. FilesInput.prototype.drag = function (e) {
  68811. e.stopPropagation();
  68812. e.preventDefault();
  68813. };
  68814. FilesInput.prototype.drop = function (eventDrop) {
  68815. eventDrop.stopPropagation();
  68816. eventDrop.preventDefault();
  68817. this.loadFiles(eventDrop);
  68818. };
  68819. FilesInput.prototype._traverseFolder = function (folder, files, remaining, callback) {
  68820. var _this = this;
  68821. var reader = folder.createReader();
  68822. var relativePath = folder.fullPath.replace(/^\//, "").replace(/(.+?)\/?$/, "$1/");
  68823. reader.readEntries(function (entries) {
  68824. remaining.count += entries.length;
  68825. for (var _i = 0, entries_1 = entries; _i < entries_1.length; _i++) {
  68826. var entry = entries_1[_i];
  68827. if (entry.isFile) {
  68828. entry.file(function (file) {
  68829. file.correctName = relativePath + file.name;
  68830. files.push(file);
  68831. if (--remaining.count === 0) {
  68832. callback();
  68833. }
  68834. });
  68835. }
  68836. else if (entry.isDirectory) {
  68837. _this._traverseFolder(entry, files, remaining, callback);
  68838. }
  68839. }
  68840. if (--remaining.count) {
  68841. callback();
  68842. }
  68843. });
  68844. };
  68845. FilesInput.prototype._processFiles = function (files) {
  68846. for (var i = 0; i < files.length; i++) {
  68847. var name = files[i].correctName.toLowerCase();
  68848. var extension = name.split('.').pop();
  68849. if (!this.onProcessFileCallback(files[i], name, extension)) {
  68850. continue;
  68851. }
  68852. if ((extension === "babylon" || extension === "stl" || extension === "obj" || extension === "gltf" || extension === "glb")
  68853. && name.indexOf(".binary.babylon") === -1 && name.indexOf(".incremental.babylon") === -1) {
  68854. this._sceneFileToLoad = files[i];
  68855. }
  68856. else {
  68857. FilesInput.FilesToLoad[name] = files[i];
  68858. }
  68859. }
  68860. };
  68861. FilesInput.prototype.loadFiles = function (event) {
  68862. var _this = this;
  68863. if (this._startingProcessingFilesCallback)
  68864. this._startingProcessingFilesCallback();
  68865. // Handling data transfer via drag'n'drop
  68866. if (event && event.dataTransfer && event.dataTransfer.files) {
  68867. this._filesToLoad = event.dataTransfer.files;
  68868. }
  68869. // Handling files from input files
  68870. if (event && event.target && event.target.files) {
  68871. this._filesToLoad = event.target.files;
  68872. }
  68873. if (this._filesToLoad && this._filesToLoad.length > 0) {
  68874. var files_1 = new Array();
  68875. var folders = [];
  68876. var items = event.dataTransfer ? event.dataTransfer.items : null;
  68877. for (var i = 0; i < this._filesToLoad.length; i++) {
  68878. var fileToLoad = this._filesToLoad[i];
  68879. var name_1 = fileToLoad.name.toLowerCase();
  68880. var entry = void 0;
  68881. fileToLoad.correctName = name_1;
  68882. if (items) {
  68883. var item = items[i];
  68884. if (item.getAsEntry) {
  68885. entry = item.getAsEntry();
  68886. }
  68887. else if (item.webkitGetAsEntry) {
  68888. entry = item.webkitGetAsEntry();
  68889. }
  68890. }
  68891. if (!entry) {
  68892. files_1.push(fileToLoad);
  68893. }
  68894. else {
  68895. if (entry.isDirectory) {
  68896. folders.push(entry);
  68897. }
  68898. else {
  68899. files_1.push(fileToLoad);
  68900. }
  68901. }
  68902. }
  68903. if (folders.length === 0) {
  68904. this._processFiles(files_1);
  68905. this._processReload();
  68906. }
  68907. else {
  68908. var remaining = { count: folders.length };
  68909. for (var _i = 0, folders_1 = folders; _i < folders_1.length; _i++) {
  68910. var folder = folders_1[_i];
  68911. this._traverseFolder(folder, files_1, remaining, function () {
  68912. _this._processFiles(files_1);
  68913. if (remaining.count === 0) {
  68914. _this._processReload();
  68915. }
  68916. });
  68917. }
  68918. }
  68919. }
  68920. };
  68921. FilesInput.prototype._processReload = function () {
  68922. if (this._onReloadCallback) {
  68923. this._onReloadCallback(this._sceneFileToLoad);
  68924. }
  68925. else {
  68926. this.reload();
  68927. }
  68928. };
  68929. FilesInput.prototype.reload = function () {
  68930. var _this = this;
  68931. // If a scene file has been provided
  68932. if (this._sceneFileToLoad) {
  68933. if (this._currentScene) {
  68934. if (BABYLON.Tools.errorsCount > 0) {
  68935. BABYLON.Tools.ClearLogCache();
  68936. }
  68937. this._engine.stopRenderLoop();
  68938. }
  68939. BABYLON.SceneLoader.LoadAsync("file:", this._sceneFileToLoad, this._engine, function (progress) {
  68940. if (_this._progressCallback) {
  68941. _this._progressCallback(progress);
  68942. }
  68943. }).then(function (scene) {
  68944. if (_this._currentScene) {
  68945. _this._currentScene.dispose();
  68946. }
  68947. _this._currentScene = scene;
  68948. if (_this._sceneLoadedCallback) {
  68949. _this._sceneLoadedCallback(_this._sceneFileToLoad, _this._currentScene);
  68950. }
  68951. // Wait for textures and shaders to be ready
  68952. _this._currentScene.executeWhenReady(function () {
  68953. _this._engine.runRenderLoop(function () {
  68954. _this.renderFunction();
  68955. });
  68956. });
  68957. }).catch(function (error) {
  68958. if (_this._errorCallback) {
  68959. _this._errorCallback(_this._sceneFileToLoad, _this._currentScene, error.message);
  68960. }
  68961. });
  68962. }
  68963. else {
  68964. BABYLON.Tools.Error("Please provide a valid .babylon file.");
  68965. }
  68966. };
  68967. FilesInput.FilesToLoad = {};
  68968. return FilesInput;
  68969. }());
  68970. BABYLON.FilesInput = FilesInput;
  68971. })(BABYLON || (BABYLON = {}));
  68972. //# sourceMappingURL=babylon.filesInput.js.map
  68973. var BABYLON;
  68974. (function (BABYLON) {
  68975. /**
  68976. * This class implement a typical dictionary using a string as key and the generic type T as value.
  68977. * The underlying implementation relies on an associative array to ensure the best performances.
  68978. * The value can be anything including 'null' but except 'undefined'
  68979. */
  68980. var StringDictionary = /** @class */ (function () {
  68981. function StringDictionary() {
  68982. this._count = 0;
  68983. this._data = {};
  68984. }
  68985. /**
  68986. * This will clear this dictionary and copy the content from the 'source' one.
  68987. * If the T value is a custom object, it won't be copied/cloned, the same object will be used
  68988. * @param source the dictionary to take the content from and copy to this dictionary
  68989. */
  68990. StringDictionary.prototype.copyFrom = function (source) {
  68991. var _this = this;
  68992. this.clear();
  68993. source.forEach(function (t, v) { return _this.add(t, v); });
  68994. };
  68995. /**
  68996. * Get a value based from its key
  68997. * @param key the given key to get the matching value from
  68998. * @return the value if found, otherwise undefined is returned
  68999. */
  69000. StringDictionary.prototype.get = function (key) {
  69001. var val = this._data[key];
  69002. if (val !== undefined) {
  69003. return val;
  69004. }
  69005. return undefined;
  69006. };
  69007. /**
  69008. * Get a value from its key or add it if it doesn't exist.
  69009. * This method will ensure you that a given key/data will be present in the dictionary.
  69010. * @param key the given key to get the matching value from
  69011. * @param factory the factory that will create the value if the key is not present in the dictionary.
  69012. * The factory will only be invoked if there's no data for the given key.
  69013. * @return the value corresponding to the key.
  69014. */
  69015. StringDictionary.prototype.getOrAddWithFactory = function (key, factory) {
  69016. var val = this.get(key);
  69017. if (val !== undefined) {
  69018. return val;
  69019. }
  69020. val = factory(key);
  69021. if (val) {
  69022. this.add(key, val);
  69023. }
  69024. return val;
  69025. };
  69026. /**
  69027. * Get a value from its key if present in the dictionary otherwise add it
  69028. * @param key the key to get the value from
  69029. * @param val if there's no such key/value pair in the dictionary add it with this value
  69030. * @return the value corresponding to the key
  69031. */
  69032. StringDictionary.prototype.getOrAdd = function (key, val) {
  69033. var curVal = this.get(key);
  69034. if (curVal !== undefined) {
  69035. return curVal;
  69036. }
  69037. this.add(key, val);
  69038. return val;
  69039. };
  69040. /**
  69041. * Check if there's a given key in the dictionary
  69042. * @param key the key to check for
  69043. * @return true if the key is present, false otherwise
  69044. */
  69045. StringDictionary.prototype.contains = function (key) {
  69046. return this._data[key] !== undefined;
  69047. };
  69048. /**
  69049. * Add a new key and its corresponding value
  69050. * @param key the key to add
  69051. * @param value the value corresponding to the key
  69052. * @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
  69053. */
  69054. StringDictionary.prototype.add = function (key, value) {
  69055. if (this._data[key] !== undefined) {
  69056. return false;
  69057. }
  69058. this._data[key] = value;
  69059. ++this._count;
  69060. return true;
  69061. };
  69062. StringDictionary.prototype.set = function (key, value) {
  69063. if (this._data[key] === undefined) {
  69064. return false;
  69065. }
  69066. this._data[key] = value;
  69067. return true;
  69068. };
  69069. /**
  69070. * Get the element of the given key and remove it from the dictionary
  69071. * @param key
  69072. */
  69073. StringDictionary.prototype.getAndRemove = function (key) {
  69074. var val = this.get(key);
  69075. if (val !== undefined) {
  69076. delete this._data[key];
  69077. --this._count;
  69078. return val;
  69079. }
  69080. return null;
  69081. };
  69082. /**
  69083. * Remove a key/value from the dictionary.
  69084. * @param key the key to remove
  69085. * @return true if the item was successfully deleted, false if no item with such key exist in the dictionary
  69086. */
  69087. StringDictionary.prototype.remove = function (key) {
  69088. if (this.contains(key)) {
  69089. delete this._data[key];
  69090. --this._count;
  69091. return true;
  69092. }
  69093. return false;
  69094. };
  69095. /**
  69096. * Clear the whole content of the dictionary
  69097. */
  69098. StringDictionary.prototype.clear = function () {
  69099. this._data = {};
  69100. this._count = 0;
  69101. };
  69102. Object.defineProperty(StringDictionary.prototype, "count", {
  69103. get: function () {
  69104. return this._count;
  69105. },
  69106. enumerable: true,
  69107. configurable: true
  69108. });
  69109. /**
  69110. * Execute a callback on each key/val of the dictionary.
  69111. * Note that you can remove any element in this dictionary in the callback implementation
  69112. * @param callback the callback to execute on a given key/value pair
  69113. */
  69114. StringDictionary.prototype.forEach = function (callback) {
  69115. for (var cur in this._data) {
  69116. var val = this._data[cur];
  69117. callback(cur, val);
  69118. }
  69119. };
  69120. /**
  69121. * Execute a callback on every occurrence of the dictionary until it returns a valid TRes object.
  69122. * If the callback returns null or undefined the method will iterate to the next key/value pair
  69123. * Note that you can remove any element in this dictionary in the callback implementation
  69124. * @param callback the callback to execute, if it return a valid T instanced object the enumeration will stop and the object will be returned
  69125. */
  69126. StringDictionary.prototype.first = function (callback) {
  69127. for (var cur in this._data) {
  69128. var val = this._data[cur];
  69129. var res = callback(cur, val);
  69130. if (res) {
  69131. return res;
  69132. }
  69133. }
  69134. return null;
  69135. };
  69136. return StringDictionary;
  69137. }());
  69138. BABYLON.StringDictionary = StringDictionary;
  69139. })(BABYLON || (BABYLON = {}));
  69140. //# sourceMappingURL=babylon.stringDictionary.js.map
  69141. var BABYLON;
  69142. (function (BABYLON) {
  69143. var Tags = /** @class */ (function () {
  69144. function Tags() {
  69145. }
  69146. Tags.EnableFor = function (obj) {
  69147. obj._tags = obj._tags || {};
  69148. obj.hasTags = function () {
  69149. return Tags.HasTags(obj);
  69150. };
  69151. obj.addTags = function (tagsString) {
  69152. return Tags.AddTagsTo(obj, tagsString);
  69153. };
  69154. obj.removeTags = function (tagsString) {
  69155. return Tags.RemoveTagsFrom(obj, tagsString);
  69156. };
  69157. obj.matchesTagsQuery = function (tagsQuery) {
  69158. return Tags.MatchesQuery(obj, tagsQuery);
  69159. };
  69160. };
  69161. Tags.DisableFor = function (obj) {
  69162. delete obj._tags;
  69163. delete obj.hasTags;
  69164. delete obj.addTags;
  69165. delete obj.removeTags;
  69166. delete obj.matchesTagsQuery;
  69167. };
  69168. Tags.HasTags = function (obj) {
  69169. if (!obj._tags) {
  69170. return false;
  69171. }
  69172. return !BABYLON.Tools.IsEmpty(obj._tags);
  69173. };
  69174. Tags.GetTags = function (obj, asString) {
  69175. if (asString === void 0) { asString = true; }
  69176. if (!obj._tags) {
  69177. return null;
  69178. }
  69179. if (asString) {
  69180. var tagsArray = [];
  69181. for (var tag in obj._tags) {
  69182. if (obj._tags.hasOwnProperty(tag) && obj._tags[tag] === true) {
  69183. tagsArray.push(tag);
  69184. }
  69185. }
  69186. return tagsArray.join(" ");
  69187. }
  69188. else {
  69189. return obj._tags;
  69190. }
  69191. };
  69192. // the tags 'true' and 'false' are reserved and cannot be used as tags
  69193. // a tag cannot start with '||', '&&', and '!'
  69194. // it cannot contain whitespaces
  69195. Tags.AddTagsTo = function (obj, tagsString) {
  69196. if (!tagsString) {
  69197. return;
  69198. }
  69199. if (typeof tagsString !== "string") {
  69200. return;
  69201. }
  69202. var tags = tagsString.split(" ");
  69203. tags.forEach(function (tag, index, array) {
  69204. Tags._AddTagTo(obj, tag);
  69205. });
  69206. };
  69207. Tags._AddTagTo = function (obj, tag) {
  69208. tag = tag.trim();
  69209. if (tag === "" || tag === "true" || tag === "false") {
  69210. return;
  69211. }
  69212. if (tag.match(/[\s]/) || tag.match(/^([!]|([|]|[&]){2})/)) {
  69213. return;
  69214. }
  69215. Tags.EnableFor(obj);
  69216. obj._tags[tag] = true;
  69217. };
  69218. Tags.RemoveTagsFrom = function (obj, tagsString) {
  69219. if (!Tags.HasTags(obj)) {
  69220. return;
  69221. }
  69222. var tags = tagsString.split(" ");
  69223. for (var t in tags) {
  69224. Tags._RemoveTagFrom(obj, tags[t]);
  69225. }
  69226. };
  69227. Tags._RemoveTagFrom = function (obj, tag) {
  69228. delete obj._tags[tag];
  69229. };
  69230. Tags.MatchesQuery = function (obj, tagsQuery) {
  69231. if (tagsQuery === undefined) {
  69232. return true;
  69233. }
  69234. if (tagsQuery === "") {
  69235. return Tags.HasTags(obj);
  69236. }
  69237. return BABYLON.AndOrNotEvaluator.Eval(tagsQuery, function (r) { return Tags.HasTags(obj) && obj._tags[r]; });
  69238. };
  69239. return Tags;
  69240. }());
  69241. BABYLON.Tags = Tags;
  69242. })(BABYLON || (BABYLON = {}));
  69243. //# sourceMappingURL=babylon.tags.js.map
  69244. var BABYLON;
  69245. (function (BABYLON) {
  69246. /**
  69247. * Class used to evalaute queries containing `and` and `or` operators
  69248. */
  69249. var AndOrNotEvaluator = /** @class */ (function () {
  69250. function AndOrNotEvaluator() {
  69251. }
  69252. /**
  69253. * Evaluate a query
  69254. * @param query defines the query to evaluate
  69255. * @param evaluateCallback defines the callback used to filter result
  69256. * @returns true if the query matches
  69257. */
  69258. AndOrNotEvaluator.Eval = function (query, evaluateCallback) {
  69259. if (!query.match(/\([^\(\)]*\)/g)) {
  69260. query = AndOrNotEvaluator._HandleParenthesisContent(query, evaluateCallback);
  69261. }
  69262. else {
  69263. query = query.replace(/\([^\(\)]*\)/g, function (r) {
  69264. // remove parenthesis
  69265. r = r.slice(1, r.length - 1);
  69266. return AndOrNotEvaluator._HandleParenthesisContent(r, evaluateCallback);
  69267. });
  69268. }
  69269. if (query === "true") {
  69270. return true;
  69271. }
  69272. if (query === "false") {
  69273. return false;
  69274. }
  69275. return AndOrNotEvaluator.Eval(query, evaluateCallback);
  69276. };
  69277. AndOrNotEvaluator._HandleParenthesisContent = function (parenthesisContent, evaluateCallback) {
  69278. evaluateCallback = evaluateCallback || (function (r) {
  69279. return r === "true" ? true : false;
  69280. });
  69281. var result;
  69282. var or = parenthesisContent.split("||");
  69283. for (var i in or) {
  69284. if (or.hasOwnProperty(i)) {
  69285. var ori = AndOrNotEvaluator._SimplifyNegation(or[i].trim());
  69286. var and = ori.split("&&");
  69287. if (and.length > 1) {
  69288. for (var j = 0; j < and.length; ++j) {
  69289. var andj = AndOrNotEvaluator._SimplifyNegation(and[j].trim());
  69290. if (andj !== "true" && andj !== "false") {
  69291. if (andj[0] === "!") {
  69292. result = !evaluateCallback(andj.substring(1));
  69293. }
  69294. else {
  69295. result = evaluateCallback(andj);
  69296. }
  69297. }
  69298. else {
  69299. result = andj === "true" ? true : false;
  69300. }
  69301. if (!result) { // no need to continue since 'false && ... && ...' will always return false
  69302. ori = "false";
  69303. break;
  69304. }
  69305. }
  69306. }
  69307. if (result || ori === "true") { // no need to continue since 'true || ... || ...' will always return true
  69308. result = true;
  69309. break;
  69310. }
  69311. // result equals false (or undefined)
  69312. if (ori !== "true" && ori !== "false") {
  69313. if (ori[0] === "!") {
  69314. result = !evaluateCallback(ori.substring(1));
  69315. }
  69316. else {
  69317. result = evaluateCallback(ori);
  69318. }
  69319. }
  69320. else {
  69321. result = ori === "true" ? true : false;
  69322. }
  69323. }
  69324. }
  69325. // the whole parenthesis scope is replaced by 'true' or 'false'
  69326. return result ? "true" : "false";
  69327. };
  69328. AndOrNotEvaluator._SimplifyNegation = function (booleanString) {
  69329. booleanString = booleanString.replace(/^[\s!]+/, function (r) {
  69330. // remove whitespaces
  69331. r = r.replace(/[\s]/g, function () { return ""; });
  69332. return r.length % 2 ? "!" : "";
  69333. });
  69334. booleanString = booleanString.trim();
  69335. if (booleanString === "!true") {
  69336. booleanString = "false";
  69337. }
  69338. else if (booleanString === "!false") {
  69339. booleanString = "true";
  69340. }
  69341. return booleanString;
  69342. };
  69343. return AndOrNotEvaluator;
  69344. }());
  69345. BABYLON.AndOrNotEvaluator = AndOrNotEvaluator;
  69346. })(BABYLON || (BABYLON = {}));
  69347. //# sourceMappingURL=babylon.andOrNotEvaluator.js.map
  69348. var BABYLON;
  69349. (function (BABYLON) {
  69350. /**
  69351. * Class used to enable access to IndexedDB
  69352. * @see @https://developer.mozilla.org/en-US/docs/Web/API/IndexedDB_API
  69353. */
  69354. var Database = /** @class */ (function () {
  69355. /**
  69356. * Creates a new Database
  69357. * @param urlToScene defines the url to load the scene
  69358. * @param callbackManifestChecked defines the callback to use when manifest is checked
  69359. * @param disableManifestCheck defines a boolean indicating that we want to skip the manifest validation (it will be considered validated and up to date)
  69360. */
  69361. function Database(urlToScene, callbackManifestChecked, disableManifestCheck) {
  69362. if (disableManifestCheck === void 0) { disableManifestCheck = false; }
  69363. var _this = this;
  69364. // Handling various flavors of prefixed version of IndexedDB
  69365. this.idbFactory = (window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB || window.msIndexedDB);
  69366. this.callbackManifestChecked = callbackManifestChecked;
  69367. this.currentSceneUrl = Database._ReturnFullUrlLocation(urlToScene);
  69368. this.db = null;
  69369. this._enableSceneOffline = false;
  69370. this._enableTexturesOffline = false;
  69371. this.manifestVersionFound = 0;
  69372. this.mustUpdateRessources = false;
  69373. this.hasReachedQuota = false;
  69374. if (!Database.IDBStorageEnabled) {
  69375. this.callbackManifestChecked(true);
  69376. }
  69377. else {
  69378. if (disableManifestCheck) {
  69379. this._enableSceneOffline = true;
  69380. this._enableTexturesOffline = true;
  69381. this.manifestVersionFound = 1;
  69382. BABYLON.Tools.SetImmediate(function () {
  69383. _this.callbackManifestChecked(true);
  69384. });
  69385. }
  69386. else {
  69387. this._checkManifestFile();
  69388. }
  69389. }
  69390. }
  69391. Object.defineProperty(Database.prototype, "enableSceneOffline", {
  69392. /**
  69393. * Gets a boolean indicating if scene must be saved in the database
  69394. */
  69395. get: function () {
  69396. return this._enableSceneOffline;
  69397. },
  69398. enumerable: true,
  69399. configurable: true
  69400. });
  69401. Object.defineProperty(Database.prototype, "enableTexturesOffline", {
  69402. /**
  69403. * Gets a boolean indicating if textures must be saved in the database
  69404. */
  69405. get: function () {
  69406. return this._enableTexturesOffline;
  69407. },
  69408. enumerable: true,
  69409. configurable: true
  69410. });
  69411. Database.prototype._checkManifestFile = function () {
  69412. var _this = this;
  69413. var noManifestFile = function () {
  69414. _this._enableSceneOffline = false;
  69415. _this._enableTexturesOffline = false;
  69416. _this.callbackManifestChecked(false);
  69417. };
  69418. var timeStampUsed = false;
  69419. var manifestURL = this.currentSceneUrl + ".manifest";
  69420. var xhr = new XMLHttpRequest();
  69421. if (navigator.onLine) {
  69422. // Adding a timestamp to by-pass browsers' cache
  69423. timeStampUsed = true;
  69424. manifestURL = manifestURL + (manifestURL.match(/\?/) == null ? "?" : "&") + Date.now();
  69425. }
  69426. xhr.open("GET", manifestURL, true);
  69427. xhr.addEventListener("load", function () {
  69428. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  69429. try {
  69430. var manifestFile = JSON.parse(xhr.response);
  69431. _this._enableSceneOffline = manifestFile.enableSceneOffline;
  69432. _this._enableTexturesOffline = manifestFile.enableTexturesOffline;
  69433. if (manifestFile.version && !isNaN(parseInt(manifestFile.version))) {
  69434. _this.manifestVersionFound = manifestFile.version;
  69435. }
  69436. if (_this.callbackManifestChecked) {
  69437. _this.callbackManifestChecked(true);
  69438. }
  69439. }
  69440. catch (ex) {
  69441. noManifestFile();
  69442. }
  69443. }
  69444. else {
  69445. noManifestFile();
  69446. }
  69447. }, false);
  69448. xhr.addEventListener("error", function (event) {
  69449. if (timeStampUsed) {
  69450. timeStampUsed = false;
  69451. // Let's retry without the timeStamp
  69452. // It could fail when coupled with HTML5 Offline API
  69453. var retryManifestURL = _this.currentSceneUrl + ".manifest";
  69454. xhr.open("GET", retryManifestURL, true);
  69455. xhr.send();
  69456. }
  69457. else {
  69458. noManifestFile();
  69459. }
  69460. }, false);
  69461. try {
  69462. xhr.send();
  69463. }
  69464. catch (ex) {
  69465. BABYLON.Tools.Error("Error on XHR send request.");
  69466. this.callbackManifestChecked(false);
  69467. }
  69468. };
  69469. /**
  69470. * Open the database and make it available
  69471. * @param successCallback defines the callback to call on success
  69472. * @param errorCallback defines the callback to call on error
  69473. */
  69474. Database.prototype.openAsync = function (successCallback, errorCallback) {
  69475. var _this = this;
  69476. var handleError = function () {
  69477. _this.isSupported = false;
  69478. if (errorCallback)
  69479. errorCallback();
  69480. };
  69481. if (!this.idbFactory || !(this._enableSceneOffline || this._enableTexturesOffline)) {
  69482. // Your browser doesn't support IndexedDB
  69483. this.isSupported = false;
  69484. if (errorCallback)
  69485. errorCallback();
  69486. }
  69487. else {
  69488. // If the DB hasn't been opened or created yet
  69489. if (!this.db) {
  69490. this.hasReachedQuota = false;
  69491. this.isSupported = true;
  69492. var request = this.idbFactory.open("babylonjs", 1);
  69493. // Could occur if user is blocking the quota for the DB and/or doesn't grant access to IndexedDB
  69494. request.onerror = function (event) {
  69495. handleError();
  69496. };
  69497. // executes when a version change transaction cannot complete due to other active transactions
  69498. request.onblocked = function (event) {
  69499. BABYLON.Tools.Error("IDB request blocked. Please reload the page.");
  69500. handleError();
  69501. };
  69502. // DB has been opened successfully
  69503. request.onsuccess = function (event) {
  69504. _this.db = request.result;
  69505. successCallback();
  69506. };
  69507. // Initialization of the DB. Creating Scenes & Textures stores
  69508. request.onupgradeneeded = function (event) {
  69509. _this.db = (event.target).result;
  69510. if (_this.db) {
  69511. try {
  69512. _this.db.createObjectStore("scenes", { keyPath: "sceneUrl" });
  69513. _this.db.createObjectStore("versions", { keyPath: "sceneUrl" });
  69514. _this.db.createObjectStore("textures", { keyPath: "textureUrl" });
  69515. }
  69516. catch (ex) {
  69517. BABYLON.Tools.Error("Error while creating object stores. Exception: " + ex.message);
  69518. handleError();
  69519. }
  69520. }
  69521. };
  69522. }
  69523. // DB has already been created and opened
  69524. else {
  69525. if (successCallback)
  69526. successCallback();
  69527. }
  69528. }
  69529. };
  69530. /**
  69531. * Loads an image from the database
  69532. * @param url defines the url to load from
  69533. * @param image defines the target DOM image
  69534. */
  69535. Database.prototype.loadImageFromDB = function (url, image) {
  69536. var _this = this;
  69537. var completeURL = Database._ReturnFullUrlLocation(url);
  69538. var saveAndLoadImage = function () {
  69539. if (!_this.hasReachedQuota && _this.db !== null) {
  69540. // the texture is not yet in the DB, let's try to save it
  69541. _this._saveImageIntoDBAsync(completeURL, image);
  69542. }
  69543. // If the texture is not in the DB and we've reached the DB quota limit
  69544. // let's load it directly from the web
  69545. else {
  69546. image.src = url;
  69547. }
  69548. };
  69549. if (!this.mustUpdateRessources) {
  69550. this._loadImageFromDBAsync(completeURL, image, saveAndLoadImage);
  69551. }
  69552. // First time we're download the images or update requested in the manifest file by a version change
  69553. else {
  69554. saveAndLoadImage();
  69555. }
  69556. };
  69557. Database.prototype._loadImageFromDBAsync = function (url, image, notInDBCallback) {
  69558. if (this.isSupported && this.db !== null) {
  69559. var texture;
  69560. var transaction = this.db.transaction(["textures"]);
  69561. transaction.onabort = function (event) {
  69562. image.src = url;
  69563. };
  69564. transaction.oncomplete = function (event) {
  69565. var blobTextureURL;
  69566. if (texture) {
  69567. var URL = window.URL || window.webkitURL;
  69568. blobTextureURL = URL.createObjectURL(texture.data, { oneTimeOnly: true });
  69569. image.onerror = function () {
  69570. BABYLON.Tools.Error("Error loading image from blob URL: " + blobTextureURL + " switching back to web url: " + url);
  69571. image.src = url;
  69572. };
  69573. image.src = blobTextureURL;
  69574. }
  69575. else {
  69576. notInDBCallback();
  69577. }
  69578. };
  69579. var getRequest = transaction.objectStore("textures").get(url);
  69580. getRequest.onsuccess = function (event) {
  69581. texture = (event.target).result;
  69582. };
  69583. getRequest.onerror = function (event) {
  69584. BABYLON.Tools.Error("Error loading texture " + url + " from DB.");
  69585. image.src = url;
  69586. };
  69587. }
  69588. else {
  69589. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69590. image.src = url;
  69591. }
  69592. };
  69593. Database.prototype._saveImageIntoDBAsync = function (url, image) {
  69594. var _this = this;
  69595. if (this.isSupported) {
  69596. // In case of error (type not supported or quota exceeded), we're at least sending back XHR data to allow texture loading later on
  69597. var generateBlobUrl = function () {
  69598. var blobTextureURL;
  69599. if (blob) {
  69600. var URL = window.URL || window.webkitURL;
  69601. try {
  69602. blobTextureURL = URL.createObjectURL(blob, { oneTimeOnly: true });
  69603. }
  69604. // Chrome is raising a type error if we're setting the oneTimeOnly parameter
  69605. catch (ex) {
  69606. blobTextureURL = URL.createObjectURL(blob);
  69607. }
  69608. }
  69609. if (blobTextureURL) {
  69610. image.src = blobTextureURL;
  69611. }
  69612. };
  69613. if (Database.IsUASupportingBlobStorage) { // Create XHR
  69614. var xhr = new XMLHttpRequest(), blob;
  69615. xhr.open("GET", url, true);
  69616. xhr.responseType = "blob";
  69617. xhr.addEventListener("load", function () {
  69618. if (xhr.status === 200 && _this.db) {
  69619. // Blob as response (XHR2)
  69620. blob = xhr.response;
  69621. var transaction = _this.db.transaction(["textures"], "readwrite");
  69622. // the transaction could abort because of a QuotaExceededError error
  69623. transaction.onabort = function (event) {
  69624. try {
  69625. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69626. var srcElement = (event.srcElement || event.target);
  69627. var error = srcElement.error;
  69628. if (error && error.name === "QuotaExceededError") {
  69629. _this.hasReachedQuota = true;
  69630. }
  69631. }
  69632. catch (ex) { }
  69633. generateBlobUrl();
  69634. };
  69635. transaction.oncomplete = function (event) {
  69636. generateBlobUrl();
  69637. };
  69638. var newTexture = { textureUrl: url, data: blob };
  69639. try {
  69640. // Put the blob into the dabase
  69641. var addRequest = transaction.objectStore("textures").put(newTexture);
  69642. addRequest.onsuccess = function (event) {
  69643. };
  69644. addRequest.onerror = function (event) {
  69645. generateBlobUrl();
  69646. };
  69647. }
  69648. catch (ex) {
  69649. // "DataCloneError" generated by Chrome when you try to inject blob into IndexedDB
  69650. if (ex.code === 25) {
  69651. Database.IsUASupportingBlobStorage = false;
  69652. }
  69653. image.src = url;
  69654. }
  69655. }
  69656. else {
  69657. image.src = url;
  69658. }
  69659. }, false);
  69660. xhr.addEventListener("error", function (event) {
  69661. BABYLON.Tools.Error("Error in XHR request in BABYLON.Database.");
  69662. image.src = url;
  69663. }, false);
  69664. xhr.send();
  69665. }
  69666. else {
  69667. image.src = url;
  69668. }
  69669. }
  69670. else {
  69671. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69672. image.src = url;
  69673. }
  69674. };
  69675. Database.prototype._checkVersionFromDB = function (url, versionLoaded) {
  69676. var _this = this;
  69677. var updateVersion = function () {
  69678. // the version is not yet in the DB or we need to update it
  69679. _this._saveVersionIntoDBAsync(url, versionLoaded);
  69680. };
  69681. this._loadVersionFromDBAsync(url, versionLoaded, updateVersion);
  69682. };
  69683. Database.prototype._loadVersionFromDBAsync = function (url, callback, updateInDBCallback) {
  69684. var _this = this;
  69685. if (this.isSupported && this.db) {
  69686. var version;
  69687. try {
  69688. var transaction = this.db.transaction(["versions"]);
  69689. transaction.oncomplete = function (event) {
  69690. if (version) {
  69691. // If the version in the JSON file is different from the version in DB
  69692. if (_this.manifestVersionFound !== version.data) {
  69693. _this.mustUpdateRessources = true;
  69694. updateInDBCallback();
  69695. }
  69696. else {
  69697. callback(version.data);
  69698. }
  69699. }
  69700. // version was not found in DB
  69701. else {
  69702. _this.mustUpdateRessources = true;
  69703. updateInDBCallback();
  69704. }
  69705. };
  69706. transaction.onabort = function (event) {
  69707. callback(-1);
  69708. };
  69709. var getRequest = transaction.objectStore("versions").get(url);
  69710. getRequest.onsuccess = function (event) {
  69711. version = (event.target).result;
  69712. };
  69713. getRequest.onerror = function (event) {
  69714. BABYLON.Tools.Error("Error loading version for scene " + url + " from DB.");
  69715. callback(-1);
  69716. };
  69717. }
  69718. catch (ex) {
  69719. BABYLON.Tools.Error("Error while accessing 'versions' object store (READ OP). Exception: " + ex.message);
  69720. callback(-1);
  69721. }
  69722. }
  69723. else {
  69724. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69725. callback(-1);
  69726. }
  69727. };
  69728. Database.prototype._saveVersionIntoDBAsync = function (url, callback) {
  69729. var _this = this;
  69730. if (this.isSupported && !this.hasReachedQuota && this.db) {
  69731. try {
  69732. // Open a transaction to the database
  69733. var transaction = this.db.transaction(["versions"], "readwrite");
  69734. // the transaction could abort because of a QuotaExceededError error
  69735. transaction.onabort = function (event) {
  69736. try { //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69737. var error = event.srcElement['error'];
  69738. if (error && error.name === "QuotaExceededError") {
  69739. _this.hasReachedQuota = true;
  69740. }
  69741. }
  69742. catch (ex) { }
  69743. callback(-1);
  69744. };
  69745. transaction.oncomplete = function (event) {
  69746. callback(_this.manifestVersionFound);
  69747. };
  69748. var newVersion = { sceneUrl: url, data: this.manifestVersionFound };
  69749. // Put the scene into the database
  69750. var addRequest = transaction.objectStore("versions").put(newVersion);
  69751. addRequest.onsuccess = function (event) {
  69752. };
  69753. addRequest.onerror = function (event) {
  69754. BABYLON.Tools.Error("Error in DB add version request in BABYLON.Database.");
  69755. };
  69756. }
  69757. catch (ex) {
  69758. BABYLON.Tools.Error("Error while accessing 'versions' object store (WRITE OP). Exception: " + ex.message);
  69759. callback(-1);
  69760. }
  69761. }
  69762. else {
  69763. callback(-1);
  69764. }
  69765. };
  69766. /**
  69767. * Loads a file from database
  69768. * @param url defines the URL to load from
  69769. * @param sceneLoaded defines a callback to call on success
  69770. * @param progressCallBack defines a callback to call when progress changed
  69771. * @param errorCallback defines a callback to call on error
  69772. * @param useArrayBuffer defines a boolean to use array buffer instead of text string
  69773. */
  69774. Database.prototype.loadFileFromDB = function (url, sceneLoaded, progressCallBack, errorCallback, useArrayBuffer) {
  69775. var _this = this;
  69776. var completeUrl = Database._ReturnFullUrlLocation(url);
  69777. var saveAndLoadFile = function () {
  69778. // the scene is not yet in the DB, let's try to save it
  69779. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack);
  69780. };
  69781. this._checkVersionFromDB(completeUrl, function (version) {
  69782. if (version !== -1) {
  69783. if (!_this.mustUpdateRessources) {
  69784. _this._loadFileFromDBAsync(completeUrl, sceneLoaded, saveAndLoadFile, useArrayBuffer);
  69785. }
  69786. else {
  69787. _this._saveFileIntoDBAsync(completeUrl, sceneLoaded, progressCallBack, useArrayBuffer);
  69788. }
  69789. }
  69790. else {
  69791. if (errorCallback) {
  69792. errorCallback();
  69793. }
  69794. }
  69795. });
  69796. };
  69797. Database.prototype._loadFileFromDBAsync = function (url, callback, notInDBCallback, useArrayBuffer) {
  69798. if (this.isSupported && this.db) {
  69799. var targetStore;
  69800. if (url.indexOf(".babylon") !== -1) {
  69801. targetStore = "scenes";
  69802. }
  69803. else {
  69804. targetStore = "textures";
  69805. }
  69806. var file;
  69807. var transaction = this.db.transaction([targetStore]);
  69808. transaction.oncomplete = function (event) {
  69809. if (file) {
  69810. callback(file.data);
  69811. }
  69812. // file was not found in DB
  69813. else {
  69814. notInDBCallback();
  69815. }
  69816. };
  69817. transaction.onabort = function (event) {
  69818. notInDBCallback();
  69819. };
  69820. var getRequest = transaction.objectStore(targetStore).get(url);
  69821. getRequest.onsuccess = function (event) {
  69822. file = (event.target).result;
  69823. };
  69824. getRequest.onerror = function (event) {
  69825. BABYLON.Tools.Error("Error loading file " + url + " from DB.");
  69826. notInDBCallback();
  69827. };
  69828. }
  69829. else {
  69830. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69831. callback();
  69832. }
  69833. };
  69834. Database.prototype._saveFileIntoDBAsync = function (url, callback, progressCallback, useArrayBuffer) {
  69835. var _this = this;
  69836. if (this.isSupported) {
  69837. var targetStore;
  69838. if (url.indexOf(".babylon") !== -1) {
  69839. targetStore = "scenes";
  69840. }
  69841. else {
  69842. targetStore = "textures";
  69843. }
  69844. // Create XHR
  69845. var xhr = new XMLHttpRequest();
  69846. var fileData;
  69847. xhr.open("GET", url, true);
  69848. if (useArrayBuffer) {
  69849. xhr.responseType = "arraybuffer";
  69850. }
  69851. if (progressCallback) {
  69852. xhr.onprogress = progressCallback;
  69853. }
  69854. xhr.addEventListener("load", function () {
  69855. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, !useArrayBuffer ? 1 : 6)) {
  69856. // Blob as response (XHR2)
  69857. //fileData = xhr.responseText;
  69858. fileData = !useArrayBuffer ? xhr.responseText : xhr.response;
  69859. if (!_this.hasReachedQuota && _this.db) {
  69860. // Open a transaction to the database
  69861. var transaction = _this.db.transaction([targetStore], "readwrite");
  69862. // the transaction could abort because of a QuotaExceededError error
  69863. transaction.onabort = function (event) {
  69864. try {
  69865. //backwards compatibility with ts 1.0, srcElement doesn't have an "error" according to ts 1.3
  69866. var error = event.srcElement['error'];
  69867. if (error && error.name === "QuotaExceededError") {
  69868. _this.hasReachedQuota = true;
  69869. }
  69870. }
  69871. catch (ex) { }
  69872. callback(fileData);
  69873. };
  69874. transaction.oncomplete = function (event) {
  69875. callback(fileData);
  69876. };
  69877. var newFile;
  69878. if (targetStore === "scenes") {
  69879. newFile = { sceneUrl: url, data: fileData, version: _this.manifestVersionFound };
  69880. }
  69881. else {
  69882. newFile = { textureUrl: url, data: fileData };
  69883. }
  69884. try {
  69885. // Put the scene into the database
  69886. var addRequest = transaction.objectStore(targetStore).put(newFile);
  69887. addRequest.onsuccess = function (event) {
  69888. };
  69889. addRequest.onerror = function (event) {
  69890. BABYLON.Tools.Error("Error in DB add file request in BABYLON.Database.");
  69891. };
  69892. }
  69893. catch (ex) {
  69894. callback(fileData);
  69895. }
  69896. }
  69897. else {
  69898. callback(fileData);
  69899. }
  69900. }
  69901. else {
  69902. callback();
  69903. }
  69904. }, false);
  69905. xhr.addEventListener("error", function (event) {
  69906. BABYLON.Tools.Error("error on XHR request.");
  69907. callback();
  69908. }, false);
  69909. xhr.send();
  69910. }
  69911. else {
  69912. BABYLON.Tools.Error("Error: IndexedDB not supported by your browser or BabylonJS Database is not open.");
  69913. callback();
  69914. }
  69915. };
  69916. /** Gets a boolean indicating if the user agent supports blob storage (this value will be updated after creating the first Database object) */
  69917. Database.IsUASupportingBlobStorage = true;
  69918. /** Gets a boolean indicating if Database storate is enabled */
  69919. Database.IDBStorageEnabled = true;
  69920. Database._ParseURL = function (url) {
  69921. var a = document.createElement('a');
  69922. a.href = url;
  69923. var urlWithoutHash = url.substring(0, url.lastIndexOf("#"));
  69924. var fileName = url.substring(urlWithoutHash.lastIndexOf("/") + 1, url.length);
  69925. var absLocation = url.substring(0, url.indexOf(fileName, 0));
  69926. return absLocation;
  69927. };
  69928. Database._ReturnFullUrlLocation = function (url) {
  69929. if (url.indexOf("http:/") === -1 && url.indexOf("https:/") === -1) {
  69930. return (Database._ParseURL(window.location.href) + url);
  69931. }
  69932. else {
  69933. return url;
  69934. }
  69935. };
  69936. return Database;
  69937. }());
  69938. BABYLON.Database = Database;
  69939. })(BABYLON || (BABYLON = {}));
  69940. //# sourceMappingURL=babylon.database.js.map
  69941. var BABYLON;
  69942. (function (BABYLON) {
  69943. var FresnelParameters = /** @class */ (function () {
  69944. function FresnelParameters() {
  69945. this._isEnabled = true;
  69946. this.leftColor = BABYLON.Color3.White();
  69947. this.rightColor = BABYLON.Color3.Black();
  69948. this.bias = 0;
  69949. this.power = 1;
  69950. }
  69951. Object.defineProperty(FresnelParameters.prototype, "isEnabled", {
  69952. get: function () {
  69953. return this._isEnabled;
  69954. },
  69955. set: function (value) {
  69956. if (this._isEnabled === value) {
  69957. return;
  69958. }
  69959. this._isEnabled = value;
  69960. BABYLON.Engine.MarkAllMaterialsAsDirty(BABYLON.Material.FresnelDirtyFlag | BABYLON.Material.MiscDirtyFlag);
  69961. },
  69962. enumerable: true,
  69963. configurable: true
  69964. });
  69965. FresnelParameters.prototype.clone = function () {
  69966. var newFresnelParameters = new FresnelParameters();
  69967. BABYLON.Tools.DeepCopy(this, newFresnelParameters);
  69968. return newFresnelParameters;
  69969. };
  69970. FresnelParameters.prototype.serialize = function () {
  69971. var serializationObject = {};
  69972. serializationObject.isEnabled = this.isEnabled;
  69973. serializationObject.leftColor = this.leftColor.asArray();
  69974. serializationObject.rightColor = this.rightColor.asArray();
  69975. serializationObject.bias = this.bias;
  69976. serializationObject.power = this.power;
  69977. return serializationObject;
  69978. };
  69979. FresnelParameters.Parse = function (parsedFresnelParameters) {
  69980. var fresnelParameters = new FresnelParameters();
  69981. fresnelParameters.isEnabled = parsedFresnelParameters.isEnabled;
  69982. fresnelParameters.leftColor = BABYLON.Color3.FromArray(parsedFresnelParameters.leftColor);
  69983. fresnelParameters.rightColor = BABYLON.Color3.FromArray(parsedFresnelParameters.rightColor);
  69984. fresnelParameters.bias = parsedFresnelParameters.bias;
  69985. fresnelParameters.power = parsedFresnelParameters.power || 1.0;
  69986. return fresnelParameters;
  69987. };
  69988. return FresnelParameters;
  69989. }());
  69990. BABYLON.FresnelParameters = FresnelParameters;
  69991. })(BABYLON || (BABYLON = {}));
  69992. //# sourceMappingURL=babylon.fresnelParameters.js.map
  69993. var BABYLON;
  69994. (function (BABYLON) {
  69995. var MultiMaterial = /** @class */ (function (_super) {
  69996. __extends(MultiMaterial, _super);
  69997. function MultiMaterial(name, scene) {
  69998. var _this = _super.call(this, name, scene, true) || this;
  69999. scene.multiMaterials.push(_this);
  70000. _this.subMaterials = new Array();
  70001. _this.storeEffectOnSubMeshes = true; // multimaterial is considered like a push material
  70002. return _this;
  70003. }
  70004. Object.defineProperty(MultiMaterial.prototype, "subMaterials", {
  70005. get: function () {
  70006. return this._subMaterials;
  70007. },
  70008. set: function (value) {
  70009. this._subMaterials = value;
  70010. this._hookArray(value);
  70011. },
  70012. enumerable: true,
  70013. configurable: true
  70014. });
  70015. MultiMaterial.prototype._hookArray = function (array) {
  70016. var _this = this;
  70017. var oldPush = array.push;
  70018. array.push = function () {
  70019. var items = [];
  70020. for (var _i = 0; _i < arguments.length; _i++) {
  70021. items[_i] = arguments[_i];
  70022. }
  70023. var result = oldPush.apply(array, items);
  70024. _this._markAllSubMeshesAsTexturesDirty();
  70025. return result;
  70026. };
  70027. var oldSplice = array.splice;
  70028. array.splice = function (index, deleteCount) {
  70029. var deleted = oldSplice.apply(array, [index, deleteCount]);
  70030. _this._markAllSubMeshesAsTexturesDirty();
  70031. return deleted;
  70032. };
  70033. };
  70034. // Properties
  70035. MultiMaterial.prototype.getSubMaterial = function (index) {
  70036. if (index < 0 || index >= this.subMaterials.length) {
  70037. return this.getScene().defaultMaterial;
  70038. }
  70039. return this.subMaterials[index];
  70040. };
  70041. MultiMaterial.prototype.getActiveTextures = function () {
  70042. return (_a = _super.prototype.getActiveTextures.call(this)).concat.apply(_a, this.subMaterials.map(function (subMaterial) {
  70043. if (subMaterial) {
  70044. return subMaterial.getActiveTextures();
  70045. }
  70046. else {
  70047. return [];
  70048. }
  70049. }));
  70050. var _a;
  70051. };
  70052. // Methods
  70053. MultiMaterial.prototype.getClassName = function () {
  70054. return "MultiMaterial";
  70055. };
  70056. MultiMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  70057. for (var index = 0; index < this.subMaterials.length; index++) {
  70058. var subMaterial = this.subMaterials[index];
  70059. if (subMaterial) {
  70060. if (subMaterial.storeEffectOnSubMeshes) {
  70061. if (!subMaterial.isReadyForSubMesh(mesh, subMesh, useInstances)) {
  70062. return false;
  70063. }
  70064. continue;
  70065. }
  70066. if (!subMaterial.isReady(mesh)) {
  70067. return false;
  70068. }
  70069. }
  70070. }
  70071. return true;
  70072. };
  70073. MultiMaterial.prototype.clone = function (name, cloneChildren) {
  70074. var newMultiMaterial = new MultiMaterial(name, this.getScene());
  70075. for (var index = 0; index < this.subMaterials.length; index++) {
  70076. var subMaterial = null;
  70077. var current = this.subMaterials[index];
  70078. if (cloneChildren && current) {
  70079. subMaterial = current.clone(name + "-" + current.name);
  70080. }
  70081. else {
  70082. subMaterial = this.subMaterials[index];
  70083. }
  70084. newMultiMaterial.subMaterials.push(subMaterial);
  70085. }
  70086. return newMultiMaterial;
  70087. };
  70088. MultiMaterial.prototype.serialize = function () {
  70089. var serializationObject = {};
  70090. serializationObject.name = this.name;
  70091. serializationObject.id = this.id;
  70092. if (BABYLON.Tags) {
  70093. serializationObject.tags = BABYLON.Tags.GetTags(this);
  70094. }
  70095. serializationObject.materials = [];
  70096. for (var matIndex = 0; matIndex < this.subMaterials.length; matIndex++) {
  70097. var subMat = this.subMaterials[matIndex];
  70098. if (subMat) {
  70099. serializationObject.materials.push(subMat.id);
  70100. }
  70101. else {
  70102. serializationObject.materials.push(null);
  70103. }
  70104. }
  70105. return serializationObject;
  70106. };
  70107. MultiMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  70108. var scene = this.getScene();
  70109. if (!scene) {
  70110. return;
  70111. }
  70112. var index = scene.multiMaterials.indexOf(this);
  70113. if (index >= 0) {
  70114. scene.multiMaterials.splice(index, 1);
  70115. }
  70116. _super.prototype.dispose.call(this, forceDisposeEffect, forceDisposeTextures);
  70117. };
  70118. return MultiMaterial;
  70119. }(BABYLON.Material));
  70120. BABYLON.MultiMaterial = MultiMaterial;
  70121. })(BABYLON || (BABYLON = {}));
  70122. //# sourceMappingURL=babylon.multiMaterial.js.map
  70123. var BABYLON;
  70124. (function (BABYLON) {
  70125. var FreeCameraTouchInput = /** @class */ (function () {
  70126. function FreeCameraTouchInput() {
  70127. this._offsetX = null;
  70128. this._offsetY = null;
  70129. this._pointerPressed = new Array();
  70130. this.touchAngularSensibility = 200000.0;
  70131. this.touchMoveSensibility = 250.0;
  70132. }
  70133. FreeCameraTouchInput.prototype.attachControl = function (element, noPreventDefault) {
  70134. var _this = this;
  70135. var previousPosition = null;
  70136. if (this._pointerInput === undefined) {
  70137. this._onLostFocus = function (evt) {
  70138. _this._offsetX = null;
  70139. _this._offsetY = null;
  70140. };
  70141. this._pointerInput = function (p, s) {
  70142. var evt = p.event;
  70143. if (evt.pointerType === "mouse") {
  70144. return;
  70145. }
  70146. if (p.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  70147. if (!noPreventDefault) {
  70148. evt.preventDefault();
  70149. }
  70150. _this._pointerPressed.push(evt.pointerId);
  70151. if (_this._pointerPressed.length !== 1) {
  70152. return;
  70153. }
  70154. previousPosition = {
  70155. x: evt.clientX,
  70156. y: evt.clientY
  70157. };
  70158. }
  70159. else if (p.type === BABYLON.PointerEventTypes.POINTERUP) {
  70160. if (!noPreventDefault) {
  70161. evt.preventDefault();
  70162. }
  70163. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70164. if (index === -1) {
  70165. return;
  70166. }
  70167. _this._pointerPressed.splice(index, 1);
  70168. if (index != 0) {
  70169. return;
  70170. }
  70171. previousPosition = null;
  70172. _this._offsetX = null;
  70173. _this._offsetY = null;
  70174. }
  70175. else if (p.type === BABYLON.PointerEventTypes.POINTERMOVE) {
  70176. if (!noPreventDefault) {
  70177. evt.preventDefault();
  70178. }
  70179. if (!previousPosition) {
  70180. return;
  70181. }
  70182. var index = _this._pointerPressed.indexOf(evt.pointerId);
  70183. if (index != 0) {
  70184. return;
  70185. }
  70186. _this._offsetX = evt.clientX - previousPosition.x;
  70187. _this._offsetY = -(evt.clientY - previousPosition.y);
  70188. }
  70189. };
  70190. }
  70191. this._observer = this.camera.getScene().onPointerObservable.add(this._pointerInput, BABYLON.PointerEventTypes.POINTERDOWN | BABYLON.PointerEventTypes.POINTERUP | BABYLON.PointerEventTypes.POINTERMOVE);
  70192. if (this._onLostFocus) {
  70193. element.addEventListener("blur", this._onLostFocus);
  70194. }
  70195. };
  70196. FreeCameraTouchInput.prototype.detachControl = function (element) {
  70197. if (this._pointerInput && element) {
  70198. if (this._observer) {
  70199. this.camera.getScene().onPointerObservable.remove(this._observer);
  70200. this._observer = null;
  70201. }
  70202. if (this._onLostFocus) {
  70203. element.removeEventListener("blur", this._onLostFocus);
  70204. this._onLostFocus = null;
  70205. }
  70206. this._pointerPressed = [];
  70207. this._offsetX = null;
  70208. this._offsetY = null;
  70209. }
  70210. };
  70211. FreeCameraTouchInput.prototype.checkInputs = function () {
  70212. if (this._offsetX && this._offsetY) {
  70213. var camera = this.camera;
  70214. camera.cameraRotation.y += this._offsetX / this.touchAngularSensibility;
  70215. if (this._pointerPressed.length > 1) {
  70216. camera.cameraRotation.x += -this._offsetY / this.touchAngularSensibility;
  70217. }
  70218. else {
  70219. var speed = camera._computeLocalCameraSpeed();
  70220. var direction = new BABYLON.Vector3(0, 0, speed * this._offsetY / this.touchMoveSensibility);
  70221. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, camera._cameraRotationMatrix);
  70222. camera.cameraDirection.addInPlace(BABYLON.Vector3.TransformCoordinates(direction, camera._cameraRotationMatrix));
  70223. }
  70224. }
  70225. };
  70226. FreeCameraTouchInput.prototype.getClassName = function () {
  70227. return "FreeCameraTouchInput";
  70228. };
  70229. FreeCameraTouchInput.prototype.getSimpleName = function () {
  70230. return "touch";
  70231. };
  70232. __decorate([
  70233. BABYLON.serialize()
  70234. ], FreeCameraTouchInput.prototype, "touchAngularSensibility", void 0);
  70235. __decorate([
  70236. BABYLON.serialize()
  70237. ], FreeCameraTouchInput.prototype, "touchMoveSensibility", void 0);
  70238. return FreeCameraTouchInput;
  70239. }());
  70240. BABYLON.FreeCameraTouchInput = FreeCameraTouchInput;
  70241. BABYLON.CameraInputTypes["FreeCameraTouchInput"] = FreeCameraTouchInput;
  70242. })(BABYLON || (BABYLON = {}));
  70243. //# sourceMappingURL=babylon.freeCameraTouchInput.js.map
  70244. var BABYLON;
  70245. (function (BABYLON) {
  70246. // We're mainly based on the logic defined into the FreeCamera code
  70247. var TouchCamera = /** @class */ (function (_super) {
  70248. __extends(TouchCamera, _super);
  70249. //-- end properties for backward compatibility for inputs
  70250. function TouchCamera(name, position, scene) {
  70251. var _this = _super.call(this, name, position, scene) || this;
  70252. _this.inputs.addTouch();
  70253. _this._setupInputs();
  70254. return _this;
  70255. }
  70256. Object.defineProperty(TouchCamera.prototype, "touchAngularSensibility", {
  70257. //-- Begin properties for backward compatibility for inputs
  70258. get: function () {
  70259. var touch = this.inputs.attached["touch"];
  70260. if (touch)
  70261. return touch.touchAngularSensibility;
  70262. return 0;
  70263. },
  70264. set: function (value) {
  70265. var touch = this.inputs.attached["touch"];
  70266. if (touch)
  70267. touch.touchAngularSensibility = value;
  70268. },
  70269. enumerable: true,
  70270. configurable: true
  70271. });
  70272. Object.defineProperty(TouchCamera.prototype, "touchMoveSensibility", {
  70273. get: function () {
  70274. var touch = this.inputs.attached["touch"];
  70275. if (touch)
  70276. return touch.touchMoveSensibility;
  70277. return 0;
  70278. },
  70279. set: function (value) {
  70280. var touch = this.inputs.attached["touch"];
  70281. if (touch)
  70282. touch.touchMoveSensibility = value;
  70283. },
  70284. enumerable: true,
  70285. configurable: true
  70286. });
  70287. TouchCamera.prototype.getClassName = function () {
  70288. return "TouchCamera";
  70289. };
  70290. TouchCamera.prototype._setupInputs = function () {
  70291. var mouse = this.inputs.attached["mouse"];
  70292. if (mouse) {
  70293. mouse.touchEnabled = false;
  70294. }
  70295. };
  70296. return TouchCamera;
  70297. }(BABYLON.FreeCamera));
  70298. BABYLON.TouchCamera = TouchCamera;
  70299. })(BABYLON || (BABYLON = {}));
  70300. //# sourceMappingURL=babylon.touchCamera.js.map
  70301. var BABYLON;
  70302. (function (BABYLON) {
  70303. var ProceduralTexture = /** @class */ (function (_super) {
  70304. __extends(ProceduralTexture, _super);
  70305. function ProceduralTexture(name, size, fragment, scene, fallbackTexture, generateMipMaps, isCube) {
  70306. if (fallbackTexture === void 0) { fallbackTexture = null; }
  70307. if (generateMipMaps === void 0) { generateMipMaps = true; }
  70308. if (isCube === void 0) { isCube = false; }
  70309. var _this = _super.call(this, null, scene, !generateMipMaps) || this;
  70310. _this.isCube = isCube;
  70311. _this.isEnabled = true;
  70312. _this._currentRefreshId = -1;
  70313. _this._refreshRate = 1;
  70314. _this._vertexBuffers = {};
  70315. _this._uniforms = new Array();
  70316. _this._samplers = new Array();
  70317. _this._textures = {};
  70318. _this._floats = {};
  70319. _this._floatsArrays = {};
  70320. _this._colors3 = {};
  70321. _this._colors4 = {};
  70322. _this._vectors2 = {};
  70323. _this._vectors3 = {};
  70324. _this._matrices = {};
  70325. _this._fallbackTextureUsed = false;
  70326. scene.proceduralTextures.push(_this);
  70327. _this._engine = scene.getEngine();
  70328. _this.name = name;
  70329. _this.isRenderTarget = true;
  70330. _this._size = size;
  70331. _this._generateMipMaps = generateMipMaps;
  70332. _this.setFragment(fragment);
  70333. _this._fallbackTexture = fallbackTexture;
  70334. if (isCube) {
  70335. _this._texture = _this._engine.createRenderTargetCubeTexture(size, { generateMipMaps: generateMipMaps });
  70336. _this.setFloat("face", 0);
  70337. }
  70338. else {
  70339. _this._texture = _this._engine.createRenderTargetTexture(size, generateMipMaps);
  70340. }
  70341. // VBO
  70342. var vertices = [];
  70343. vertices.push(1, 1);
  70344. vertices.push(-1, 1);
  70345. vertices.push(-1, -1);
  70346. vertices.push(1, -1);
  70347. _this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(_this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  70348. _this._createIndexBuffer();
  70349. return _this;
  70350. }
  70351. ProceduralTexture.prototype._createIndexBuffer = function () {
  70352. var engine = this._engine;
  70353. // Indices
  70354. var indices = [];
  70355. indices.push(0);
  70356. indices.push(1);
  70357. indices.push(2);
  70358. indices.push(0);
  70359. indices.push(2);
  70360. indices.push(3);
  70361. this._indexBuffer = engine.createIndexBuffer(indices);
  70362. };
  70363. ProceduralTexture.prototype._rebuild = function () {
  70364. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70365. if (vb) {
  70366. vb._rebuild();
  70367. }
  70368. this._createIndexBuffer();
  70369. if (this.refreshRate === BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE) {
  70370. this.refreshRate = BABYLON.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  70371. }
  70372. };
  70373. ProceduralTexture.prototype.reset = function () {
  70374. if (this._effect === undefined) {
  70375. return;
  70376. }
  70377. var engine = this._engine;
  70378. engine._releaseEffect(this._effect);
  70379. };
  70380. ProceduralTexture.prototype.isReady = function () {
  70381. var _this = this;
  70382. var engine = this._engine;
  70383. var shaders;
  70384. if (!this._fragment) {
  70385. return false;
  70386. }
  70387. if (this._fallbackTextureUsed) {
  70388. return true;
  70389. }
  70390. if (this._fragment.fragmentElement !== undefined) {
  70391. shaders = { vertex: "procedural", fragmentElement: this._fragment.fragmentElement };
  70392. }
  70393. else {
  70394. shaders = { vertex: "procedural", fragment: this._fragment };
  70395. }
  70396. this._effect = engine.createEffect(shaders, [BABYLON.VertexBuffer.PositionKind], this._uniforms, this._samplers, "", undefined, undefined, function () {
  70397. _this.releaseInternalTexture();
  70398. if (_this._fallbackTexture) {
  70399. _this._texture = _this._fallbackTexture._texture;
  70400. if (_this._texture) {
  70401. _this._texture.incrementReferences();
  70402. }
  70403. }
  70404. _this._fallbackTextureUsed = true;
  70405. });
  70406. return this._effect.isReady();
  70407. };
  70408. ProceduralTexture.prototype.resetRefreshCounter = function () {
  70409. this._currentRefreshId = -1;
  70410. };
  70411. ProceduralTexture.prototype.setFragment = function (fragment) {
  70412. this._fragment = fragment;
  70413. };
  70414. Object.defineProperty(ProceduralTexture.prototype, "refreshRate", {
  70415. get: function () {
  70416. return this._refreshRate;
  70417. },
  70418. // Use 0 to render just once, 1 to render on every frame, 2 to render every two frames and so on...
  70419. set: function (value) {
  70420. this._refreshRate = value;
  70421. this.resetRefreshCounter();
  70422. },
  70423. enumerable: true,
  70424. configurable: true
  70425. });
  70426. ProceduralTexture.prototype._shouldRender = function () {
  70427. if (!this.isEnabled || !this.isReady() || !this._texture) {
  70428. return false;
  70429. }
  70430. if (this._fallbackTextureUsed) {
  70431. return false;
  70432. }
  70433. if (this._currentRefreshId === -1) { // At least render once
  70434. this._currentRefreshId = 1;
  70435. return true;
  70436. }
  70437. if (this.refreshRate === this._currentRefreshId) {
  70438. this._currentRefreshId = 1;
  70439. return true;
  70440. }
  70441. this._currentRefreshId++;
  70442. return false;
  70443. };
  70444. ProceduralTexture.prototype.getRenderSize = function () {
  70445. return this._size;
  70446. };
  70447. ProceduralTexture.prototype.resize = function (size, generateMipMaps) {
  70448. if (this._fallbackTextureUsed) {
  70449. return;
  70450. }
  70451. this.releaseInternalTexture();
  70452. this._texture = this._engine.createRenderTargetTexture(size, generateMipMaps);
  70453. // Update properties
  70454. this._size = size;
  70455. this._generateMipMaps = generateMipMaps;
  70456. };
  70457. ProceduralTexture.prototype._checkUniform = function (uniformName) {
  70458. if (this._uniforms.indexOf(uniformName) === -1) {
  70459. this._uniforms.push(uniformName);
  70460. }
  70461. };
  70462. ProceduralTexture.prototype.setTexture = function (name, texture) {
  70463. if (this._samplers.indexOf(name) === -1) {
  70464. this._samplers.push(name);
  70465. }
  70466. this._textures[name] = texture;
  70467. return this;
  70468. };
  70469. ProceduralTexture.prototype.setFloat = function (name, value) {
  70470. this._checkUniform(name);
  70471. this._floats[name] = value;
  70472. return this;
  70473. };
  70474. ProceduralTexture.prototype.setFloats = function (name, value) {
  70475. this._checkUniform(name);
  70476. this._floatsArrays[name] = value;
  70477. return this;
  70478. };
  70479. ProceduralTexture.prototype.setColor3 = function (name, value) {
  70480. this._checkUniform(name);
  70481. this._colors3[name] = value;
  70482. return this;
  70483. };
  70484. ProceduralTexture.prototype.setColor4 = function (name, value) {
  70485. this._checkUniform(name);
  70486. this._colors4[name] = value;
  70487. return this;
  70488. };
  70489. ProceduralTexture.prototype.setVector2 = function (name, value) {
  70490. this._checkUniform(name);
  70491. this._vectors2[name] = value;
  70492. return this;
  70493. };
  70494. ProceduralTexture.prototype.setVector3 = function (name, value) {
  70495. this._checkUniform(name);
  70496. this._vectors3[name] = value;
  70497. return this;
  70498. };
  70499. ProceduralTexture.prototype.setMatrix = function (name, value) {
  70500. this._checkUniform(name);
  70501. this._matrices[name] = value;
  70502. return this;
  70503. };
  70504. ProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70505. var scene = this.getScene();
  70506. if (!scene) {
  70507. return;
  70508. }
  70509. var engine = this._engine;
  70510. // Render
  70511. engine.enableEffect(this._effect);
  70512. engine.setState(false);
  70513. // Texture
  70514. for (var name in this._textures) {
  70515. this._effect.setTexture(name, this._textures[name]);
  70516. }
  70517. // Float
  70518. for (name in this._floats) {
  70519. this._effect.setFloat(name, this._floats[name]);
  70520. }
  70521. // Floats
  70522. for (name in this._floatsArrays) {
  70523. this._effect.setArray(name, this._floatsArrays[name]);
  70524. }
  70525. // Color3
  70526. for (name in this._colors3) {
  70527. this._effect.setColor3(name, this._colors3[name]);
  70528. }
  70529. // Color4
  70530. for (name in this._colors4) {
  70531. var color = this._colors4[name];
  70532. this._effect.setFloat4(name, color.r, color.g, color.b, color.a);
  70533. }
  70534. // Vector2
  70535. for (name in this._vectors2) {
  70536. this._effect.setVector2(name, this._vectors2[name]);
  70537. }
  70538. // Vector3
  70539. for (name in this._vectors3) {
  70540. this._effect.setVector3(name, this._vectors3[name]);
  70541. }
  70542. // Matrix
  70543. for (name in this._matrices) {
  70544. this._effect.setMatrix(name, this._matrices[name]);
  70545. }
  70546. if (!this._texture) {
  70547. return;
  70548. }
  70549. if (this.isCube) {
  70550. for (var face = 0; face < 6; face++) {
  70551. engine.bindFramebuffer(this._texture, face, undefined, undefined, true);
  70552. // VBOs
  70553. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70554. this._effect.setFloat("face", face);
  70555. // Clear
  70556. engine.clear(scene.clearColor, true, true, true);
  70557. // Draw order
  70558. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70559. // Mipmaps
  70560. if (face === 5) {
  70561. engine.generateMipMapsForCubemap(this._texture);
  70562. }
  70563. }
  70564. }
  70565. else {
  70566. engine.bindFramebuffer(this._texture, 0, undefined, undefined, true);
  70567. // VBOs
  70568. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  70569. // Clear
  70570. engine.clear(scene.clearColor, true, true, true);
  70571. // Draw order
  70572. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  70573. }
  70574. // Unbind
  70575. engine.unBindFramebuffer(this._texture, this.isCube);
  70576. if (this.onGenerated) {
  70577. this.onGenerated();
  70578. }
  70579. };
  70580. ProceduralTexture.prototype.clone = function () {
  70581. var textureSize = this.getSize();
  70582. var newTexture = new ProceduralTexture(this.name, textureSize.width, this._fragment, this.getScene(), this._fallbackTexture, this._generateMipMaps);
  70583. // Base texture
  70584. newTexture.hasAlpha = this.hasAlpha;
  70585. newTexture.level = this.level;
  70586. // RenderTarget Texture
  70587. newTexture.coordinatesMode = this.coordinatesMode;
  70588. return newTexture;
  70589. };
  70590. ProceduralTexture.prototype.dispose = function () {
  70591. var scene = this.getScene();
  70592. if (!scene) {
  70593. return;
  70594. }
  70595. var index = scene.proceduralTextures.indexOf(this);
  70596. if (index >= 0) {
  70597. scene.proceduralTextures.splice(index, 1);
  70598. }
  70599. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  70600. if (vertexBuffer) {
  70601. vertexBuffer.dispose();
  70602. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  70603. }
  70604. if (this._indexBuffer && this._engine._releaseBuffer(this._indexBuffer)) {
  70605. this._indexBuffer = null;
  70606. }
  70607. _super.prototype.dispose.call(this);
  70608. };
  70609. __decorate([
  70610. BABYLON.serialize()
  70611. ], ProceduralTexture.prototype, "_size", void 0);
  70612. __decorate([
  70613. BABYLON.serialize()
  70614. ], ProceduralTexture.prototype, "_generateMipMaps", void 0);
  70615. __decorate([
  70616. BABYLON.serialize()
  70617. ], ProceduralTexture.prototype, "isEnabled", void 0);
  70618. __decorate([
  70619. BABYLON.serialize()
  70620. ], ProceduralTexture.prototype, "refreshRate", null);
  70621. return ProceduralTexture;
  70622. }(BABYLON.Texture));
  70623. BABYLON.ProceduralTexture = ProceduralTexture;
  70624. })(BABYLON || (BABYLON = {}));
  70625. //# sourceMappingURL=babylon.proceduralTexture.js.map
  70626. var BABYLON;
  70627. (function (BABYLON) {
  70628. var CustomProceduralTexture = /** @class */ (function (_super) {
  70629. __extends(CustomProceduralTexture, _super);
  70630. function CustomProceduralTexture(name, texturePath, size, scene, fallbackTexture, generateMipMaps) {
  70631. var _this = _super.call(this, name, size, null, scene, fallbackTexture, generateMipMaps) || this;
  70632. _this._animate = true;
  70633. _this._time = 0;
  70634. _this._texturePath = texturePath;
  70635. //Try to load json
  70636. _this.loadJson(texturePath);
  70637. _this.refreshRate = 1;
  70638. return _this;
  70639. }
  70640. CustomProceduralTexture.prototype.loadJson = function (jsonUrl) {
  70641. var _this = this;
  70642. var noConfigFile = function () {
  70643. BABYLON.Tools.Log("No config file found in " + jsonUrl + " trying to use ShadersStore or DOM element");
  70644. try {
  70645. _this.setFragment(_this._texturePath);
  70646. }
  70647. catch (ex) {
  70648. BABYLON.Tools.Error("No json or ShaderStore or DOM element found for CustomProceduralTexture");
  70649. }
  70650. };
  70651. var configFileUrl = jsonUrl + "/config.json";
  70652. var xhr = new XMLHttpRequest();
  70653. xhr.open("GET", configFileUrl, true);
  70654. xhr.addEventListener("load", function () {
  70655. if (xhr.status === 200 || BABYLON.Tools.ValidateXHRData(xhr, 1)) {
  70656. try {
  70657. _this._config = JSON.parse(xhr.response);
  70658. _this.updateShaderUniforms();
  70659. _this.updateTextures();
  70660. _this.setFragment(_this._texturePath + "/custom");
  70661. _this._animate = _this._config.animate;
  70662. _this.refreshRate = _this._config.refreshrate;
  70663. }
  70664. catch (ex) {
  70665. noConfigFile();
  70666. }
  70667. }
  70668. else {
  70669. noConfigFile();
  70670. }
  70671. }, false);
  70672. xhr.addEventListener("error", function () {
  70673. noConfigFile();
  70674. }, false);
  70675. try {
  70676. xhr.send();
  70677. }
  70678. catch (ex) {
  70679. BABYLON.Tools.Error("CustomProceduralTexture: Error on XHR send request.");
  70680. }
  70681. };
  70682. CustomProceduralTexture.prototype.isReady = function () {
  70683. if (!_super.prototype.isReady.call(this)) {
  70684. return false;
  70685. }
  70686. for (var name in this._textures) {
  70687. var texture = this._textures[name];
  70688. if (!texture.isReady()) {
  70689. return false;
  70690. }
  70691. }
  70692. return true;
  70693. };
  70694. CustomProceduralTexture.prototype.render = function (useCameraPostProcess) {
  70695. var scene = this.getScene();
  70696. if (this._animate && scene) {
  70697. this._time += scene.getAnimationRatio() * 0.03;
  70698. this.updateShaderUniforms();
  70699. }
  70700. _super.prototype.render.call(this, useCameraPostProcess);
  70701. };
  70702. CustomProceduralTexture.prototype.updateTextures = function () {
  70703. for (var i = 0; i < this._config.sampler2Ds.length; i++) {
  70704. this.setTexture(this._config.sampler2Ds[i].sample2Dname, new BABYLON.Texture(this._texturePath + "/" + this._config.sampler2Ds[i].textureRelativeUrl, this.getScene()));
  70705. }
  70706. };
  70707. CustomProceduralTexture.prototype.updateShaderUniforms = function () {
  70708. if (this._config) {
  70709. for (var j = 0; j < this._config.uniforms.length; j++) {
  70710. var uniform = this._config.uniforms[j];
  70711. switch (uniform.type) {
  70712. case "float":
  70713. this.setFloat(uniform.name, uniform.value);
  70714. break;
  70715. case "color3":
  70716. this.setColor3(uniform.name, new BABYLON.Color3(uniform.r, uniform.g, uniform.b));
  70717. break;
  70718. case "color4":
  70719. this.setColor4(uniform.name, new BABYLON.Color4(uniform.r, uniform.g, uniform.b, uniform.a));
  70720. break;
  70721. case "vector2":
  70722. this.setVector2(uniform.name, new BABYLON.Vector2(uniform.x, uniform.y));
  70723. break;
  70724. case "vector3":
  70725. this.setVector3(uniform.name, new BABYLON.Vector3(uniform.x, uniform.y, uniform.z));
  70726. break;
  70727. }
  70728. }
  70729. }
  70730. this.setFloat("time", this._time);
  70731. };
  70732. Object.defineProperty(CustomProceduralTexture.prototype, "animate", {
  70733. get: function () {
  70734. return this._animate;
  70735. },
  70736. set: function (value) {
  70737. this._animate = value;
  70738. },
  70739. enumerable: true,
  70740. configurable: true
  70741. });
  70742. return CustomProceduralTexture;
  70743. }(BABYLON.ProceduralTexture));
  70744. BABYLON.CustomProceduralTexture = CustomProceduralTexture;
  70745. })(BABYLON || (BABYLON = {}));
  70746. //# sourceMappingURL=babylon.customProceduralTexture.js.map
  70747. var BABYLON;
  70748. (function (BABYLON) {
  70749. var FreeCameraGamepadInput = /** @class */ (function () {
  70750. function FreeCameraGamepadInput() {
  70751. this.gamepadAngularSensibility = 200;
  70752. this.gamepadMoveSensibility = 40;
  70753. // private members
  70754. this._cameraTransform = BABYLON.Matrix.Identity();
  70755. this._deltaTransform = BABYLON.Vector3.Zero();
  70756. this._vector3 = BABYLON.Vector3.Zero();
  70757. this._vector2 = BABYLON.Vector2.Zero();
  70758. }
  70759. FreeCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70760. var _this = this;
  70761. var manager = this.camera.getScene().gamepadManager;
  70762. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70763. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70764. // prioritize XBOX gamepads.
  70765. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70766. _this.gamepad = gamepad;
  70767. }
  70768. }
  70769. });
  70770. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70771. if (_this.gamepad === gamepad) {
  70772. _this.gamepad = null;
  70773. }
  70774. });
  70775. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70776. };
  70777. FreeCameraGamepadInput.prototype.detachControl = function (element) {
  70778. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70779. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70780. this.gamepad = null;
  70781. };
  70782. FreeCameraGamepadInput.prototype.checkInputs = function () {
  70783. if (this.gamepad && this.gamepad.leftStick) {
  70784. var camera = this.camera;
  70785. var LSValues = this.gamepad.leftStick;
  70786. var normalizedLX = LSValues.x / this.gamepadMoveSensibility;
  70787. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70788. LSValues.x = Math.abs(normalizedLX) > 0.005 ? 0 + normalizedLX : 0;
  70789. LSValues.y = Math.abs(normalizedLY) > 0.005 ? 0 + normalizedLY : 0;
  70790. var RSValues = this.gamepad.rightStick;
  70791. if (RSValues) {
  70792. var normalizedRX = RSValues.x / this.gamepadAngularSensibility;
  70793. var normalizedRY = RSValues.y / this.gamepadAngularSensibility;
  70794. RSValues.x = Math.abs(normalizedRX) > 0.001 ? 0 + normalizedRX : 0;
  70795. RSValues.y = Math.abs(normalizedRY) > 0.001 ? 0 + normalizedRY : 0;
  70796. }
  70797. else {
  70798. RSValues = { x: 0, y: 0 };
  70799. }
  70800. if (!camera.rotationQuaternion) {
  70801. BABYLON.Matrix.RotationYawPitchRollToRef(camera.rotation.y, camera.rotation.x, 0, this._cameraTransform);
  70802. }
  70803. else {
  70804. camera.rotationQuaternion.toRotationMatrix(this._cameraTransform);
  70805. }
  70806. var speed = camera._computeLocalCameraSpeed() * 50.0;
  70807. this._vector3.copyFromFloats(LSValues.x * speed, 0, -LSValues.y * speed);
  70808. BABYLON.Vector3.TransformCoordinatesToRef(this._vector3, this._cameraTransform, this._deltaTransform);
  70809. camera.cameraDirection.addInPlace(this._deltaTransform);
  70810. this._vector2.copyFromFloats(RSValues.y, RSValues.x);
  70811. camera.cameraRotation.addInPlace(this._vector2);
  70812. }
  70813. };
  70814. FreeCameraGamepadInput.prototype.getClassName = function () {
  70815. return "FreeCameraGamepadInput";
  70816. };
  70817. FreeCameraGamepadInput.prototype.getSimpleName = function () {
  70818. return "gamepad";
  70819. };
  70820. __decorate([
  70821. BABYLON.serialize()
  70822. ], FreeCameraGamepadInput.prototype, "gamepadAngularSensibility", void 0);
  70823. __decorate([
  70824. BABYLON.serialize()
  70825. ], FreeCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70826. return FreeCameraGamepadInput;
  70827. }());
  70828. BABYLON.FreeCameraGamepadInput = FreeCameraGamepadInput;
  70829. BABYLON.CameraInputTypes["FreeCameraGamepadInput"] = FreeCameraGamepadInput;
  70830. })(BABYLON || (BABYLON = {}));
  70831. //# sourceMappingURL=babylon.freeCameraGamepadInput.js.map
  70832. var BABYLON;
  70833. (function (BABYLON) {
  70834. var ArcRotateCameraGamepadInput = /** @class */ (function () {
  70835. function ArcRotateCameraGamepadInput() {
  70836. this.gamepadRotationSensibility = 80;
  70837. this.gamepadMoveSensibility = 40;
  70838. }
  70839. ArcRotateCameraGamepadInput.prototype.attachControl = function (element, noPreventDefault) {
  70840. var _this = this;
  70841. var manager = this.camera.getScene().gamepadManager;
  70842. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  70843. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  70844. // prioritize XBOX gamepads.
  70845. if (!_this.gamepad || gamepad.type === BABYLON.Gamepad.XBOX) {
  70846. _this.gamepad = gamepad;
  70847. }
  70848. }
  70849. });
  70850. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  70851. if (_this.gamepad === gamepad) {
  70852. _this.gamepad = null;
  70853. }
  70854. });
  70855. this.gamepad = manager.getGamepadByType(BABYLON.Gamepad.XBOX);
  70856. };
  70857. ArcRotateCameraGamepadInput.prototype.detachControl = function (element) {
  70858. this.camera.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  70859. this.camera.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  70860. this.gamepad = null;
  70861. };
  70862. ArcRotateCameraGamepadInput.prototype.checkInputs = function () {
  70863. if (this.gamepad) {
  70864. var camera = this.camera;
  70865. var RSValues = this.gamepad.rightStick;
  70866. if (RSValues) {
  70867. if (RSValues.x != 0) {
  70868. var normalizedRX = RSValues.x / this.gamepadRotationSensibility;
  70869. if (normalizedRX != 0 && Math.abs(normalizedRX) > 0.005) {
  70870. camera.inertialAlphaOffset += normalizedRX;
  70871. }
  70872. }
  70873. if (RSValues.y != 0) {
  70874. var normalizedRY = RSValues.y / this.gamepadRotationSensibility;
  70875. if (normalizedRY != 0 && Math.abs(normalizedRY) > 0.005) {
  70876. camera.inertialBetaOffset += normalizedRY;
  70877. }
  70878. }
  70879. }
  70880. var LSValues = this.gamepad.leftStick;
  70881. if (LSValues && LSValues.y != 0) {
  70882. var normalizedLY = LSValues.y / this.gamepadMoveSensibility;
  70883. if (normalizedLY != 0 && Math.abs(normalizedLY) > 0.005) {
  70884. this.camera.inertialRadiusOffset -= normalizedLY;
  70885. }
  70886. }
  70887. }
  70888. };
  70889. ArcRotateCameraGamepadInput.prototype.getClassName = function () {
  70890. return "ArcRotateCameraGamepadInput";
  70891. };
  70892. ArcRotateCameraGamepadInput.prototype.getSimpleName = function () {
  70893. return "gamepad";
  70894. };
  70895. __decorate([
  70896. BABYLON.serialize()
  70897. ], ArcRotateCameraGamepadInput.prototype, "gamepadRotationSensibility", void 0);
  70898. __decorate([
  70899. BABYLON.serialize()
  70900. ], ArcRotateCameraGamepadInput.prototype, "gamepadMoveSensibility", void 0);
  70901. return ArcRotateCameraGamepadInput;
  70902. }());
  70903. BABYLON.ArcRotateCameraGamepadInput = ArcRotateCameraGamepadInput;
  70904. BABYLON.CameraInputTypes["ArcRotateCameraGamepadInput"] = ArcRotateCameraGamepadInput;
  70905. })(BABYLON || (BABYLON = {}));
  70906. //# sourceMappingURL=babylon.arcRotateCameraGamepadInput.js.map
  70907. var BABYLON;
  70908. (function (BABYLON) {
  70909. var GamepadManager = /** @class */ (function () {
  70910. function GamepadManager(_scene) {
  70911. var _this = this;
  70912. this._scene = _scene;
  70913. this._babylonGamepads = [];
  70914. this._oneGamepadConnected = false;
  70915. this._isMonitoring = false;
  70916. this.onGamepadDisconnectedObservable = new BABYLON.Observable();
  70917. if (!BABYLON.Tools.IsWindowObjectExist()) {
  70918. this._gamepadEventSupported = false;
  70919. }
  70920. else {
  70921. this._gamepadEventSupported = 'GamepadEvent' in window;
  70922. this._gamepadSupport = (navigator.getGamepads ||
  70923. navigator.webkitGetGamepads || navigator.msGetGamepads || navigator.webkitGamepads);
  70924. }
  70925. this.onGamepadConnectedObservable = new BABYLON.Observable(function (observer) {
  70926. // This will be used to raise the onGamepadConnected for all gamepads ALREADY connected
  70927. for (var i in _this._babylonGamepads) {
  70928. var gamepad = _this._babylonGamepads[i];
  70929. if (gamepad && gamepad._isConnected) {
  70930. _this.onGamepadConnectedObservable.notifyObserver(observer, gamepad);
  70931. }
  70932. }
  70933. });
  70934. this._onGamepadConnectedEvent = function (evt) {
  70935. var gamepad = evt.gamepad;
  70936. if (gamepad.index in _this._babylonGamepads) {
  70937. if (_this._babylonGamepads[gamepad.index].isConnected) {
  70938. return;
  70939. }
  70940. }
  70941. var newGamepad;
  70942. if (_this._babylonGamepads[gamepad.index]) {
  70943. newGamepad = _this._babylonGamepads[gamepad.index];
  70944. newGamepad.browserGamepad = gamepad;
  70945. newGamepad._isConnected = true;
  70946. }
  70947. else {
  70948. newGamepad = _this._addNewGamepad(gamepad);
  70949. }
  70950. _this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  70951. _this._startMonitoringGamepads();
  70952. };
  70953. this._onGamepadDisconnectedEvent = function (evt) {
  70954. var gamepad = evt.gamepad;
  70955. // Remove the gamepad from the list of gamepads to monitor.
  70956. for (var i in _this._babylonGamepads) {
  70957. if (_this._babylonGamepads[i].index === gamepad.index) {
  70958. var disconnectedGamepad = _this._babylonGamepads[i];
  70959. disconnectedGamepad._isConnected = false;
  70960. _this.onGamepadDisconnectedObservable.notifyObservers(disconnectedGamepad);
  70961. break;
  70962. }
  70963. }
  70964. };
  70965. if (this._gamepadSupport) {
  70966. //first add already-connected gamepads
  70967. this._updateGamepadObjects();
  70968. if (this._babylonGamepads.length) {
  70969. this._startMonitoringGamepads();
  70970. }
  70971. // Checking if the gamepad connected event is supported (like in Firefox)
  70972. if (this._gamepadEventSupported) {
  70973. window.addEventListener('gamepadconnected', this._onGamepadConnectedEvent, false);
  70974. window.addEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent, false);
  70975. }
  70976. else {
  70977. this._startMonitoringGamepads();
  70978. }
  70979. }
  70980. }
  70981. Object.defineProperty(GamepadManager.prototype, "gamepads", {
  70982. get: function () {
  70983. return this._babylonGamepads;
  70984. },
  70985. enumerable: true,
  70986. configurable: true
  70987. });
  70988. GamepadManager.prototype.getGamepadByType = function (type) {
  70989. if (type === void 0) { type = BABYLON.Gamepad.XBOX; }
  70990. for (var _i = 0, _a = this._babylonGamepads; _i < _a.length; _i++) {
  70991. var gamepad = _a[_i];
  70992. if (gamepad && gamepad.type === type) {
  70993. return gamepad;
  70994. }
  70995. }
  70996. return null;
  70997. };
  70998. GamepadManager.prototype.dispose = function () {
  70999. if (this._gamepadEventSupported) {
  71000. if (this._onGamepadConnectedEvent) {
  71001. window.removeEventListener('gamepadconnected', this._onGamepadConnectedEvent);
  71002. }
  71003. if (this._onGamepadDisconnectedEvent) {
  71004. window.removeEventListener('gamepaddisconnected', this._onGamepadDisconnectedEvent);
  71005. }
  71006. this._onGamepadConnectedEvent = null;
  71007. this._onGamepadDisconnectedEvent = null;
  71008. }
  71009. this._babylonGamepads.forEach(function (gamepad) {
  71010. gamepad.dispose();
  71011. });
  71012. this.onGamepadConnectedObservable.clear();
  71013. this.onGamepadDisconnectedObservable.clear();
  71014. this._oneGamepadConnected = false;
  71015. this._stopMonitoringGamepads();
  71016. this._babylonGamepads = [];
  71017. };
  71018. GamepadManager.prototype._addNewGamepad = function (gamepad) {
  71019. if (!this._oneGamepadConnected) {
  71020. this._oneGamepadConnected = true;
  71021. }
  71022. var newGamepad;
  71023. var xboxOne = (gamepad.id.search("Xbox One") !== -1);
  71024. if (xboxOne || gamepad.id.search("Xbox 360") !== -1 || gamepad.id.search("xinput") !== -1) {
  71025. newGamepad = new BABYLON.Xbox360Pad(gamepad.id, gamepad.index, gamepad, xboxOne);
  71026. }
  71027. // if pose is supported, use the (WebVR) pose enabled controller
  71028. else if (gamepad.pose) {
  71029. newGamepad = BABYLON.PoseEnabledControllerHelper.InitiateController(gamepad);
  71030. }
  71031. else {
  71032. newGamepad = new BABYLON.GenericPad(gamepad.id, gamepad.index, gamepad);
  71033. }
  71034. this._babylonGamepads[newGamepad.index] = newGamepad;
  71035. return newGamepad;
  71036. };
  71037. GamepadManager.prototype._startMonitoringGamepads = function () {
  71038. if (!this._isMonitoring) {
  71039. this._isMonitoring = true;
  71040. //back-comp
  71041. if (!this._scene) {
  71042. this._checkGamepadsStatus();
  71043. }
  71044. }
  71045. };
  71046. GamepadManager.prototype._stopMonitoringGamepads = function () {
  71047. this._isMonitoring = false;
  71048. };
  71049. GamepadManager.prototype._checkGamepadsStatus = function () {
  71050. var _this = this;
  71051. // Hack to be compatible Chrome
  71052. this._updateGamepadObjects();
  71053. for (var i in this._babylonGamepads) {
  71054. var gamepad = this._babylonGamepads[i];
  71055. if (!gamepad || !gamepad.isConnected) {
  71056. continue;
  71057. }
  71058. gamepad.update();
  71059. }
  71060. if (this._isMonitoring && !this._scene) {
  71061. BABYLON.Tools.QueueNewFrame(function () { _this._checkGamepadsStatus(); });
  71062. }
  71063. };
  71064. // This function is called only on Chrome, which does not properly support
  71065. // connection/disconnection events and forces you to recopy again the gamepad object
  71066. GamepadManager.prototype._updateGamepadObjects = function () {
  71067. var gamepads = navigator.getGamepads ? navigator.getGamepads() : (navigator.webkitGetGamepads ? navigator.webkitGetGamepads() : []);
  71068. for (var i = 0; i < gamepads.length; i++) {
  71069. var gamepad = gamepads[i];
  71070. if (gamepad) {
  71071. if (!this._babylonGamepads[gamepad.index]) {
  71072. var newGamepad = this._addNewGamepad(gamepad);
  71073. this.onGamepadConnectedObservable.notifyObservers(newGamepad);
  71074. }
  71075. else {
  71076. // Forced to copy again this object for Chrome for unknown reason
  71077. this._babylonGamepads[i].browserGamepad = gamepad;
  71078. if (!this._babylonGamepads[i].isConnected) {
  71079. this._babylonGamepads[i]._isConnected = true;
  71080. this.onGamepadConnectedObservable.notifyObservers(this._babylonGamepads[i]);
  71081. }
  71082. }
  71083. }
  71084. }
  71085. };
  71086. return GamepadManager;
  71087. }());
  71088. BABYLON.GamepadManager = GamepadManager;
  71089. })(BABYLON || (BABYLON = {}));
  71090. //# sourceMappingURL=babylon.gamepadManager.js.map
  71091. var BABYLON;
  71092. (function (BABYLON) {
  71093. var StickValues = /** @class */ (function () {
  71094. function StickValues(x, y) {
  71095. this.x = x;
  71096. this.y = y;
  71097. }
  71098. return StickValues;
  71099. }());
  71100. BABYLON.StickValues = StickValues;
  71101. var Gamepad = /** @class */ (function () {
  71102. function Gamepad(id, index, browserGamepad, leftStickX, leftStickY, rightStickX, rightStickY) {
  71103. if (leftStickX === void 0) { leftStickX = 0; }
  71104. if (leftStickY === void 0) { leftStickY = 1; }
  71105. if (rightStickX === void 0) { rightStickX = 2; }
  71106. if (rightStickY === void 0) { rightStickY = 3; }
  71107. this.id = id;
  71108. this.index = index;
  71109. this.browserGamepad = browserGamepad;
  71110. this._isConnected = true;
  71111. this._invertLeftStickY = false;
  71112. this.type = Gamepad.GAMEPAD;
  71113. this._leftStickAxisX = leftStickX;
  71114. this._leftStickAxisY = leftStickY;
  71115. this._rightStickAxisX = rightStickX;
  71116. this._rightStickAxisY = rightStickY;
  71117. if (this.browserGamepad.axes.length >= 2) {
  71118. this._leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71119. }
  71120. if (this.browserGamepad.axes.length >= 4) {
  71121. this._rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71122. }
  71123. }
  71124. Object.defineProperty(Gamepad.prototype, "isConnected", {
  71125. get: function () {
  71126. return this._isConnected;
  71127. },
  71128. enumerable: true,
  71129. configurable: true
  71130. });
  71131. Gamepad.prototype.onleftstickchanged = function (callback) {
  71132. this._onleftstickchanged = callback;
  71133. };
  71134. Gamepad.prototype.onrightstickchanged = function (callback) {
  71135. this._onrightstickchanged = callback;
  71136. };
  71137. Object.defineProperty(Gamepad.prototype, "leftStick", {
  71138. get: function () {
  71139. return this._leftStick;
  71140. },
  71141. set: function (newValues) {
  71142. if (this._onleftstickchanged && (this._leftStick.x !== newValues.x || this._leftStick.y !== newValues.y)) {
  71143. this._onleftstickchanged(newValues);
  71144. }
  71145. this._leftStick = newValues;
  71146. },
  71147. enumerable: true,
  71148. configurable: true
  71149. });
  71150. Object.defineProperty(Gamepad.prototype, "rightStick", {
  71151. get: function () {
  71152. return this._rightStick;
  71153. },
  71154. set: function (newValues) {
  71155. if (this._onrightstickchanged && (this._rightStick.x !== newValues.x || this._rightStick.y !== newValues.y)) {
  71156. this._onrightstickchanged(newValues);
  71157. }
  71158. this._rightStick = newValues;
  71159. },
  71160. enumerable: true,
  71161. configurable: true
  71162. });
  71163. Gamepad.prototype.update = function () {
  71164. if (this._leftStick) {
  71165. this.leftStick = { x: this.browserGamepad.axes[this._leftStickAxisX], y: this.browserGamepad.axes[this._leftStickAxisY] };
  71166. if (this._invertLeftStickY) {
  71167. this.leftStick.y *= -1;
  71168. }
  71169. }
  71170. if (this._rightStick) {
  71171. this.rightStick = { x: this.browserGamepad.axes[this._rightStickAxisX], y: this.browserGamepad.axes[this._rightStickAxisY] };
  71172. }
  71173. };
  71174. Gamepad.prototype.dispose = function () {
  71175. };
  71176. Gamepad.GAMEPAD = 0;
  71177. Gamepad.GENERIC = 1;
  71178. Gamepad.XBOX = 2;
  71179. Gamepad.POSE_ENABLED = 3;
  71180. return Gamepad;
  71181. }());
  71182. BABYLON.Gamepad = Gamepad;
  71183. var GenericPad = /** @class */ (function (_super) {
  71184. __extends(GenericPad, _super);
  71185. function GenericPad(id, index, browserGamepad) {
  71186. var _this = _super.call(this, id, index, browserGamepad) || this;
  71187. _this.onButtonDownObservable = new BABYLON.Observable();
  71188. _this.onButtonUpObservable = new BABYLON.Observable();
  71189. _this.type = Gamepad.GENERIC;
  71190. _this._buttons = new Array(browserGamepad.buttons.length);
  71191. return _this;
  71192. }
  71193. GenericPad.prototype.onbuttondown = function (callback) {
  71194. this._onbuttondown = callback;
  71195. };
  71196. GenericPad.prototype.onbuttonup = function (callback) {
  71197. this._onbuttonup = callback;
  71198. };
  71199. GenericPad.prototype._setButtonValue = function (newValue, currentValue, buttonIndex) {
  71200. if (newValue !== currentValue) {
  71201. if (newValue === 1) {
  71202. if (this._onbuttondown) {
  71203. this._onbuttondown(buttonIndex);
  71204. }
  71205. this.onButtonDownObservable.notifyObservers(buttonIndex);
  71206. }
  71207. if (newValue === 0) {
  71208. if (this._onbuttonup) {
  71209. this._onbuttonup(buttonIndex);
  71210. }
  71211. this.onButtonUpObservable.notifyObservers(buttonIndex);
  71212. }
  71213. }
  71214. return newValue;
  71215. };
  71216. GenericPad.prototype.update = function () {
  71217. _super.prototype.update.call(this);
  71218. for (var index = 0; index < this._buttons.length; index++) {
  71219. this._buttons[index] = this._setButtonValue(this.browserGamepad.buttons[index].value, this._buttons[index], index);
  71220. }
  71221. };
  71222. GenericPad.prototype.dispose = function () {
  71223. _super.prototype.dispose.call(this);
  71224. this.onButtonDownObservable.clear();
  71225. this.onButtonUpObservable.clear();
  71226. };
  71227. return GenericPad;
  71228. }(Gamepad));
  71229. BABYLON.GenericPad = GenericPad;
  71230. })(BABYLON || (BABYLON = {}));
  71231. //# sourceMappingURL=babylon.gamepad.js.map
  71232. var BABYLON;
  71233. (function (BABYLON) {
  71234. /**
  71235. * Defines supported buttons for XBox360 compatible gamepads
  71236. */
  71237. var Xbox360Button;
  71238. (function (Xbox360Button) {
  71239. /** A */
  71240. Xbox360Button[Xbox360Button["A"] = 0] = "A";
  71241. /** B */
  71242. Xbox360Button[Xbox360Button["B"] = 1] = "B";
  71243. /** X */
  71244. Xbox360Button[Xbox360Button["X"] = 2] = "X";
  71245. /** Y */
  71246. Xbox360Button[Xbox360Button["Y"] = 3] = "Y";
  71247. /** Start */
  71248. Xbox360Button[Xbox360Button["Start"] = 4] = "Start";
  71249. /** Back */
  71250. Xbox360Button[Xbox360Button["Back"] = 5] = "Back";
  71251. /** Left button */
  71252. Xbox360Button[Xbox360Button["LB"] = 6] = "LB";
  71253. /** Right button */
  71254. Xbox360Button[Xbox360Button["RB"] = 7] = "RB";
  71255. /** Left stick */
  71256. Xbox360Button[Xbox360Button["LeftStick"] = 8] = "LeftStick";
  71257. /** Right stick */
  71258. Xbox360Button[Xbox360Button["RightStick"] = 9] = "RightStick";
  71259. })(Xbox360Button = BABYLON.Xbox360Button || (BABYLON.Xbox360Button = {}));
  71260. /** Defines values for XBox360 DPad */
  71261. var Xbox360Dpad;
  71262. (function (Xbox360Dpad) {
  71263. /** Up */
  71264. Xbox360Dpad[Xbox360Dpad["Up"] = 0] = "Up";
  71265. /** Down */
  71266. Xbox360Dpad[Xbox360Dpad["Down"] = 1] = "Down";
  71267. /** Left */
  71268. Xbox360Dpad[Xbox360Dpad["Left"] = 2] = "Left";
  71269. /** Right */
  71270. Xbox360Dpad[Xbox360Dpad["Right"] = 3] = "Right";
  71271. })(Xbox360Dpad = BABYLON.Xbox360Dpad || (BABYLON.Xbox360Dpad = {}));
  71272. /**
  71273. * Defines a XBox360 gamepad
  71274. */
  71275. var Xbox360Pad = /** @class */ (function (_super) {
  71276. __extends(Xbox360Pad, _super);
  71277. /**
  71278. * Creates a new XBox360 gamepad object
  71279. * @param id defines the id of this gamepad
  71280. * @param index defines its index
  71281. * @param gamepad defines the internal HTML gamepad object
  71282. * @param xboxOne defines if it is a XBox One gamepad
  71283. */
  71284. function Xbox360Pad(id, index, gamepad, xboxOne) {
  71285. if (xboxOne === void 0) { xboxOne = false; }
  71286. var _this = _super.call(this, id, index, gamepad, 0, 1, 2, 3) || this;
  71287. _this._leftTrigger = 0;
  71288. _this._rightTrigger = 0;
  71289. /** Observable raised when a button is pressed */
  71290. _this.onButtonDownObservable = new BABYLON.Observable();
  71291. /** Observable raised when a button is released */
  71292. _this.onButtonUpObservable = new BABYLON.Observable();
  71293. /** Observable raised when a pad is pressed */
  71294. _this.onPadDownObservable = new BABYLON.Observable();
  71295. /** Observable raised when a pad is released */
  71296. _this.onPadUpObservable = new BABYLON.Observable();
  71297. _this._buttonA = 0;
  71298. _this._buttonB = 0;
  71299. _this._buttonX = 0;
  71300. _this._buttonY = 0;
  71301. _this._buttonBack = 0;
  71302. _this._buttonStart = 0;
  71303. _this._buttonLB = 0;
  71304. _this._buttonRB = 0;
  71305. _this._buttonLeftStick = 0;
  71306. _this._buttonRightStick = 0;
  71307. _this._dPadUp = 0;
  71308. _this._dPadDown = 0;
  71309. _this._dPadLeft = 0;
  71310. _this._dPadRight = 0;
  71311. _this._isXboxOnePad = false;
  71312. _this.type = BABYLON.Gamepad.XBOX;
  71313. _this._isXboxOnePad = xboxOne;
  71314. return _this;
  71315. }
  71316. /**
  71317. * Defines the callback to call when left trigger is pressed
  71318. * @param callback defines the callback to use
  71319. */
  71320. Xbox360Pad.prototype.onlefttriggerchanged = function (callback) {
  71321. this._onlefttriggerchanged = callback;
  71322. };
  71323. /**
  71324. * Defines the callback to call when right trigger is pressed
  71325. * @param callback defines the callback to use
  71326. */
  71327. Xbox360Pad.prototype.onrighttriggerchanged = function (callback) {
  71328. this._onrighttriggerchanged = callback;
  71329. };
  71330. Object.defineProperty(Xbox360Pad.prototype, "leftTrigger", {
  71331. /**
  71332. * Gets or sets left trigger value
  71333. */
  71334. get: function () {
  71335. return this._leftTrigger;
  71336. },
  71337. set: function (newValue) {
  71338. if (this._onlefttriggerchanged && this._leftTrigger !== newValue) {
  71339. this._onlefttriggerchanged(newValue);
  71340. }
  71341. this._leftTrigger = newValue;
  71342. },
  71343. enumerable: true,
  71344. configurable: true
  71345. });
  71346. Object.defineProperty(Xbox360Pad.prototype, "rightTrigger", {
  71347. /**
  71348. * Gets or sets right trigger value
  71349. */
  71350. get: function () {
  71351. return this._rightTrigger;
  71352. },
  71353. set: function (newValue) {
  71354. if (this._onrighttriggerchanged && this._rightTrigger !== newValue) {
  71355. this._onrighttriggerchanged(newValue);
  71356. }
  71357. this._rightTrigger = newValue;
  71358. },
  71359. enumerable: true,
  71360. configurable: true
  71361. });
  71362. /**
  71363. * Defines the callback to call when a button is pressed
  71364. * @param callback defines the callback to use
  71365. */
  71366. Xbox360Pad.prototype.onbuttondown = function (callback) {
  71367. this._onbuttondown = callback;
  71368. };
  71369. /**
  71370. * Defines the callback to call when a button is released
  71371. * @param callback defines the callback to use
  71372. */
  71373. Xbox360Pad.prototype.onbuttonup = function (callback) {
  71374. this._onbuttonup = callback;
  71375. };
  71376. /**
  71377. * Defines the callback to call when a pad is pressed
  71378. * @param callback defines the callback to use
  71379. */
  71380. Xbox360Pad.prototype.ondpaddown = function (callback) {
  71381. this._ondpaddown = callback;
  71382. };
  71383. /**
  71384. * Defines the callback to call when a pad is released
  71385. * @param callback defines the callback to use
  71386. */
  71387. Xbox360Pad.prototype.ondpadup = function (callback) {
  71388. this._ondpadup = callback;
  71389. };
  71390. Xbox360Pad.prototype._setButtonValue = function (newValue, currentValue, buttonType) {
  71391. if (newValue !== currentValue) {
  71392. if (newValue === 1) {
  71393. if (this._onbuttondown) {
  71394. this._onbuttondown(buttonType);
  71395. }
  71396. this.onButtonDownObservable.notifyObservers(buttonType);
  71397. }
  71398. if (newValue === 0) {
  71399. if (this._onbuttonup) {
  71400. this._onbuttonup(buttonType);
  71401. }
  71402. this.onButtonUpObservable.notifyObservers(buttonType);
  71403. }
  71404. }
  71405. return newValue;
  71406. };
  71407. Xbox360Pad.prototype._setDPadValue = function (newValue, currentValue, buttonType) {
  71408. if (newValue !== currentValue) {
  71409. if (newValue === 1) {
  71410. if (this._ondpaddown) {
  71411. this._ondpaddown(buttonType);
  71412. }
  71413. this.onPadDownObservable.notifyObservers(buttonType);
  71414. }
  71415. if (newValue === 0) {
  71416. if (this._ondpadup) {
  71417. this._ondpadup(buttonType);
  71418. }
  71419. this.onPadUpObservable.notifyObservers(buttonType);
  71420. }
  71421. }
  71422. return newValue;
  71423. };
  71424. Object.defineProperty(Xbox360Pad.prototype, "buttonA", {
  71425. /** Gets or sets value of A button */
  71426. get: function () {
  71427. return this._buttonA;
  71428. },
  71429. set: function (value) {
  71430. this._buttonA = this._setButtonValue(value, this._buttonA, Xbox360Button.A);
  71431. },
  71432. enumerable: true,
  71433. configurable: true
  71434. });
  71435. Object.defineProperty(Xbox360Pad.prototype, "buttonB", {
  71436. /** Gets or sets value of B button */
  71437. get: function () {
  71438. return this._buttonB;
  71439. },
  71440. set: function (value) {
  71441. this._buttonB = this._setButtonValue(value, this._buttonB, Xbox360Button.B);
  71442. },
  71443. enumerable: true,
  71444. configurable: true
  71445. });
  71446. Object.defineProperty(Xbox360Pad.prototype, "buttonX", {
  71447. /** Gets or sets value of X button */
  71448. get: function () {
  71449. return this._buttonX;
  71450. },
  71451. set: function (value) {
  71452. this._buttonX = this._setButtonValue(value, this._buttonX, Xbox360Button.X);
  71453. },
  71454. enumerable: true,
  71455. configurable: true
  71456. });
  71457. Object.defineProperty(Xbox360Pad.prototype, "buttonY", {
  71458. /** Gets or sets value of Y button */
  71459. get: function () {
  71460. return this._buttonY;
  71461. },
  71462. set: function (value) {
  71463. this._buttonY = this._setButtonValue(value, this._buttonY, Xbox360Button.Y);
  71464. },
  71465. enumerable: true,
  71466. configurable: true
  71467. });
  71468. Object.defineProperty(Xbox360Pad.prototype, "buttonStart", {
  71469. /** Gets or sets value of Start button */
  71470. get: function () {
  71471. return this._buttonStart;
  71472. },
  71473. set: function (value) {
  71474. this._buttonStart = this._setButtonValue(value, this._buttonStart, Xbox360Button.Start);
  71475. },
  71476. enumerable: true,
  71477. configurable: true
  71478. });
  71479. Object.defineProperty(Xbox360Pad.prototype, "buttonBack", {
  71480. /** Gets or sets value of Back button */
  71481. get: function () {
  71482. return this._buttonBack;
  71483. },
  71484. set: function (value) {
  71485. this._buttonBack = this._setButtonValue(value, this._buttonBack, Xbox360Button.Back);
  71486. },
  71487. enumerable: true,
  71488. configurable: true
  71489. });
  71490. Object.defineProperty(Xbox360Pad.prototype, "buttonLB", {
  71491. /** Gets or sets value of Left button */
  71492. get: function () {
  71493. return this._buttonLB;
  71494. },
  71495. set: function (value) {
  71496. this._buttonLB = this._setButtonValue(value, this._buttonLB, Xbox360Button.LB);
  71497. },
  71498. enumerable: true,
  71499. configurable: true
  71500. });
  71501. Object.defineProperty(Xbox360Pad.prototype, "buttonRB", {
  71502. /** Gets or sets value of Right button */
  71503. get: function () {
  71504. return this._buttonRB;
  71505. },
  71506. set: function (value) {
  71507. this._buttonRB = this._setButtonValue(value, this._buttonRB, Xbox360Button.RB);
  71508. },
  71509. enumerable: true,
  71510. configurable: true
  71511. });
  71512. Object.defineProperty(Xbox360Pad.prototype, "buttonLeftStick", {
  71513. /** Gets or sets value of left stick */
  71514. get: function () {
  71515. return this._buttonLeftStick;
  71516. },
  71517. set: function (value) {
  71518. this._buttonLeftStick = this._setButtonValue(value, this._buttonLeftStick, Xbox360Button.LeftStick);
  71519. },
  71520. enumerable: true,
  71521. configurable: true
  71522. });
  71523. Object.defineProperty(Xbox360Pad.prototype, "buttonRightStick", {
  71524. /** Gets or sets value of right stick */
  71525. get: function () {
  71526. return this._buttonRightStick;
  71527. },
  71528. set: function (value) {
  71529. this._buttonRightStick = this._setButtonValue(value, this._buttonRightStick, Xbox360Button.RightStick);
  71530. },
  71531. enumerable: true,
  71532. configurable: true
  71533. });
  71534. Object.defineProperty(Xbox360Pad.prototype, "dPadUp", {
  71535. /** Gets or sets value of DPad up */
  71536. get: function () {
  71537. return this._dPadUp;
  71538. },
  71539. set: function (value) {
  71540. this._dPadUp = this._setDPadValue(value, this._dPadUp, Xbox360Dpad.Up);
  71541. },
  71542. enumerable: true,
  71543. configurable: true
  71544. });
  71545. Object.defineProperty(Xbox360Pad.prototype, "dPadDown", {
  71546. /** Gets or sets value of DPad down */
  71547. get: function () {
  71548. return this._dPadDown;
  71549. },
  71550. set: function (value) {
  71551. this._dPadDown = this._setDPadValue(value, this._dPadDown, Xbox360Dpad.Down);
  71552. },
  71553. enumerable: true,
  71554. configurable: true
  71555. });
  71556. Object.defineProperty(Xbox360Pad.prototype, "dPadLeft", {
  71557. /** Gets or sets value of DPad left */
  71558. get: function () {
  71559. return this._dPadLeft;
  71560. },
  71561. set: function (value) {
  71562. this._dPadLeft = this._setDPadValue(value, this._dPadLeft, Xbox360Dpad.Left);
  71563. },
  71564. enumerable: true,
  71565. configurable: true
  71566. });
  71567. Object.defineProperty(Xbox360Pad.prototype, "dPadRight", {
  71568. /** Gets or sets value of DPad right */
  71569. get: function () {
  71570. return this._dPadRight;
  71571. },
  71572. set: function (value) {
  71573. this._dPadRight = this._setDPadValue(value, this._dPadRight, Xbox360Dpad.Right);
  71574. },
  71575. enumerable: true,
  71576. configurable: true
  71577. });
  71578. /**
  71579. * Force the gamepad to synchronize with device values
  71580. */
  71581. Xbox360Pad.prototype.update = function () {
  71582. _super.prototype.update.call(this);
  71583. if (this._isXboxOnePad) {
  71584. this.buttonA = this.browserGamepad.buttons[0].value;
  71585. this.buttonB = this.browserGamepad.buttons[1].value;
  71586. this.buttonX = this.browserGamepad.buttons[2].value;
  71587. this.buttonY = this.browserGamepad.buttons[3].value;
  71588. this.buttonLB = this.browserGamepad.buttons[4].value;
  71589. this.buttonRB = this.browserGamepad.buttons[5].value;
  71590. this.leftTrigger = this.browserGamepad.axes[2];
  71591. this.rightTrigger = this.browserGamepad.axes[5];
  71592. this.buttonBack = this.browserGamepad.buttons[9].value;
  71593. this.buttonStart = this.browserGamepad.buttons[8].value;
  71594. this.buttonLeftStick = this.browserGamepad.buttons[6].value;
  71595. this.buttonRightStick = this.browserGamepad.buttons[7].value;
  71596. this.dPadUp = this.browserGamepad.buttons[11].value;
  71597. this.dPadDown = this.browserGamepad.buttons[12].value;
  71598. this.dPadLeft = this.browserGamepad.buttons[13].value;
  71599. this.dPadRight = this.browserGamepad.buttons[14].value;
  71600. }
  71601. else {
  71602. this.buttonA = this.browserGamepad.buttons[0].value;
  71603. this.buttonB = this.browserGamepad.buttons[1].value;
  71604. this.buttonX = this.browserGamepad.buttons[2].value;
  71605. this.buttonY = this.browserGamepad.buttons[3].value;
  71606. this.buttonLB = this.browserGamepad.buttons[4].value;
  71607. this.buttonRB = this.browserGamepad.buttons[5].value;
  71608. this.leftTrigger = this.browserGamepad.buttons[6].value;
  71609. this.rightTrigger = this.browserGamepad.buttons[7].value;
  71610. this.buttonBack = this.browserGamepad.buttons[8].value;
  71611. this.buttonStart = this.browserGamepad.buttons[9].value;
  71612. this.buttonLeftStick = this.browserGamepad.buttons[10].value;
  71613. this.buttonRightStick = this.browserGamepad.buttons[11].value;
  71614. this.dPadUp = this.browserGamepad.buttons[12].value;
  71615. this.dPadDown = this.browserGamepad.buttons[13].value;
  71616. this.dPadLeft = this.browserGamepad.buttons[14].value;
  71617. this.dPadRight = this.browserGamepad.buttons[15].value;
  71618. }
  71619. };
  71620. Xbox360Pad.prototype.dispose = function () {
  71621. _super.prototype.dispose.call(this);
  71622. this.onButtonDownObservable.clear();
  71623. this.onButtonUpObservable.clear();
  71624. this.onPadDownObservable.clear();
  71625. this.onPadUpObservable.clear();
  71626. };
  71627. return Xbox360Pad;
  71628. }(BABYLON.Gamepad));
  71629. BABYLON.Xbox360Pad = Xbox360Pad;
  71630. })(BABYLON || (BABYLON = {}));
  71631. //# sourceMappingURL=babylon.xboxGamepad.js.map
  71632. var BABYLON;
  71633. (function (BABYLON) {
  71634. /**
  71635. * Defines the types of pose enabled controllers that are supported
  71636. */
  71637. var PoseEnabledControllerType;
  71638. (function (PoseEnabledControllerType) {
  71639. /**
  71640. * HTC Vive
  71641. */
  71642. PoseEnabledControllerType[PoseEnabledControllerType["VIVE"] = 0] = "VIVE";
  71643. /**
  71644. * Oculus Rift
  71645. */
  71646. PoseEnabledControllerType[PoseEnabledControllerType["OCULUS"] = 1] = "OCULUS";
  71647. /**
  71648. * Windows mixed reality
  71649. */
  71650. PoseEnabledControllerType[PoseEnabledControllerType["WINDOWS"] = 2] = "WINDOWS";
  71651. /**
  71652. * Samsung gear VR
  71653. */
  71654. PoseEnabledControllerType[PoseEnabledControllerType["GEAR_VR"] = 3] = "GEAR_VR";
  71655. /**
  71656. * Google Daydream
  71657. */
  71658. PoseEnabledControllerType[PoseEnabledControllerType["DAYDREAM"] = 4] = "DAYDREAM";
  71659. /**
  71660. * Generic
  71661. */
  71662. PoseEnabledControllerType[PoseEnabledControllerType["GENERIC"] = 5] = "GENERIC";
  71663. })(PoseEnabledControllerType = BABYLON.PoseEnabledControllerType || (BABYLON.PoseEnabledControllerType = {}));
  71664. /**
  71665. * Defines the PoseEnabledControllerHelper object that is used initialize a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71666. */
  71667. var PoseEnabledControllerHelper = /** @class */ (function () {
  71668. function PoseEnabledControllerHelper() {
  71669. }
  71670. /**
  71671. * Initializes a gamepad as the controller type it is specified as (eg. windows mixed reality controller)
  71672. * @param vrGamepad the gamepad to initialized
  71673. * @returns a vr controller of the type the gamepad identified as
  71674. */
  71675. PoseEnabledControllerHelper.InitiateController = function (vrGamepad) {
  71676. // Oculus Touch
  71677. if (vrGamepad.id.indexOf('Oculus Touch') !== -1) {
  71678. return new BABYLON.OculusTouchController(vrGamepad);
  71679. }
  71680. // Windows Mixed Reality controllers
  71681. else if (vrGamepad.id.indexOf(BABYLON.WindowsMotionController.GAMEPAD_ID_PREFIX) === 0) {
  71682. return new BABYLON.WindowsMotionController(vrGamepad);
  71683. }
  71684. // HTC Vive
  71685. else if (vrGamepad.id.toLowerCase().indexOf('openvr') !== -1) {
  71686. return new BABYLON.ViveController(vrGamepad);
  71687. }
  71688. // Samsung/Oculus Gear VR or Oculus Go
  71689. else if (vrGamepad.id.indexOf(BABYLON.GearVRController.GAMEPAD_ID_PREFIX) === 0 || vrGamepad.id.indexOf('Oculus Go') !== -1) {
  71690. return new BABYLON.GearVRController(vrGamepad);
  71691. }
  71692. // Google Daydream
  71693. else if (vrGamepad.id.indexOf(BABYLON.DaydreamController.GAMEPAD_ID_PREFIX) === 0) {
  71694. return new BABYLON.DaydreamController(vrGamepad);
  71695. }
  71696. // Generic
  71697. else {
  71698. return new BABYLON.GenericController(vrGamepad);
  71699. }
  71700. };
  71701. return PoseEnabledControllerHelper;
  71702. }());
  71703. BABYLON.PoseEnabledControllerHelper = PoseEnabledControllerHelper;
  71704. /**
  71705. * Defines the PoseEnabledController object that contains state of a vr capable controller
  71706. */
  71707. var PoseEnabledController = /** @class */ (function (_super) {
  71708. __extends(PoseEnabledController, _super);
  71709. /**
  71710. * Creates a new PoseEnabledController from a gamepad
  71711. * @param browserGamepad the gamepad that the PoseEnabledController should be created from
  71712. */
  71713. function PoseEnabledController(browserGamepad) {
  71714. var _this = _super.call(this, browserGamepad.id, browserGamepad.index, browserGamepad) || this;
  71715. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  71716. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  71717. _this._deviceRoomRotationQuaternion = new BABYLON.Quaternion();
  71718. /**
  71719. * The device position in babylon space
  71720. */
  71721. _this.devicePosition = BABYLON.Vector3.Zero();
  71722. /**
  71723. * The device rotation in babylon space
  71724. */
  71725. _this.deviceRotationQuaternion = new BABYLON.Quaternion();
  71726. /**
  71727. * The scale factor of the device in babylon space
  71728. */
  71729. _this.deviceScaleFactor = 1;
  71730. _this._leftHandSystemQuaternion = new BABYLON.Quaternion();
  71731. /**
  71732. * Internal, matrix used to convert room space to babylon space
  71733. */
  71734. _this._deviceToWorld = BABYLON.Matrix.Identity();
  71735. /**
  71736. * Node to be used when casting a ray from the controller
  71737. */
  71738. _this._pointingPoseNode = null;
  71739. _this._workingMatrix = BABYLON.Matrix.Identity();
  71740. /**
  71741. * @hidden
  71742. */
  71743. _this._meshAttachedObservable = new BABYLON.Observable();
  71744. _this.type = BABYLON.Gamepad.POSE_ENABLED;
  71745. _this.controllerType = PoseEnabledControllerType.GENERIC;
  71746. _this.position = BABYLON.Vector3.Zero();
  71747. _this.rotationQuaternion = new BABYLON.Quaternion();
  71748. _this._calculatedPosition = BABYLON.Vector3.Zero();
  71749. _this._calculatedRotation = new BABYLON.Quaternion();
  71750. BABYLON.Quaternion.RotationYawPitchRollToRef(Math.PI, 0, 0, _this._leftHandSystemQuaternion);
  71751. return _this;
  71752. }
  71753. /**
  71754. * Updates the state of the pose enbaled controller and mesh based on the current position and rotation of the controller
  71755. */
  71756. PoseEnabledController.prototype.update = function () {
  71757. _super.prototype.update.call(this);
  71758. this._updatePoseAndMesh();
  71759. };
  71760. /**
  71761. * Updates only the pose device and mesh without doing any button event checking
  71762. */
  71763. PoseEnabledController.prototype._updatePoseAndMesh = function () {
  71764. var pose = this.browserGamepad.pose;
  71765. this.updateFromDevice(pose);
  71766. BABYLON.Vector3.TransformCoordinatesToRef(this._calculatedPosition, this._deviceToWorld, this.devicePosition);
  71767. this._deviceToWorld.getRotationMatrixToRef(this._workingMatrix);
  71768. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  71769. this.deviceRotationQuaternion.multiplyInPlace(this._calculatedRotation);
  71770. if (this._mesh) {
  71771. this._mesh.position.copyFrom(this.devicePosition);
  71772. if (this._mesh.rotationQuaternion) {
  71773. this._mesh.rotationQuaternion.copyFrom(this.deviceRotationQuaternion);
  71774. }
  71775. }
  71776. };
  71777. /**
  71778. * Updates the state of the pose enbaled controller based on the raw pose data from the device
  71779. * @param poseData raw pose fromthe device
  71780. */
  71781. PoseEnabledController.prototype.updateFromDevice = function (poseData) {
  71782. if (poseData) {
  71783. this.rawPose = poseData;
  71784. if (poseData.position) {
  71785. this._deviceRoomPosition.copyFromFloats(poseData.position[0], poseData.position[1], -poseData.position[2]);
  71786. if (this._mesh && this._mesh.getScene().useRightHandedSystem) {
  71787. this._deviceRoomPosition.z *= -1;
  71788. }
  71789. this._deviceRoomPosition.scaleToRef(this.deviceScaleFactor, this._calculatedPosition);
  71790. this._calculatedPosition.addInPlace(this.position);
  71791. }
  71792. var pose = this.rawPose;
  71793. if (poseData.orientation && pose.orientation) {
  71794. this._deviceRoomRotationQuaternion.copyFromFloats(pose.orientation[0], pose.orientation[1], -pose.orientation[2], -pose.orientation[3]);
  71795. if (this._mesh) {
  71796. if (this._mesh.getScene().useRightHandedSystem) {
  71797. this._deviceRoomRotationQuaternion.z *= -1;
  71798. this._deviceRoomRotationQuaternion.w *= -1;
  71799. }
  71800. else {
  71801. this._deviceRoomRotationQuaternion.multiplyToRef(this._leftHandSystemQuaternion, this._deviceRoomRotationQuaternion);
  71802. }
  71803. }
  71804. // if the camera is set, rotate to the camera's rotation
  71805. this._deviceRoomRotationQuaternion.multiplyToRef(this.rotationQuaternion, this._calculatedRotation);
  71806. }
  71807. }
  71808. };
  71809. /**
  71810. * Attaches a mesh to the controller
  71811. * @param mesh the mesh to be attached
  71812. */
  71813. PoseEnabledController.prototype.attachToMesh = function (mesh) {
  71814. if (this._mesh) {
  71815. this._mesh.parent = null;
  71816. }
  71817. this._mesh = mesh;
  71818. if (this._poseControlledCamera) {
  71819. this._mesh.parent = this._poseControlledCamera;
  71820. }
  71821. if (!this._mesh.rotationQuaternion) {
  71822. this._mesh.rotationQuaternion = new BABYLON.Quaternion();
  71823. }
  71824. // Sync controller mesh and pointing pose node's state with controller, this is done to avoid a frame where position is 0,0,0 when attaching mesh
  71825. this._updatePoseAndMesh();
  71826. if (this._pointingPoseNode) {
  71827. var parents = [];
  71828. var obj = this._pointingPoseNode;
  71829. while (obj.parent) {
  71830. parents.push(obj.parent);
  71831. obj = obj.parent;
  71832. }
  71833. parents.reverse().forEach(function (p) { p.computeWorldMatrix(true); });
  71834. }
  71835. this._meshAttachedObservable.notifyObservers(mesh);
  71836. };
  71837. /**
  71838. * Attaches the controllers mesh to a camera
  71839. * @param camera the camera the mesh should be attached to
  71840. */
  71841. PoseEnabledController.prototype.attachToPoseControlledCamera = function (camera) {
  71842. this._poseControlledCamera = camera;
  71843. if (this._mesh) {
  71844. this._mesh.parent = this._poseControlledCamera;
  71845. }
  71846. };
  71847. /**
  71848. * Disposes of the controller
  71849. */
  71850. PoseEnabledController.prototype.dispose = function () {
  71851. if (this._mesh) {
  71852. this._mesh.dispose();
  71853. }
  71854. this._mesh = null;
  71855. _super.prototype.dispose.call(this);
  71856. };
  71857. Object.defineProperty(PoseEnabledController.prototype, "mesh", {
  71858. /**
  71859. * The mesh that is attached to the controller
  71860. */
  71861. get: function () {
  71862. return this._mesh;
  71863. },
  71864. enumerable: true,
  71865. configurable: true
  71866. });
  71867. /**
  71868. * Gets the ray of the controller in the direction the controller is pointing
  71869. * @param length the length the resulting ray should be
  71870. * @returns a ray in the direction the controller is pointing
  71871. */
  71872. PoseEnabledController.prototype.getForwardRay = function (length) {
  71873. if (length === void 0) { length = 100; }
  71874. if (!this.mesh) {
  71875. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, 1), length);
  71876. }
  71877. var m = this._pointingPoseNode ? this._pointingPoseNode.getWorldMatrix() : this.mesh.getWorldMatrix();
  71878. var origin = m.getTranslation();
  71879. var forward = new BABYLON.Vector3(0, 0, -1);
  71880. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  71881. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  71882. return new BABYLON.Ray(origin, direction, length);
  71883. };
  71884. /**
  71885. * Name of the child mesh that can be used to cast a ray from the controller
  71886. */
  71887. PoseEnabledController.POINTING_POSE = "POINTING_POSE";
  71888. return PoseEnabledController;
  71889. }(BABYLON.Gamepad));
  71890. BABYLON.PoseEnabledController = PoseEnabledController;
  71891. })(BABYLON || (BABYLON = {}));
  71892. //# sourceMappingURL=babylon.poseEnabledController.js.map
  71893. var BABYLON;
  71894. (function (BABYLON) {
  71895. /**
  71896. * Defines the WebVRController object that represents controllers tracked in 3D space
  71897. */
  71898. var WebVRController = /** @class */ (function (_super) {
  71899. __extends(WebVRController, _super);
  71900. /**
  71901. * Creates a new WebVRController from a gamepad
  71902. * @param vrGamepad the gamepad that the WebVRController should be created from
  71903. */
  71904. function WebVRController(vrGamepad) {
  71905. var _this = _super.call(this, vrGamepad) || this;
  71906. // Observables
  71907. /**
  71908. * Fired when the trigger state has changed
  71909. */
  71910. _this.onTriggerStateChangedObservable = new BABYLON.Observable();
  71911. /**
  71912. * Fired when the main button state has changed
  71913. */
  71914. _this.onMainButtonStateChangedObservable = new BABYLON.Observable();
  71915. /**
  71916. * Fired when the secondary button state has changed
  71917. */
  71918. _this.onSecondaryButtonStateChangedObservable = new BABYLON.Observable();
  71919. /**
  71920. * Fired when the pad state has changed
  71921. */
  71922. _this.onPadStateChangedObservable = new BABYLON.Observable();
  71923. /**
  71924. * Fired when controllers stick values have changed
  71925. */
  71926. _this.onPadValuesChangedObservable = new BABYLON.Observable();
  71927. /**
  71928. * X and Y axis corrisponding to the controllers joystick
  71929. */
  71930. _this.pad = { x: 0, y: 0 };
  71931. // avoid GC, store state in a tmp object
  71932. _this._changes = {
  71933. pressChanged: false,
  71934. touchChanged: false,
  71935. valueChanged: false,
  71936. changed: false
  71937. };
  71938. _this._buttons = new Array(vrGamepad.buttons.length);
  71939. _this.hand = vrGamepad.hand;
  71940. return _this;
  71941. }
  71942. /**
  71943. * Fired when a controller button's state has changed
  71944. * @param callback the callback containing the button that was modified
  71945. */
  71946. WebVRController.prototype.onButtonStateChange = function (callback) {
  71947. this._onButtonStateChange = callback;
  71948. };
  71949. Object.defineProperty(WebVRController.prototype, "defaultModel", {
  71950. /**
  71951. * The default controller model for the controller
  71952. */
  71953. get: function () {
  71954. return this._defaultModel;
  71955. },
  71956. enumerable: true,
  71957. configurable: true
  71958. });
  71959. /**
  71960. * Updates the state of the controller and mesh based on the current position and rotation of the controller
  71961. */
  71962. WebVRController.prototype.update = function () {
  71963. _super.prototype.update.call(this);
  71964. for (var index = 0; index < this._buttons.length; index++) {
  71965. this._setButtonValue(this.browserGamepad.buttons[index], this._buttons[index], index);
  71966. }
  71967. ;
  71968. if (this.leftStick.x !== this.pad.x || this.leftStick.y !== this.pad.y) {
  71969. this.pad.x = this.leftStick.x;
  71970. this.pad.y = this.leftStick.y;
  71971. this.onPadValuesChangedObservable.notifyObservers(this.pad);
  71972. }
  71973. };
  71974. WebVRController.prototype._setButtonValue = function (newState, currentState, buttonIndex) {
  71975. if (!newState) {
  71976. newState = {
  71977. pressed: false,
  71978. touched: false,
  71979. value: 0
  71980. };
  71981. }
  71982. if (!currentState) {
  71983. this._buttons[buttonIndex] = {
  71984. pressed: newState.pressed,
  71985. touched: newState.touched,
  71986. value: newState.value
  71987. };
  71988. return;
  71989. }
  71990. this._checkChanges(newState, currentState);
  71991. if (this._changes.changed) {
  71992. this._onButtonStateChange && this._onButtonStateChange(this.index, buttonIndex, newState);
  71993. this._handleButtonChange(buttonIndex, newState, this._changes);
  71994. }
  71995. this._buttons[buttonIndex].pressed = newState.pressed;
  71996. this._buttons[buttonIndex].touched = newState.touched;
  71997. // oculus triggers are never 0, thou not touched.
  71998. this._buttons[buttonIndex].value = newState.value < 0.00000001 ? 0 : newState.value;
  71999. };
  72000. WebVRController.prototype._checkChanges = function (newState, currentState) {
  72001. this._changes.pressChanged = newState.pressed !== currentState.pressed;
  72002. this._changes.touchChanged = newState.touched !== currentState.touched;
  72003. this._changes.valueChanged = newState.value !== currentState.value;
  72004. this._changes.changed = this._changes.pressChanged || this._changes.touchChanged || this._changes.valueChanged;
  72005. return this._changes;
  72006. };
  72007. /**
  72008. * Disposes of th webVRCOntroller
  72009. */
  72010. WebVRController.prototype.dispose = function () {
  72011. _super.prototype.dispose.call(this);
  72012. this.onTriggerStateChangedObservable.clear();
  72013. this.onMainButtonStateChangedObservable.clear();
  72014. this.onSecondaryButtonStateChangedObservable.clear();
  72015. this.onPadStateChangedObservable.clear();
  72016. this.onPadValuesChangedObservable.clear();
  72017. };
  72018. return WebVRController;
  72019. }(BABYLON.PoseEnabledController));
  72020. BABYLON.WebVRController = WebVRController;
  72021. })(BABYLON || (BABYLON = {}));
  72022. //# sourceMappingURL=babylon.webVRController.js.map
  72023. var BABYLON;
  72024. (function (BABYLON) {
  72025. /**
  72026. * Oculus Touch Controller
  72027. */
  72028. var OculusTouchController = /** @class */ (function (_super) {
  72029. __extends(OculusTouchController, _super);
  72030. /**
  72031. * Creates a new OculusTouchController from a gamepad
  72032. * @param vrGamepad the gamepad that the controller should be created from
  72033. */
  72034. function OculusTouchController(vrGamepad) {
  72035. var _this = _super.call(this, vrGamepad) || this;
  72036. /**
  72037. * Fired when the secondary trigger on this controller is modified
  72038. */
  72039. _this.onSecondaryTriggerStateChangedObservable = new BABYLON.Observable();
  72040. /**
  72041. * Fired when the thumb rest on this controller is modified
  72042. */
  72043. _this.onThumbRestChangedObservable = new BABYLON.Observable();
  72044. _this.controllerType = BABYLON.PoseEnabledControllerType.OCULUS;
  72045. return _this;
  72046. }
  72047. /**
  72048. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72049. * @param scene scene in which to add meshes
  72050. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72051. */
  72052. OculusTouchController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72053. var _this = this;
  72054. var meshName;
  72055. // Hand
  72056. if (this.hand === 'left') {
  72057. meshName = OculusTouchController.MODEL_LEFT_FILENAME;
  72058. }
  72059. else { // Right is the default if no hand is specified
  72060. meshName = OculusTouchController.MODEL_RIGHT_FILENAME;
  72061. }
  72062. BABYLON.SceneLoader.ImportMesh("", OculusTouchController.MODEL_BASE_URL, meshName, scene, function (newMeshes) {
  72063. /*
  72064. Parent Mesh name: oculus_touch_left
  72065. - body
  72066. - trigger
  72067. - thumbstick
  72068. - grip
  72069. - button_y
  72070. - button_x
  72071. - button_enter
  72072. */
  72073. _this._defaultModel = newMeshes[1];
  72074. _this.attachToMesh(_this._defaultModel);
  72075. if (meshLoaded) {
  72076. meshLoaded(_this._defaultModel);
  72077. }
  72078. });
  72079. };
  72080. Object.defineProperty(OculusTouchController.prototype, "onAButtonStateChangedObservable", {
  72081. /**
  72082. * Fired when the A button on this controller is modified
  72083. */
  72084. get: function () {
  72085. if (this.hand === 'right') {
  72086. return this.onMainButtonStateChangedObservable;
  72087. }
  72088. else {
  72089. throw new Error('No A button on left hand');
  72090. }
  72091. },
  72092. enumerable: true,
  72093. configurable: true
  72094. });
  72095. Object.defineProperty(OculusTouchController.prototype, "onBButtonStateChangedObservable", {
  72096. /**
  72097. * Fired when the B button on this controller is modified
  72098. */
  72099. get: function () {
  72100. if (this.hand === 'right') {
  72101. return this.onSecondaryButtonStateChangedObservable;
  72102. }
  72103. else {
  72104. throw new Error('No B button on left hand');
  72105. }
  72106. },
  72107. enumerable: true,
  72108. configurable: true
  72109. });
  72110. Object.defineProperty(OculusTouchController.prototype, "onXButtonStateChangedObservable", {
  72111. /**
  72112. * Fired when the X button on this controller is modified
  72113. */
  72114. get: function () {
  72115. if (this.hand === 'left') {
  72116. return this.onMainButtonStateChangedObservable;
  72117. }
  72118. else {
  72119. throw new Error('No X button on right hand');
  72120. }
  72121. },
  72122. enumerable: true,
  72123. configurable: true
  72124. });
  72125. Object.defineProperty(OculusTouchController.prototype, "onYButtonStateChangedObservable", {
  72126. /**
  72127. * Fired when the Y button on this controller is modified
  72128. */
  72129. get: function () {
  72130. if (this.hand === 'left') {
  72131. return this.onSecondaryButtonStateChangedObservable;
  72132. }
  72133. else {
  72134. throw new Error('No Y button on right hand');
  72135. }
  72136. },
  72137. enumerable: true,
  72138. configurable: true
  72139. });
  72140. /**
  72141. * Called once for each button that changed state since the last frame
  72142. * 0) thumb stick (touch, press, value = pressed (0,1)). value is in this.leftStick
  72143. * 1) index trigger (touch (?), press (only when value > 0.1), value 0 to 1)
  72144. * 2) secondary trigger (same)
  72145. * 3) A (right) X (left), touch, pressed = value
  72146. * 4) B / Y
  72147. * 5) thumb rest
  72148. * @param buttonIdx Which button index changed
  72149. * @param state New state of the button
  72150. * @param changes Which properties on the state changed since last frame
  72151. */
  72152. OculusTouchController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72153. var notifyObject = state; //{ state: state, changes: changes };
  72154. var triggerDirection = this.hand === 'right' ? -1 : 1;
  72155. switch (buttonIdx) {
  72156. case 0:
  72157. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72158. return;
  72159. case 1: // index trigger
  72160. if (this._defaultModel) {
  72161. (this._defaultModel.getChildren()[3]).rotation.x = -notifyObject.value * 0.20;
  72162. (this._defaultModel.getChildren()[3]).position.y = -notifyObject.value * 0.005;
  72163. (this._defaultModel.getChildren()[3]).position.z = -notifyObject.value * 0.005;
  72164. }
  72165. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72166. return;
  72167. case 2: // secondary trigger
  72168. if (this._defaultModel) {
  72169. (this._defaultModel.getChildren()[4]).position.x = triggerDirection * notifyObject.value * 0.0035;
  72170. }
  72171. this.onSecondaryTriggerStateChangedObservable.notifyObservers(notifyObject);
  72172. return;
  72173. case 3:
  72174. if (this._defaultModel) {
  72175. if (notifyObject.pressed) {
  72176. (this._defaultModel.getChildren()[1]).position.y = -0.001;
  72177. }
  72178. else {
  72179. (this._defaultModel.getChildren()[1]).position.y = 0;
  72180. }
  72181. }
  72182. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72183. return;
  72184. case 4:
  72185. if (this._defaultModel) {
  72186. if (notifyObject.pressed) {
  72187. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72188. }
  72189. else {
  72190. (this._defaultModel.getChildren()[2]).position.y = 0;
  72191. }
  72192. }
  72193. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72194. return;
  72195. case 5:
  72196. this.onThumbRestChangedObservable.notifyObservers(notifyObject);
  72197. return;
  72198. }
  72199. };
  72200. /**
  72201. * Base Url for the controller model.
  72202. */
  72203. OculusTouchController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/oculus/';
  72204. /**
  72205. * File name for the left controller model.
  72206. */
  72207. OculusTouchController.MODEL_LEFT_FILENAME = 'left.babylon';
  72208. /**
  72209. * File name for the right controller model.
  72210. */
  72211. OculusTouchController.MODEL_RIGHT_FILENAME = 'right.babylon';
  72212. return OculusTouchController;
  72213. }(BABYLON.WebVRController));
  72214. BABYLON.OculusTouchController = OculusTouchController;
  72215. })(BABYLON || (BABYLON = {}));
  72216. //# sourceMappingURL=babylon.oculusTouchController.js.map
  72217. var BABYLON;
  72218. (function (BABYLON) {
  72219. /**
  72220. * Vive Controller
  72221. */
  72222. var ViveController = /** @class */ (function (_super) {
  72223. __extends(ViveController, _super);
  72224. /**
  72225. * Creates a new ViveController from a gamepad
  72226. * @param vrGamepad the gamepad that the controller should be created from
  72227. */
  72228. function ViveController(vrGamepad) {
  72229. var _this = _super.call(this, vrGamepad) || this;
  72230. _this.controllerType = BABYLON.PoseEnabledControllerType.VIVE;
  72231. _this._invertLeftStickY = true;
  72232. return _this;
  72233. }
  72234. /**
  72235. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72236. * @param scene scene in which to add meshes
  72237. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72238. */
  72239. ViveController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72240. var _this = this;
  72241. BABYLON.SceneLoader.ImportMesh("", ViveController.MODEL_BASE_URL, ViveController.MODEL_FILENAME, scene, function (newMeshes) {
  72242. /*
  72243. Parent Mesh name: ViveWand
  72244. - body
  72245. - r_gripper
  72246. - l_gripper
  72247. - menu_button
  72248. - system_button
  72249. - trackpad
  72250. - trigger
  72251. - LED
  72252. */
  72253. _this._defaultModel = newMeshes[1];
  72254. _this.attachToMesh(_this._defaultModel);
  72255. if (meshLoaded) {
  72256. meshLoaded(_this._defaultModel);
  72257. }
  72258. });
  72259. };
  72260. Object.defineProperty(ViveController.prototype, "onLeftButtonStateChangedObservable", {
  72261. /**
  72262. * Fired when the left button on this controller is modified
  72263. */
  72264. get: function () {
  72265. return this.onMainButtonStateChangedObservable;
  72266. },
  72267. enumerable: true,
  72268. configurable: true
  72269. });
  72270. Object.defineProperty(ViveController.prototype, "onRightButtonStateChangedObservable", {
  72271. /**
  72272. * Fired when the right button on this controller is modified
  72273. */
  72274. get: function () {
  72275. return this.onMainButtonStateChangedObservable;
  72276. },
  72277. enumerable: true,
  72278. configurable: true
  72279. });
  72280. Object.defineProperty(ViveController.prototype, "onMenuButtonStateChangedObservable", {
  72281. /**
  72282. * Fired when the menu button on this controller is modified
  72283. */
  72284. get: function () {
  72285. return this.onSecondaryButtonStateChangedObservable;
  72286. },
  72287. enumerable: true,
  72288. configurable: true
  72289. });
  72290. /**
  72291. * Called once for each button that changed state since the last frame
  72292. * Vive mapping:
  72293. * 0: touchpad
  72294. * 1: trigger
  72295. * 2: left AND right buttons
  72296. * 3: menu button
  72297. * @param buttonIdx Which button index changed
  72298. * @param state New state of the button
  72299. * @param changes Which properties on the state changed since last frame
  72300. */
  72301. ViveController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72302. var notifyObject = state; //{ state: state, changes: changes };
  72303. switch (buttonIdx) {
  72304. case 0:
  72305. this.onPadStateChangedObservable.notifyObservers(notifyObject);
  72306. return;
  72307. case 1: // index trigger
  72308. if (this._defaultModel) {
  72309. (this._defaultModel.getChildren()[6]).rotation.x = -notifyObject.value * 0.15;
  72310. }
  72311. this.onTriggerStateChangedObservable.notifyObservers(notifyObject);
  72312. return;
  72313. case 2: // left AND right button
  72314. this.onMainButtonStateChangedObservable.notifyObservers(notifyObject);
  72315. return;
  72316. case 3:
  72317. if (this._defaultModel) {
  72318. if (notifyObject.pressed) {
  72319. (this._defaultModel.getChildren()[2]).position.y = -0.001;
  72320. }
  72321. else {
  72322. (this._defaultModel.getChildren()[2]).position.y = 0;
  72323. }
  72324. }
  72325. this.onSecondaryButtonStateChangedObservable.notifyObservers(notifyObject);
  72326. return;
  72327. }
  72328. };
  72329. /**
  72330. * Base Url for the controller model.
  72331. */
  72332. ViveController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/vive/';
  72333. /**
  72334. * File name for the controller model.
  72335. */
  72336. ViveController.MODEL_FILENAME = 'wand.babylon';
  72337. return ViveController;
  72338. }(BABYLON.WebVRController));
  72339. BABYLON.ViveController = ViveController;
  72340. })(BABYLON || (BABYLON = {}));
  72341. //# sourceMappingURL=babylon.viveController.js.map
  72342. var BABYLON;
  72343. (function (BABYLON) {
  72344. /**
  72345. * Generic Controller
  72346. */
  72347. var GenericController = /** @class */ (function (_super) {
  72348. __extends(GenericController, _super);
  72349. /**
  72350. * Creates a new GenericController from a gamepad
  72351. * @param vrGamepad the gamepad that the controller should be created from
  72352. */
  72353. function GenericController(vrGamepad) {
  72354. return _super.call(this, vrGamepad) || this;
  72355. }
  72356. /**
  72357. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72358. * @param scene scene in which to add meshes
  72359. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72360. */
  72361. GenericController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72362. var _this = this;
  72363. BABYLON.SceneLoader.ImportMesh("", GenericController.MODEL_BASE_URL, GenericController.MODEL_FILENAME, scene, function (newMeshes) {
  72364. _this._defaultModel = newMeshes[1];
  72365. _this.attachToMesh(_this._defaultModel);
  72366. if (meshLoaded) {
  72367. meshLoaded(_this._defaultModel);
  72368. }
  72369. });
  72370. };
  72371. /**
  72372. * Called once for each button that changed state since the last frame
  72373. * @param buttonIdx Which button index changed
  72374. * @param state New state of the button
  72375. * @param changes Which properties on the state changed since last frame
  72376. */
  72377. GenericController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72378. console.log("Button id: " + buttonIdx + "state: ");
  72379. console.dir(state);
  72380. };
  72381. /**
  72382. * Base Url for the controller model.
  72383. */
  72384. GenericController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72385. /**
  72386. * File name for the controller model.
  72387. */
  72388. GenericController.MODEL_FILENAME = 'generic.babylon';
  72389. return GenericController;
  72390. }(BABYLON.WebVRController));
  72391. BABYLON.GenericController = GenericController;
  72392. })(BABYLON || (BABYLON = {}));
  72393. //# sourceMappingURL=babylon.genericController.js.map
  72394. var BABYLON;
  72395. (function (BABYLON) {
  72396. /**
  72397. * Defines the LoadedMeshInfo object that describes information about the loaded webVR controller mesh
  72398. */
  72399. var LoadedMeshInfo = /** @class */ (function () {
  72400. function LoadedMeshInfo() {
  72401. /**
  72402. * Map of the button meshes contained in the controller
  72403. */
  72404. this.buttonMeshes = {};
  72405. /**
  72406. * Map of the axis meshes contained in the controller
  72407. */
  72408. this.axisMeshes = {};
  72409. }
  72410. return LoadedMeshInfo;
  72411. }());
  72412. /**
  72413. * Defines the WindowsMotionController object that the state of the windows motion controller
  72414. */
  72415. var WindowsMotionController = /** @class */ (function (_super) {
  72416. __extends(WindowsMotionController, _super);
  72417. /**
  72418. * Creates a new WindowsMotionController from a gamepad
  72419. * @param vrGamepad the gamepad that the controller should be created from
  72420. */
  72421. function WindowsMotionController(vrGamepad) {
  72422. var _this = _super.call(this, vrGamepad) || this;
  72423. _this._mapping = {
  72424. // Semantic button names
  72425. buttons: ['thumbstick', 'trigger', 'grip', 'menu', 'trackpad'],
  72426. // A mapping of the button name to glTF model node name
  72427. // that should be transformed by button value.
  72428. buttonMeshNames: {
  72429. 'trigger': 'SELECT',
  72430. 'menu': 'MENU',
  72431. 'grip': 'GRASP',
  72432. 'thumbstick': 'THUMBSTICK_PRESS',
  72433. 'trackpad': 'TOUCHPAD_PRESS'
  72434. },
  72435. // This mapping is used to translate from the Motion Controller to Babylon semantics
  72436. buttonObservableNames: {
  72437. 'trigger': 'onTriggerStateChangedObservable',
  72438. 'menu': 'onSecondaryButtonStateChangedObservable',
  72439. 'grip': 'onMainButtonStateChangedObservable',
  72440. 'thumbstick': 'onPadStateChangedObservable',
  72441. 'trackpad': 'onTrackpadChangedObservable'
  72442. },
  72443. // A mapping of the axis name to glTF model node name
  72444. // that should be transformed by axis value.
  72445. // This array mirrors the browserGamepad.axes array, such that
  72446. // the mesh corresponding to axis 0 is in this array index 0.
  72447. axisMeshNames: [
  72448. 'THUMBSTICK_X',
  72449. 'THUMBSTICK_Y',
  72450. 'TOUCHPAD_TOUCH_X',
  72451. 'TOUCHPAD_TOUCH_Y'
  72452. ],
  72453. pointingPoseMeshName: BABYLON.PoseEnabledController.POINTING_POSE
  72454. };
  72455. /**
  72456. * Fired when the trackpad on this controller is clicked
  72457. */
  72458. _this.onTrackpadChangedObservable = new BABYLON.Observable();
  72459. /**
  72460. * Fired when the trackpad on this controller is modified
  72461. */
  72462. _this.onTrackpadValuesChangedObservable = new BABYLON.Observable();
  72463. /**
  72464. * The current x and y values of this controller's trackpad
  72465. */
  72466. _this.trackpad = { x: 0, y: 0 };
  72467. _this.controllerType = BABYLON.PoseEnabledControllerType.WINDOWS;
  72468. _this._loadedMeshInfo = null;
  72469. return _this;
  72470. }
  72471. Object.defineProperty(WindowsMotionController.prototype, "onTriggerButtonStateChangedObservable", {
  72472. /**
  72473. * Fired when the trigger on this controller is modified
  72474. */
  72475. get: function () {
  72476. return this.onTriggerStateChangedObservable;
  72477. },
  72478. enumerable: true,
  72479. configurable: true
  72480. });
  72481. Object.defineProperty(WindowsMotionController.prototype, "onMenuButtonStateChangedObservable", {
  72482. /**
  72483. * Fired when the menu button on this controller is modified
  72484. */
  72485. get: function () {
  72486. return this.onSecondaryButtonStateChangedObservable;
  72487. },
  72488. enumerable: true,
  72489. configurable: true
  72490. });
  72491. Object.defineProperty(WindowsMotionController.prototype, "onGripButtonStateChangedObservable", {
  72492. /**
  72493. * Fired when the grip button on this controller is modified
  72494. */
  72495. get: function () {
  72496. return this.onMainButtonStateChangedObservable;
  72497. },
  72498. enumerable: true,
  72499. configurable: true
  72500. });
  72501. Object.defineProperty(WindowsMotionController.prototype, "onThumbstickButtonStateChangedObservable", {
  72502. /**
  72503. * Fired when the thumbstick button on this controller is modified
  72504. */
  72505. get: function () {
  72506. return this.onPadStateChangedObservable;
  72507. },
  72508. enumerable: true,
  72509. configurable: true
  72510. });
  72511. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadButtonStateChangedObservable", {
  72512. /**
  72513. * Fired when the touchpad button on this controller is modified
  72514. */
  72515. get: function () {
  72516. return this.onTrackpadChangedObservable;
  72517. },
  72518. enumerable: true,
  72519. configurable: true
  72520. });
  72521. Object.defineProperty(WindowsMotionController.prototype, "onTouchpadValuesChangedObservable", {
  72522. /**
  72523. * Fired when the touchpad values on this controller are modified
  72524. */
  72525. get: function () {
  72526. return this.onTrackpadValuesChangedObservable;
  72527. },
  72528. enumerable: true,
  72529. configurable: true
  72530. });
  72531. WindowsMotionController.prototype._updateTrackpad = function () {
  72532. if (this.browserGamepad.axes && (this.browserGamepad.axes[2] != this.trackpad.x || this.browserGamepad.axes[3] != this.trackpad.y)) {
  72533. this.trackpad.x = this.browserGamepad["axes"][2];
  72534. this.trackpad.y = this.browserGamepad["axes"][3];
  72535. this.onTrackpadValuesChangedObservable.notifyObservers(this.trackpad);
  72536. }
  72537. };
  72538. /**
  72539. * Called once per frame by the engine.
  72540. */
  72541. WindowsMotionController.prototype.update = function () {
  72542. _super.prototype.update.call(this);
  72543. if (this.browserGamepad.axes) {
  72544. this._updateTrackpad();
  72545. // Only need to animate axes if there is a loaded mesh
  72546. if (this._loadedMeshInfo) {
  72547. for (var axis = 0; axis < this._mapping.axisMeshNames.length; axis++) {
  72548. this._lerpAxisTransform(axis, this.browserGamepad.axes[axis]);
  72549. }
  72550. }
  72551. }
  72552. };
  72553. /**
  72554. * Called once for each button that changed state since the last frame
  72555. * @param buttonIdx Which button index changed
  72556. * @param state New state of the button
  72557. * @param changes Which properties on the state changed since last frame
  72558. */
  72559. WindowsMotionController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72560. var buttonName = this._mapping.buttons[buttonIdx];
  72561. if (!buttonName) {
  72562. return;
  72563. }
  72564. // Update the trackpad to ensure trackpad.x/y are accurate during button events between frames
  72565. this._updateTrackpad();
  72566. // Only emit events for buttons that we know how to map from index to name
  72567. var observable = this[(this._mapping.buttonObservableNames)[buttonName]];
  72568. if (observable) {
  72569. observable.notifyObservers(state);
  72570. }
  72571. this._lerpButtonTransform(buttonName, state.value);
  72572. };
  72573. /**
  72574. * Moves the buttons on the controller mesh based on their current state
  72575. * @param buttonName the name of the button to move
  72576. * @param buttonValue the value of the button which determines the buttons new position
  72577. */
  72578. WindowsMotionController.prototype._lerpButtonTransform = function (buttonName, buttonValue) {
  72579. // If there is no loaded mesh, there is nothing to transform.
  72580. if (!this._loadedMeshInfo) {
  72581. return;
  72582. }
  72583. var meshInfo = this._loadedMeshInfo.buttonMeshes[buttonName];
  72584. if (!meshInfo.unpressed.rotationQuaternion || !meshInfo.pressed.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72585. return;
  72586. }
  72587. BABYLON.Quaternion.SlerpToRef(meshInfo.unpressed.rotationQuaternion, meshInfo.pressed.rotationQuaternion, buttonValue, meshInfo.value.rotationQuaternion);
  72588. BABYLON.Vector3.LerpToRef(meshInfo.unpressed.position, meshInfo.pressed.position, buttonValue, meshInfo.value.position);
  72589. };
  72590. /**
  72591. * Moves the axis on the controller mesh based on its current state
  72592. * @param axis the index of the axis
  72593. * @param axisValue the value of the axis which determines the meshes new position
  72594. * @hidden
  72595. */
  72596. WindowsMotionController.prototype._lerpAxisTransform = function (axis, axisValue) {
  72597. if (!this._loadedMeshInfo) {
  72598. return;
  72599. }
  72600. var meshInfo = this._loadedMeshInfo.axisMeshes[axis];
  72601. if (!meshInfo) {
  72602. return;
  72603. }
  72604. if (!meshInfo.min.rotationQuaternion || !meshInfo.max.rotationQuaternion || !meshInfo.value.rotationQuaternion) {
  72605. return;
  72606. }
  72607. // Convert from gamepad value range (-1 to +1) to lerp range (0 to 1)
  72608. var lerpValue = axisValue * 0.5 + 0.5;
  72609. BABYLON.Quaternion.SlerpToRef(meshInfo.min.rotationQuaternion, meshInfo.max.rotationQuaternion, lerpValue, meshInfo.value.rotationQuaternion);
  72610. BABYLON.Vector3.LerpToRef(meshInfo.min.position, meshInfo.max.position, lerpValue, meshInfo.value.position);
  72611. };
  72612. /**
  72613. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72614. * @param scene scene in which to add meshes
  72615. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72616. */
  72617. WindowsMotionController.prototype.initControllerMesh = function (scene, meshLoaded, forceDefault) {
  72618. var _this = this;
  72619. if (forceDefault === void 0) { forceDefault = false; }
  72620. var path;
  72621. var filename;
  72622. // Checking if GLB loader is present
  72623. if (BABYLON.SceneLoader.IsPluginForExtensionAvailable(".glb")) {
  72624. // Determine the device specific folder based on the ID suffix
  72625. var device = 'default';
  72626. if (this.id && !forceDefault) {
  72627. var match = this.id.match(WindowsMotionController.GAMEPAD_ID_PATTERN);
  72628. device = ((match && match[0]) || device);
  72629. }
  72630. // Hand
  72631. if (this.hand === 'left') {
  72632. filename = WindowsMotionController.MODEL_LEFT_FILENAME;
  72633. }
  72634. else { // Right is the default if no hand is specified
  72635. filename = WindowsMotionController.MODEL_RIGHT_FILENAME;
  72636. }
  72637. path = WindowsMotionController.MODEL_BASE_URL + device + '/';
  72638. }
  72639. else {
  72640. BABYLON.Tools.Warn("You need to reference GLTF loader to load Windows Motion Controllers model. Falling back to generic models");
  72641. path = BABYLON.GenericController.MODEL_BASE_URL;
  72642. filename = BABYLON.GenericController.MODEL_FILENAME;
  72643. }
  72644. BABYLON.SceneLoader.ImportMesh("", path, filename, scene, function (meshes) {
  72645. // glTF files successfully loaded from the remote server, now process them to ensure they are in the right format.
  72646. _this._loadedMeshInfo = _this.processModel(scene, meshes);
  72647. if (!_this._loadedMeshInfo) {
  72648. return;
  72649. }
  72650. _this._defaultModel = _this._loadedMeshInfo.rootNode;
  72651. _this.attachToMesh(_this._defaultModel);
  72652. if (meshLoaded) {
  72653. meshLoaded(_this._defaultModel);
  72654. }
  72655. }, null, function (scene, message) {
  72656. BABYLON.Tools.Log(message);
  72657. BABYLON.Tools.Warn('Failed to retrieve controller model from the remote server: ' + path + filename);
  72658. if (!forceDefault) {
  72659. _this.initControllerMesh(scene, meshLoaded, true);
  72660. }
  72661. });
  72662. };
  72663. /**
  72664. * Takes a list of meshes (as loaded from the glTF file) and finds the root node, as well as nodes that
  72665. * can be transformed by button presses and axes values, based on this._mapping.
  72666. *
  72667. * @param scene scene in which the meshes exist
  72668. * @param meshes list of meshes that make up the controller model to process
  72669. * @return structured view of the given meshes, with mapping of buttons and axes to meshes that can be transformed.
  72670. */
  72671. WindowsMotionController.prototype.processModel = function (scene, meshes) {
  72672. var loadedMeshInfo = null;
  72673. // Create a new mesh to contain the glTF hierarchy
  72674. var parentMesh = new BABYLON.Mesh(this.id + " " + this.hand, scene);
  72675. // Find the root node in the loaded glTF scene, and attach it as a child of 'parentMesh'
  72676. var childMesh = null;
  72677. for (var i = 0; i < meshes.length; i++) {
  72678. var mesh = meshes[i];
  72679. if (!mesh.parent) {
  72680. // Exclude controller meshes from picking results
  72681. mesh.isPickable = false;
  72682. // Handle root node, attach to the new parentMesh
  72683. childMesh = mesh;
  72684. break;
  72685. }
  72686. }
  72687. if (childMesh) {
  72688. childMesh.setParent(parentMesh);
  72689. // Create our mesh info. Note that this method will always return non-null.
  72690. loadedMeshInfo = this.createMeshInfo(parentMesh);
  72691. }
  72692. else {
  72693. BABYLON.Tools.Warn('Could not find root node in model file.');
  72694. }
  72695. return loadedMeshInfo;
  72696. };
  72697. WindowsMotionController.prototype.createMeshInfo = function (rootNode) {
  72698. var loadedMeshInfo = new LoadedMeshInfo();
  72699. var i;
  72700. loadedMeshInfo.rootNode = rootNode;
  72701. // Reset the caches
  72702. loadedMeshInfo.buttonMeshes = {};
  72703. loadedMeshInfo.axisMeshes = {};
  72704. // Button Meshes
  72705. for (i = 0; i < this._mapping.buttons.length; i++) {
  72706. var buttonMeshName = this._mapping.buttonMeshNames[this._mapping.buttons[i]];
  72707. if (!buttonMeshName) {
  72708. BABYLON.Tools.Log('Skipping unknown button at index: ' + i + ' with mapped name: ' + this._mapping.buttons[i]);
  72709. continue;
  72710. }
  72711. var buttonMesh = getChildByName(rootNode, buttonMeshName);
  72712. if (!buttonMesh) {
  72713. BABYLON.Tools.Warn('Missing button mesh with name: ' + buttonMeshName);
  72714. continue;
  72715. }
  72716. var buttonMeshInfo = {
  72717. index: i,
  72718. value: getImmediateChildByName(buttonMesh, 'VALUE'),
  72719. pressed: getImmediateChildByName(buttonMesh, 'PRESSED'),
  72720. unpressed: getImmediateChildByName(buttonMesh, 'UNPRESSED')
  72721. };
  72722. if (buttonMeshInfo.value && buttonMeshInfo.pressed && buttonMeshInfo.unpressed) {
  72723. loadedMeshInfo.buttonMeshes[this._mapping.buttons[i]] = buttonMeshInfo;
  72724. }
  72725. else {
  72726. // If we didn't find the mesh, it simply means this button won't have transforms applied as mapped button value changes.
  72727. BABYLON.Tools.Warn('Missing button submesh under mesh with name: ' + buttonMeshName +
  72728. '(VALUE: ' + !!buttonMeshInfo.value +
  72729. ', PRESSED: ' + !!buttonMeshInfo.pressed +
  72730. ', UNPRESSED:' + !!buttonMeshInfo.unpressed +
  72731. ')');
  72732. }
  72733. }
  72734. // Axis Meshes
  72735. for (i = 0; i < this._mapping.axisMeshNames.length; i++) {
  72736. var axisMeshName = this._mapping.axisMeshNames[i];
  72737. if (!axisMeshName) {
  72738. BABYLON.Tools.Log('Skipping unknown axis at index: ' + i);
  72739. continue;
  72740. }
  72741. var axisMesh = getChildByName(rootNode, axisMeshName);
  72742. if (!axisMesh) {
  72743. BABYLON.Tools.Warn('Missing axis mesh with name: ' + axisMeshName);
  72744. continue;
  72745. }
  72746. var axisMeshInfo = {
  72747. index: i,
  72748. value: getImmediateChildByName(axisMesh, 'VALUE'),
  72749. min: getImmediateChildByName(axisMesh, 'MIN'),
  72750. max: getImmediateChildByName(axisMesh, 'MAX')
  72751. };
  72752. if (axisMeshInfo.value && axisMeshInfo.min && axisMeshInfo.max) {
  72753. loadedMeshInfo.axisMeshes[i] = axisMeshInfo;
  72754. }
  72755. else {
  72756. // If we didn't find the mesh, it simply means thit axis won't have transforms applied as mapped axis values change.
  72757. BABYLON.Tools.Warn('Missing axis submesh under mesh with name: ' + axisMeshName +
  72758. '(VALUE: ' + !!axisMeshInfo.value +
  72759. ', MIN: ' + !!axisMeshInfo.min +
  72760. ', MAX:' + !!axisMeshInfo.max +
  72761. ')');
  72762. }
  72763. }
  72764. // Pointing Ray
  72765. loadedMeshInfo.pointingPoseNode = getChildByName(rootNode, this._mapping.pointingPoseMeshName);
  72766. if (!loadedMeshInfo.pointingPoseNode) {
  72767. BABYLON.Tools.Warn('Missing pointing pose mesh with name: ' + this._mapping.pointingPoseMeshName);
  72768. }
  72769. else {
  72770. this._pointingPoseNode = loadedMeshInfo.pointingPoseNode;
  72771. }
  72772. return loadedMeshInfo;
  72773. // Look through all children recursively. This will return null if no mesh exists with the given name.
  72774. function getChildByName(node, name) {
  72775. return node.getChildMeshes(false, function (n) { return n.name === name; })[0];
  72776. }
  72777. // Look through only immediate children. This will return null if no mesh exists with the given name.
  72778. function getImmediateChildByName(node, name) {
  72779. return node.getChildMeshes(true, function (n) { return n.name == name; })[0];
  72780. }
  72781. };
  72782. /**
  72783. * Gets the ray of the controller in the direction the controller is pointing
  72784. * @param length the length the resulting ray should be
  72785. * @returns a ray in the direction the controller is pointing
  72786. */
  72787. WindowsMotionController.prototype.getForwardRay = function (length) {
  72788. if (length === void 0) { length = 100; }
  72789. if (!(this._loadedMeshInfo && this._loadedMeshInfo.pointingPoseNode)) {
  72790. return _super.prototype.getForwardRay.call(this, length);
  72791. }
  72792. var m = this._loadedMeshInfo.pointingPoseNode.getWorldMatrix();
  72793. var origin = m.getTranslation();
  72794. var forward = new BABYLON.Vector3(0, 0, -1);
  72795. var forwardWorld = BABYLON.Vector3.TransformNormal(forward, m);
  72796. var direction = BABYLON.Vector3.Normalize(forwardWorld);
  72797. return new BABYLON.Ray(origin, direction, length);
  72798. };
  72799. /**
  72800. * Disposes of the controller
  72801. */
  72802. WindowsMotionController.prototype.dispose = function () {
  72803. _super.prototype.dispose.call(this);
  72804. this.onTrackpadChangedObservable.clear();
  72805. };
  72806. /**
  72807. * The base url used to load the left and right controller models
  72808. */
  72809. WindowsMotionController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/microsoft/';
  72810. /**
  72811. * The name of the left controller model file
  72812. */
  72813. WindowsMotionController.MODEL_LEFT_FILENAME = 'left.glb';
  72814. /**
  72815. * The name of the right controller model file
  72816. */
  72817. WindowsMotionController.MODEL_RIGHT_FILENAME = 'right.glb';
  72818. /**
  72819. * The controller name prefix for this controller type
  72820. */
  72821. WindowsMotionController.GAMEPAD_ID_PREFIX = 'Spatial Controller (Spatial Interaction Source) ';
  72822. /**
  72823. * The controller id pattern for this controller type
  72824. */
  72825. WindowsMotionController.GAMEPAD_ID_PATTERN = /([0-9a-zA-Z]+-[0-9a-zA-Z]+)$/;
  72826. return WindowsMotionController;
  72827. }(BABYLON.WebVRController));
  72828. BABYLON.WindowsMotionController = WindowsMotionController;
  72829. })(BABYLON || (BABYLON = {}));
  72830. //# sourceMappingURL=babylon.windowsMotionController.js.map
  72831. var BABYLON;
  72832. (function (BABYLON) {
  72833. /**
  72834. * Gear VR Controller
  72835. */
  72836. var GearVRController = /** @class */ (function (_super) {
  72837. __extends(GearVRController, _super);
  72838. /**
  72839. * Creates a new GearVRController from a gamepad
  72840. * @param vrGamepad the gamepad that the controller should be created from
  72841. */
  72842. function GearVRController(vrGamepad) {
  72843. var _this = _super.call(this, vrGamepad) || this;
  72844. _this._buttonIndexToObservableNameMap = [
  72845. 'onTrackpadChangedObservable',
  72846. 'onTriggerStateChangedObservable' // Trigger
  72847. ];
  72848. _this.controllerType = BABYLON.PoseEnabledControllerType.GEAR_VR;
  72849. // Initial starting position defaults to where hand would be (incase of only 3dof controller)
  72850. _this._calculatedPosition = new BABYLON.Vector3(_this.hand == "left" ? -0.15 : 0.15, -0.5, 0.4);
  72851. return _this;
  72852. }
  72853. /**
  72854. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72855. * @param scene scene in which to add meshes
  72856. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72857. */
  72858. GearVRController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72859. var _this = this;
  72860. BABYLON.SceneLoader.ImportMesh("", GearVRController.MODEL_BASE_URL, GearVRController.MODEL_FILENAME, scene, function (newMeshes) {
  72861. _this._defaultModel = newMeshes[1];
  72862. _this.attachToMesh(_this._defaultModel);
  72863. if (meshLoaded) {
  72864. meshLoaded(_this._defaultModel);
  72865. }
  72866. });
  72867. };
  72868. /**
  72869. * Called once for each button that changed state since the last frame
  72870. * @param buttonIdx Which button index changed
  72871. * @param state New state of the button
  72872. * @param changes Which properties on the state changed since last frame
  72873. */
  72874. GearVRController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72875. if (buttonIdx < this._buttonIndexToObservableNameMap.length) {
  72876. var observableName = this._buttonIndexToObservableNameMap[buttonIdx];
  72877. // Only emit events for buttons that we know how to map from index to observable
  72878. var observable = this[observableName];
  72879. if (observable) {
  72880. observable.notifyObservers(state);
  72881. }
  72882. }
  72883. };
  72884. /**
  72885. * Base Url for the controller model.
  72886. */
  72887. GearVRController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72888. /**
  72889. * File name for the controller model.
  72890. */
  72891. GearVRController.MODEL_FILENAME = 'generic.babylon';
  72892. /**
  72893. * Gamepad Id prefix used to identify this controller.
  72894. */
  72895. GearVRController.GAMEPAD_ID_PREFIX = 'Gear VR'; // id is 'Gear VR Controller'
  72896. return GearVRController;
  72897. }(BABYLON.WebVRController));
  72898. BABYLON.GearVRController = GearVRController;
  72899. })(BABYLON || (BABYLON = {}));
  72900. //# sourceMappingURL=babylon.gearVRController.js.map
  72901. var BABYLON;
  72902. (function (BABYLON) {
  72903. /**
  72904. * Google Daydream controller
  72905. */
  72906. var DaydreamController = /** @class */ (function (_super) {
  72907. __extends(DaydreamController, _super);
  72908. /**
  72909. * Creates a new DaydreamController from a gamepad
  72910. * @param vrGamepad the gamepad that the controller should be created from
  72911. */
  72912. function DaydreamController(vrGamepad) {
  72913. var _this = _super.call(this, vrGamepad) || this;
  72914. _this.controllerType = BABYLON.PoseEnabledControllerType.DAYDREAM;
  72915. return _this;
  72916. }
  72917. /**
  72918. * Implements abstract method on WebVRController class, loading controller meshes and calling this.attachToMesh if successful.
  72919. * @param scene scene in which to add meshes
  72920. * @param meshLoaded optional callback function that will be called if the mesh loads successfully.
  72921. */
  72922. DaydreamController.prototype.initControllerMesh = function (scene, meshLoaded) {
  72923. var _this = this;
  72924. BABYLON.SceneLoader.ImportMesh("", DaydreamController.MODEL_BASE_URL, DaydreamController.MODEL_FILENAME, scene, function (newMeshes) {
  72925. _this._defaultModel = newMeshes[1];
  72926. _this.attachToMesh(_this._defaultModel);
  72927. if (meshLoaded) {
  72928. meshLoaded(_this._defaultModel);
  72929. }
  72930. });
  72931. };
  72932. /**
  72933. * Called once for each button that changed state since the last frame
  72934. * @param buttonIdx Which button index changed
  72935. * @param state New state of the button
  72936. * @param changes Which properties on the state changed since last frame
  72937. */
  72938. DaydreamController.prototype._handleButtonChange = function (buttonIdx, state, changes) {
  72939. // Daydream controller only has 1 GamepadButton (on the trackpad).
  72940. if (buttonIdx === 0) {
  72941. var observable = this.onTriggerStateChangedObservable;
  72942. if (observable) {
  72943. observable.notifyObservers(state);
  72944. }
  72945. }
  72946. else {
  72947. // If the app or home buttons are ever made available
  72948. BABYLON.Tools.Warn("Unrecognized Daydream button index: " + buttonIdx);
  72949. }
  72950. };
  72951. /**
  72952. * Base Url for the controller model.
  72953. */
  72954. DaydreamController.MODEL_BASE_URL = 'https://controllers.babylonjs.com/generic/';
  72955. /**
  72956. * File name for the controller model.
  72957. */
  72958. DaydreamController.MODEL_FILENAME = 'generic.babylon';
  72959. /**
  72960. * Gamepad Id prefix used to identify Daydream Controller.
  72961. */
  72962. DaydreamController.GAMEPAD_ID_PREFIX = 'Daydream'; // id is 'Daydream Controller'
  72963. return DaydreamController;
  72964. }(BABYLON.WebVRController));
  72965. BABYLON.DaydreamController = DaydreamController;
  72966. })(BABYLON || (BABYLON = {}));
  72967. //# sourceMappingURL=babylon.daydreamController.js.map
  72968. var BABYLON;
  72969. (function (BABYLON) {
  72970. var FollowCamera = /** @class */ (function (_super) {
  72971. __extends(FollowCamera, _super);
  72972. function FollowCamera(name, position, scene, lockedTarget) {
  72973. if (lockedTarget === void 0) { lockedTarget = null; }
  72974. var _this = _super.call(this, name, position, scene) || this;
  72975. _this.radius = 12;
  72976. _this.rotationOffset = 0;
  72977. _this.heightOffset = 4;
  72978. _this.cameraAcceleration = 0.05;
  72979. _this.maxCameraSpeed = 20;
  72980. _this.lockedTarget = lockedTarget;
  72981. return _this;
  72982. }
  72983. FollowCamera.prototype.getRadians = function (degrees) {
  72984. return degrees * Math.PI / 180;
  72985. };
  72986. FollowCamera.prototype.follow = function (cameraTarget) {
  72987. if (!cameraTarget)
  72988. return;
  72989. var yRotation;
  72990. if (cameraTarget.rotationQuaternion) {
  72991. var rotMatrix = new BABYLON.Matrix();
  72992. cameraTarget.rotationQuaternion.toRotationMatrix(rotMatrix);
  72993. yRotation = Math.atan2(rotMatrix.m[8], rotMatrix.m[10]);
  72994. }
  72995. else {
  72996. yRotation = cameraTarget.rotation.y;
  72997. }
  72998. var radians = this.getRadians(this.rotationOffset) + yRotation;
  72999. var targetPosition = cameraTarget.getAbsolutePosition();
  73000. var targetX = targetPosition.x + Math.sin(radians) * this.radius;
  73001. var targetZ = targetPosition.z + Math.cos(radians) * this.radius;
  73002. var dx = targetX - this.position.x;
  73003. var dy = (targetPosition.y + this.heightOffset) - this.position.y;
  73004. var dz = (targetZ) - this.position.z;
  73005. var vx = dx * this.cameraAcceleration * 2; //this is set to .05
  73006. var vy = dy * this.cameraAcceleration;
  73007. var vz = dz * this.cameraAcceleration * 2;
  73008. if (vx > this.maxCameraSpeed || vx < -this.maxCameraSpeed) {
  73009. vx = vx < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73010. }
  73011. if (vy > this.maxCameraSpeed || vy < -this.maxCameraSpeed) {
  73012. vy = vy < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73013. }
  73014. if (vz > this.maxCameraSpeed || vz < -this.maxCameraSpeed) {
  73015. vz = vz < 1 ? -this.maxCameraSpeed : this.maxCameraSpeed;
  73016. }
  73017. this.position = new BABYLON.Vector3(this.position.x + vx, this.position.y + vy, this.position.z + vz);
  73018. this.setTarget(targetPosition);
  73019. };
  73020. FollowCamera.prototype._checkInputs = function () {
  73021. _super.prototype._checkInputs.call(this);
  73022. if (this.lockedTarget) {
  73023. this.follow(this.lockedTarget);
  73024. }
  73025. };
  73026. FollowCamera.prototype.getClassName = function () {
  73027. return "FollowCamera";
  73028. };
  73029. __decorate([
  73030. BABYLON.serialize()
  73031. ], FollowCamera.prototype, "radius", void 0);
  73032. __decorate([
  73033. BABYLON.serialize()
  73034. ], FollowCamera.prototype, "rotationOffset", void 0);
  73035. __decorate([
  73036. BABYLON.serialize()
  73037. ], FollowCamera.prototype, "heightOffset", void 0);
  73038. __decorate([
  73039. BABYLON.serialize()
  73040. ], FollowCamera.prototype, "cameraAcceleration", void 0);
  73041. __decorate([
  73042. BABYLON.serialize()
  73043. ], FollowCamera.prototype, "maxCameraSpeed", void 0);
  73044. __decorate([
  73045. BABYLON.serializeAsMeshReference("lockedTargetId")
  73046. ], FollowCamera.prototype, "lockedTarget", void 0);
  73047. return FollowCamera;
  73048. }(BABYLON.TargetCamera));
  73049. BABYLON.FollowCamera = FollowCamera;
  73050. var ArcFollowCamera = /** @class */ (function (_super) {
  73051. __extends(ArcFollowCamera, _super);
  73052. function ArcFollowCamera(name, alpha, beta, radius, target, scene) {
  73053. var _this = _super.call(this, name, BABYLON.Vector3.Zero(), scene) || this;
  73054. _this.alpha = alpha;
  73055. _this.beta = beta;
  73056. _this.radius = radius;
  73057. _this.target = target;
  73058. _this._cartesianCoordinates = BABYLON.Vector3.Zero();
  73059. _this.follow();
  73060. return _this;
  73061. }
  73062. ArcFollowCamera.prototype.follow = function () {
  73063. if (!this.target) {
  73064. return;
  73065. }
  73066. this._cartesianCoordinates.x = this.radius * Math.cos(this.alpha) * Math.cos(this.beta);
  73067. this._cartesianCoordinates.y = this.radius * Math.sin(this.beta);
  73068. this._cartesianCoordinates.z = this.radius * Math.sin(this.alpha) * Math.cos(this.beta);
  73069. var targetPosition = this.target.getAbsolutePosition();
  73070. this.position = targetPosition.add(this._cartesianCoordinates);
  73071. this.setTarget(targetPosition);
  73072. };
  73073. ArcFollowCamera.prototype._checkInputs = function () {
  73074. _super.prototype._checkInputs.call(this);
  73075. this.follow();
  73076. };
  73077. ArcFollowCamera.prototype.getClassName = function () {
  73078. return "ArcFollowCamera";
  73079. };
  73080. return ArcFollowCamera;
  73081. }(BABYLON.TargetCamera));
  73082. BABYLON.ArcFollowCamera = ArcFollowCamera;
  73083. })(BABYLON || (BABYLON = {}));
  73084. //# sourceMappingURL=babylon.followCamera.js.map
  73085. var BABYLON;
  73086. (function (BABYLON) {
  73087. // We're mainly based on the logic defined into the FreeCamera code
  73088. var UniversalCamera = /** @class */ (function (_super) {
  73089. __extends(UniversalCamera, _super);
  73090. //-- end properties for backward compatibility for inputs
  73091. function UniversalCamera(name, position, scene) {
  73092. var _this = _super.call(this, name, position, scene) || this;
  73093. _this.inputs.addGamepad();
  73094. return _this;
  73095. }
  73096. Object.defineProperty(UniversalCamera.prototype, "gamepadAngularSensibility", {
  73097. //-- Begin properties for backward compatibility for inputs
  73098. get: function () {
  73099. var gamepad = this.inputs.attached["gamepad"];
  73100. if (gamepad)
  73101. return gamepad.gamepadAngularSensibility;
  73102. return 0;
  73103. },
  73104. set: function (value) {
  73105. var gamepad = this.inputs.attached["gamepad"];
  73106. if (gamepad)
  73107. gamepad.gamepadAngularSensibility = value;
  73108. },
  73109. enumerable: true,
  73110. configurable: true
  73111. });
  73112. Object.defineProperty(UniversalCamera.prototype, "gamepadMoveSensibility", {
  73113. get: function () {
  73114. var gamepad = this.inputs.attached["gamepad"];
  73115. if (gamepad)
  73116. return gamepad.gamepadMoveSensibility;
  73117. return 0;
  73118. },
  73119. set: function (value) {
  73120. var gamepad = this.inputs.attached["gamepad"];
  73121. if (gamepad)
  73122. gamepad.gamepadMoveSensibility = value;
  73123. },
  73124. enumerable: true,
  73125. configurable: true
  73126. });
  73127. UniversalCamera.prototype.getClassName = function () {
  73128. return "UniversalCamera";
  73129. };
  73130. return UniversalCamera;
  73131. }(BABYLON.TouchCamera));
  73132. BABYLON.UniversalCamera = UniversalCamera;
  73133. })(BABYLON || (BABYLON = {}));
  73134. //# sourceMappingURL=babylon.universalCamera.js.map
  73135. var BABYLON;
  73136. (function (BABYLON) {
  73137. // We're mainly based on the logic defined into the FreeCamera code
  73138. var GamepadCamera = /** @class */ (function (_super) {
  73139. __extends(GamepadCamera, _super);
  73140. //-- end properties for backward compatibility for inputs
  73141. function GamepadCamera(name, position, scene) {
  73142. return _super.call(this, name, position, scene) || this;
  73143. }
  73144. Object.defineProperty(GamepadCamera.prototype, "gamepadAngularSensibility", {
  73145. //-- Begin properties for backward compatibility for inputs
  73146. get: function () {
  73147. var gamepad = this.inputs.attached["gamepad"];
  73148. if (gamepad)
  73149. return gamepad.gamepadAngularSensibility;
  73150. return 0;
  73151. },
  73152. set: function (value) {
  73153. var gamepad = this.inputs.attached["gamepad"];
  73154. if (gamepad)
  73155. gamepad.gamepadAngularSensibility = value;
  73156. },
  73157. enumerable: true,
  73158. configurable: true
  73159. });
  73160. Object.defineProperty(GamepadCamera.prototype, "gamepadMoveSensibility", {
  73161. get: function () {
  73162. var gamepad = this.inputs.attached["gamepad"];
  73163. if (gamepad)
  73164. return gamepad.gamepadMoveSensibility;
  73165. return 0;
  73166. },
  73167. set: function (value) {
  73168. var gamepad = this.inputs.attached["gamepad"];
  73169. if (gamepad)
  73170. gamepad.gamepadMoveSensibility = value;
  73171. },
  73172. enumerable: true,
  73173. configurable: true
  73174. });
  73175. GamepadCamera.prototype.getClassName = function () {
  73176. return "GamepadCamera";
  73177. };
  73178. return GamepadCamera;
  73179. }(BABYLON.UniversalCamera));
  73180. BABYLON.GamepadCamera = GamepadCamera;
  73181. })(BABYLON || (BABYLON = {}));
  73182. //# sourceMappingURL=babylon.gamepadCamera.js.map
  73183. var BABYLON;
  73184. (function (BABYLON) {
  73185. var PostProcessRenderPipelineManager = /** @class */ (function () {
  73186. function PostProcessRenderPipelineManager() {
  73187. this._renderPipelines = {};
  73188. }
  73189. PostProcessRenderPipelineManager.prototype.addPipeline = function (renderPipeline) {
  73190. this._renderPipelines[renderPipeline._name] = renderPipeline;
  73191. };
  73192. PostProcessRenderPipelineManager.prototype.attachCamerasToRenderPipeline = function (renderPipelineName, cameras, unique) {
  73193. if (unique === void 0) { unique = false; }
  73194. var renderPipeline = this._renderPipelines[renderPipelineName];
  73195. if (!renderPipeline) {
  73196. return;
  73197. }
  73198. renderPipeline._attachCameras(cameras, unique);
  73199. };
  73200. PostProcessRenderPipelineManager.prototype.detachCamerasFromRenderPipeline = function (renderPipelineName, cameras) {
  73201. var renderPipeline = this._renderPipelines[renderPipelineName];
  73202. if (!renderPipeline) {
  73203. return;
  73204. }
  73205. renderPipeline._detachCameras(cameras);
  73206. };
  73207. PostProcessRenderPipelineManager.prototype.enableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73208. var renderPipeline = this._renderPipelines[renderPipelineName];
  73209. if (!renderPipeline) {
  73210. return;
  73211. }
  73212. renderPipeline._enableEffect(renderEffectName, cameras);
  73213. };
  73214. PostProcessRenderPipelineManager.prototype.disableEffectInPipeline = function (renderPipelineName, renderEffectName, cameras) {
  73215. var renderPipeline = this._renderPipelines[renderPipelineName];
  73216. if (!renderPipeline) {
  73217. return;
  73218. }
  73219. renderPipeline._disableEffect(renderEffectName, cameras);
  73220. };
  73221. PostProcessRenderPipelineManager.prototype.update = function () {
  73222. for (var renderPipelineName in this._renderPipelines) {
  73223. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73224. var pipeline = this._renderPipelines[renderPipelineName];
  73225. if (!pipeline.isSupported) {
  73226. pipeline.dispose();
  73227. delete this._renderPipelines[renderPipelineName];
  73228. }
  73229. else {
  73230. pipeline._update();
  73231. }
  73232. }
  73233. }
  73234. };
  73235. PostProcessRenderPipelineManager.prototype._rebuild = function () {
  73236. for (var renderPipelineName in this._renderPipelines) {
  73237. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73238. var pipeline = this._renderPipelines[renderPipelineName];
  73239. pipeline._rebuild();
  73240. }
  73241. }
  73242. };
  73243. PostProcessRenderPipelineManager.prototype.dispose = function () {
  73244. for (var renderPipelineName in this._renderPipelines) {
  73245. if (this._renderPipelines.hasOwnProperty(renderPipelineName)) {
  73246. var pipeline = this._renderPipelines[renderPipelineName];
  73247. pipeline.dispose();
  73248. }
  73249. }
  73250. };
  73251. return PostProcessRenderPipelineManager;
  73252. }());
  73253. BABYLON.PostProcessRenderPipelineManager = PostProcessRenderPipelineManager;
  73254. })(BABYLON || (BABYLON = {}));
  73255. //# sourceMappingURL=babylon.postProcessRenderPipelineManager.js.map
  73256. var BABYLON;
  73257. (function (BABYLON) {
  73258. /**
  73259. * This represents a set of one or more post processes in Babylon.
  73260. * A post process can be used to apply a shader to a texture after it is rendered.
  73261. * @example https://doc.babylonjs.com/how_to/how_to_use_postprocessrenderpipeline
  73262. */
  73263. var PostProcessRenderEffect = /** @class */ (function () {
  73264. /**
  73265. * Instantiates a post process render effect.
  73266. * A post process can be used to apply a shader to a texture after it is rendered.
  73267. * @param engine The engine the effect is tied to
  73268. * @param name The name of the effect
  73269. * @param getPostProcesses A function that returns a set of post processes which the effect will run in order to be run.
  73270. * @param singleInstance False if this post process can be run on multiple cameras. (default: true)
  73271. */
  73272. function PostProcessRenderEffect(engine, name, getPostProcesses, singleInstance) {
  73273. this._name = name;
  73274. this._singleInstance = singleInstance || true;
  73275. this._getPostProcesses = getPostProcesses;
  73276. this._cameras = {};
  73277. this._indicesForCamera = {};
  73278. this._postProcesses = {};
  73279. }
  73280. Object.defineProperty(PostProcessRenderEffect.prototype, "isSupported", {
  73281. /**
  73282. * Checks if all the post processes in the effect are supported.
  73283. */
  73284. get: function () {
  73285. for (var index in this._postProcesses) {
  73286. if (this._postProcesses.hasOwnProperty(index)) {
  73287. var pps = this._postProcesses[index];
  73288. for (var ppIndex = 0; ppIndex < pps.length; ppIndex++) {
  73289. if (!pps[ppIndex].isSupported) {
  73290. return false;
  73291. }
  73292. }
  73293. }
  73294. }
  73295. return true;
  73296. },
  73297. enumerable: true,
  73298. configurable: true
  73299. });
  73300. /**
  73301. * Updates the current state of the effect
  73302. */
  73303. PostProcessRenderEffect.prototype._update = function () {
  73304. };
  73305. /**
  73306. * Attaches the effect on cameras
  73307. * @param cameras The camera to attach to.
  73308. */
  73309. PostProcessRenderEffect.prototype._attachCameras = function (cameras) {
  73310. var _this = this;
  73311. var cameraKey;
  73312. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73313. if (!cams) {
  73314. return;
  73315. }
  73316. for (var i = 0; i < cams.length; i++) {
  73317. var camera = cams[i];
  73318. var cameraName = camera.name;
  73319. if (this._singleInstance) {
  73320. cameraKey = 0;
  73321. }
  73322. else {
  73323. cameraKey = cameraName;
  73324. }
  73325. if (!this._postProcesses[cameraKey]) {
  73326. var postProcess = this._getPostProcesses();
  73327. if (postProcess) {
  73328. this._postProcesses[cameraKey] = Array.isArray(postProcess) ? postProcess : [postProcess];
  73329. }
  73330. }
  73331. if (!this._indicesForCamera[cameraName]) {
  73332. this._indicesForCamera[cameraName] = [];
  73333. }
  73334. this._postProcesses[cameraKey].forEach(function (postProcess) {
  73335. var index = camera.attachPostProcess(postProcess);
  73336. _this._indicesForCamera[cameraName].push(index);
  73337. });
  73338. if (!this._cameras[cameraName]) {
  73339. this._cameras[cameraName] = camera;
  73340. }
  73341. }
  73342. };
  73343. /**
  73344. * Detatches the effect on cameras
  73345. * @param cameras The camera to detatch from.
  73346. */
  73347. PostProcessRenderEffect.prototype._detachCameras = function (cameras) {
  73348. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73349. if (!cams) {
  73350. return;
  73351. }
  73352. for (var i = 0; i < cams.length; i++) {
  73353. var camera = cams[i];
  73354. var cameraName = camera.name;
  73355. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73356. camera.detachPostProcess(postProcess);
  73357. });
  73358. if (this._cameras[cameraName]) {
  73359. //this._indicesForCamera.splice(index, 1);
  73360. this._cameras[cameraName] = null;
  73361. }
  73362. }
  73363. };
  73364. /**
  73365. * Enables the effect on given cameras
  73366. * @param cameras The camera to enable.
  73367. */
  73368. PostProcessRenderEffect.prototype._enable = function (cameras) {
  73369. var _this = this;
  73370. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73371. if (!cams) {
  73372. return;
  73373. }
  73374. for (var i = 0; i < cams.length; i++) {
  73375. var camera = cams[i];
  73376. var cameraName = camera.name;
  73377. for (var j = 0; j < this._indicesForCamera[cameraName].length; j++) {
  73378. if (camera._postProcesses[this._indicesForCamera[cameraName][j]] === undefined || camera._postProcesses[this._indicesForCamera[cameraName][j]] === null) {
  73379. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73380. cams[i].attachPostProcess(postProcess, _this._indicesForCamera[cameraName][j]);
  73381. });
  73382. }
  73383. }
  73384. }
  73385. };
  73386. /**
  73387. * Disables the effect on the given cameras
  73388. * @param cameras The camera to disable.
  73389. */
  73390. PostProcessRenderEffect.prototype._disable = function (cameras) {
  73391. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73392. if (!cams) {
  73393. return;
  73394. }
  73395. for (var i = 0; i < cams.length; i++) {
  73396. var camera = cams[i];
  73397. var cameraName = camera.name;
  73398. this._postProcesses[this._singleInstance ? 0 : cameraName].forEach(function (postProcess) {
  73399. camera.detachPostProcess(postProcess);
  73400. });
  73401. }
  73402. };
  73403. /**
  73404. * Gets a list of the post processes contained in the effect.
  73405. * @param camera The camera to get the post processes on.
  73406. * @returns The list of the post processes in the effect.
  73407. */
  73408. PostProcessRenderEffect.prototype.getPostProcesses = function (camera) {
  73409. if (this._singleInstance) {
  73410. return this._postProcesses[0];
  73411. }
  73412. else {
  73413. if (!camera) {
  73414. return null;
  73415. }
  73416. return this._postProcesses[camera.name];
  73417. }
  73418. };
  73419. return PostProcessRenderEffect;
  73420. }());
  73421. BABYLON.PostProcessRenderEffect = PostProcessRenderEffect;
  73422. })(BABYLON || (BABYLON = {}));
  73423. //# sourceMappingURL=babylon.postProcessRenderEffect.js.map
  73424. var BABYLON;
  73425. (function (BABYLON) {
  73426. var PostProcessRenderPipeline = /** @class */ (function () {
  73427. function PostProcessRenderPipeline(engine, name) {
  73428. this.engine = engine;
  73429. this._name = name;
  73430. this._renderEffects = {};
  73431. this._renderEffectsForIsolatedPass = new Array();
  73432. this._cameras = [];
  73433. }
  73434. PostProcessRenderPipeline.prototype.getClassName = function () {
  73435. return "PostProcessRenderPipeline";
  73436. };
  73437. Object.defineProperty(PostProcessRenderPipeline.prototype, "isSupported", {
  73438. get: function () {
  73439. for (var renderEffectName in this._renderEffects) {
  73440. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73441. if (!this._renderEffects[renderEffectName].isSupported) {
  73442. return false;
  73443. }
  73444. }
  73445. }
  73446. return true;
  73447. },
  73448. enumerable: true,
  73449. configurable: true
  73450. });
  73451. PostProcessRenderPipeline.prototype.addEffect = function (renderEffect) {
  73452. this._renderEffects[renderEffect._name] = renderEffect;
  73453. };
  73454. // private
  73455. PostProcessRenderPipeline.prototype._rebuild = function () {
  73456. };
  73457. PostProcessRenderPipeline.prototype._enableEffect = function (renderEffectName, cameras) {
  73458. var renderEffects = this._renderEffects[renderEffectName];
  73459. if (!renderEffects) {
  73460. return;
  73461. }
  73462. renderEffects._enable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73463. };
  73464. PostProcessRenderPipeline.prototype._disableEffect = function (renderEffectName, cameras) {
  73465. var renderEffects = this._renderEffects[renderEffectName];
  73466. if (!renderEffects) {
  73467. return;
  73468. }
  73469. renderEffects._disable(BABYLON.Tools.MakeArray(cameras || this._cameras));
  73470. };
  73471. PostProcessRenderPipeline.prototype._attachCameras = function (cameras, unique) {
  73472. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73473. if (!cams) {
  73474. return;
  73475. }
  73476. var indicesToDelete = [];
  73477. var i;
  73478. for (i = 0; i < cams.length; i++) {
  73479. var camera = cams[i];
  73480. var cameraName = camera.name;
  73481. if (this._cameras.indexOf(camera) === -1) {
  73482. this._cameras[cameraName] = camera;
  73483. }
  73484. else if (unique) {
  73485. indicesToDelete.push(i);
  73486. }
  73487. }
  73488. for (i = 0; i < indicesToDelete.length; i++) {
  73489. cameras.splice(indicesToDelete[i], 1);
  73490. }
  73491. for (var renderEffectName in this._renderEffects) {
  73492. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73493. this._renderEffects[renderEffectName]._attachCameras(cams);
  73494. }
  73495. }
  73496. };
  73497. PostProcessRenderPipeline.prototype._detachCameras = function (cameras) {
  73498. var cams = BABYLON.Tools.MakeArray(cameras || this._cameras);
  73499. if (!cams) {
  73500. return;
  73501. }
  73502. for (var renderEffectName in this._renderEffects) {
  73503. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73504. this._renderEffects[renderEffectName]._detachCameras(cams);
  73505. }
  73506. }
  73507. for (var i = 0; i < cams.length; i++) {
  73508. this._cameras.splice(this._cameras.indexOf(cams[i]), 1);
  73509. }
  73510. };
  73511. PostProcessRenderPipeline.prototype._update = function () {
  73512. for (var renderEffectName in this._renderEffects) {
  73513. if (this._renderEffects.hasOwnProperty(renderEffectName)) {
  73514. this._renderEffects[renderEffectName]._update();
  73515. }
  73516. }
  73517. for (var i = 0; i < this._cameras.length; i++) {
  73518. var cameraName = this._cameras[i].name;
  73519. if (this._renderEffectsForIsolatedPass[cameraName]) {
  73520. this._renderEffectsForIsolatedPass[cameraName]._update();
  73521. }
  73522. }
  73523. };
  73524. PostProcessRenderPipeline.prototype._reset = function () {
  73525. this._renderEffects = {};
  73526. this._renderEffectsForIsolatedPass = new Array();
  73527. };
  73528. PostProcessRenderPipeline.prototype._enableMSAAOnFirstPostProcess = function (sampleCount) {
  73529. // 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)
  73530. var effectKeys = Object.keys(this._renderEffects);
  73531. if (this.engine.webGLVersion >= 2 && effectKeys.length > 0) {
  73532. var postProcesses = this._renderEffects[effectKeys[0]].getPostProcesses();
  73533. if (postProcesses) {
  73534. postProcesses[0].samples = sampleCount;
  73535. return true;
  73536. }
  73537. }
  73538. return false;
  73539. };
  73540. PostProcessRenderPipeline.prototype.dispose = function () {
  73541. // Must be implemented by children
  73542. };
  73543. __decorate([
  73544. BABYLON.serialize()
  73545. ], PostProcessRenderPipeline.prototype, "_name", void 0);
  73546. return PostProcessRenderPipeline;
  73547. }());
  73548. BABYLON.PostProcessRenderPipeline = PostProcessRenderPipeline;
  73549. })(BABYLON || (BABYLON = {}));
  73550. //# sourceMappingURL=babylon.postProcessRenderPipeline.js.map
  73551. var BABYLON;
  73552. (function (BABYLON) {
  73553. /**
  73554. * This represents a depth renderer in Babylon.
  73555. * A depth renderer will render to it's depth map every frame which can be displayed or used in post processing
  73556. */
  73557. var DepthRenderer = /** @class */ (function () {
  73558. /**
  73559. * Instantiates a depth renderer
  73560. * @param scene The scene the renderer belongs to
  73561. * @param type The texture type of the depth map (default: Engine.TEXTURETYPE_FLOAT)
  73562. * @param camera The camera to be used to render the depth map (default: scene's active camera)
  73563. */
  73564. function DepthRenderer(scene, type, camera) {
  73565. if (type === void 0) { type = BABYLON.Engine.TEXTURETYPE_FLOAT; }
  73566. if (camera === void 0) { camera = null; }
  73567. var _this = this;
  73568. this._scene = scene;
  73569. this._camera = camera;
  73570. var engine = scene.getEngine();
  73571. // Render target
  73572. this._depthMap = new BABYLON.RenderTargetTexture("depthMap", { width: engine.getRenderWidth(), height: engine.getRenderHeight() }, this._scene, false, true, type);
  73573. this._depthMap.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73574. this._depthMap.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  73575. this._depthMap.refreshRate = 1;
  73576. this._depthMap.renderParticles = false;
  73577. this._depthMap.renderList = null;
  73578. // Camera to get depth map from to support multiple concurrent cameras
  73579. this._depthMap.activeCamera = this._camera;
  73580. this._depthMap.ignoreCameraViewport = true;
  73581. this._depthMap.useCameraPostProcesses = false;
  73582. // set default depth value to 1.0 (far away)
  73583. this._depthMap.onClearObservable.add(function (engine) {
  73584. engine.clear(new BABYLON.Color4(1.0, 1.0, 1.0, 1.0), true, true, true);
  73585. });
  73586. // Custom render function
  73587. var renderSubMesh = function (subMesh) {
  73588. var mesh = subMesh.getRenderingMesh();
  73589. var scene = _this._scene;
  73590. var engine = scene.getEngine();
  73591. var material = subMesh.getMaterial();
  73592. if (!material) {
  73593. return;
  73594. }
  73595. // Culling and reverse (right handed system)
  73596. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  73597. // Managing instances
  73598. var batch = mesh._getInstancesRenderList(subMesh._id);
  73599. if (batch.mustReturn) {
  73600. return;
  73601. }
  73602. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  73603. var camera = _this._camera || scene.activeCamera;
  73604. if (_this.isReady(subMesh, hardwareInstancedRendering) && camera) {
  73605. engine.enableEffect(_this._effect);
  73606. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  73607. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  73608. _this._effect.setFloat2("depthValues", camera.minZ, camera.minZ + camera.maxZ);
  73609. // Alpha test
  73610. if (material && material.needAlphaTesting()) {
  73611. var alphaTexture = material.getAlphaTestTexture();
  73612. if (alphaTexture) {
  73613. _this._effect.setTexture("diffuseSampler", alphaTexture);
  73614. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  73615. }
  73616. }
  73617. // Bones
  73618. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  73619. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  73620. }
  73621. // Draw
  73622. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  73623. }
  73624. };
  73625. this._depthMap.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  73626. var index;
  73627. if (depthOnlySubMeshes.length) {
  73628. engine.setColorWrite(false);
  73629. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  73630. renderSubMesh(depthOnlySubMeshes.data[index]);
  73631. }
  73632. engine.setColorWrite(true);
  73633. }
  73634. for (index = 0; index < opaqueSubMeshes.length; index++) {
  73635. renderSubMesh(opaqueSubMeshes.data[index]);
  73636. }
  73637. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  73638. renderSubMesh(alphaTestSubMeshes.data[index]);
  73639. }
  73640. };
  73641. }
  73642. /**
  73643. * Creates the depth rendering effect and checks if the effect is ready.
  73644. * @param subMesh The submesh to be used to render the depth map of
  73645. * @param useInstances If multiple world instances should be used
  73646. * @returns if the depth renderer is ready to render the depth map
  73647. */
  73648. DepthRenderer.prototype.isReady = function (subMesh, useInstances) {
  73649. var material = subMesh.getMaterial();
  73650. if (material.disableDepthWrite) {
  73651. return false;
  73652. }
  73653. var defines = [];
  73654. var attribs = [BABYLON.VertexBuffer.PositionKind];
  73655. var mesh = subMesh.getMesh();
  73656. // Alpha test
  73657. if (material && material.needAlphaTesting() && material.getAlphaTestTexture()) {
  73658. defines.push("#define ALPHATEST");
  73659. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  73660. attribs.push(BABYLON.VertexBuffer.UVKind);
  73661. defines.push("#define UV1");
  73662. }
  73663. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  73664. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  73665. defines.push("#define UV2");
  73666. }
  73667. }
  73668. // Bones
  73669. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  73670. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  73671. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  73672. if (mesh.numBoneInfluencers > 4) {
  73673. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  73674. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  73675. }
  73676. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  73677. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  73678. }
  73679. else {
  73680. defines.push("#define NUM_BONE_INFLUENCERS 0");
  73681. }
  73682. // Instances
  73683. if (useInstances) {
  73684. defines.push("#define INSTANCES");
  73685. attribs.push("world0");
  73686. attribs.push("world1");
  73687. attribs.push("world2");
  73688. attribs.push("world3");
  73689. }
  73690. // Get correct effect
  73691. var join = defines.join("\n");
  73692. if (this._cachedDefines !== join) {
  73693. this._cachedDefines = join;
  73694. this._effect = this._scene.getEngine().createEffect("depth", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "depthValues"], ["diffuseSampler"], join);
  73695. }
  73696. return this._effect.isReady();
  73697. };
  73698. /**
  73699. * Gets the texture which the depth map will be written to.
  73700. * @returns The depth map texture
  73701. */
  73702. DepthRenderer.prototype.getDepthMap = function () {
  73703. return this._depthMap;
  73704. };
  73705. /**
  73706. * Disposes of the depth renderer.
  73707. */
  73708. DepthRenderer.prototype.dispose = function () {
  73709. this._depthMap.dispose();
  73710. };
  73711. return DepthRenderer;
  73712. }());
  73713. BABYLON.DepthRenderer = DepthRenderer;
  73714. })(BABYLON || (BABYLON = {}));
  73715. //# sourceMappingURL=babylon.depthRenderer.js.map
  73716. var BABYLON;
  73717. (function (BABYLON) {
  73718. var SSAORenderingPipeline = /** @class */ (function (_super) {
  73719. __extends(SSAORenderingPipeline, _super);
  73720. /**
  73721. * @constructor
  73722. * @param {string} name - The rendering pipeline name
  73723. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73724. * @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 }
  73725. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73726. */
  73727. function SSAORenderingPipeline(name, scene, ratio, cameras) {
  73728. var _this = _super.call(this, scene.getEngine(), name) || this;
  73729. // Members
  73730. /**
  73731. * The PassPostProcess id in the pipeline that contains the original scene color
  73732. */
  73733. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73734. /**
  73735. * The SSAO PostProcess id in the pipeline
  73736. */
  73737. _this.SSAORenderEffect = "SSAORenderEffect";
  73738. /**
  73739. * The horizontal blur PostProcess id in the pipeline
  73740. */
  73741. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73742. /**
  73743. * The vertical blur PostProcess id in the pipeline
  73744. */
  73745. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73746. /**
  73747. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73748. */
  73749. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73750. /**
  73751. * The output strength of the SSAO post-process. Default value is 1.0.
  73752. */
  73753. _this.totalStrength = 1.0;
  73754. /**
  73755. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 0.0006
  73756. */
  73757. _this.radius = 0.0001;
  73758. /**
  73759. * Related to fallOff, used to interpolate SSAO samples (first interpolate function input) based on the occlusion difference of each pixel
  73760. * Must not be equal to fallOff and superior to fallOff.
  73761. * Default value is 0.975
  73762. */
  73763. _this.area = 0.0075;
  73764. /**
  73765. * Related to area, used to interpolate SSAO samples (second interpolate function input) based on the occlusion difference of each pixel
  73766. * Must not be equal to area and inferior to area.
  73767. * Default value is 0.0
  73768. */
  73769. _this.fallOff = 0.000001;
  73770. /**
  73771. * The base color of the SSAO post-process
  73772. * The final result is "base + ssao" between [0, 1]
  73773. */
  73774. _this.base = 0.5;
  73775. _this._firstUpdate = true;
  73776. _this._scene = scene;
  73777. // Set up assets
  73778. _this._createRandomTexture();
  73779. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  73780. var ssaoRatio = ratio.ssaoRatio || ratio;
  73781. var combineRatio = ratio.combineRatio || ratio;
  73782. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", combineRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  73783. _this._createSSAOPostProcess(ssaoRatio);
  73784. _this._createBlurPostProcess(ssaoRatio);
  73785. _this._createSSAOCombinePostProcess(combineRatio);
  73786. // Set up pipeline
  73787. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  73788. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  73789. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  73790. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  73791. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  73792. // Finish
  73793. scene.postProcessRenderPipelineManager.addPipeline(_this);
  73794. if (cameras)
  73795. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  73796. return _this;
  73797. }
  73798. // Public Methods
  73799. /**
  73800. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  73801. */
  73802. SSAORenderingPipeline.prototype.dispose = function (disableDepthRender) {
  73803. if (disableDepthRender === void 0) { disableDepthRender = false; }
  73804. for (var i = 0; i < this._scene.cameras.length; i++) {
  73805. var camera = this._scene.cameras[i];
  73806. this._originalColorPostProcess.dispose(camera);
  73807. this._ssaoPostProcess.dispose(camera);
  73808. this._blurHPostProcess.dispose(camera);
  73809. this._blurVPostProcess.dispose(camera);
  73810. this._ssaoCombinePostProcess.dispose(camera);
  73811. }
  73812. this._randomTexture.dispose();
  73813. if (disableDepthRender)
  73814. this._scene.disableDepthRenderer();
  73815. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  73816. _super.prototype.dispose.call(this);
  73817. };
  73818. // Private Methods
  73819. SSAORenderingPipeline.prototype._createBlurPostProcess = function (ratio) {
  73820. var _this = this;
  73821. var size = 16;
  73822. 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);
  73823. 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);
  73824. this._blurHPostProcess.onActivateObservable.add(function () {
  73825. var dw = _this._blurHPostProcess.width / _this._scene.getEngine().getRenderWidth();
  73826. _this._blurHPostProcess.kernel = size * dw;
  73827. });
  73828. this._blurVPostProcess.onActivateObservable.add(function () {
  73829. var dw = _this._blurVPostProcess.height / _this._scene.getEngine().getRenderHeight();
  73830. _this._blurVPostProcess.kernel = size * dw;
  73831. });
  73832. };
  73833. SSAORenderingPipeline.prototype._rebuild = function () {
  73834. this._firstUpdate = true;
  73835. _super.prototype._rebuild.call(this);
  73836. };
  73837. SSAORenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  73838. var _this = this;
  73839. var numSamples = 16;
  73840. var sampleSphere = [
  73841. 0.5381, 0.1856, -0.4319,
  73842. 0.1379, 0.2486, 0.4430,
  73843. 0.3371, 0.5679, -0.0057,
  73844. -0.6999, -0.0451, -0.0019,
  73845. 0.0689, -0.1598, -0.8547,
  73846. 0.0560, 0.0069, -0.1843,
  73847. -0.0146, 0.1402, 0.0762,
  73848. 0.0100, -0.1924, -0.0344,
  73849. -0.3577, -0.5301, -0.4358,
  73850. -0.3169, 0.1063, 0.0158,
  73851. 0.0103, -0.5869, 0.0046,
  73852. -0.0897, -0.4940, 0.3287,
  73853. 0.7119, -0.0154, -0.0918,
  73854. -0.0533, 0.0596, -0.5411,
  73855. 0.0352, -0.0631, 0.5460,
  73856. -0.4776, 0.2847, -0.0271
  73857. ];
  73858. var samplesFactor = 1.0 / numSamples;
  73859. this._ssaoPostProcess = new BABYLON.PostProcess("ssao", "ssao", [
  73860. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  73861. "area", "fallOff", "base", "range", "viewport"
  73862. ], ["randomSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  73863. this._ssaoPostProcess.onApply = function (effect) {
  73864. if (_this._firstUpdate) {
  73865. effect.setArray3("sampleSphere", sampleSphere);
  73866. effect.setFloat("samplesFactor", samplesFactor);
  73867. effect.setFloat("randTextureTiles", 4.0);
  73868. }
  73869. effect.setFloat("totalStrength", _this.totalStrength);
  73870. effect.setFloat("radius", _this.radius);
  73871. effect.setFloat("area", _this.area);
  73872. effect.setFloat("fallOff", _this.fallOff);
  73873. effect.setFloat("base", _this.base);
  73874. effect.setTexture("textureSampler", _this._depthTexture);
  73875. effect.setTexture("randomSampler", _this._randomTexture);
  73876. };
  73877. };
  73878. SSAORenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  73879. var _this = this;
  73880. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  73881. this._ssaoCombinePostProcess.onApply = function (effect) {
  73882. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(0, 0, 1.0, 1.0));
  73883. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  73884. };
  73885. };
  73886. SSAORenderingPipeline.prototype._createRandomTexture = function () {
  73887. var size = 512;
  73888. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  73889. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  73890. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  73891. var context = this._randomTexture.getContext();
  73892. var rand = function (min, max) {
  73893. return Math.random() * (max - min) + min;
  73894. };
  73895. var randVector = BABYLON.Vector3.Zero();
  73896. for (var x = 0; x < size; x++) {
  73897. for (var y = 0; y < size; y++) {
  73898. randVector.x = Math.floor(rand(-1.0, 1.0) * 255);
  73899. randVector.y = Math.floor(rand(-1.0, 1.0) * 255);
  73900. randVector.z = Math.floor(rand(-1.0, 1.0) * 255);
  73901. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  73902. context.fillRect(x, y, 1, 1);
  73903. }
  73904. }
  73905. this._randomTexture.update(false);
  73906. };
  73907. __decorate([
  73908. BABYLON.serialize()
  73909. ], SSAORenderingPipeline.prototype, "totalStrength", void 0);
  73910. __decorate([
  73911. BABYLON.serialize()
  73912. ], SSAORenderingPipeline.prototype, "radius", void 0);
  73913. __decorate([
  73914. BABYLON.serialize()
  73915. ], SSAORenderingPipeline.prototype, "area", void 0);
  73916. __decorate([
  73917. BABYLON.serialize()
  73918. ], SSAORenderingPipeline.prototype, "fallOff", void 0);
  73919. __decorate([
  73920. BABYLON.serialize()
  73921. ], SSAORenderingPipeline.prototype, "base", void 0);
  73922. return SSAORenderingPipeline;
  73923. }(BABYLON.PostProcessRenderPipeline));
  73924. BABYLON.SSAORenderingPipeline = SSAORenderingPipeline;
  73925. })(BABYLON || (BABYLON = {}));
  73926. //# sourceMappingURL=babylon.ssaoRenderingPipeline.js.map
  73927. var BABYLON;
  73928. (function (BABYLON) {
  73929. var SSAO2RenderingPipeline = /** @class */ (function (_super) {
  73930. __extends(SSAO2RenderingPipeline, _super);
  73931. /**
  73932. * @constructor
  73933. * @param {string} name - The rendering pipeline name
  73934. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  73935. * @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 }
  73936. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  73937. */
  73938. function SSAO2RenderingPipeline(name, scene, ratio, cameras) {
  73939. var _this = _super.call(this, scene.getEngine(), name) || this;
  73940. // Members
  73941. /**
  73942. * The PassPostProcess id in the pipeline that contains the original scene color
  73943. */
  73944. _this.SSAOOriginalSceneColorEffect = "SSAOOriginalSceneColorEffect";
  73945. /**
  73946. * The SSAO PostProcess id in the pipeline
  73947. */
  73948. _this.SSAORenderEffect = "SSAORenderEffect";
  73949. /**
  73950. * The horizontal blur PostProcess id in the pipeline
  73951. */
  73952. _this.SSAOBlurHRenderEffect = "SSAOBlurHRenderEffect";
  73953. /**
  73954. * The vertical blur PostProcess id in the pipeline
  73955. */
  73956. _this.SSAOBlurVRenderEffect = "SSAOBlurVRenderEffect";
  73957. /**
  73958. * The PostProcess id in the pipeline that combines the SSAO-Blur output with the original scene color (SSAOOriginalSceneColorEffect)
  73959. */
  73960. _this.SSAOCombineRenderEffect = "SSAOCombineRenderEffect";
  73961. /**
  73962. * The output strength of the SSAO post-process. Default value is 1.0.
  73963. */
  73964. _this.totalStrength = 1.0;
  73965. /**
  73966. * Maximum depth value to still render AO. A smooth falloff makes the dimming more natural, so there will be no abrupt shading change.
  73967. */
  73968. _this.maxZ = 100.0;
  73969. /**
  73970. * In order to save performances, SSAO radius is clamped on close geometry. This ratio changes by how much
  73971. */
  73972. _this.minZAspect = 0.2;
  73973. /**
  73974. * Number of samples used for the SSAO calculations. Default value is 8
  73975. */
  73976. _this._samples = 8;
  73977. /**
  73978. * Are we using bilateral blur ?
  73979. */
  73980. _this._expensiveBlur = true;
  73981. /**
  73982. * The radius around the analyzed pixel used by the SSAO post-process. Default value is 2.0
  73983. */
  73984. _this.radius = 2.0;
  73985. /**
  73986. * The base color of the SSAO post-process
  73987. * The final result is "base + ssao" between [0, 1]
  73988. */
  73989. _this.base = 0.1;
  73990. _this._firstUpdate = true;
  73991. _this._scene = scene;
  73992. _this._ratio = ratio;
  73993. if (!_this.isSupported) {
  73994. BABYLON.Tools.Error("SSAO 2 needs WebGL 2 support.");
  73995. return _this;
  73996. }
  73997. var ssaoRatio = _this._ratio.ssaoRatio || ratio;
  73998. var blurRatio = _this._ratio.blurRatio || ratio;
  73999. // Set up assets
  74000. var geometryBufferRenderer = scene.enableGeometryBufferRenderer();
  74001. _this._createRandomTexture();
  74002. _this._depthTexture = geometryBufferRenderer.getGBuffer().textures[0];
  74003. _this._normalTexture = geometryBufferRenderer.getGBuffer().textures[1];
  74004. _this._originalColorPostProcess = new BABYLON.PassPostProcess("SSAOOriginalSceneColor", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false);
  74005. _this._createSSAOPostProcess(1.0);
  74006. _this._createBlurPostProcess(ssaoRatio, blurRatio);
  74007. _this._createSSAOCombinePostProcess(blurRatio);
  74008. // Set up pipeline
  74009. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOOriginalSceneColorEffect, function () { return _this._originalColorPostProcess; }, true));
  74010. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAORenderEffect, function () { return _this._ssaoPostProcess; }, true));
  74011. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurHRenderEffect, function () { return _this._blurHPostProcess; }, true));
  74012. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOBlurVRenderEffect, function () { return _this._blurVPostProcess; }, true));
  74013. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.SSAOCombineRenderEffect, function () { return _this._ssaoCombinePostProcess; }, true));
  74014. // Finish
  74015. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74016. if (cameras)
  74017. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74018. return _this;
  74019. }
  74020. Object.defineProperty(SSAO2RenderingPipeline.prototype, "samples", {
  74021. get: function () {
  74022. return this._samples;
  74023. },
  74024. set: function (n) {
  74025. this._ssaoPostProcess.updateEffect("#define SAMPLES " + n + "\n#define SSAO");
  74026. this._samples = n;
  74027. this._sampleSphere = this._generateHemisphere();
  74028. this._firstUpdate = true;
  74029. },
  74030. enumerable: true,
  74031. configurable: true
  74032. });
  74033. Object.defineProperty(SSAO2RenderingPipeline.prototype, "expensiveBlur", {
  74034. get: function () {
  74035. return this._expensiveBlur;
  74036. },
  74037. set: function (b) {
  74038. 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"]);
  74039. this._blurVPostProcess.updateEffect("#define BILATERAL_BLUR\n#define SAMPLES 16\n#define EXPENSIVE " + (b ? "1" : "0") + "\n", null, ["textureSampler", "depthSampler"]);
  74040. this._expensiveBlur = b;
  74041. this._firstUpdate = true;
  74042. },
  74043. enumerable: true,
  74044. configurable: true
  74045. });
  74046. Object.defineProperty(SSAO2RenderingPipeline, "IsSupported", {
  74047. /**
  74048. * Support test.
  74049. */
  74050. get: function () {
  74051. var engine = BABYLON.Engine.LastCreatedEngine;
  74052. if (!engine) {
  74053. return false;
  74054. }
  74055. return engine.getCaps().drawBuffersExtension;
  74056. },
  74057. enumerable: true,
  74058. configurable: true
  74059. });
  74060. // Public Methods
  74061. /**
  74062. * Removes the internal pipeline assets and detatches the pipeline from the scene cameras
  74063. */
  74064. SSAO2RenderingPipeline.prototype.dispose = function (disableGeometryBufferRenderer) {
  74065. if (disableGeometryBufferRenderer === void 0) { disableGeometryBufferRenderer = false; }
  74066. for (var i = 0; i < this._scene.cameras.length; i++) {
  74067. var camera = this._scene.cameras[i];
  74068. this._originalColorPostProcess.dispose(camera);
  74069. this._ssaoPostProcess.dispose(camera);
  74070. this._blurHPostProcess.dispose(camera);
  74071. this._blurVPostProcess.dispose(camera);
  74072. this._ssaoCombinePostProcess.dispose(camera);
  74073. }
  74074. this._randomTexture.dispose();
  74075. if (disableGeometryBufferRenderer)
  74076. this._scene.disableGeometryBufferRenderer();
  74077. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74078. _super.prototype.dispose.call(this);
  74079. };
  74080. // Private Methods
  74081. SSAO2RenderingPipeline.prototype._createBlurPostProcess = function (ssaoRatio, blurRatio) {
  74082. var _this = this;
  74083. this._samplerOffsets = [];
  74084. var expensive = this.expensiveBlur;
  74085. for (var i = -8; i < 8; i++) {
  74086. this._samplerOffsets.push(i * 2 + 0.5);
  74087. }
  74088. 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");
  74089. this._blurHPostProcess.onApply = function (effect) {
  74090. if (!_this._scene.activeCamera) {
  74091. return;
  74092. }
  74093. effect.setFloat("outSize", _this._ssaoCombinePostProcess.width > 0 ? _this._ssaoCombinePostProcess.width : _this._originalColorPostProcess.width);
  74094. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74095. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74096. effect.setFloat("radius", _this.radius);
  74097. effect.setTexture("depthSampler", _this._depthTexture);
  74098. if (_this._firstUpdate) {
  74099. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74100. }
  74101. };
  74102. 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");
  74103. this._blurVPostProcess.onApply = function (effect) {
  74104. if (!_this._scene.activeCamera) {
  74105. return;
  74106. }
  74107. effect.setFloat("outSize", _this._ssaoCombinePostProcess.height > 0 ? _this._ssaoCombinePostProcess.height : _this._originalColorPostProcess.height);
  74108. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74109. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74110. effect.setFloat("radius", _this.radius);
  74111. effect.setTexture("depthSampler", _this._depthTexture);
  74112. if (_this._firstUpdate) {
  74113. effect.setArray("samplerOffsets", _this._samplerOffsets);
  74114. _this._firstUpdate = false;
  74115. }
  74116. };
  74117. };
  74118. SSAO2RenderingPipeline.prototype._rebuild = function () {
  74119. this._firstUpdate = true;
  74120. _super.prototype._rebuild.call(this);
  74121. };
  74122. SSAO2RenderingPipeline.prototype._generateHemisphere = function () {
  74123. var numSamples = this.samples;
  74124. var result = [];
  74125. var vector, scale;
  74126. var rand = function (min, max) {
  74127. return Math.random() * (max - min) + min;
  74128. };
  74129. var i = 0;
  74130. while (i < numSamples) {
  74131. vector = new BABYLON.Vector3(rand(-1.0, 1.0), rand(-1.0, 1.0), rand(0.30, 1.0));
  74132. vector.normalize();
  74133. scale = i / numSamples;
  74134. scale = BABYLON.Scalar.Lerp(0.1, 1.0, scale * scale);
  74135. vector.scaleInPlace(scale);
  74136. result.push(vector.x, vector.y, vector.z);
  74137. i++;
  74138. }
  74139. return result;
  74140. };
  74141. SSAO2RenderingPipeline.prototype._createSSAOPostProcess = function (ratio) {
  74142. var _this = this;
  74143. var numSamples = this.samples;
  74144. this._sampleSphere = this._generateHemisphere();
  74145. this._ssaoPostProcess = new BABYLON.PostProcess("ssao2", "ssao2", [
  74146. "sampleSphere", "samplesFactor", "randTextureTiles", "totalStrength", "radius",
  74147. "base", "range", "projection", "near", "far", "texelSize",
  74148. "xViewport", "yViewport", "maxZ", "minZAspect"
  74149. ], ["randomSampler", "normalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, "#define SAMPLES " + numSamples + "\n#define SSAO");
  74150. this._ssaoPostProcess.onApply = function (effect) {
  74151. if (_this._firstUpdate) {
  74152. effect.setArray3("sampleSphere", _this._sampleSphere);
  74153. effect.setFloat("randTextureTiles", 4.0);
  74154. }
  74155. if (!_this._scene.activeCamera) {
  74156. return;
  74157. }
  74158. effect.setFloat("samplesFactor", 1 / _this.samples);
  74159. effect.setFloat("totalStrength", _this.totalStrength);
  74160. effect.setFloat2("texelSize", 1 / _this._ssaoPostProcess.width, 1 / _this._ssaoPostProcess.height);
  74161. effect.setFloat("radius", _this.radius);
  74162. effect.setFloat("maxZ", _this.maxZ);
  74163. effect.setFloat("minZAspect", _this.minZAspect);
  74164. effect.setFloat("base", _this.base);
  74165. effect.setFloat("near", _this._scene.activeCamera.minZ);
  74166. effect.setFloat("far", _this._scene.activeCamera.maxZ);
  74167. effect.setFloat("xViewport", Math.tan(_this._scene.activeCamera.fov / 2) * _this._scene.getEngine().getAspectRatio(_this._scene.activeCamera, true));
  74168. effect.setFloat("yViewport", Math.tan(_this._scene.activeCamera.fov / 2));
  74169. effect.setMatrix("projection", _this._scene.getProjectionMatrix());
  74170. effect.setTexture("textureSampler", _this._depthTexture);
  74171. effect.setTexture("normalSampler", _this._normalTexture);
  74172. effect.setTexture("randomSampler", _this._randomTexture);
  74173. };
  74174. };
  74175. SSAO2RenderingPipeline.prototype._createSSAOCombinePostProcess = function (ratio) {
  74176. var _this = this;
  74177. this._ssaoCombinePostProcess = new BABYLON.PostProcess("ssaoCombine", "ssaoCombine", [], ["originalColor", "viewport"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74178. this._ssaoCombinePostProcess.onApply = function (effect) {
  74179. var viewport = _this._scene.activeCamera.viewport;
  74180. effect.setVector4("viewport", BABYLON.Tmp.Vector4[0].copyFromFloats(viewport.x, viewport.y, viewport.width, viewport.height));
  74181. effect.setTextureFromPostProcess("originalColor", _this._originalColorPostProcess);
  74182. };
  74183. };
  74184. SSAO2RenderingPipeline.prototype._createRandomTexture = function () {
  74185. var size = 512;
  74186. this._randomTexture = new BABYLON.DynamicTexture("SSAORandomTexture", size, this._scene, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  74187. this._randomTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74188. this._randomTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74189. var context = this._randomTexture.getContext();
  74190. var rand = function (min, max) {
  74191. return Math.random() * (max - min) + min;
  74192. };
  74193. var randVector = BABYLON.Vector3.Zero();
  74194. for (var x = 0; x < size; x++) {
  74195. for (var y = 0; y < size; y++) {
  74196. randVector.x = rand(0.0, 1.0);
  74197. randVector.y = rand(0.0, 1.0);
  74198. randVector.z = 0.0;
  74199. randVector.normalize();
  74200. randVector.scaleInPlace(255);
  74201. randVector.x = Math.floor(randVector.x);
  74202. randVector.y = Math.floor(randVector.y);
  74203. context.fillStyle = 'rgb(' + randVector.x + ', ' + randVector.y + ', ' + randVector.z + ')';
  74204. context.fillRect(x, y, 1, 1);
  74205. }
  74206. }
  74207. this._randomTexture.update(false);
  74208. };
  74209. /**
  74210. * Serialize the rendering pipeline (Used when exporting)
  74211. * @returns the serialized object
  74212. */
  74213. SSAO2RenderingPipeline.prototype.serialize = function () {
  74214. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  74215. serializationObject.customType = "SSAO2RenderingPipeline";
  74216. return serializationObject;
  74217. };
  74218. /**
  74219. * Parse the serialized pipeline
  74220. * @param source Source pipeline.
  74221. * @param scene The scene to load the pipeline to.
  74222. * @param rootUrl The URL of the serialized pipeline.
  74223. * @returns An instantiated pipeline from the serialized object.
  74224. */
  74225. SSAO2RenderingPipeline.Parse = function (source, scene, rootUrl) {
  74226. return BABYLON.SerializationHelper.Parse(function () { return new SSAO2RenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  74227. };
  74228. __decorate([
  74229. BABYLON.serialize()
  74230. ], SSAO2RenderingPipeline.prototype, "totalStrength", void 0);
  74231. __decorate([
  74232. BABYLON.serialize()
  74233. ], SSAO2RenderingPipeline.prototype, "maxZ", void 0);
  74234. __decorate([
  74235. BABYLON.serialize()
  74236. ], SSAO2RenderingPipeline.prototype, "minZAspect", void 0);
  74237. __decorate([
  74238. BABYLON.serialize("samples")
  74239. ], SSAO2RenderingPipeline.prototype, "_samples", void 0);
  74240. __decorate([
  74241. BABYLON.serialize()
  74242. ], SSAO2RenderingPipeline.prototype, "_ratio", void 0);
  74243. __decorate([
  74244. BABYLON.serialize("expensiveBlur")
  74245. ], SSAO2RenderingPipeline.prototype, "_expensiveBlur", void 0);
  74246. __decorate([
  74247. BABYLON.serialize()
  74248. ], SSAO2RenderingPipeline.prototype, "radius", void 0);
  74249. __decorate([
  74250. BABYLON.serialize()
  74251. ], SSAO2RenderingPipeline.prototype, "base", void 0);
  74252. return SSAO2RenderingPipeline;
  74253. }(BABYLON.PostProcessRenderPipeline));
  74254. BABYLON.SSAO2RenderingPipeline = SSAO2RenderingPipeline;
  74255. })(BABYLON || (BABYLON = {}));
  74256. //# sourceMappingURL=babylon.ssao2RenderingPipeline.js.map
  74257. // BABYLON.JS Chromatic Aberration GLSL Shader
  74258. // Author: Olivier Guyot
  74259. // Separates very slightly R, G and B colors on the edges of the screen
  74260. // Inspired by Francois Tarlier & Martins Upitis
  74261. var BABYLON;
  74262. (function (BABYLON) {
  74263. var LensRenderingPipeline = /** @class */ (function (_super) {
  74264. __extends(LensRenderingPipeline, _super);
  74265. /**
  74266. * @constructor
  74267. *
  74268. * Effect parameters are as follow:
  74269. * {
  74270. * chromatic_aberration: number; // from 0 to x (1 for realism)
  74271. * edge_blur: number; // from 0 to x (1 for realism)
  74272. * distortion: number; // from 0 to x (1 for realism)
  74273. * grain_amount: number; // from 0 to 1
  74274. * grain_texture: BABYLON.Texture; // texture to use for grain effect; if unset, use random B&W noise
  74275. * dof_focus_distance: number; // depth-of-field: focus distance; unset to disable (disabled by default)
  74276. * dof_aperture: number; // depth-of-field: focus blur bias (default: 1)
  74277. * dof_darken: number; // depth-of-field: darken that which is out of focus (from 0 to 1, disabled by default)
  74278. * dof_pentagon: boolean; // depth-of-field: makes a pentagon-like "bokeh" effect
  74279. * dof_gain: number; // depth-of-field: highlights gain; unset to disable (disabled by default)
  74280. * dof_threshold: number; // depth-of-field: highlights threshold (default: 1)
  74281. * blur_noise: boolean; // add a little bit of noise to the blur (default: true)
  74282. * }
  74283. * Note: if an effect parameter is unset, effect is disabled
  74284. *
  74285. * @param {string} name - The rendering pipeline name
  74286. * @param {object} parameters - An object containing all parameters (see above)
  74287. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74288. * @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)
  74289. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74290. */
  74291. function LensRenderingPipeline(name, parameters, scene, ratio, cameras) {
  74292. if (ratio === void 0) { ratio = 1.0; }
  74293. var _this = _super.call(this, scene.getEngine(), name) || this;
  74294. // Lens effects can be of the following:
  74295. // - chromatic aberration (slight shift of RGB colors)
  74296. // - blur on the edge of the lens
  74297. // - lens distortion
  74298. // - depth-of-field blur & highlights enhancing
  74299. // - depth-of-field 'bokeh' effect (shapes appearing in blurred areas)
  74300. // - grain effect (noise or custom texture)
  74301. // Two additional texture samplers are needed:
  74302. // - depth map (for depth-of-field)
  74303. // - grain texture
  74304. /**
  74305. * The chromatic aberration PostProcess id in the pipeline
  74306. */
  74307. _this.LensChromaticAberrationEffect = "LensChromaticAberrationEffect";
  74308. /**
  74309. * The highlights enhancing PostProcess id in the pipeline
  74310. */
  74311. _this.HighlightsEnhancingEffect = "HighlightsEnhancingEffect";
  74312. /**
  74313. * The depth-of-field PostProcess id in the pipeline
  74314. */
  74315. _this.LensDepthOfFieldEffect = "LensDepthOfFieldEffect";
  74316. _this._scene = scene;
  74317. // Fetch texture samplers
  74318. _this._depthTexture = scene.enableDepthRenderer().getDepthMap(); // Force depth renderer "on"
  74319. if (parameters.grain_texture) {
  74320. _this._grainTexture = parameters.grain_texture;
  74321. }
  74322. else {
  74323. _this._createGrainTexture();
  74324. }
  74325. // save parameters
  74326. _this._edgeBlur = parameters.edge_blur ? parameters.edge_blur : 0;
  74327. _this._grainAmount = parameters.grain_amount ? parameters.grain_amount : 0;
  74328. _this._chromaticAberration = parameters.chromatic_aberration ? parameters.chromatic_aberration : 0;
  74329. _this._distortion = parameters.distortion ? parameters.distortion : 0;
  74330. _this._highlightsGain = parameters.dof_gain !== undefined ? parameters.dof_gain : -1;
  74331. _this._highlightsThreshold = parameters.dof_threshold ? parameters.dof_threshold : 1;
  74332. _this._dofDistance = parameters.dof_focus_distance !== undefined ? parameters.dof_focus_distance : -1;
  74333. _this._dofAperture = parameters.dof_aperture ? parameters.dof_aperture : 1;
  74334. _this._dofDarken = parameters.dof_darken ? parameters.dof_darken : 0;
  74335. _this._dofPentagon = parameters.dof_pentagon !== undefined ? parameters.dof_pentagon : true;
  74336. _this._blurNoise = parameters.blur_noise !== undefined ? parameters.blur_noise : true;
  74337. // Create effects
  74338. _this._createChromaticAberrationPostProcess(ratio);
  74339. _this._createHighlightsPostProcess(ratio);
  74340. _this._createDepthOfFieldPostProcess(ratio / 4);
  74341. // Set up pipeline
  74342. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensChromaticAberrationEffect, function () { return _this._chromaticAberrationPostProcess; }, true));
  74343. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.HighlightsEnhancingEffect, function () { return _this._highlightsPostProcess; }, true));
  74344. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), _this.LensDepthOfFieldEffect, function () { return _this._depthOfFieldPostProcess; }, true));
  74345. if (_this._highlightsGain === -1) {
  74346. _this._disableEffect(_this.HighlightsEnhancingEffect, null);
  74347. }
  74348. // Finish
  74349. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74350. if (cameras) {
  74351. scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(name, cameras);
  74352. }
  74353. return _this;
  74354. }
  74355. // public methods (self explanatory)
  74356. LensRenderingPipeline.prototype.setEdgeBlur = function (amount) { this._edgeBlur = amount; };
  74357. LensRenderingPipeline.prototype.disableEdgeBlur = function () { this._edgeBlur = 0; };
  74358. LensRenderingPipeline.prototype.setGrainAmount = function (amount) { this._grainAmount = amount; };
  74359. LensRenderingPipeline.prototype.disableGrain = function () { this._grainAmount = 0; };
  74360. LensRenderingPipeline.prototype.setChromaticAberration = function (amount) { this._chromaticAberration = amount; };
  74361. LensRenderingPipeline.prototype.disableChromaticAberration = function () { this._chromaticAberration = 0; };
  74362. LensRenderingPipeline.prototype.setEdgeDistortion = function (amount) { this._distortion = amount; };
  74363. LensRenderingPipeline.prototype.disableEdgeDistortion = function () { this._distortion = 0; };
  74364. LensRenderingPipeline.prototype.setFocusDistance = function (amount) { this._dofDistance = amount; };
  74365. LensRenderingPipeline.prototype.disableDepthOfField = function () { this._dofDistance = -1; };
  74366. LensRenderingPipeline.prototype.setAperture = function (amount) { this._dofAperture = amount; };
  74367. LensRenderingPipeline.prototype.setDarkenOutOfFocus = function (amount) { this._dofDarken = amount; };
  74368. LensRenderingPipeline.prototype.enablePentagonBokeh = function () {
  74369. this._highlightsPostProcess.updateEffect("#define PENTAGON\n");
  74370. };
  74371. LensRenderingPipeline.prototype.disablePentagonBokeh = function () {
  74372. this._highlightsPostProcess.updateEffect();
  74373. };
  74374. LensRenderingPipeline.prototype.enableNoiseBlur = function () { this._blurNoise = true; };
  74375. LensRenderingPipeline.prototype.disableNoiseBlur = function () { this._blurNoise = false; };
  74376. LensRenderingPipeline.prototype.setHighlightsGain = function (amount) {
  74377. this._highlightsGain = amount;
  74378. };
  74379. LensRenderingPipeline.prototype.setHighlightsThreshold = function (amount) {
  74380. if (this._highlightsGain === -1) {
  74381. this._highlightsGain = 1.0;
  74382. }
  74383. this._highlightsThreshold = amount;
  74384. };
  74385. LensRenderingPipeline.prototype.disableHighlights = function () {
  74386. this._highlightsGain = -1;
  74387. };
  74388. /**
  74389. * Removes the internal pipeline assets and detaches the pipeline from the scene cameras
  74390. */
  74391. LensRenderingPipeline.prototype.dispose = function (disableDepthRender) {
  74392. if (disableDepthRender === void 0) { disableDepthRender = false; }
  74393. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._scene.cameras);
  74394. this._chromaticAberrationPostProcess = null;
  74395. this._highlightsPostProcess = null;
  74396. this._depthOfFieldPostProcess = null;
  74397. this._grainTexture.dispose();
  74398. if (disableDepthRender)
  74399. this._scene.disableDepthRenderer();
  74400. };
  74401. // colors shifting and distortion
  74402. LensRenderingPipeline.prototype._createChromaticAberrationPostProcess = function (ratio) {
  74403. var _this = this;
  74404. this._chromaticAberrationPostProcess = new BABYLON.PostProcess("LensChromaticAberration", "chromaticAberration", ["chromatic_aberration", "screen_width", "screen_height", "direction", "radialIntensity", "centerPosition"], // uniforms
  74405. [], // samplers
  74406. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74407. this._chromaticAberrationPostProcess.onApply = function (effect) {
  74408. effect.setFloat('chromatic_aberration', _this._chromaticAberration);
  74409. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74410. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74411. effect.setFloat('radialIntensity', 1);
  74412. effect.setFloat2('direction', 17, 17);
  74413. effect.setFloat2('centerPosition', 0.5, 0.5);
  74414. };
  74415. };
  74416. // highlights enhancing
  74417. LensRenderingPipeline.prototype._createHighlightsPostProcess = function (ratio) {
  74418. var _this = this;
  74419. this._highlightsPostProcess = new BABYLON.PostProcess("LensHighlights", "lensHighlights", ["gain", "threshold", "screen_width", "screen_height"], // uniforms
  74420. [], // samplers
  74421. ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, this._dofPentagon ? "#define PENTAGON\n" : "");
  74422. this._highlightsPostProcess.onApply = function (effect) {
  74423. effect.setFloat('gain', _this._highlightsGain);
  74424. effect.setFloat('threshold', _this._highlightsThreshold);
  74425. effect.setTextureFromPostProcess("textureSampler", _this._chromaticAberrationPostProcess);
  74426. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74427. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74428. };
  74429. };
  74430. // colors shifting and distortion
  74431. LensRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (ratio) {
  74432. var _this = this;
  74433. this._depthOfFieldPostProcess = new BABYLON.PostProcess("LensDepthOfField", "depthOfField", [
  74434. "grain_amount", "blur_noise", "screen_width", "screen_height", "distortion", "dof_enabled",
  74435. "screen_distance", "aperture", "darken", "edge_blur", "highlights", "near", "far"
  74436. ], ["depthSampler", "grainSampler", "highlightsSampler"], ratio, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, this._scene.getEngine(), false);
  74437. this._depthOfFieldPostProcess.onApply = function (effect) {
  74438. effect.setTexture("depthSampler", _this._depthTexture);
  74439. effect.setTexture("grainSampler", _this._grainTexture);
  74440. effect.setTextureFromPostProcess("textureSampler", _this._highlightsPostProcess);
  74441. effect.setTextureFromPostProcess("highlightsSampler", _this._depthOfFieldPostProcess);
  74442. effect.setFloat('grain_amount', _this._grainAmount);
  74443. effect.setBool('blur_noise', _this._blurNoise);
  74444. effect.setFloat('screen_width', _this._scene.getEngine().getRenderWidth());
  74445. effect.setFloat('screen_height', _this._scene.getEngine().getRenderHeight());
  74446. effect.setFloat('distortion', _this._distortion);
  74447. effect.setBool('dof_enabled', (_this._dofDistance !== -1));
  74448. effect.setFloat('screen_distance', 1.0 / (0.1 - 1.0 / _this._dofDistance));
  74449. effect.setFloat('aperture', _this._dofAperture);
  74450. effect.setFloat('darken', _this._dofDarken);
  74451. effect.setFloat('edge_blur', _this._edgeBlur);
  74452. effect.setBool('highlights', (_this._highlightsGain !== -1));
  74453. if (_this._scene.activeCamera) {
  74454. effect.setFloat('near', _this._scene.activeCamera.minZ);
  74455. effect.setFloat('far', _this._scene.activeCamera.maxZ);
  74456. }
  74457. };
  74458. };
  74459. // creates a black and white random noise texture, 512x512
  74460. LensRenderingPipeline.prototype._createGrainTexture = function () {
  74461. var size = 512;
  74462. this._grainTexture = new BABYLON.DynamicTexture("LensNoiseTexture", size, this._scene, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  74463. this._grainTexture.wrapU = BABYLON.Texture.WRAP_ADDRESSMODE;
  74464. this._grainTexture.wrapV = BABYLON.Texture.WRAP_ADDRESSMODE;
  74465. var context = this._grainTexture.getContext();
  74466. var rand = function (min, max) {
  74467. return Math.random() * (max - min) + min;
  74468. };
  74469. var value;
  74470. for (var x = 0; x < size; x++) {
  74471. for (var y = 0; y < size; y++) {
  74472. value = Math.floor(rand(0.42, 0.58) * 255);
  74473. context.fillStyle = 'rgb(' + value + ', ' + value + ', ' + value + ')';
  74474. context.fillRect(x, y, 1, 1);
  74475. }
  74476. }
  74477. this._grainTexture.update(false);
  74478. };
  74479. return LensRenderingPipeline;
  74480. }(BABYLON.PostProcessRenderPipeline));
  74481. BABYLON.LensRenderingPipeline = LensRenderingPipeline;
  74482. })(BABYLON || (BABYLON = {}));
  74483. //# sourceMappingURL=babylon.lensRenderingPipeline.js.map
  74484. var BABYLON;
  74485. (function (BABYLON) {
  74486. var StandardRenderingPipeline = /** @class */ (function (_super) {
  74487. __extends(StandardRenderingPipeline, _super);
  74488. /**
  74489. * @constructor
  74490. * @param {string} name - The rendering pipeline name
  74491. * @param {BABYLON.Scene} scene - The scene linked to this pipeline
  74492. * @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)
  74493. * @param {BABYLON.PostProcess} originalPostProcess - the custom original color post-process. Must be "reusable". Can be null.
  74494. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to
  74495. */
  74496. function StandardRenderingPipeline(name, scene, ratio, originalPostProcess, cameras) {
  74497. if (originalPostProcess === void 0) { originalPostProcess = null; }
  74498. var _this = _super.call(this, scene.getEngine(), name) || this;
  74499. _this.downSampleX4PostProcess = null;
  74500. _this.brightPassPostProcess = null;
  74501. _this.blurHPostProcesses = [];
  74502. _this.blurVPostProcesses = [];
  74503. _this.textureAdderPostProcess = null;
  74504. _this.volumetricLightPostProcess = null;
  74505. _this.volumetricLightSmoothXPostProcess = null;
  74506. _this.volumetricLightSmoothYPostProcess = null;
  74507. _this.volumetricLightMergePostProces = null;
  74508. _this.volumetricLightFinalPostProcess = null;
  74509. _this.luminancePostProcess = null;
  74510. _this.luminanceDownSamplePostProcesses = [];
  74511. _this.hdrPostProcess = null;
  74512. _this.textureAdderFinalPostProcess = null;
  74513. _this.lensFlareFinalPostProcess = null;
  74514. _this.hdrFinalPostProcess = null;
  74515. _this.lensFlarePostProcess = null;
  74516. _this.lensFlareComposePostProcess = null;
  74517. _this.motionBlurPostProcess = null;
  74518. _this.depthOfFieldPostProcess = null;
  74519. // Values
  74520. _this.brightThreshold = 1.0;
  74521. _this.blurWidth = 512.0;
  74522. _this.horizontalBlur = false;
  74523. _this.exposure = 1.0;
  74524. _this.lensTexture = null;
  74525. _this.volumetricLightCoefficient = 0.2;
  74526. _this.volumetricLightPower = 4.0;
  74527. _this.volumetricLightBlurScale = 64.0;
  74528. _this.sourceLight = null;
  74529. _this.hdrMinimumLuminance = 1.0;
  74530. _this.hdrDecreaseRate = 0.5;
  74531. _this.hdrIncreaseRate = 0.5;
  74532. _this.lensColorTexture = null;
  74533. _this.lensFlareStrength = 20.0;
  74534. _this.lensFlareGhostDispersal = 1.4;
  74535. _this.lensFlareHaloWidth = 0.7;
  74536. _this.lensFlareDistortionStrength = 16.0;
  74537. _this.lensStarTexture = null;
  74538. _this.lensFlareDirtTexture = null;
  74539. _this.depthOfFieldDistance = 10.0;
  74540. _this.depthOfFieldBlurWidth = 64.0;
  74541. _this.motionStrength = 1.0;
  74542. // IAnimatable
  74543. _this.animations = [];
  74544. _this._currentDepthOfFieldSource = null;
  74545. _this._hdrCurrentLuminance = 1.0;
  74546. // Getters and setters
  74547. _this._bloomEnabled = true;
  74548. _this._depthOfFieldEnabled = false;
  74549. _this._vlsEnabled = false;
  74550. _this._lensFlareEnabled = false;
  74551. _this._hdrEnabled = false;
  74552. _this._motionBlurEnabled = false;
  74553. _this._motionBlurSamples = 64.0;
  74554. _this._volumetricLightStepsCount = 50.0;
  74555. _this._cameras = cameras || [];
  74556. // Initialize
  74557. _this._scene = scene;
  74558. _this._basePostProcess = originalPostProcess;
  74559. _this._ratio = ratio;
  74560. // Misc
  74561. _this._floatTextureType = scene.getEngine().getCaps().textureFloatRender ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  74562. // Finish
  74563. scene.postProcessRenderPipelineManager.addPipeline(_this);
  74564. _this._buildPipeline();
  74565. return _this;
  74566. }
  74567. Object.defineProperty(StandardRenderingPipeline.prototype, "BloomEnabled", {
  74568. get: function () {
  74569. return this._bloomEnabled;
  74570. },
  74571. set: function (enabled) {
  74572. if (this._bloomEnabled === enabled) {
  74573. return;
  74574. }
  74575. this._bloomEnabled = enabled;
  74576. this._buildPipeline();
  74577. },
  74578. enumerable: true,
  74579. configurable: true
  74580. });
  74581. Object.defineProperty(StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", {
  74582. get: function () {
  74583. return this._depthOfFieldEnabled;
  74584. },
  74585. set: function (enabled) {
  74586. if (this._depthOfFieldEnabled === enabled) {
  74587. return;
  74588. }
  74589. this._depthOfFieldEnabled = enabled;
  74590. this._buildPipeline();
  74591. },
  74592. enumerable: true,
  74593. configurable: true
  74594. });
  74595. Object.defineProperty(StandardRenderingPipeline.prototype, "LensFlareEnabled", {
  74596. get: function () {
  74597. return this._lensFlareEnabled;
  74598. },
  74599. set: function (enabled) {
  74600. if (this._lensFlareEnabled === enabled) {
  74601. return;
  74602. }
  74603. this._lensFlareEnabled = enabled;
  74604. this._buildPipeline();
  74605. },
  74606. enumerable: true,
  74607. configurable: true
  74608. });
  74609. Object.defineProperty(StandardRenderingPipeline.prototype, "HDREnabled", {
  74610. get: function () {
  74611. return this._hdrEnabled;
  74612. },
  74613. set: function (enabled) {
  74614. if (this._hdrEnabled === enabled) {
  74615. return;
  74616. }
  74617. this._hdrEnabled = enabled;
  74618. this._buildPipeline();
  74619. },
  74620. enumerable: true,
  74621. configurable: true
  74622. });
  74623. Object.defineProperty(StandardRenderingPipeline.prototype, "VLSEnabled", {
  74624. get: function () {
  74625. return this._vlsEnabled;
  74626. },
  74627. set: function (enabled) {
  74628. if (this._vlsEnabled === enabled) {
  74629. return;
  74630. }
  74631. if (enabled) {
  74632. var geometry = this._scene.enableGeometryBufferRenderer();
  74633. if (!geometry) {
  74634. BABYLON.Tools.Warn("Geometry renderer is not supported, cannot create volumetric lights in Standard Rendering Pipeline");
  74635. return;
  74636. }
  74637. }
  74638. this._vlsEnabled = enabled;
  74639. this._buildPipeline();
  74640. },
  74641. enumerable: true,
  74642. configurable: true
  74643. });
  74644. Object.defineProperty(StandardRenderingPipeline.prototype, "MotionBlurEnabled", {
  74645. get: function () {
  74646. return this._motionBlurEnabled;
  74647. },
  74648. set: function (enabled) {
  74649. if (this._motionBlurEnabled === enabled) {
  74650. return;
  74651. }
  74652. this._motionBlurEnabled = enabled;
  74653. this._buildPipeline();
  74654. },
  74655. enumerable: true,
  74656. configurable: true
  74657. });
  74658. Object.defineProperty(StandardRenderingPipeline.prototype, "volumetricLightStepsCount", {
  74659. get: function () {
  74660. return this._volumetricLightStepsCount;
  74661. },
  74662. set: function (count) {
  74663. if (this.volumetricLightPostProcess) {
  74664. this.volumetricLightPostProcess.updateEffect("#define VLS\n#define NB_STEPS " + count.toFixed(1));
  74665. }
  74666. this._volumetricLightStepsCount = count;
  74667. },
  74668. enumerable: true,
  74669. configurable: true
  74670. });
  74671. Object.defineProperty(StandardRenderingPipeline.prototype, "motionBlurSamples", {
  74672. get: function () {
  74673. return this._motionBlurSamples;
  74674. },
  74675. set: function (samples) {
  74676. if (this.motionBlurPostProcess) {
  74677. this.motionBlurPostProcess.updateEffect("#define MOTION_BLUR\n#define MAX_MOTION_SAMPLES " + samples.toFixed(1));
  74678. }
  74679. this._motionBlurSamples = samples;
  74680. },
  74681. enumerable: true,
  74682. configurable: true
  74683. });
  74684. StandardRenderingPipeline.prototype._buildPipeline = function () {
  74685. var _this = this;
  74686. var ratio = this._ratio;
  74687. var scene = this._scene;
  74688. this._disposePostProcesses();
  74689. this._reset();
  74690. // Create pass post-process
  74691. if (!this._basePostProcess) {
  74692. this.originalPostProcess = new BABYLON.PostProcess("HDRPass", "standard", [], [], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define PASS_POST_PROCESS", this._floatTextureType);
  74693. this.originalPostProcess.onApply = function (effect) {
  74694. _this._currentDepthOfFieldSource = _this.originalPostProcess;
  74695. };
  74696. }
  74697. else {
  74698. this.originalPostProcess = this._basePostProcess;
  74699. }
  74700. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPassPostProcess", function () { return _this.originalPostProcess; }, true));
  74701. this._currentDepthOfFieldSource = this.originalPostProcess;
  74702. if (this._bloomEnabled) {
  74703. // Create down sample X4 post-process
  74704. this._createDownSampleX4PostProcess(scene, ratio / 2);
  74705. // Create bright pass post-process
  74706. this._createBrightPassPostProcess(scene, ratio / 2);
  74707. // Create gaussian blur post-processes (down sampling blurs)
  74708. this._createBlurPostProcesses(scene, ratio / 4, 1);
  74709. // Create texture adder post-process
  74710. this._createTextureAdderPostProcess(scene, ratio);
  74711. // Create depth-of-field source post-process
  74712. 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);
  74713. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBaseDepthOfFieldSource", function () { return _this.textureAdderFinalPostProcess; }, true));
  74714. }
  74715. if (this._vlsEnabled) {
  74716. // Create volumetric light
  74717. this._createVolumetricLightPostProcess(scene, ratio);
  74718. // Create volumetric light final post-process
  74719. 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);
  74720. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSFinal", function () { return _this.volumetricLightFinalPostProcess; }, true));
  74721. }
  74722. if (this._lensFlareEnabled) {
  74723. // Create lens flare post-process
  74724. this._createLensFlarePostProcess(scene, ratio);
  74725. // Create depth-of-field source post-process post lens-flare and disable it now
  74726. 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);
  74727. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostLensFlareDepthOfFieldSource", function () { return _this.lensFlareFinalPostProcess; }, true));
  74728. }
  74729. if (this._hdrEnabled) {
  74730. // Create luminance
  74731. this._createLuminancePostProcesses(scene, this._floatTextureType);
  74732. // Create HDR
  74733. this._createHdrPostProcess(scene, ratio);
  74734. // Create depth-of-field source post-process post hdr and disable it now
  74735. 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);
  74736. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRPostHDReDepthOfFieldSource", function () { return _this.hdrFinalPostProcess; }, true));
  74737. }
  74738. if (this._depthOfFieldEnabled) {
  74739. // Create gaussian blur used by depth-of-field
  74740. this._createBlurPostProcesses(scene, ratio / 2, 3, "depthOfFieldBlurWidth");
  74741. // Create depth-of-field post-process
  74742. this._createDepthOfFieldPostProcess(scene, ratio);
  74743. }
  74744. if (this._motionBlurEnabled) {
  74745. // Create motion blur post-process
  74746. this._createMotionBlurPostProcess(scene, ratio);
  74747. }
  74748. if (this._cameras !== null) {
  74749. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  74750. }
  74751. };
  74752. // Down Sample X4 Post-Processs
  74753. StandardRenderingPipeline.prototype._createDownSampleX4PostProcess = function (scene, ratio) {
  74754. var _this = this;
  74755. var downSampleX4Offsets = new Array(32);
  74756. 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);
  74757. this.downSampleX4PostProcess.onApply = function (effect) {
  74758. var id = 0;
  74759. var width = _this.downSampleX4PostProcess.width;
  74760. var height = _this.downSampleX4PostProcess.height;
  74761. for (var i = -2; i < 2; i++) {
  74762. for (var j = -2; j < 2; j++) {
  74763. downSampleX4Offsets[id] = (i + 0.5) * (1.0 / width);
  74764. downSampleX4Offsets[id + 1] = (j + 0.5) * (1.0 / height);
  74765. id += 2;
  74766. }
  74767. }
  74768. effect.setArray2("dsOffsets", downSampleX4Offsets);
  74769. };
  74770. // Add to pipeline
  74771. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDownSampleX4", function () { return _this.downSampleX4PostProcess; }, true));
  74772. };
  74773. // Brightpass Post-Process
  74774. StandardRenderingPipeline.prototype._createBrightPassPostProcess = function (scene, ratio) {
  74775. var _this = this;
  74776. var brightOffsets = new Array(8);
  74777. 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);
  74778. this.brightPassPostProcess.onApply = function (effect) {
  74779. var sU = (1.0 / _this.brightPassPostProcess.width);
  74780. var sV = (1.0 / _this.brightPassPostProcess.height);
  74781. brightOffsets[0] = -0.5 * sU;
  74782. brightOffsets[1] = 0.5 * sV;
  74783. brightOffsets[2] = 0.5 * sU;
  74784. brightOffsets[3] = 0.5 * sV;
  74785. brightOffsets[4] = -0.5 * sU;
  74786. brightOffsets[5] = -0.5 * sV;
  74787. brightOffsets[6] = 0.5 * sU;
  74788. brightOffsets[7] = -0.5 * sV;
  74789. effect.setArray2("dsOffsets", brightOffsets);
  74790. effect.setFloat("brightThreshold", _this.brightThreshold);
  74791. };
  74792. // Add to pipeline
  74793. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBrightPass", function () { return _this.brightPassPostProcess; }, true));
  74794. };
  74795. // Create blur H&V post-processes
  74796. StandardRenderingPipeline.prototype._createBlurPostProcesses = function (scene, ratio, indice, blurWidthKey) {
  74797. var _this = this;
  74798. if (blurWidthKey === void 0) { blurWidthKey = "blurWidth"; }
  74799. var engine = scene.getEngine();
  74800. 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);
  74801. 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);
  74802. blurX.onActivateObservable.add(function () {
  74803. var dw = blurX.width / engine.getRenderWidth();
  74804. blurX.kernel = _this[blurWidthKey] * dw;
  74805. });
  74806. blurY.onActivateObservable.add(function () {
  74807. var dw = blurY.height / engine.getRenderHeight();
  74808. blurY.kernel = _this.horizontalBlur ? 64 * dw : _this[blurWidthKey] * dw;
  74809. });
  74810. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurH" + indice, function () { return blurX; }, true));
  74811. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRBlurV" + indice, function () { return blurY; }, true));
  74812. this.blurHPostProcesses.push(blurX);
  74813. this.blurVPostProcesses.push(blurY);
  74814. };
  74815. // Create texture adder post-process
  74816. StandardRenderingPipeline.prototype._createTextureAdderPostProcess = function (scene, ratio) {
  74817. var _this = this;
  74818. 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);
  74819. this.textureAdderPostProcess.onApply = function (effect) {
  74820. effect.setTextureFromPostProcess("otherSampler", _this._vlsEnabled ? _this._currentDepthOfFieldSource : _this.originalPostProcess);
  74821. effect.setTexture("lensSampler", _this.lensTexture);
  74822. effect.setFloat("exposure", _this.exposure);
  74823. _this._currentDepthOfFieldSource = _this.textureAdderFinalPostProcess;
  74824. };
  74825. // Add to pipeline
  74826. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRTextureAdder", function () { return _this.textureAdderPostProcess; }, true));
  74827. };
  74828. StandardRenderingPipeline.prototype._createVolumetricLightPostProcess = function (scene, ratio) {
  74829. var _this = this;
  74830. var geometryRenderer = scene.enableGeometryBufferRenderer();
  74831. geometryRenderer.enablePosition = true;
  74832. var geometry = geometryRenderer.getGBuffer();
  74833. // Base post-process
  74834. 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));
  74835. var depthValues = BABYLON.Vector2.Zero();
  74836. this.volumetricLightPostProcess.onApply = function (effect) {
  74837. if (_this.sourceLight && _this.sourceLight.getShadowGenerator() && _this._scene.activeCamera) {
  74838. var generator = _this.sourceLight.getShadowGenerator();
  74839. effect.setTexture("shadowMapSampler", generator.getShadowMap());
  74840. effect.setTexture("positionSampler", geometry.textures[2]);
  74841. effect.setColor3("sunColor", _this.sourceLight.diffuse);
  74842. effect.setVector3("sunDirection", _this.sourceLight.getShadowDirection());
  74843. effect.setVector3("cameraPosition", _this._scene.activeCamera.globalPosition);
  74844. effect.setMatrix("shadowViewProjection", generator.getTransformMatrix());
  74845. effect.setFloat("scatteringCoefficient", _this.volumetricLightCoefficient);
  74846. effect.setFloat("scatteringPower", _this.volumetricLightPower);
  74847. depthValues.x = generator.getLight().getDepthMinZ(_this._scene.activeCamera);
  74848. depthValues.y = generator.getLight().getDepthMaxZ(_this._scene.activeCamera);
  74849. effect.setVector2("depthValues", depthValues);
  74850. }
  74851. };
  74852. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLS", function () { return _this.volumetricLightPostProcess; }, true));
  74853. // Smooth
  74854. this._createBlurPostProcesses(scene, ratio / 4, 0, "volumetricLightBlurScale");
  74855. // Merge
  74856. this.volumetricLightMergePostProces = new BABYLON.PostProcess("HDRVLSMerge", "standard", [], ["originalSampler"], ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define VLSMERGE");
  74857. this.volumetricLightMergePostProces.onApply = function (effect) {
  74858. effect.setTextureFromPostProcess("originalSampler", _this._bloomEnabled ? _this.textureAdderFinalPostProcess : _this.originalPostProcess);
  74859. _this._currentDepthOfFieldSource = _this.volumetricLightFinalPostProcess;
  74860. };
  74861. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRVLSMerge", function () { return _this.volumetricLightMergePostProces; }, true));
  74862. };
  74863. // Create luminance
  74864. StandardRenderingPipeline.prototype._createLuminancePostProcesses = function (scene, textureType) {
  74865. var _this = this;
  74866. // Create luminance
  74867. var size = Math.pow(3, StandardRenderingPipeline.LuminanceSteps);
  74868. this.luminancePostProcess = new BABYLON.PostProcess("HDRLuminance", "standard", ["lumOffsets"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, "#define LUMINANCE", textureType);
  74869. var offsets = [];
  74870. this.luminancePostProcess.onApply = function (effect) {
  74871. var sU = (1.0 / _this.luminancePostProcess.width);
  74872. var sV = (1.0 / _this.luminancePostProcess.height);
  74873. offsets[0] = -0.5 * sU;
  74874. offsets[1] = 0.5 * sV;
  74875. offsets[2] = 0.5 * sU;
  74876. offsets[3] = 0.5 * sV;
  74877. offsets[4] = -0.5 * sU;
  74878. offsets[5] = -0.5 * sV;
  74879. offsets[6] = 0.5 * sU;
  74880. offsets[7] = -0.5 * sV;
  74881. effect.setArray2("lumOffsets", offsets);
  74882. };
  74883. // Add to pipeline
  74884. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminance", function () { return _this.luminancePostProcess; }, true));
  74885. // Create down sample luminance
  74886. for (var i = StandardRenderingPipeline.LuminanceSteps - 1; i >= 0; i--) {
  74887. var size = Math.pow(3, i);
  74888. var defines = "#define LUMINANCE_DOWN_SAMPLE\n";
  74889. if (i === 0) {
  74890. defines += "#define FINAL_DOWN_SAMPLER";
  74891. }
  74892. var postProcess = new BABYLON.PostProcess("HDRLuminanceDownSample" + i, "standard", ["dsOffsets", "halfDestPixelSize"], [], { width: size, height: size }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, defines, textureType);
  74893. this.luminanceDownSamplePostProcesses.push(postProcess);
  74894. }
  74895. // Create callbacks and add effects
  74896. var lastLuminance = this.luminancePostProcess;
  74897. this.luminanceDownSamplePostProcesses.forEach(function (pp, index) {
  74898. var downSampleOffsets = new Array(18);
  74899. pp.onApply = function (effect) {
  74900. if (!lastLuminance) {
  74901. return;
  74902. }
  74903. var id = 0;
  74904. for (var x = -1; x < 2; x++) {
  74905. for (var y = -1; y < 2; y++) {
  74906. downSampleOffsets[id] = x / lastLuminance.width;
  74907. downSampleOffsets[id + 1] = y / lastLuminance.height;
  74908. id += 2;
  74909. }
  74910. }
  74911. effect.setArray2("dsOffsets", downSampleOffsets);
  74912. effect.setFloat("halfDestPixelSize", 0.5 / lastLuminance.width);
  74913. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74914. lastLuminance = _this.luminancePostProcess;
  74915. }
  74916. else {
  74917. lastLuminance = pp;
  74918. }
  74919. };
  74920. if (index === _this.luminanceDownSamplePostProcesses.length - 1) {
  74921. pp.onAfterRender = function (effect) {
  74922. var pixel = scene.getEngine().readPixels(0, 0, 1, 1);
  74923. 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);
  74924. _this._hdrCurrentLuminance = (pixel[0] * bit_shift.x + pixel[1] * bit_shift.y + pixel[2] * bit_shift.z + pixel[3] * bit_shift.w) / 100.0;
  74925. };
  74926. }
  74927. _this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLuminanceDownSample" + index, function () { return pp; }, true));
  74928. });
  74929. };
  74930. // Create HDR post-process
  74931. StandardRenderingPipeline.prototype._createHdrPostProcess = function (scene, ratio) {
  74932. var _this = this;
  74933. 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);
  74934. var outputLiminance = 1;
  74935. var time = 0;
  74936. var lastTime = 0;
  74937. this.hdrPostProcess.onApply = function (effect) {
  74938. effect.setTextureFromPostProcess("textureAdderSampler", _this._currentDepthOfFieldSource);
  74939. time += scene.getEngine().getDeltaTime();
  74940. if (outputLiminance < 0) {
  74941. outputLiminance = _this._hdrCurrentLuminance;
  74942. }
  74943. else {
  74944. var dt = (lastTime - time) / 1000.0;
  74945. if (_this._hdrCurrentLuminance < outputLiminance + _this.hdrDecreaseRate * dt) {
  74946. outputLiminance += _this.hdrDecreaseRate * dt;
  74947. }
  74948. else if (_this._hdrCurrentLuminance > outputLiminance - _this.hdrIncreaseRate * dt) {
  74949. outputLiminance -= _this.hdrIncreaseRate * dt;
  74950. }
  74951. else {
  74952. outputLiminance = _this._hdrCurrentLuminance;
  74953. }
  74954. }
  74955. outputLiminance = BABYLON.Scalar.Clamp(outputLiminance, _this.hdrMinimumLuminance, 1e20);
  74956. effect.setFloat("averageLuminance", outputLiminance);
  74957. lastTime = time;
  74958. _this._currentDepthOfFieldSource = _this.hdrFinalPostProcess;
  74959. };
  74960. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDR", function () { return _this.hdrPostProcess; }, true));
  74961. };
  74962. // Create lens flare post-process
  74963. StandardRenderingPipeline.prototype._createLensFlarePostProcess = function (scene, ratio) {
  74964. var _this = this;
  74965. 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);
  74966. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlare", function () { return _this.lensFlarePostProcess; }, true));
  74967. this._createBlurPostProcesses(scene, ratio / 4, 2);
  74968. 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);
  74969. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRLensFlareCompose", function () { return _this.lensFlareComposePostProcess; }, true));
  74970. var resolution = new BABYLON.Vector2(0, 0);
  74971. // Lens flare
  74972. this.lensFlarePostProcess.onApply = function (effect) {
  74973. effect.setTextureFromPostProcess("textureSampler", _this._bloomEnabled ? _this.blurHPostProcesses[0] : _this.originalPostProcess);
  74974. effect.setTexture("lensColorSampler", _this.lensColorTexture);
  74975. effect.setFloat("strength", _this.lensFlareStrength);
  74976. effect.setFloat("ghostDispersal", _this.lensFlareGhostDispersal);
  74977. effect.setFloat("haloWidth", _this.lensFlareHaloWidth);
  74978. // Shift
  74979. resolution.x = _this.lensFlarePostProcess.width;
  74980. resolution.y = _this.lensFlarePostProcess.height;
  74981. effect.setVector2("resolution", resolution);
  74982. effect.setFloat("distortionStrength", _this.lensFlareDistortionStrength);
  74983. };
  74984. // Compose
  74985. 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);
  74986. 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);
  74987. this.lensFlareComposePostProcess.onApply = function (effect) {
  74988. if (!_this._scene.activeCamera) {
  74989. return;
  74990. }
  74991. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  74992. effect.setTexture("lensDirtSampler", _this.lensFlareDirtTexture);
  74993. effect.setTexture("lensStarSampler", _this.lensStarTexture);
  74994. // Lens start rotation matrix
  74995. var camerax = _this._scene.activeCamera.getViewMatrix().getRow(0);
  74996. var cameraz = _this._scene.activeCamera.getViewMatrix().getRow(2);
  74997. 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));
  74998. camRot *= 4.0;
  74999. 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);
  75000. var lensStarMatrix = scaleBias2.multiply(starRotation).multiply(scaleBias1);
  75001. effect.setMatrix("lensStarMatrix", lensStarMatrix);
  75002. _this._currentDepthOfFieldSource = _this.lensFlareFinalPostProcess;
  75003. };
  75004. };
  75005. // Create depth-of-field post-process
  75006. StandardRenderingPipeline.prototype._createDepthOfFieldPostProcess = function (scene, ratio) {
  75007. var _this = this;
  75008. 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);
  75009. this.depthOfFieldPostProcess.onApply = function (effect) {
  75010. effect.setTextureFromPostProcess("otherSampler", _this._currentDepthOfFieldSource);
  75011. effect.setTexture("depthSampler", _this._getDepthTexture());
  75012. effect.setFloat("distance", _this.depthOfFieldDistance);
  75013. };
  75014. // Add to pipeline
  75015. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRDepthOfField", function () { return _this.depthOfFieldPostProcess; }, true));
  75016. };
  75017. // Create motion blur post-process
  75018. StandardRenderingPipeline.prototype._createMotionBlurPostProcess = function (scene, ratio) {
  75019. var _this = this;
  75020. 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);
  75021. var motionScale = 0;
  75022. var prevViewProjection = BABYLON.Matrix.Identity();
  75023. var invViewProjection = BABYLON.Matrix.Identity();
  75024. var viewProjection = BABYLON.Matrix.Identity();
  75025. var screenSize = BABYLON.Vector2.Zero();
  75026. this.motionBlurPostProcess.onApply = function (effect) {
  75027. viewProjection = scene.getProjectionMatrix().multiply(scene.getViewMatrix());
  75028. viewProjection.invertToRef(invViewProjection);
  75029. effect.setMatrix("inverseViewProjection", invViewProjection);
  75030. effect.setMatrix("prevViewProjection", prevViewProjection);
  75031. prevViewProjection = viewProjection;
  75032. screenSize.x = _this.motionBlurPostProcess.width;
  75033. screenSize.y = _this.motionBlurPostProcess.height;
  75034. effect.setVector2("screenSize", screenSize);
  75035. motionScale = scene.getEngine().getFps() / 60.0;
  75036. effect.setFloat("motionScale", motionScale);
  75037. effect.setFloat("motionStrength", _this.motionStrength);
  75038. effect.setTexture("depthSampler", _this._getDepthTexture());
  75039. };
  75040. this.addEffect(new BABYLON.PostProcessRenderEffect(scene.getEngine(), "HDRMotionBlur", function () { return _this.motionBlurPostProcess; }, true));
  75041. };
  75042. StandardRenderingPipeline.prototype._getDepthTexture = function () {
  75043. if (this._scene.getEngine().getCaps().drawBuffersExtension) {
  75044. var renderer = this._scene.enableGeometryBufferRenderer();
  75045. return renderer.getGBuffer().textures[0];
  75046. }
  75047. return this._scene.enableDepthRenderer().getDepthMap();
  75048. };
  75049. StandardRenderingPipeline.prototype._disposePostProcesses = function () {
  75050. for (var i = 0; i < this._cameras.length; i++) {
  75051. var camera = this._cameras[i];
  75052. if (this.originalPostProcess) {
  75053. this.originalPostProcess.dispose(camera);
  75054. }
  75055. if (this.downSampleX4PostProcess) {
  75056. this.downSampleX4PostProcess.dispose(camera);
  75057. }
  75058. if (this.brightPassPostProcess) {
  75059. this.brightPassPostProcess.dispose(camera);
  75060. }
  75061. if (this.textureAdderPostProcess) {
  75062. this.textureAdderPostProcess.dispose(camera);
  75063. }
  75064. if (this.textureAdderFinalPostProcess) {
  75065. this.textureAdderFinalPostProcess.dispose(camera);
  75066. }
  75067. if (this.volumetricLightPostProcess) {
  75068. this.volumetricLightPostProcess.dispose(camera);
  75069. }
  75070. if (this.volumetricLightSmoothXPostProcess) {
  75071. this.volumetricLightSmoothXPostProcess.dispose(camera);
  75072. }
  75073. if (this.volumetricLightSmoothYPostProcess) {
  75074. this.volumetricLightSmoothYPostProcess.dispose(camera);
  75075. }
  75076. if (this.volumetricLightMergePostProces) {
  75077. this.volumetricLightMergePostProces.dispose(camera);
  75078. }
  75079. if (this.volumetricLightFinalPostProcess) {
  75080. this.volumetricLightFinalPostProcess.dispose(camera);
  75081. }
  75082. if (this.lensFlarePostProcess) {
  75083. this.lensFlarePostProcess.dispose(camera);
  75084. }
  75085. if (this.lensFlareComposePostProcess) {
  75086. this.lensFlareComposePostProcess.dispose(camera);
  75087. }
  75088. for (var j = 0; j < this.luminanceDownSamplePostProcesses.length; j++) {
  75089. this.luminanceDownSamplePostProcesses[j].dispose(camera);
  75090. }
  75091. if (this.luminancePostProcess) {
  75092. this.luminancePostProcess.dispose(camera);
  75093. }
  75094. if (this.hdrPostProcess) {
  75095. this.hdrPostProcess.dispose(camera);
  75096. }
  75097. if (this.hdrFinalPostProcess) {
  75098. this.hdrFinalPostProcess.dispose(camera);
  75099. }
  75100. if (this.depthOfFieldPostProcess) {
  75101. this.depthOfFieldPostProcess.dispose(camera);
  75102. }
  75103. if (this.motionBlurPostProcess) {
  75104. this.motionBlurPostProcess.dispose(camera);
  75105. }
  75106. for (var j = 0; j < this.blurHPostProcesses.length; j++) {
  75107. this.blurHPostProcesses[j].dispose(camera);
  75108. }
  75109. for (var j = 0; j < this.blurVPostProcesses.length; j++) {
  75110. this.blurVPostProcesses[j].dispose(camera);
  75111. }
  75112. }
  75113. this.originalPostProcess = null;
  75114. this.downSampleX4PostProcess = null;
  75115. this.brightPassPostProcess = null;
  75116. this.textureAdderPostProcess = null;
  75117. this.textureAdderFinalPostProcess = null;
  75118. this.volumetricLightPostProcess = null;
  75119. this.volumetricLightSmoothXPostProcess = null;
  75120. this.volumetricLightSmoothYPostProcess = null;
  75121. this.volumetricLightMergePostProces = null;
  75122. this.volumetricLightFinalPostProcess = null;
  75123. this.lensFlarePostProcess = null;
  75124. this.lensFlareComposePostProcess = null;
  75125. this.luminancePostProcess = null;
  75126. this.hdrPostProcess = null;
  75127. this.hdrFinalPostProcess = null;
  75128. this.depthOfFieldPostProcess = null;
  75129. this.motionBlurPostProcess = null;
  75130. this.luminanceDownSamplePostProcesses = [];
  75131. this.blurHPostProcesses = [];
  75132. this.blurVPostProcesses = [];
  75133. };
  75134. /**
  75135. * Dispose of the pipeline and stop all post processes
  75136. */
  75137. StandardRenderingPipeline.prototype.dispose = function () {
  75138. this._disposePostProcesses();
  75139. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  75140. _super.prototype.dispose.call(this);
  75141. };
  75142. /**
  75143. * Serialize the rendering pipeline (Used when exporting)
  75144. * @returns the serialized object
  75145. */
  75146. StandardRenderingPipeline.prototype.serialize = function () {
  75147. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  75148. if (this.sourceLight) {
  75149. serializationObject.sourceLightId = this.sourceLight.id;
  75150. }
  75151. serializationObject.customType = "StandardRenderingPipeline";
  75152. return serializationObject;
  75153. };
  75154. /**
  75155. * Parse the serialized pipeline
  75156. * @param source Source pipeline.
  75157. * @param scene The scene to load the pipeline to.
  75158. * @param rootUrl The URL of the serialized pipeline.
  75159. * @returns An instantiated pipeline from the serialized object.
  75160. */
  75161. StandardRenderingPipeline.Parse = function (source, scene, rootUrl) {
  75162. var p = BABYLON.SerializationHelper.Parse(function () { return new StandardRenderingPipeline(source._name, scene, source._ratio); }, source, scene, rootUrl);
  75163. if (source.sourceLightId) {
  75164. p.sourceLight = scene.getLightByID(source.sourceLightId);
  75165. }
  75166. return p;
  75167. };
  75168. // Luminance steps
  75169. StandardRenderingPipeline.LuminanceSteps = 6;
  75170. __decorate([
  75171. BABYLON.serialize()
  75172. ], StandardRenderingPipeline.prototype, "brightThreshold", void 0);
  75173. __decorate([
  75174. BABYLON.serialize()
  75175. ], StandardRenderingPipeline.prototype, "blurWidth", void 0);
  75176. __decorate([
  75177. BABYLON.serialize()
  75178. ], StandardRenderingPipeline.prototype, "horizontalBlur", void 0);
  75179. __decorate([
  75180. BABYLON.serialize()
  75181. ], StandardRenderingPipeline.prototype, "exposure", void 0);
  75182. __decorate([
  75183. BABYLON.serializeAsTexture("lensTexture")
  75184. ], StandardRenderingPipeline.prototype, "lensTexture", void 0);
  75185. __decorate([
  75186. BABYLON.serialize()
  75187. ], StandardRenderingPipeline.prototype, "volumetricLightCoefficient", void 0);
  75188. __decorate([
  75189. BABYLON.serialize()
  75190. ], StandardRenderingPipeline.prototype, "volumetricLightPower", void 0);
  75191. __decorate([
  75192. BABYLON.serialize()
  75193. ], StandardRenderingPipeline.prototype, "volumetricLightBlurScale", void 0);
  75194. __decorate([
  75195. BABYLON.serialize()
  75196. ], StandardRenderingPipeline.prototype, "hdrMinimumLuminance", void 0);
  75197. __decorate([
  75198. BABYLON.serialize()
  75199. ], StandardRenderingPipeline.prototype, "hdrDecreaseRate", void 0);
  75200. __decorate([
  75201. BABYLON.serialize()
  75202. ], StandardRenderingPipeline.prototype, "hdrIncreaseRate", void 0);
  75203. __decorate([
  75204. BABYLON.serializeAsTexture("lensColorTexture")
  75205. ], StandardRenderingPipeline.prototype, "lensColorTexture", void 0);
  75206. __decorate([
  75207. BABYLON.serialize()
  75208. ], StandardRenderingPipeline.prototype, "lensFlareStrength", void 0);
  75209. __decorate([
  75210. BABYLON.serialize()
  75211. ], StandardRenderingPipeline.prototype, "lensFlareGhostDispersal", void 0);
  75212. __decorate([
  75213. BABYLON.serialize()
  75214. ], StandardRenderingPipeline.prototype, "lensFlareHaloWidth", void 0);
  75215. __decorate([
  75216. BABYLON.serialize()
  75217. ], StandardRenderingPipeline.prototype, "lensFlareDistortionStrength", void 0);
  75218. __decorate([
  75219. BABYLON.serializeAsTexture("lensStarTexture")
  75220. ], StandardRenderingPipeline.prototype, "lensStarTexture", void 0);
  75221. __decorate([
  75222. BABYLON.serializeAsTexture("lensFlareDirtTexture")
  75223. ], StandardRenderingPipeline.prototype, "lensFlareDirtTexture", void 0);
  75224. __decorate([
  75225. BABYLON.serialize()
  75226. ], StandardRenderingPipeline.prototype, "depthOfFieldDistance", void 0);
  75227. __decorate([
  75228. BABYLON.serialize()
  75229. ], StandardRenderingPipeline.prototype, "depthOfFieldBlurWidth", void 0);
  75230. __decorate([
  75231. BABYLON.serialize()
  75232. ], StandardRenderingPipeline.prototype, "motionStrength", void 0);
  75233. __decorate([
  75234. BABYLON.serialize()
  75235. ], StandardRenderingPipeline.prototype, "_ratio", void 0);
  75236. __decorate([
  75237. BABYLON.serialize()
  75238. ], StandardRenderingPipeline.prototype, "BloomEnabled", null);
  75239. __decorate([
  75240. BABYLON.serialize()
  75241. ], StandardRenderingPipeline.prototype, "DepthOfFieldEnabled", null);
  75242. __decorate([
  75243. BABYLON.serialize()
  75244. ], StandardRenderingPipeline.prototype, "LensFlareEnabled", null);
  75245. __decorate([
  75246. BABYLON.serialize()
  75247. ], StandardRenderingPipeline.prototype, "HDREnabled", null);
  75248. __decorate([
  75249. BABYLON.serialize()
  75250. ], StandardRenderingPipeline.prototype, "VLSEnabled", null);
  75251. __decorate([
  75252. BABYLON.serialize()
  75253. ], StandardRenderingPipeline.prototype, "MotionBlurEnabled", null);
  75254. __decorate([
  75255. BABYLON.serialize()
  75256. ], StandardRenderingPipeline.prototype, "volumetricLightStepsCount", null);
  75257. __decorate([
  75258. BABYLON.serialize()
  75259. ], StandardRenderingPipeline.prototype, "motionBlurSamples", null);
  75260. return StandardRenderingPipeline;
  75261. }(BABYLON.PostProcessRenderPipeline));
  75262. BABYLON.StandardRenderingPipeline = StandardRenderingPipeline;
  75263. })(BABYLON || (BABYLON = {}));
  75264. //# sourceMappingURL=babylon.standardRenderingPipeline.js.map
  75265. var BABYLON;
  75266. (function (BABYLON) {
  75267. var FxaaPostProcess = /** @class */ (function (_super) {
  75268. __extends(FxaaPostProcess, _super);
  75269. function FxaaPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  75270. if (camera === void 0) { camera = null; }
  75271. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75272. var _this = _super.call(this, name, "fxaa", ["texelSize"], null, options, camera, samplingMode || BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, reusable, null, textureType, "fxaa", undefined, true) || this;
  75273. var defines = _this._getDefines();
  75274. _this.updateEffect(defines);
  75275. _this.onApplyObservable.add(function (effect) {
  75276. var texelSize = _this.texelSize;
  75277. effect.setFloat2("texelSize", texelSize.x, texelSize.y);
  75278. });
  75279. return _this;
  75280. }
  75281. FxaaPostProcess.prototype._getDefines = function () {
  75282. var engine = this.getEngine();
  75283. if (!engine) {
  75284. return null;
  75285. }
  75286. var glInfo = engine.getGlInfo();
  75287. if (glInfo && glInfo.renderer && glInfo.renderer.toLowerCase().indexOf("mali") > -1) {
  75288. return "#define MALI 1\n";
  75289. }
  75290. return null;
  75291. };
  75292. return FxaaPostProcess;
  75293. }(BABYLON.PostProcess));
  75294. BABYLON.FxaaPostProcess = FxaaPostProcess;
  75295. })(BABYLON || (BABYLON = {}));
  75296. //# sourceMappingURL=babylon.fxaaPostProcess.js.map
  75297. var BABYLON;
  75298. (function (BABYLON) {
  75299. /**
  75300. * The ChromaticAberrationPostProcess separates the rgb channels in an image to produce chromatic distortion around the edges of the screen
  75301. */
  75302. var ChromaticAberrationPostProcess = /** @class */ (function (_super) {
  75303. __extends(ChromaticAberrationPostProcess, _super);
  75304. /**
  75305. * Creates a new instance ChromaticAberrationPostProcess
  75306. * @param name The name of the effect.
  75307. * @param screenWidth The width of the screen to apply the effect on.
  75308. * @param screenHeight The height of the screen to apply the effect on.
  75309. * @param options The required width/height ratio to downsize to before computing the render pass.
  75310. * @param camera The camera to apply the render pass to.
  75311. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75312. * @param engine The engine which the post process will be applied. (default: current engine)
  75313. * @param reusable If the post process can be reused on the same frame. (default: false)
  75314. * @param textureType Type of textures used when performing the post process. (default: 0)
  75315. * @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)
  75316. */
  75317. function ChromaticAberrationPostProcess(name, screenWidth, screenHeight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75318. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75319. if (blockCompilation === void 0) { blockCompilation = false; }
  75320. 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;
  75321. /**
  75322. * The amount of seperation of rgb channels (default: 30)
  75323. */
  75324. _this.aberrationAmount = 30;
  75325. /**
  75326. * The amount the effect will increase for pixels closer to the edge of the screen. (default: 0)
  75327. */
  75328. _this.radialIntensity = 0;
  75329. /**
  75330. * 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))
  75331. */
  75332. _this.direction = new BABYLON.Vector2(0.707, 0.707);
  75333. /**
  75334. * 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))
  75335. */
  75336. _this.centerPosition = new BABYLON.Vector2(0.5, 0.5);
  75337. _this.onApplyObservable.add(function (effect) {
  75338. effect.setFloat('chromatic_aberration', _this.aberrationAmount);
  75339. effect.setFloat('screen_width', screenWidth);
  75340. effect.setFloat('screen_height', screenHeight);
  75341. effect.setFloat('radialIntensity', _this.radialIntensity);
  75342. effect.setFloat2('direction', _this.direction.x, _this.direction.y);
  75343. effect.setFloat2('centerPosition', _this.centerPosition.x, _this.centerPosition.y);
  75344. });
  75345. return _this;
  75346. }
  75347. return ChromaticAberrationPostProcess;
  75348. }(BABYLON.PostProcess));
  75349. BABYLON.ChromaticAberrationPostProcess = ChromaticAberrationPostProcess;
  75350. })(BABYLON || (BABYLON = {}));
  75351. //# sourceMappingURL=babylon.chromaticAberrationPostProcess.js.map
  75352. var BABYLON;
  75353. (function (BABYLON) {
  75354. /**
  75355. * The GrainPostProcess adds noise to the image at mid luminance levels
  75356. */
  75357. var GrainPostProcess = /** @class */ (function (_super) {
  75358. __extends(GrainPostProcess, _super);
  75359. /**
  75360. * Creates a new instance of @see GrainPostProcess
  75361. * @param name The name of the effect.
  75362. * @param options The required width/height ratio to downsize to before computing the render pass.
  75363. * @param camera The camera to apply the render pass to.
  75364. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75365. * @param engine The engine which the post process will be applied. (default: current engine)
  75366. * @param reusable If the post process can be reused on the same frame. (default: false)
  75367. * @param textureType Type of textures used when performing the post process. (default: 0)
  75368. * @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)
  75369. */
  75370. function GrainPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75371. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75372. if (blockCompilation === void 0) { blockCompilation = false; }
  75373. var _this = _super.call(this, name, "grain", ["intensity", "animatedSeed"], [], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75374. /**
  75375. * The intensity of the grain added (default: 30)
  75376. */
  75377. _this.intensity = 30;
  75378. /**
  75379. * If the grain should be randomized on every frame
  75380. */
  75381. _this.animated = false;
  75382. _this.onApplyObservable.add(function (effect) {
  75383. effect.setFloat('intensity', _this.intensity);
  75384. effect.setFloat('animatedSeed', _this.animated ? Math.random() + 1 : 1);
  75385. });
  75386. return _this;
  75387. }
  75388. return GrainPostProcess;
  75389. }(BABYLON.PostProcess));
  75390. BABYLON.GrainPostProcess = GrainPostProcess;
  75391. })(BABYLON || (BABYLON = {}));
  75392. //# sourceMappingURL=babylon.grainPostProcess.js.map
  75393. var BABYLON;
  75394. (function (BABYLON) {
  75395. /**
  75396. * The SharpenPostProcess applies a sharpen kernel to every pixel
  75397. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  75398. */
  75399. var SharpenPostProcess = /** @class */ (function (_super) {
  75400. __extends(SharpenPostProcess, _super);
  75401. /**
  75402. * Creates a new instance ConvolutionPostProcess
  75403. * @param name The name of the effect.
  75404. * @param options The required width/height ratio to downsize to before computing the render pass.
  75405. * @param camera The camera to apply the render pass to.
  75406. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75407. * @param engine The engine which the post process will be applied. (default: current engine)
  75408. * @param reusable If the post process can be reused on the same frame. (default: false)
  75409. * @param textureType Type of textures used when performing the post process. (default: 0)
  75410. * @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)
  75411. */
  75412. function SharpenPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75413. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75414. if (blockCompilation === void 0) { blockCompilation = false; }
  75415. var _this = _super.call(this, name, "sharpen", ["sharpnessAmounts", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75416. /**
  75417. * How much of the original color should be applied. Setting this to 0 will display edge detection. (default: 1)
  75418. */
  75419. _this.colorAmount = 1.0;
  75420. /**
  75421. * How much sharpness should be applied (default: 0.3)
  75422. */
  75423. _this.edgeAmount = 0.3;
  75424. _this.onApply = function (effect) {
  75425. effect.setFloat2("screenSize", _this.width, _this.height);
  75426. effect.setFloat2("sharpnessAmounts", _this.edgeAmount, _this.colorAmount);
  75427. };
  75428. return _this;
  75429. }
  75430. return SharpenPostProcess;
  75431. }(BABYLON.PostProcess));
  75432. BABYLON.SharpenPostProcess = SharpenPostProcess;
  75433. })(BABYLON || (BABYLON = {}));
  75434. //# sourceMappingURL=babylon.sharpenPostProcess.js.map
  75435. var BABYLON;
  75436. (function (BABYLON) {
  75437. /**
  75438. * The Blur Post Process which blurs an image based on a kernel and direction.
  75439. * Can be used twice in x and y directions to perform a guassian blur in two passes.
  75440. */
  75441. var BlurPostProcess = /** @class */ (function (_super) {
  75442. __extends(BlurPostProcess, _super);
  75443. /**
  75444. * Creates a new instance BlurPostProcess
  75445. * @param name The name of the effect.
  75446. * @param direction The direction in which to blur the image.
  75447. * @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.
  75448. * @param options The required width/height ratio to downsize to before computing the render pass. (Use 1.0 for full size)
  75449. * @param camera The camera to apply the render pass to.
  75450. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75451. * @param engine The engine which the post process will be applied. (default: current engine)
  75452. * @param reusable If the post process can be reused on the same frame. (default: false)
  75453. * @param textureType Type of textures used when performing the post process. (default: 0)
  75454. * @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)
  75455. */
  75456. function BlurPostProcess(name, /** The direction in which to blur the image. */ direction, kernel, options, camera, samplingMode, engine, reusable, textureType, defines, blockCompilation) {
  75457. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75458. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75459. if (defines === void 0) { defines = ""; }
  75460. if (blockCompilation === void 0) { blockCompilation = false; }
  75461. 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;
  75462. _this.direction = direction;
  75463. _this.blockCompilation = blockCompilation;
  75464. _this._packedFloat = false;
  75465. _this._staticDefines = "";
  75466. _this._staticDefines = defines;
  75467. _this.onApplyObservable.add(function (effect) {
  75468. if (_this._outputTexture) {
  75469. effect.setFloat2('delta', (1 / _this._outputTexture.width) * _this.direction.x, (1 / _this._outputTexture.height) * _this.direction.y);
  75470. }
  75471. else {
  75472. effect.setFloat2('delta', (1 / _this.width) * _this.direction.x, (1 / _this.height) * _this.direction.y);
  75473. }
  75474. });
  75475. _this.kernel = kernel;
  75476. return _this;
  75477. }
  75478. Object.defineProperty(BlurPostProcess.prototype, "kernel", {
  75479. /**
  75480. * Gets the length in pixels of the blur sample region
  75481. */
  75482. get: function () {
  75483. return this._idealKernel;
  75484. },
  75485. /**
  75486. * Sets the length in pixels of the blur sample region
  75487. */
  75488. set: function (v) {
  75489. if (this._idealKernel === v) {
  75490. return;
  75491. }
  75492. v = Math.max(v, 1);
  75493. this._idealKernel = v;
  75494. this._kernel = this._nearestBestKernel(v);
  75495. if (!this.blockCompilation) {
  75496. this._updateParameters();
  75497. }
  75498. },
  75499. enumerable: true,
  75500. configurable: true
  75501. });
  75502. Object.defineProperty(BlurPostProcess.prototype, "packedFloat", {
  75503. /**
  75504. * Gets wether or not the blur is unpacking/repacking floats
  75505. */
  75506. get: function () {
  75507. return this._packedFloat;
  75508. },
  75509. /**
  75510. * Sets wether or not the blur needs to unpack/repack floats
  75511. */
  75512. set: function (v) {
  75513. if (this._packedFloat === v) {
  75514. return;
  75515. }
  75516. this._packedFloat = v;
  75517. if (!this.blockCompilation) {
  75518. this._updateParameters();
  75519. }
  75520. },
  75521. enumerable: true,
  75522. configurable: true
  75523. });
  75524. /**
  75525. * Updates the effect with the current post process compile time values and recompiles the shader.
  75526. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75527. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75528. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75529. * @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
  75530. * @param onCompiled Called when the shader has been compiled.
  75531. * @param onError Called if there is an error when compiling a shader.
  75532. */
  75533. BlurPostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75534. if (defines === void 0) { defines = null; }
  75535. if (uniforms === void 0) { uniforms = null; }
  75536. if (samplers === void 0) { samplers = null; }
  75537. this._updateParameters(onCompiled, onError);
  75538. };
  75539. BlurPostProcess.prototype._updateParameters = function (onCompiled, onError) {
  75540. // Generate sampling offsets and weights
  75541. var N = this._kernel;
  75542. var centerIndex = (N - 1) / 2;
  75543. // Generate Gaussian sampling weights over kernel
  75544. var offsets = [];
  75545. var weights = [];
  75546. var totalWeight = 0;
  75547. for (var i = 0; i < N; i++) {
  75548. var u = i / (N - 1);
  75549. var w = this._gaussianWeight(u * 2.0 - 1);
  75550. offsets[i] = (i - centerIndex);
  75551. weights[i] = w;
  75552. totalWeight += w;
  75553. }
  75554. // Normalize weights
  75555. for (var i = 0; i < weights.length; i++) {
  75556. weights[i] /= totalWeight;
  75557. }
  75558. // Optimize: combine samples to take advantage of hardware linear sampling
  75559. // Walk from left to center, combining pairs (symmetrically)
  75560. var linearSamplingWeights = [];
  75561. var linearSamplingOffsets = [];
  75562. var linearSamplingMap = [];
  75563. for (var i = 0; i <= centerIndex; i += 2) {
  75564. var j = Math.min(i + 1, Math.floor(centerIndex));
  75565. var singleCenterSample = i === j;
  75566. if (singleCenterSample) {
  75567. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75568. }
  75569. else {
  75570. var sharedCell = j === centerIndex;
  75571. var weightLinear = (weights[i] + weights[j] * (sharedCell ? .5 : 1.));
  75572. var offsetLinear = offsets[i] + 1 / (1 + weights[i] / weights[j]);
  75573. if (offsetLinear === 0) {
  75574. linearSamplingMap.push({ o: offsets[i], w: weights[i] });
  75575. linearSamplingMap.push({ o: offsets[i + 1], w: weights[i + 1] });
  75576. }
  75577. else {
  75578. linearSamplingMap.push({ o: offsetLinear, w: weightLinear });
  75579. linearSamplingMap.push({ o: -offsetLinear, w: weightLinear });
  75580. }
  75581. }
  75582. }
  75583. for (var i = 0; i < linearSamplingMap.length; i++) {
  75584. linearSamplingOffsets[i] = linearSamplingMap[i].o;
  75585. linearSamplingWeights[i] = linearSamplingMap[i].w;
  75586. }
  75587. // Replace with optimized
  75588. offsets = linearSamplingOffsets;
  75589. weights = linearSamplingWeights;
  75590. // Generate shaders
  75591. var maxVaryingRows = this.getEngine().getCaps().maxVaryingVectors;
  75592. var freeVaryingVec2 = Math.max(maxVaryingRows, 0.) - 1; // Because of sampleCenter
  75593. var varyingCount = Math.min(offsets.length, freeVaryingVec2);
  75594. var defines = "";
  75595. defines += this._staticDefines;
  75596. // The DOF fragment should ignore the center pixel when looping as it is handled manualy in the fragment shader.
  75597. if (this._staticDefines.indexOf("DOF") != -1) {
  75598. defines += "#define CENTER_WEIGHT " + this._glslFloat(weights[varyingCount - 1]) + "\r\n";
  75599. varyingCount--;
  75600. }
  75601. for (var i = 0; i < varyingCount; i++) {
  75602. defines += "#define KERNEL_OFFSET" + i + " " + this._glslFloat(offsets[i]) + "\r\n";
  75603. defines += "#define KERNEL_WEIGHT" + i + " " + this._glslFloat(weights[i]) + "\r\n";
  75604. }
  75605. var depCount = 0;
  75606. for (var i = freeVaryingVec2; i < offsets.length; i++) {
  75607. defines += "#define KERNEL_DEP_OFFSET" + depCount + " " + this._glslFloat(offsets[i]) + "\r\n";
  75608. defines += "#define KERNEL_DEP_WEIGHT" + depCount + " " + this._glslFloat(weights[i]) + "\r\n";
  75609. depCount++;
  75610. }
  75611. if (this.packedFloat) {
  75612. defines += "#define PACKEDFLOAT 1";
  75613. }
  75614. this.blockCompilation = false;
  75615. _super.prototype.updateEffect.call(this, defines, null, null, {
  75616. varyingCount: varyingCount,
  75617. depCount: depCount
  75618. }, onCompiled, onError);
  75619. };
  75620. /**
  75621. * Best kernels are odd numbers that when divided by 2, their integer part is even, so 5, 9 or 13.
  75622. * Other odd kernels optimize correctly but require proportionally more samples, even kernels are
  75623. * possible but will produce minor visual artifacts. Since each new kernel requires a new shader we
  75624. * want to minimize kernel changes, having gaps between physical kernels is helpful in that regard.
  75625. * The gaps between physical kernels are compensated for in the weighting of the samples
  75626. * @param idealKernel Ideal blur kernel.
  75627. * @return Nearest best kernel.
  75628. */
  75629. BlurPostProcess.prototype._nearestBestKernel = function (idealKernel) {
  75630. var v = Math.round(idealKernel);
  75631. for (var _i = 0, _a = [v, v - 1, v + 1, v - 2, v + 2]; _i < _a.length; _i++) {
  75632. var k = _a[_i];
  75633. if (((k % 2) !== 0) && ((Math.floor(k / 2) % 2) === 0) && k > 0) {
  75634. return Math.max(k, 3);
  75635. }
  75636. }
  75637. return Math.max(v, 3);
  75638. };
  75639. /**
  75640. * Calculates the value of a Gaussian distribution with sigma 3 at a given point.
  75641. * @param x The point on the Gaussian distribution to sample.
  75642. * @return the value of the Gaussian function at x.
  75643. */
  75644. BlurPostProcess.prototype._gaussianWeight = function (x) {
  75645. //reference: Engine/ImageProcessingBlur.cpp #dcc760
  75646. // We are evaluating the Gaussian (normal) distribution over a kernel parameter space of [-1,1],
  75647. // so we truncate at three standard deviations by setting stddev (sigma) to 1/3.
  75648. // The choice of 3-sigma truncation is common but arbitrary, and means that the signal is
  75649. // truncated at around 1.3% of peak strength.
  75650. //the distribution is scaled to account for the difference between the actual kernel size and the requested kernel size
  75651. var sigma = (1 / 3);
  75652. var denominator = Math.sqrt(2.0 * Math.PI) * sigma;
  75653. var exponent = -((x * x) / (2.0 * sigma * sigma));
  75654. var weight = (1.0 / denominator) * Math.exp(exponent);
  75655. return weight;
  75656. };
  75657. /**
  75658. * Generates a string that can be used as a floating point number in GLSL.
  75659. * @param x Value to print.
  75660. * @param decimalFigures Number of decimal places to print the number to (excluding trailing 0s).
  75661. * @return GLSL float string.
  75662. */
  75663. BlurPostProcess.prototype._glslFloat = function (x, decimalFigures) {
  75664. if (decimalFigures === void 0) { decimalFigures = 8; }
  75665. return x.toFixed(decimalFigures).replace(/0+$/, '');
  75666. };
  75667. return BlurPostProcess;
  75668. }(BABYLON.PostProcess));
  75669. BABYLON.BlurPostProcess = BlurPostProcess;
  75670. })(BABYLON || (BABYLON = {}));
  75671. //# sourceMappingURL=babylon.blurPostProcess.js.map
  75672. var BABYLON;
  75673. (function (BABYLON) {
  75674. /**
  75675. * The DepthOfFieldBlurPostProcess applied a blur in a give direction.
  75676. * This blur differs from the standard BlurPostProcess as it attempts to avoid blurring pixels
  75677. * based on samples that have a large difference in distance than the center pixel.
  75678. * See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75679. */
  75680. var DepthOfFieldBlurPostProcess = /** @class */ (function (_super) {
  75681. __extends(DepthOfFieldBlurPostProcess, _super);
  75682. /**
  75683. * Creates a new instance CircleOfConfusionPostProcess
  75684. * @param name The name of the effect.
  75685. * @param scene The scene the effect belongs to.
  75686. * @param direction The direction the blur should be applied.
  75687. * @param kernel The size of the kernel used to blur.
  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 circleOfConfusion The circle of confusion + depth map to be used to avoid blurring accross edges
  75691. * @param imageToBlur The image to apply the blur to (default: Current rendered frame)
  75692. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75693. * @param engine The engine which the post process will be applied. (default: current engine)
  75694. * @param reusable If the post process can be reused on the same frame. (default: false)
  75695. * @param textureType Type of textures used when performing the post process. (default: 0)
  75696. * @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)
  75697. */
  75698. function DepthOfFieldBlurPostProcess(name, scene, direction, kernel, options, camera, circleOfConfusion, imageToBlur, samplingMode, engine, reusable, textureType, blockCompilation) {
  75699. if (imageToBlur === void 0) { imageToBlur = null; }
  75700. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  75701. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75702. if (blockCompilation === void 0) { blockCompilation = false; }
  75703. 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;
  75704. _this.direction = direction;
  75705. _this.onApplyObservable.add(function (effect) {
  75706. if (imageToBlur != null) {
  75707. effect.setTextureFromPostProcess("textureSampler", imageToBlur);
  75708. }
  75709. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75710. if (scene.activeCamera) {
  75711. effect.setFloat2('cameraMinMaxZ', scene.activeCamera.minZ, scene.activeCamera.maxZ);
  75712. }
  75713. });
  75714. return _this;
  75715. }
  75716. return DepthOfFieldBlurPostProcess;
  75717. }(BABYLON.BlurPostProcess));
  75718. BABYLON.DepthOfFieldBlurPostProcess = DepthOfFieldBlurPostProcess;
  75719. })(BABYLON || (BABYLON = {}));
  75720. //# sourceMappingURL=babylon.depthOfFieldBlurPostProcess.js.map
  75721. var BABYLON;
  75722. (function (BABYLON) {
  75723. /**
  75724. * Options to be set when merging outputs from the default pipeline.
  75725. */
  75726. var DepthOfFieldMergePostProcessOptions = /** @class */ (function () {
  75727. function DepthOfFieldMergePostProcessOptions() {
  75728. }
  75729. return DepthOfFieldMergePostProcessOptions;
  75730. }());
  75731. BABYLON.DepthOfFieldMergePostProcessOptions = DepthOfFieldMergePostProcessOptions;
  75732. /**
  75733. * The DepthOfFieldMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  75734. */
  75735. var DepthOfFieldMergePostProcess = /** @class */ (function (_super) {
  75736. __extends(DepthOfFieldMergePostProcess, _super);
  75737. /**
  75738. * Creates a new instance of DepthOfFieldMergePostProcess
  75739. * @param name The name of the effect.
  75740. * @param originalFromInput Post process which's input will be used for the merge.
  75741. * @param circleOfConfusion Circle of confusion post process which's output will be used to blur each pixel.
  75742. * @param blurSteps Blur post processes from low to high which will be mixed with the original image.
  75743. * @param options The required width/height ratio to downsize to before computing the render pass.
  75744. * @param camera The camera to apply the render pass to.
  75745. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75746. * @param engine The engine which the post process will be applied. (default: current engine)
  75747. * @param reusable If the post process can be reused on the same frame. (default: false)
  75748. * @param textureType Type of textures used when performing the post process. (default: 0)
  75749. * @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)
  75750. */
  75751. function DepthOfFieldMergePostProcess(name, originalFromInput, circleOfConfusion, blurSteps, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75752. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75753. if (blockCompilation === void 0) { blockCompilation = false; }
  75754. var _this = _super.call(this, name, "depthOfFieldMerge", [], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  75755. _this.blurSteps = blurSteps;
  75756. _this.onApplyObservable.add(function (effect) {
  75757. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  75758. effect.setTextureFromPostProcessOutput("circleOfConfusionSampler", circleOfConfusion);
  75759. blurSteps.forEach(function (step, index) {
  75760. effect.setTextureFromPostProcessOutput("blurStep" + (blurSteps.length - index - 1), step);
  75761. });
  75762. });
  75763. if (!blockCompilation) {
  75764. _this.updateEffect();
  75765. }
  75766. return _this;
  75767. }
  75768. /**
  75769. * Updates the effect with the current post process compile time values and recompiles the shader.
  75770. * @param defines Define statements that should be added at the beginning of the shader. (default: null)
  75771. * @param uniforms Set of uniform variables that will be passed to the shader. (default: null)
  75772. * @param samplers Set of Texture2D variables that will be passed to the shader. (default: null)
  75773. * @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
  75774. * @param onCompiled Called when the shader has been compiled.
  75775. * @param onError Called if there is an error when compiling a shader.
  75776. */
  75777. DepthOfFieldMergePostProcess.prototype.updateEffect = function (defines, uniforms, samplers, indexParameters, onCompiled, onError) {
  75778. if (defines === void 0) { defines = null; }
  75779. if (uniforms === void 0) { uniforms = null; }
  75780. if (samplers === void 0) { samplers = null; }
  75781. if (!defines) {
  75782. defines = "";
  75783. defines += "#define BLUR_LEVEL " + (this.blurSteps.length - 1) + "\n";
  75784. }
  75785. _super.prototype.updateEffect.call(this, defines, uniforms, samplers, indexParameters, onCompiled, onError);
  75786. };
  75787. return DepthOfFieldMergePostProcess;
  75788. }(BABYLON.PostProcess));
  75789. BABYLON.DepthOfFieldMergePostProcess = DepthOfFieldMergePostProcess;
  75790. })(BABYLON || (BABYLON = {}));
  75791. //# sourceMappingURL=babylon.depthOfFieldMergePostProcess.js.map
  75792. var BABYLON;
  75793. (function (BABYLON) {
  75794. /**
  75795. * The CircleOfConfusionPostProcess computes the circle of confusion value for each pixel given required lens parameters. See https://en.wikipedia.org/wiki/Circle_of_confusion
  75796. */
  75797. var CircleOfConfusionPostProcess = /** @class */ (function (_super) {
  75798. __extends(CircleOfConfusionPostProcess, _super);
  75799. /**
  75800. * Creates a new instance CircleOfConfusionPostProcess
  75801. * @param name The name of the effect.
  75802. * @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.
  75803. * @param options The required width/height ratio to downsize to before computing the render pass.
  75804. * @param camera The camera to apply the render pass to.
  75805. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  75806. * @param engine The engine which the post process will be applied. (default: current engine)
  75807. * @param reusable If the post process can be reused on the same frame. (default: false)
  75808. * @param textureType Type of textures used when performing the post process. (default: 0)
  75809. * @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)
  75810. */
  75811. function CircleOfConfusionPostProcess(name, depthTexture, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  75812. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  75813. if (blockCompilation === void 0) { blockCompilation = false; }
  75814. var _this = _super.call(this, name, "circleOfConfusion", ["cameraMinMaxZ", "focusDistance", "cocPrecalculation"], ["depthSampler"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  75815. /**
  75816. * 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.
  75817. */
  75818. _this.lensSize = 50;
  75819. /**
  75820. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75821. */
  75822. _this.fStop = 1.4;
  75823. /**
  75824. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75825. */
  75826. _this.focusDistance = 2000;
  75827. /**
  75828. * Focal length of the effect's camera in scene units/1000 (eg. millimeter). (default: 50)
  75829. */
  75830. _this.focalLength = 50;
  75831. _this._depthTexture = null;
  75832. _this._depthTexture = depthTexture;
  75833. _this.onApplyObservable.add(function (effect) {
  75834. if (!_this._depthTexture) {
  75835. BABYLON.Tools.Warn("No depth texture set on CircleOfConfusionPostProcess");
  75836. return;
  75837. }
  75838. effect.setTexture("depthSampler", _this._depthTexture);
  75839. // Circle of confusion calculation, See https://developer.nvidia.com/gpugems/GPUGems/gpugems_ch23.html
  75840. var aperture = _this.lensSize / _this.fStop;
  75841. var cocPrecalculation = ((aperture * _this.focalLength) / ((_this.focusDistance - _this.focalLength))); // * ((this.focusDistance - pixelDistance)/pixelDistance) [This part is done in shader]
  75842. effect.setFloat('focusDistance', _this.focusDistance);
  75843. effect.setFloat('cocPrecalculation', cocPrecalculation);
  75844. effect.setFloat2('cameraMinMaxZ', _this._depthTexture.activeCamera.minZ, _this._depthTexture.activeCamera.maxZ);
  75845. });
  75846. return _this;
  75847. }
  75848. Object.defineProperty(CircleOfConfusionPostProcess.prototype, "depthTexture", {
  75849. /**
  75850. * 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.
  75851. */
  75852. set: function (value) {
  75853. this._depthTexture = value;
  75854. },
  75855. enumerable: true,
  75856. configurable: true
  75857. });
  75858. return CircleOfConfusionPostProcess;
  75859. }(BABYLON.PostProcess));
  75860. BABYLON.CircleOfConfusionPostProcess = CircleOfConfusionPostProcess;
  75861. })(BABYLON || (BABYLON = {}));
  75862. //# sourceMappingURL=babylon.circleOfConfusionPostProcess.js.map
  75863. var BABYLON;
  75864. (function (BABYLON) {
  75865. /**
  75866. * Specifies the level of max blur that should be applied when using the depth of field effect
  75867. */
  75868. var DepthOfFieldEffectBlurLevel;
  75869. (function (DepthOfFieldEffectBlurLevel) {
  75870. /**
  75871. * Subtle blur
  75872. */
  75873. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Low"] = 0] = "Low";
  75874. /**
  75875. * Medium blur
  75876. */
  75877. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["Medium"] = 1] = "Medium";
  75878. /**
  75879. * Large blur
  75880. */
  75881. DepthOfFieldEffectBlurLevel[DepthOfFieldEffectBlurLevel["High"] = 2] = "High";
  75882. })(DepthOfFieldEffectBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel || (BABYLON.DepthOfFieldEffectBlurLevel = {}));
  75883. ;
  75884. /**
  75885. * The depth of field effect applies a blur to objects that are closer or further from where the camera is focusing.
  75886. */
  75887. var DepthOfFieldEffect = /** @class */ (function (_super) {
  75888. __extends(DepthOfFieldEffect, _super);
  75889. /**
  75890. * Creates a new instance DepthOfFieldEffect
  75891. * @param scene The scene the effect belongs to.
  75892. * @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.
  75893. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  75894. * @param blockCompilation If compilation of the shader should not be done in the constructor. The updateEffect method can be used to compile the shader at a later time. (default: false)
  75895. */
  75896. function DepthOfFieldEffect(scene, depthTexture, blurLevel, pipelineTextureType, blockCompilation) {
  75897. if (blurLevel === void 0) { blurLevel = DepthOfFieldEffectBlurLevel.Low; }
  75898. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  75899. if (blockCompilation === void 0) { blockCompilation = false; }
  75900. var _this = _super.call(this, scene.getEngine(), "depth of field", function () {
  75901. return _this._effects;
  75902. }, true) || this;
  75903. /**
  75904. * Internal post processes in depth of field effect
  75905. */
  75906. _this._effects = [];
  75907. // Circle of confusion value for each pixel is used to determine how much to blur that pixel
  75908. _this._circleOfConfusion = new BABYLON.CircleOfConfusionPostProcess("circleOfConfusion", depthTexture, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75909. // 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)
  75910. // Blur the image but do not blur on sharp far to near distance changes to avoid bleeding artifacts
  75911. // See section 2.6.2 http://fileadmin.cs.lth.se/cs/education/edan35/lectures/12dof.pdf
  75912. _this._depthOfFieldBlurY = [];
  75913. _this._depthOfFieldBlurX = [];
  75914. var blurCount = 1;
  75915. var kernelSize = 15;
  75916. switch (blurLevel) {
  75917. case DepthOfFieldEffectBlurLevel.High: {
  75918. blurCount = 3;
  75919. kernelSize = 51;
  75920. break;
  75921. }
  75922. case DepthOfFieldEffectBlurLevel.Medium: {
  75923. blurCount = 2;
  75924. kernelSize = 31;
  75925. break;
  75926. }
  75927. default: {
  75928. kernelSize = 15;
  75929. blurCount = 1;
  75930. break;
  75931. }
  75932. }
  75933. var adjustedKernelSize = kernelSize / Math.pow(2, blurCount - 1);
  75934. var ratio = 1.0;
  75935. for (var i = 0; i < blurCount; i++) {
  75936. 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);
  75937. blurY.autoClear = false;
  75938. ratio = 0.75 / Math.pow(2, i);
  75939. 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);
  75940. blurX.autoClear = false;
  75941. _this._depthOfFieldBlurY.push(blurY);
  75942. _this._depthOfFieldBlurX.push(blurX);
  75943. }
  75944. // Set all post processes on the effect.
  75945. _this._effects = [_this._circleOfConfusion];
  75946. for (var i = 0; i < _this._depthOfFieldBlurX.length; i++) {
  75947. _this._effects.push(_this._depthOfFieldBlurY[i]);
  75948. _this._effects.push(_this._depthOfFieldBlurX[i]);
  75949. }
  75950. // Merge blurred images with original image based on circleOfConfusion
  75951. _this._dofMerge = new BABYLON.DepthOfFieldMergePostProcess("dofMerge", _this._circleOfConfusion, _this._circleOfConfusion, _this._depthOfFieldBlurX, ratio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  75952. _this._dofMerge.autoClear = false;
  75953. _this._effects.push(_this._dofMerge);
  75954. return _this;
  75955. }
  75956. Object.defineProperty(DepthOfFieldEffect.prototype, "focalLength", {
  75957. get: function () {
  75958. return this._circleOfConfusion.focalLength;
  75959. },
  75960. /**
  75961. * The focal the length of the camera used in the effect in scene units/1000 (eg. millimeter)
  75962. */
  75963. set: function (value) {
  75964. this._circleOfConfusion.focalLength = value;
  75965. },
  75966. enumerable: true,
  75967. configurable: true
  75968. });
  75969. Object.defineProperty(DepthOfFieldEffect.prototype, "fStop", {
  75970. get: function () {
  75971. return this._circleOfConfusion.fStop;
  75972. },
  75973. /**
  75974. * F-Stop of the effect's camera. The diamater of the resulting aperture can be computed by lensSize/fStop. (default: 1.4)
  75975. */
  75976. set: function (value) {
  75977. this._circleOfConfusion.fStop = value;
  75978. },
  75979. enumerable: true,
  75980. configurable: true
  75981. });
  75982. Object.defineProperty(DepthOfFieldEffect.prototype, "focusDistance", {
  75983. get: function () {
  75984. return this._circleOfConfusion.focusDistance;
  75985. },
  75986. /**
  75987. * Distance away from the camera to focus on in scene units/1000 (eg. millimeter). (default: 2000)
  75988. */
  75989. set: function (value) {
  75990. this._circleOfConfusion.focusDistance = value;
  75991. },
  75992. enumerable: true,
  75993. configurable: true
  75994. });
  75995. Object.defineProperty(DepthOfFieldEffect.prototype, "lensSize", {
  75996. get: function () {
  75997. return this._circleOfConfusion.lensSize;
  75998. },
  75999. /**
  76000. * 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.
  76001. */
  76002. set: function (value) {
  76003. this._circleOfConfusion.lensSize = value;
  76004. },
  76005. enumerable: true,
  76006. configurable: true
  76007. });
  76008. Object.defineProperty(DepthOfFieldEffect.prototype, "depthTexture", {
  76009. /**
  76010. * 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.
  76011. */
  76012. set: function (value) {
  76013. this._circleOfConfusion.depthTexture = value;
  76014. },
  76015. enumerable: true,
  76016. configurable: true
  76017. });
  76018. /**
  76019. * Disposes each of the internal effects for a given camera.
  76020. * @param camera The camera to dispose the effect on.
  76021. */
  76022. DepthOfFieldEffect.prototype.disposeEffects = function (camera) {
  76023. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76024. this._effects[effectIndex].dispose(camera);
  76025. }
  76026. };
  76027. /**
  76028. * Internal
  76029. */
  76030. DepthOfFieldEffect.prototype._updateEffects = function () {
  76031. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76032. this._effects[effectIndex].updateEffect();
  76033. }
  76034. };
  76035. /**
  76036. * Internal
  76037. * @returns if all the contained post processes are ready.
  76038. */
  76039. DepthOfFieldEffect.prototype._isReady = function () {
  76040. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76041. if (!this._effects[effectIndex].isReady()) {
  76042. return false;
  76043. }
  76044. }
  76045. return true;
  76046. };
  76047. return DepthOfFieldEffect;
  76048. }(BABYLON.PostProcessRenderEffect));
  76049. BABYLON.DepthOfFieldEffect = DepthOfFieldEffect;
  76050. })(BABYLON || (BABYLON = {}));
  76051. //# sourceMappingURL=babylon.depthOfFieldEffect.js.map
  76052. var BABYLON;
  76053. (function (BABYLON) {
  76054. /**
  76055. * The BloomMergePostProcess merges blurred images with the original based on the values of the circle of confusion.
  76056. */
  76057. var BloomMergePostProcess = /** @class */ (function (_super) {
  76058. __extends(BloomMergePostProcess, _super);
  76059. /**
  76060. * Creates a new instance of @see BloomMergePostProcess
  76061. * @param name The name of the effect.
  76062. * @param originalFromInput Post process which's input will be used for the merge.
  76063. * @param blurred Blurred highlights post process which's output will be used.
  76064. * @param weight Weight of the bloom to be added to the original input.
  76065. * @param options The required width/height ratio to downsize to before computing the render pass.
  76066. * @param camera The camera to apply the render pass to.
  76067. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  76068. * @param engine The engine which the post process will be applied. (default: current engine)
  76069. * @param reusable If the post process can be reused on the same frame. (default: false)
  76070. * @param textureType Type of textures used when performing the post process. (default: 0)
  76071. * @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)
  76072. */
  76073. function BloomMergePostProcess(name, originalFromInput, blurred, /** Weight of the bloom to be added to the original input. */ weight, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76074. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76075. if (blockCompilation === void 0) { blockCompilation = false; }
  76076. var _this = _super.call(this, name, "bloomMerge", ["bloomWeight"], ["circleOfConfusionSampler", "blurStep0", "blurStep1", "blurStep2", "bloomBlur"], options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, true) || this;
  76077. _this.weight = weight;
  76078. _this.onApplyObservable.add(function (effect) {
  76079. effect.setTextureFromPostProcess("textureSampler", originalFromInput);
  76080. effect.setTextureFromPostProcessOutput("bloomBlur", blurred);
  76081. effect.setFloat("bloomWeight", _this.weight);
  76082. });
  76083. if (!blockCompilation) {
  76084. _this.updateEffect();
  76085. }
  76086. return _this;
  76087. }
  76088. return BloomMergePostProcess;
  76089. }(BABYLON.PostProcess));
  76090. BABYLON.BloomMergePostProcess = BloomMergePostProcess;
  76091. })(BABYLON || (BABYLON = {}));
  76092. //# sourceMappingURL=babylon.bloomMergePostProcess.js.map
  76093. var BABYLON;
  76094. (function (BABYLON) {
  76095. /**
  76096. * 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.
  76097. */
  76098. var ExtractHighlightsPostProcess = /** @class */ (function (_super) {
  76099. __extends(ExtractHighlightsPostProcess, _super);
  76100. function ExtractHighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, blockCompilation) {
  76101. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  76102. if (blockCompilation === void 0) { blockCompilation = false; }
  76103. var _this = _super.call(this, name, "extractHighlights", ["threshold", "exposure"], null, options, camera, samplingMode, engine, reusable, null, textureType, undefined, null, blockCompilation) || this;
  76104. /**
  76105. * The luminance threshold, pixels below this value will be set to black.
  76106. */
  76107. _this.threshold = 0.9;
  76108. /**
  76109. * Internal
  76110. */
  76111. _this._exposure = 1;
  76112. /**
  76113. * Post process which has the input texture to be used when performing highlight extraction
  76114. */
  76115. _this._inputPostProcess = null;
  76116. _this.onApplyObservable.add(function (effect) {
  76117. if (_this._inputPostProcess) {
  76118. effect.setTextureFromPostProcess("textureSampler", _this._inputPostProcess);
  76119. }
  76120. effect.setFloat('threshold', Math.pow(_this.threshold, BABYLON.ToGammaSpace));
  76121. effect.setFloat('exposure', _this._exposure);
  76122. });
  76123. return _this;
  76124. }
  76125. return ExtractHighlightsPostProcess;
  76126. }(BABYLON.PostProcess));
  76127. BABYLON.ExtractHighlightsPostProcess = ExtractHighlightsPostProcess;
  76128. })(BABYLON || (BABYLON = {}));
  76129. //# sourceMappingURL=babylon.extractHighlightsPostProcess.js.map
  76130. var BABYLON;
  76131. (function (BABYLON) {
  76132. /**
  76133. * The bloom effect spreads bright areas of an image to simulate artifacts seen in cameras
  76134. */
  76135. var BloomEffect = /** @class */ (function (_super) {
  76136. __extends(BloomEffect, _super);
  76137. /**
  76138. * Creates a new instance of @see BloomEffect
  76139. * @param scene The scene the effect belongs to.
  76140. * @param bloomScale The ratio of the blur texture to the input texture that should be used to compute the bloom.
  76141. * @param bloomKernel The size of the kernel to be used when applying the blur.
  76142. * @param bloomWeight The the strength of bloom.
  76143. * @param pipelineTextureType The type of texture to be used when performing the post processing.
  76144. * @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)
  76145. */
  76146. function BloomEffect(scene, bloomScale, bloomWeight, bloomKernel, pipelineTextureType, blockCompilation) {
  76147. if (pipelineTextureType === void 0) { pipelineTextureType = 0; }
  76148. if (blockCompilation === void 0) { blockCompilation = false; }
  76149. var _this = _super.call(this, scene.getEngine(), "bloom", function () {
  76150. return _this._effects;
  76151. }, true) || this;
  76152. _this.bloomScale = bloomScale;
  76153. /**
  76154. * Internal
  76155. */
  76156. _this._effects = [];
  76157. _this._downscale = new BABYLON.ExtractHighlightsPostProcess("highlights", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76158. _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);
  76159. _this._blurX.alwaysForcePOT = true;
  76160. _this._blurX.autoClear = false;
  76161. _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);
  76162. _this._blurY.alwaysForcePOT = true;
  76163. _this._blurY.autoClear = false;
  76164. _this.kernel = bloomKernel;
  76165. _this._effects = [_this._downscale, _this._blurX, _this._blurY];
  76166. _this._merge = new BABYLON.BloomMergePostProcess("bloomMerge", _this._downscale, _this._blurY, bloomWeight, bloomScale, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, scene.getEngine(), false, pipelineTextureType, blockCompilation);
  76167. _this._merge.autoClear = false;
  76168. _this._effects.push(_this._merge);
  76169. return _this;
  76170. }
  76171. Object.defineProperty(BloomEffect.prototype, "threshold", {
  76172. /**
  76173. * The luminance threshold to find bright areas of the image to bloom.
  76174. */
  76175. get: function () {
  76176. return this._downscale.threshold;
  76177. },
  76178. set: function (value) {
  76179. this._downscale.threshold = value;
  76180. },
  76181. enumerable: true,
  76182. configurable: true
  76183. });
  76184. Object.defineProperty(BloomEffect.prototype, "weight", {
  76185. /**
  76186. * The strength of the bloom.
  76187. */
  76188. get: function () {
  76189. return this._merge.weight;
  76190. },
  76191. set: function (value) {
  76192. this._merge.weight = value;
  76193. },
  76194. enumerable: true,
  76195. configurable: true
  76196. });
  76197. Object.defineProperty(BloomEffect.prototype, "kernel", {
  76198. /**
  76199. * Specifies the size of the bloom blur kernel, relative to the final output size
  76200. */
  76201. get: function () {
  76202. return this._blurX.kernel / this.bloomScale;
  76203. },
  76204. set: function (value) {
  76205. this._blurX.kernel = value * this.bloomScale;
  76206. this._blurY.kernel = value * this.bloomScale;
  76207. },
  76208. enumerable: true,
  76209. configurable: true
  76210. });
  76211. /**
  76212. * Disposes each of the internal effects for a given camera.
  76213. * @param camera The camera to dispose the effect on.
  76214. */
  76215. BloomEffect.prototype.disposeEffects = function (camera) {
  76216. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76217. this._effects[effectIndex].dispose(camera);
  76218. }
  76219. };
  76220. /**
  76221. * Internal
  76222. */
  76223. BloomEffect.prototype._updateEffects = function () {
  76224. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76225. this._effects[effectIndex].updateEffect();
  76226. }
  76227. };
  76228. /**
  76229. * Internal
  76230. * @returns if all the contained post processes are ready.
  76231. */
  76232. BloomEffect.prototype._isReady = function () {
  76233. for (var effectIndex = 0; effectIndex < this._effects.length; effectIndex++) {
  76234. if (!this._effects[effectIndex].isReady()) {
  76235. return false;
  76236. }
  76237. }
  76238. return true;
  76239. };
  76240. return BloomEffect;
  76241. }(BABYLON.PostProcessRenderEffect));
  76242. BABYLON.BloomEffect = BloomEffect;
  76243. })(BABYLON || (BABYLON = {}));
  76244. //# sourceMappingURL=babylon.bloomEffect.js.map
  76245. var BABYLON;
  76246. (function (BABYLON) {
  76247. /**
  76248. * The default rendering pipeline can be added to a scene to apply common post processing effects such as anti-aliasing or depth of field.
  76249. * See https://doc.babylonjs.com/how_to/using_default_rendering_pipeline
  76250. */
  76251. var DefaultRenderingPipeline = /** @class */ (function (_super) {
  76252. __extends(DefaultRenderingPipeline, _super);
  76253. /**
  76254. * @constructor
  76255. * @param {string} name - The rendering pipeline name (default: "")
  76256. * @param {boolean} hdr - If high dynamic range textures should be used (default: true)
  76257. * @param {BABYLON.Scene} scene - The scene linked to this pipeline (default: the last created scene)
  76258. * @param {BABYLON.Camera[]} cameras - The array of cameras that the rendering pipeline will be attached to (default: scene.cameras)
  76259. * @param {boolean} automaticBuild - if false, you will have to manually call prepare() to update the pipeline (default: true)
  76260. */
  76261. function DefaultRenderingPipeline(name, hdr, scene, cameras, automaticBuild) {
  76262. if (name === void 0) { name = ""; }
  76263. if (hdr === void 0) { hdr = true; }
  76264. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  76265. if (automaticBuild === void 0) { automaticBuild = true; }
  76266. var _this = _super.call(this, scene.getEngine(), name) || this;
  76267. _this._camerasToBeAttached = [];
  76268. /**
  76269. * ID of the sharpen post process,
  76270. */
  76271. _this.SharpenPostProcessId = "SharpenPostProcessEffect";
  76272. /**
  76273. * ID of the image processing post process;
  76274. */
  76275. _this.ImageProcessingPostProcessId = "ImageProcessingPostProcessEffect";
  76276. /**
  76277. * ID of the Fast Approximate Anti-Aliasing post process;
  76278. */
  76279. _this.FxaaPostProcessId = "FxaaPostProcessEffect";
  76280. /**
  76281. * ID of the chromatic aberration post process,
  76282. */
  76283. _this.ChromaticAberrationPostProcessId = "ChromaticAberrationPostProcessEffect";
  76284. /**
  76285. * ID of the grain post process
  76286. */
  76287. _this.GrainPostProcessId = "GrainPostProcessEffect";
  76288. /**
  76289. * Glow post process which adds a glow to emmisive areas of the image
  76290. */
  76291. _this._glowLayer = null;
  76292. /**
  76293. * Animations which can be used to tweak settings over a period of time
  76294. */
  76295. _this.animations = [];
  76296. _this._imageProcessingConfigurationObserver = null;
  76297. // Values
  76298. _this._sharpenEnabled = false;
  76299. _this._bloomEnabled = false;
  76300. _this._depthOfFieldEnabled = false;
  76301. _this._depthOfFieldBlurLevel = BABYLON.DepthOfFieldEffectBlurLevel.Low;
  76302. _this._fxaaEnabled = false;
  76303. _this._imageProcessingEnabled = true;
  76304. _this._bloomScale = 0.5;
  76305. _this._chromaticAberrationEnabled = false;
  76306. _this._grainEnabled = false;
  76307. _this._buildAllowed = true;
  76308. _this._resizeObserver = null;
  76309. _this._hardwareScaleLevel = 1.0;
  76310. _this._bloomKernel = 64;
  76311. /**
  76312. * Specifies the weight of the bloom in the final rendering
  76313. */
  76314. _this._bloomWeight = 0.15;
  76315. /**
  76316. * Specifies the luma threshold for the area that will be blurred by the bloom
  76317. */
  76318. _this._bloomThreshold = 0.9;
  76319. _this._samples = 1;
  76320. _this._hasCleared = false;
  76321. _this._prevPostProcess = null;
  76322. _this._prevPrevPostProcess = null;
  76323. _this._cameras = cameras || scene.cameras;
  76324. _this._camerasToBeAttached = _this._cameras.slice();
  76325. _this._buildAllowed = automaticBuild;
  76326. // Initialize
  76327. _this._scene = scene;
  76328. var caps = _this._scene.getEngine().getCaps();
  76329. _this._hdr = hdr && (caps.textureHalfFloatRender || caps.textureFloatRender);
  76330. // Misc
  76331. if (_this._hdr) {
  76332. if (caps.textureHalfFloatRender) {
  76333. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  76334. }
  76335. else if (caps.textureFloatRender) {
  76336. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  76337. }
  76338. }
  76339. else {
  76340. _this._defaultPipelineTextureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  76341. }
  76342. // Attach
  76343. scene.postProcessRenderPipelineManager.addPipeline(_this);
  76344. var engine = _this._scene.getEngine();
  76345. // Create post processes before hand so they can be modified before enabled.
  76346. // Block compilation flag is set to true to avoid compilation prior to use, these will be updated on first use in build pipeline.
  76347. _this.sharpen = new BABYLON.SharpenPostProcess("sharpen", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76348. _this._sharpenEffect = new BABYLON.PostProcessRenderEffect(engine, _this.SharpenPostProcessId, function () { return _this.sharpen; }, true);
  76349. _this.depthOfField = new BABYLON.DepthOfFieldEffect(_this._scene, null, _this._depthOfFieldBlurLevel, _this._defaultPipelineTextureType, true);
  76350. _this.bloom = new BABYLON.BloomEffect(_this._scene, _this._bloomScale, _this._bloomWeight, _this.bloomKernel, _this._defaultPipelineTextureType, true);
  76351. _this.chromaticAberration = new BABYLON.ChromaticAberrationPostProcess("ChromaticAberration", engine.getRenderWidth(), engine.getRenderHeight(), 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76352. _this._chromaticAberrationEffect = new BABYLON.PostProcessRenderEffect(engine, _this.ChromaticAberrationPostProcessId, function () { return _this.chromaticAberration; }, true);
  76353. _this.grain = new BABYLON.GrainPostProcess("Grain", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, _this._defaultPipelineTextureType, true);
  76354. _this._grainEffect = new BABYLON.PostProcessRenderEffect(engine, _this.GrainPostProcessId, function () { return _this.grain; }, true);
  76355. _this._resizeObserver = engine.onResizeObservable.add(function () {
  76356. _this._hardwareScaleLevel = engine.getHardwareScalingLevel();
  76357. _this.bloomKernel = _this.bloomKernel;
  76358. });
  76359. _this._imageProcessingConfigurationObserver = _this._scene.imageProcessingConfiguration.onUpdateParameters.add(function () {
  76360. _this.bloom._downscale._exposure = _this._scene.imageProcessingConfiguration.exposure;
  76361. });
  76362. _this._buildPipeline();
  76363. return _this;
  76364. }
  76365. Object.defineProperty(DefaultRenderingPipeline.prototype, "sharpenEnabled", {
  76366. get: function () {
  76367. return this._sharpenEnabled;
  76368. },
  76369. /**
  76370. * Enable or disable the sharpen process from the pipeline
  76371. */
  76372. set: function (enabled) {
  76373. if (this._sharpenEnabled === enabled) {
  76374. return;
  76375. }
  76376. this._sharpenEnabled = enabled;
  76377. this._buildPipeline();
  76378. },
  76379. enumerable: true,
  76380. configurable: true
  76381. });
  76382. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomKernel", {
  76383. /**
  76384. * Specifies the size of the bloom blur kernel, relative to the final output size
  76385. */
  76386. get: function () {
  76387. return this._bloomKernel;
  76388. },
  76389. set: function (value) {
  76390. this._bloomKernel = value;
  76391. this.bloom.kernel = value / this._hardwareScaleLevel;
  76392. },
  76393. enumerable: true,
  76394. configurable: true
  76395. });
  76396. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomWeight", {
  76397. get: function () {
  76398. return this._bloomWeight;
  76399. },
  76400. /**
  76401. * The strength of the bloom.
  76402. */
  76403. set: function (value) {
  76404. if (this._bloomWeight === value) {
  76405. return;
  76406. }
  76407. this.bloom.weight = value;
  76408. this._bloomWeight = value;
  76409. },
  76410. enumerable: true,
  76411. configurable: true
  76412. });
  76413. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomThreshold", {
  76414. get: function () {
  76415. return this._bloomThreshold;
  76416. },
  76417. /**
  76418. * The strength of the bloom.
  76419. */
  76420. set: function (value) {
  76421. if (this._bloomThreshold === value) {
  76422. return;
  76423. }
  76424. this.bloom.threshold = value;
  76425. this._bloomThreshold = value;
  76426. },
  76427. enumerable: true,
  76428. configurable: true
  76429. });
  76430. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomScale", {
  76431. get: function () {
  76432. return this._bloomScale;
  76433. },
  76434. /**
  76435. * The scale of the bloom, lower value will provide better performance.
  76436. */
  76437. set: function (value) {
  76438. if (this._bloomScale === value) {
  76439. return;
  76440. }
  76441. this._bloomScale = value;
  76442. // recreate bloom and dispose old as this setting is not dynamic
  76443. this._rebuildBloom();
  76444. this._buildPipeline();
  76445. },
  76446. enumerable: true,
  76447. configurable: true
  76448. });
  76449. Object.defineProperty(DefaultRenderingPipeline.prototype, "bloomEnabled", {
  76450. get: function () {
  76451. return this._bloomEnabled;
  76452. },
  76453. /**
  76454. * Enable or disable the bloom from the pipeline
  76455. */
  76456. set: function (enabled) {
  76457. if (this._bloomEnabled === enabled) {
  76458. return;
  76459. }
  76460. this._bloomEnabled = enabled;
  76461. this._buildPipeline();
  76462. },
  76463. enumerable: true,
  76464. configurable: true
  76465. });
  76466. DefaultRenderingPipeline.prototype._rebuildBloom = function () {
  76467. // recreate bloom and dispose old as this setting is not dynamic
  76468. var oldBloom = this.bloom;
  76469. this.bloom = new BABYLON.BloomEffect(this._scene, this.bloomScale, this._bloomWeight, this.bloomKernel, this._defaultPipelineTextureType, false);
  76470. this.bloom.threshold = oldBloom.threshold;
  76471. for (var i = 0; i < this._cameras.length; i++) {
  76472. oldBloom.disposeEffects(this._cameras[i]);
  76473. }
  76474. };
  76475. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", {
  76476. /**
  76477. * If the depth of field is enabled.
  76478. */
  76479. get: function () {
  76480. return this._depthOfFieldEnabled;
  76481. },
  76482. set: function (enabled) {
  76483. if (this._depthOfFieldEnabled === enabled) {
  76484. return;
  76485. }
  76486. this._depthOfFieldEnabled = enabled;
  76487. this._buildPipeline();
  76488. },
  76489. enumerable: true,
  76490. configurable: true
  76491. });
  76492. Object.defineProperty(DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", {
  76493. /**
  76494. * Blur level of the depth of field effect. (Higher blur will effect performance)
  76495. */
  76496. get: function () {
  76497. return this._depthOfFieldBlurLevel;
  76498. },
  76499. set: function (value) {
  76500. if (this._depthOfFieldBlurLevel === value) {
  76501. return;
  76502. }
  76503. this._depthOfFieldBlurLevel = value;
  76504. // recreate dof and dispose old as this setting is not dynamic
  76505. var oldDof = this.depthOfField;
  76506. this.depthOfField = new BABYLON.DepthOfFieldEffect(this._scene, null, this._depthOfFieldBlurLevel, this._defaultPipelineTextureType, false);
  76507. this.depthOfField.focalLength = oldDof.focalLength;
  76508. this.depthOfField.focusDistance = oldDof.focusDistance;
  76509. this.depthOfField.fStop = oldDof.fStop;
  76510. this.depthOfField.lensSize = oldDof.lensSize;
  76511. for (var i = 0; i < this._cameras.length; i++) {
  76512. oldDof.disposeEffects(this._cameras[i]);
  76513. }
  76514. this._buildPipeline();
  76515. },
  76516. enumerable: true,
  76517. configurable: true
  76518. });
  76519. Object.defineProperty(DefaultRenderingPipeline.prototype, "fxaaEnabled", {
  76520. get: function () {
  76521. return this._fxaaEnabled;
  76522. },
  76523. /**
  76524. * If the anti aliasing is enabled.
  76525. */
  76526. set: function (enabled) {
  76527. if (this._fxaaEnabled === enabled) {
  76528. return;
  76529. }
  76530. this._fxaaEnabled = enabled;
  76531. this._buildPipeline();
  76532. },
  76533. enumerable: true,
  76534. configurable: true
  76535. });
  76536. Object.defineProperty(DefaultRenderingPipeline.prototype, "samples", {
  76537. get: function () {
  76538. return this._samples;
  76539. },
  76540. /**
  76541. * MSAA sample count, setting this to 4 will provide 4x anti aliasing. (default: 1)
  76542. */
  76543. set: function (sampleCount) {
  76544. if (this._samples === sampleCount) {
  76545. return;
  76546. }
  76547. this._samples = sampleCount;
  76548. this._buildPipeline();
  76549. },
  76550. enumerable: true,
  76551. configurable: true
  76552. });
  76553. Object.defineProperty(DefaultRenderingPipeline.prototype, "imageProcessingEnabled", {
  76554. get: function () {
  76555. return this._imageProcessingEnabled;
  76556. },
  76557. /**
  76558. * If image processing is enabled.
  76559. */
  76560. set: function (enabled) {
  76561. if (this._imageProcessingEnabled === enabled) {
  76562. return;
  76563. }
  76564. this._imageProcessingEnabled = enabled;
  76565. this._buildPipeline();
  76566. },
  76567. enumerable: true,
  76568. configurable: true
  76569. });
  76570. Object.defineProperty(DefaultRenderingPipeline.prototype, "glowLayerEnabled", {
  76571. get: function () {
  76572. return this._glowLayer == null;
  76573. },
  76574. /**
  76575. * If glow layer is enabled. (Adds a glow effect to emmissive materials)
  76576. */
  76577. set: function (enabled) {
  76578. if (enabled && !this._glowLayer) {
  76579. this._glowLayer = new BABYLON.GlowLayer("", this._scene);
  76580. }
  76581. else if (!enabled && this._glowLayer) {
  76582. this._glowLayer.dispose();
  76583. this._glowLayer = null;
  76584. }
  76585. },
  76586. enumerable: true,
  76587. configurable: true
  76588. });
  76589. Object.defineProperty(DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", {
  76590. get: function () {
  76591. return this._chromaticAberrationEnabled;
  76592. },
  76593. /**
  76594. * Enable or disable the chromaticAberration process from the pipeline
  76595. */
  76596. set: function (enabled) {
  76597. if (this._chromaticAberrationEnabled === enabled) {
  76598. return;
  76599. }
  76600. this._chromaticAberrationEnabled = enabled;
  76601. this._buildPipeline();
  76602. },
  76603. enumerable: true,
  76604. configurable: true
  76605. });
  76606. Object.defineProperty(DefaultRenderingPipeline.prototype, "grainEnabled", {
  76607. get: function () {
  76608. return this._grainEnabled;
  76609. },
  76610. /**
  76611. * Enable or disable the grain process from the pipeline
  76612. */
  76613. set: function (enabled) {
  76614. if (this._grainEnabled === enabled) {
  76615. return;
  76616. }
  76617. this._grainEnabled = enabled;
  76618. this._buildPipeline();
  76619. },
  76620. enumerable: true,
  76621. configurable: true
  76622. });
  76623. /**
  76624. * Force the compilation of the entire pipeline.
  76625. */
  76626. DefaultRenderingPipeline.prototype.prepare = function () {
  76627. var previousState = this._buildAllowed;
  76628. this._buildAllowed = true;
  76629. this._buildPipeline();
  76630. this._buildAllowed = previousState;
  76631. };
  76632. DefaultRenderingPipeline.prototype._setAutoClearAndTextureSharing = function (postProcess, skipTextureSharing) {
  76633. if (skipTextureSharing === void 0) { skipTextureSharing = false; }
  76634. if (this._hasCleared) {
  76635. postProcess.autoClear = false;
  76636. }
  76637. else {
  76638. postProcess.autoClear = true;
  76639. this._scene.autoClear = false;
  76640. this._hasCleared = true;
  76641. }
  76642. if (!skipTextureSharing) {
  76643. if (this._prevPrevPostProcess) {
  76644. postProcess.shareOutputWith(this._prevPrevPostProcess);
  76645. }
  76646. else {
  76647. postProcess.useOwnOutput();
  76648. }
  76649. if (this._prevPostProcess) {
  76650. this._prevPrevPostProcess = this._prevPostProcess;
  76651. }
  76652. this._prevPostProcess = postProcess;
  76653. }
  76654. };
  76655. DefaultRenderingPipeline.prototype._buildPipeline = function () {
  76656. var _this = this;
  76657. if (!this._buildAllowed) {
  76658. return;
  76659. }
  76660. this._scene.autoClear = true;
  76661. var engine = this._scene.getEngine();
  76662. this._disposePostProcesses();
  76663. if (this._cameras !== null) {
  76664. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76665. // get back cameras to be used to reattach pipeline
  76666. this._cameras = this._camerasToBeAttached.slice();
  76667. }
  76668. this._reset();
  76669. this._prevPostProcess = null;
  76670. this._prevPrevPostProcess = null;
  76671. this._hasCleared = false;
  76672. if (this.depthOfFieldEnabled) {
  76673. var depthTexture = this._scene.enableDepthRenderer(this._cameras[0]).getDepthMap();
  76674. this.depthOfField.depthTexture = depthTexture;
  76675. if (!this.depthOfField._isReady()) {
  76676. this.depthOfField._updateEffects();
  76677. }
  76678. this.addEffect(this.depthOfField);
  76679. this._setAutoClearAndTextureSharing(this.depthOfField._effects[0], true);
  76680. }
  76681. if (this.bloomEnabled) {
  76682. if (!this.bloom._isReady()) {
  76683. this.bloom._updateEffects();
  76684. }
  76685. this.addEffect(this.bloom);
  76686. this._setAutoClearAndTextureSharing(this.bloom._effects[0], true);
  76687. }
  76688. if (this._imageProcessingEnabled) {
  76689. this.imageProcessing = new BABYLON.ImageProcessingPostProcess("imageProcessing", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76690. if (this._hdr) {
  76691. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.ImageProcessingPostProcessId, function () { return _this.imageProcessing; }, true));
  76692. this._setAutoClearAndTextureSharing(this.imageProcessing);
  76693. }
  76694. else {
  76695. this._scene.imageProcessingConfiguration.applyByPostProcess = false;
  76696. }
  76697. }
  76698. if (this.sharpenEnabled) {
  76699. if (!this.sharpen.isReady()) {
  76700. this.sharpen.updateEffect();
  76701. }
  76702. this.addEffect(this._sharpenEffect);
  76703. this._setAutoClearAndTextureSharing(this.sharpen);
  76704. }
  76705. if (this.grainEnabled) {
  76706. if (!this.grain.isReady()) {
  76707. this.grain.updateEffect();
  76708. }
  76709. this.addEffect(this._grainEffect);
  76710. this._setAutoClearAndTextureSharing(this.grain);
  76711. }
  76712. if (this.chromaticAberrationEnabled) {
  76713. if (!this.chromaticAberration.isReady()) {
  76714. this.chromaticAberration.updateEffect();
  76715. }
  76716. this.addEffect(this._chromaticAberrationEffect);
  76717. this._setAutoClearAndTextureSharing(this.chromaticAberration);
  76718. }
  76719. if (this.fxaaEnabled) {
  76720. this.fxaa = new BABYLON.FxaaPostProcess("fxaa", 1.0, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, engine, false, this._defaultPipelineTextureType);
  76721. this.addEffect(new BABYLON.PostProcessRenderEffect(engine, this.FxaaPostProcessId, function () { return _this.fxaa; }, true));
  76722. this._setAutoClearAndTextureSharing(this.fxaa, true);
  76723. }
  76724. if (this._cameras !== null) {
  76725. this._scene.postProcessRenderPipelineManager.attachCamerasToRenderPipeline(this._name, this._cameras);
  76726. }
  76727. if (!this._enableMSAAOnFirstPostProcess(this.samples) && this.samples > 1) {
  76728. BABYLON.Tools.Warn("MSAA failed to enable, MSAA is only supported in browsers that support webGL >= 2.0");
  76729. }
  76730. };
  76731. DefaultRenderingPipeline.prototype._disposePostProcesses = function (disposeNonRecreated) {
  76732. if (disposeNonRecreated === void 0) { disposeNonRecreated = false; }
  76733. for (var i = 0; i < this._cameras.length; i++) {
  76734. var camera = this._cameras[i];
  76735. if (this.imageProcessing) {
  76736. this.imageProcessing.dispose(camera);
  76737. }
  76738. if (this.fxaa) {
  76739. this.fxaa.dispose(camera);
  76740. }
  76741. // These are created in the constructor and should not be disposed on every pipeline change
  76742. if (disposeNonRecreated) {
  76743. if (this.sharpen) {
  76744. this.sharpen.dispose(camera);
  76745. }
  76746. if (this.depthOfField) {
  76747. this.depthOfField.disposeEffects(camera);
  76748. }
  76749. if (this.bloom) {
  76750. this.bloom.disposeEffects(camera);
  76751. }
  76752. if (this.chromaticAberration) {
  76753. this.chromaticAberration.dispose(camera);
  76754. }
  76755. if (this.grain) {
  76756. this.grain.dispose(camera);
  76757. }
  76758. if (this._glowLayer) {
  76759. this._glowLayer.dispose();
  76760. }
  76761. }
  76762. }
  76763. this.imageProcessing = null;
  76764. this.fxaa = null;
  76765. if (disposeNonRecreated) {
  76766. this.sharpen = null;
  76767. this._sharpenEffect = null;
  76768. this.depthOfField = null;
  76769. this.bloom = null;
  76770. this.chromaticAberration = null;
  76771. this._chromaticAberrationEffect = null;
  76772. this.grain = null;
  76773. this._grainEffect = null;
  76774. this._glowLayer = null;
  76775. }
  76776. };
  76777. /**
  76778. * Adds a camera to the pipeline
  76779. * @param camera the camera to be added
  76780. */
  76781. DefaultRenderingPipeline.prototype.addCamera = function (camera) {
  76782. this._camerasToBeAttached.push(camera);
  76783. this._buildPipeline();
  76784. };
  76785. /**
  76786. * Removes a camera from the pipeline
  76787. * @param camera the camera to remove
  76788. */
  76789. DefaultRenderingPipeline.prototype.removeCamera = function (camera) {
  76790. var index = this._camerasToBeAttached.indexOf(camera);
  76791. this._camerasToBeAttached.splice(index, 1);
  76792. this._buildPipeline();
  76793. };
  76794. /**
  76795. * Dispose of the pipeline and stop all post processes
  76796. */
  76797. DefaultRenderingPipeline.prototype.dispose = function () {
  76798. this._disposePostProcesses(true);
  76799. this._scene.postProcessRenderPipelineManager.detachCamerasFromRenderPipeline(this._name, this._cameras);
  76800. this._scene.autoClear = true;
  76801. if (this._resizeObserver) {
  76802. this._scene.getEngine().onResizeObservable.remove(this._resizeObserver);
  76803. this._resizeObserver = null;
  76804. }
  76805. this._scene.imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingConfigurationObserver);
  76806. _super.prototype.dispose.call(this);
  76807. };
  76808. /**
  76809. * Serialize the rendering pipeline (Used when exporting)
  76810. * @returns the serialized object
  76811. */
  76812. DefaultRenderingPipeline.prototype.serialize = function () {
  76813. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  76814. serializationObject.customType = "DefaultRenderingPipeline";
  76815. return serializationObject;
  76816. };
  76817. /**
  76818. * Parse the serialized pipeline
  76819. * @param source Source pipeline.
  76820. * @param scene The scene to load the pipeline to.
  76821. * @param rootUrl The URL of the serialized pipeline.
  76822. * @returns An instantiated pipeline from the serialized object.
  76823. */
  76824. DefaultRenderingPipeline.Parse = function (source, scene, rootUrl) {
  76825. return BABYLON.SerializationHelper.Parse(function () { return new DefaultRenderingPipeline(source._name, source._name._hdr, scene); }, source, scene, rootUrl);
  76826. };
  76827. __decorate([
  76828. BABYLON.serialize()
  76829. ], DefaultRenderingPipeline.prototype, "sharpenEnabled", null);
  76830. __decorate([
  76831. BABYLON.serialize()
  76832. ], DefaultRenderingPipeline.prototype, "bloomKernel", null);
  76833. __decorate([
  76834. BABYLON.serialize()
  76835. ], DefaultRenderingPipeline.prototype, "_bloomWeight", void 0);
  76836. __decorate([
  76837. BABYLON.serialize()
  76838. ], DefaultRenderingPipeline.prototype, "_bloomThreshold", void 0);
  76839. __decorate([
  76840. BABYLON.serialize()
  76841. ], DefaultRenderingPipeline.prototype, "_hdr", void 0);
  76842. __decorate([
  76843. BABYLON.serialize()
  76844. ], DefaultRenderingPipeline.prototype, "bloomWeight", null);
  76845. __decorate([
  76846. BABYLON.serialize()
  76847. ], DefaultRenderingPipeline.prototype, "bloomThreshold", null);
  76848. __decorate([
  76849. BABYLON.serialize()
  76850. ], DefaultRenderingPipeline.prototype, "bloomScale", null);
  76851. __decorate([
  76852. BABYLON.serialize()
  76853. ], DefaultRenderingPipeline.prototype, "bloomEnabled", null);
  76854. __decorate([
  76855. BABYLON.serialize()
  76856. ], DefaultRenderingPipeline.prototype, "depthOfFieldEnabled", null);
  76857. __decorate([
  76858. BABYLON.serialize()
  76859. ], DefaultRenderingPipeline.prototype, "depthOfFieldBlurLevel", null);
  76860. __decorate([
  76861. BABYLON.serialize()
  76862. ], DefaultRenderingPipeline.prototype, "fxaaEnabled", null);
  76863. __decorate([
  76864. BABYLON.serialize()
  76865. ], DefaultRenderingPipeline.prototype, "samples", null);
  76866. __decorate([
  76867. BABYLON.serialize()
  76868. ], DefaultRenderingPipeline.prototype, "imageProcessingEnabled", null);
  76869. __decorate([
  76870. BABYLON.serialize()
  76871. ], DefaultRenderingPipeline.prototype, "glowLayerEnabled", null);
  76872. __decorate([
  76873. BABYLON.serialize()
  76874. ], DefaultRenderingPipeline.prototype, "chromaticAberrationEnabled", null);
  76875. __decorate([
  76876. BABYLON.serialize()
  76877. ], DefaultRenderingPipeline.prototype, "grainEnabled", null);
  76878. return DefaultRenderingPipeline;
  76879. }(BABYLON.PostProcessRenderPipeline));
  76880. BABYLON.DefaultRenderingPipeline = DefaultRenderingPipeline;
  76881. })(BABYLON || (BABYLON = {}));
  76882. //# sourceMappingURL=babylon.defaultRenderingPipeline.js.map
  76883. var BABYLON;
  76884. (function (BABYLON) {
  76885. /**
  76886. * This renderer is helpfull to fill one of the render target with a geometry buffer.
  76887. */
  76888. var GeometryBufferRenderer = /** @class */ (function () {
  76889. /**
  76890. * Creates a new G Buffer for the scene
  76891. * @param scene The scene the buffer belongs to
  76892. * @param ratio How big is the buffer related to the main canvas.
  76893. */
  76894. function GeometryBufferRenderer(scene, ratio) {
  76895. if (ratio === void 0) { ratio = 1; }
  76896. this._enablePosition = false;
  76897. this._scene = scene;
  76898. this._ratio = ratio;
  76899. // Render target
  76900. this._createRenderTargets();
  76901. }
  76902. Object.defineProperty(GeometryBufferRenderer.prototype, "renderList", {
  76903. /**
  76904. * Set the render list (meshes to be rendered) used in the G buffer.
  76905. */
  76906. set: function (meshes) {
  76907. this._multiRenderTarget.renderList = meshes;
  76908. },
  76909. enumerable: true,
  76910. configurable: true
  76911. });
  76912. Object.defineProperty(GeometryBufferRenderer.prototype, "isSupported", {
  76913. /**
  76914. * Gets wether or not G buffer are supported by the running hardware.
  76915. * This requires draw buffer supports
  76916. */
  76917. get: function () {
  76918. return this._multiRenderTarget.isSupported;
  76919. },
  76920. enumerable: true,
  76921. configurable: true
  76922. });
  76923. Object.defineProperty(GeometryBufferRenderer.prototype, "enablePosition", {
  76924. /**
  76925. * Gets wether or not position are enabled for the G buffer.
  76926. */
  76927. get: function () {
  76928. return this._enablePosition;
  76929. },
  76930. /**
  76931. * Sets wether or not position are enabled for the G buffer.
  76932. */
  76933. set: function (enable) {
  76934. this._enablePosition = enable;
  76935. this.dispose();
  76936. this._createRenderTargets();
  76937. },
  76938. enumerable: true,
  76939. configurable: true
  76940. });
  76941. Object.defineProperty(GeometryBufferRenderer.prototype, "scene", {
  76942. /**
  76943. * Gets the scene associated with the buffer.
  76944. */
  76945. get: function () {
  76946. return this._scene;
  76947. },
  76948. enumerable: true,
  76949. configurable: true
  76950. });
  76951. Object.defineProperty(GeometryBufferRenderer.prototype, "ratio", {
  76952. /**
  76953. * Gets the ratio used by the buffer during its creation.
  76954. * How big is the buffer related to the main canvas.
  76955. */
  76956. get: function () {
  76957. return this._ratio;
  76958. },
  76959. enumerable: true,
  76960. configurable: true
  76961. });
  76962. /**
  76963. * Checks wether everything is ready to render a submesh to the G buffer.
  76964. * @param subMesh the submesh to check readiness for
  76965. * @param useInstances is the mesh drawn using instance or not
  76966. * @returns true if ready otherwise false
  76967. */
  76968. GeometryBufferRenderer.prototype.isReady = function (subMesh, useInstances) {
  76969. var material = subMesh.getMaterial();
  76970. if (material && material.disableDepthWrite) {
  76971. return false;
  76972. }
  76973. var defines = [];
  76974. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  76975. var mesh = subMesh.getMesh();
  76976. // Alpha test
  76977. if (material && material.needAlphaTesting()) {
  76978. defines.push("#define ALPHATEST");
  76979. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  76980. attribs.push(BABYLON.VertexBuffer.UVKind);
  76981. defines.push("#define UV1");
  76982. }
  76983. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  76984. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  76985. defines.push("#define UV2");
  76986. }
  76987. }
  76988. // Buffers
  76989. if (this._enablePosition) {
  76990. defines.push("#define POSITION");
  76991. }
  76992. // Bones
  76993. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  76994. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  76995. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  76996. if (mesh.numBoneInfluencers > 4) {
  76997. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  76998. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  76999. }
  77000. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  77001. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  77002. }
  77003. else {
  77004. defines.push("#define NUM_BONE_INFLUENCERS 0");
  77005. }
  77006. // Instances
  77007. if (useInstances) {
  77008. defines.push("#define INSTANCES");
  77009. attribs.push("world0");
  77010. attribs.push("world1");
  77011. attribs.push("world2");
  77012. attribs.push("world3");
  77013. }
  77014. // Get correct effect
  77015. var join = defines.join("\n");
  77016. if (this._cachedDefines !== join) {
  77017. this._cachedDefines = join;
  77018. this._effect = this._scene.getEngine().createEffect("geometry", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "view"], ["diffuseSampler"], join, undefined, undefined, undefined, { buffersCount: this._enablePosition ? 3 : 2 });
  77019. }
  77020. return this._effect.isReady();
  77021. };
  77022. /**
  77023. * Gets the current underlying G Buffer.
  77024. * @returns the buffer
  77025. */
  77026. GeometryBufferRenderer.prototype.getGBuffer = function () {
  77027. return this._multiRenderTarget;
  77028. };
  77029. Object.defineProperty(GeometryBufferRenderer.prototype, "samples", {
  77030. /**
  77031. * Gets the number of samples used to render the buffer (anti aliasing).
  77032. */
  77033. get: function () {
  77034. return this._multiRenderTarget.samples;
  77035. },
  77036. /**
  77037. * Sets the number of samples used to render the buffer (anti aliasing).
  77038. */
  77039. set: function (value) {
  77040. this._multiRenderTarget.samples = value;
  77041. },
  77042. enumerable: true,
  77043. configurable: true
  77044. });
  77045. /**
  77046. * Disposes the renderer and frees up associated resources.
  77047. */
  77048. GeometryBufferRenderer.prototype.dispose = function () {
  77049. this.getGBuffer().dispose();
  77050. };
  77051. GeometryBufferRenderer.prototype._createRenderTargets = function () {
  77052. var _this = this;
  77053. var engine = this._scene.getEngine();
  77054. var count = this._enablePosition ? 3 : 2;
  77055. 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 });
  77056. if (!this.isSupported) {
  77057. return;
  77058. }
  77059. this._multiRenderTarget.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77060. this._multiRenderTarget.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77061. this._multiRenderTarget.refreshRate = 1;
  77062. this._multiRenderTarget.renderParticles = false;
  77063. this._multiRenderTarget.renderList = null;
  77064. // set default depth value to 1.0 (far away)
  77065. this._multiRenderTarget.onClearObservable.add(function (engine) {
  77066. engine.clear(new BABYLON.Color4(0.0, 0.0, 0.0, 1.0), true, true, true);
  77067. });
  77068. // Custom render function
  77069. var renderSubMesh = function (subMesh) {
  77070. var mesh = subMesh.getRenderingMesh();
  77071. var scene = _this._scene;
  77072. var engine = scene.getEngine();
  77073. var material = subMesh.getMaterial();
  77074. if (!material) {
  77075. return;
  77076. }
  77077. // Culling
  77078. engine.setState(material.backFaceCulling, 0, false, scene.useRightHandedSystem);
  77079. // Managing instances
  77080. var batch = mesh._getInstancesRenderList(subMesh._id);
  77081. if (batch.mustReturn) {
  77082. return;
  77083. }
  77084. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  77085. if (_this.isReady(subMesh, hardwareInstancedRendering)) {
  77086. engine.enableEffect(_this._effect);
  77087. mesh._bind(subMesh, _this._effect, BABYLON.Material.TriangleFillMode);
  77088. _this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  77089. _this._effect.setMatrix("view", scene.getViewMatrix());
  77090. // Alpha test
  77091. if (material && material.needAlphaTesting()) {
  77092. var alphaTexture = material.getAlphaTestTexture();
  77093. if (alphaTexture) {
  77094. _this._effect.setTexture("diffuseSampler", alphaTexture);
  77095. _this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  77096. }
  77097. }
  77098. // Bones
  77099. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  77100. _this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  77101. }
  77102. // Draw
  77103. mesh._processRendering(subMesh, _this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effect.setMatrix("world", world); });
  77104. }
  77105. };
  77106. this._multiRenderTarget.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  77107. var index;
  77108. if (depthOnlySubMeshes.length) {
  77109. engine.setColorWrite(false);
  77110. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  77111. renderSubMesh(depthOnlySubMeshes.data[index]);
  77112. }
  77113. engine.setColorWrite(true);
  77114. }
  77115. for (index = 0; index < opaqueSubMeshes.length; index++) {
  77116. renderSubMesh(opaqueSubMeshes.data[index]);
  77117. }
  77118. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  77119. renderSubMesh(alphaTestSubMeshes.data[index]);
  77120. }
  77121. };
  77122. };
  77123. return GeometryBufferRenderer;
  77124. }());
  77125. BABYLON.GeometryBufferRenderer = GeometryBufferRenderer;
  77126. })(BABYLON || (BABYLON = {}));
  77127. //# sourceMappingURL=babylon.geometryBufferRenderer.js.map
  77128. var BABYLON;
  77129. (function (BABYLON) {
  77130. /**
  77131. * This groups together the common properties used for image processing either in direct forward pass
  77132. * or through post processing effect depending on the use of the image processing pipeline in your scene
  77133. * or not.
  77134. */
  77135. var ImageProcessingConfiguration = /** @class */ (function () {
  77136. function ImageProcessingConfiguration() {
  77137. /**
  77138. * Color curves setup used in the effect if colorCurvesEnabled is set to true
  77139. */
  77140. this.colorCurves = new BABYLON.ColorCurves();
  77141. this._colorCurvesEnabled = false;
  77142. this._colorGradingEnabled = false;
  77143. this._colorGradingWithGreenDepth = true;
  77144. this._colorGradingBGR = true;
  77145. this._exposure = 1.0;
  77146. this._toneMappingEnabled = false;
  77147. this._contrast = 1.0;
  77148. /**
  77149. * Vignette stretch size.
  77150. */
  77151. this.vignetteStretch = 0;
  77152. /**
  77153. * Vignette centre X Offset.
  77154. */
  77155. this.vignetteCentreX = 0;
  77156. /**
  77157. * Vignette centre Y Offset.
  77158. */
  77159. this.vignetteCentreY = 0;
  77160. /**
  77161. * Vignette weight or intensity of the vignette effect.
  77162. */
  77163. this.vignetteWeight = 1.5;
  77164. /**
  77165. * Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  77166. * if vignetteEnabled is set to true.
  77167. */
  77168. this.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  77169. /**
  77170. * Camera field of view used by the Vignette effect.
  77171. */
  77172. this.vignetteCameraFov = 0.5;
  77173. this._vignetteBlendMode = ImageProcessingConfiguration.VIGNETTEMODE_MULTIPLY;
  77174. this._vignetteEnabled = false;
  77175. this._applyByPostProcess = false;
  77176. this._isEnabled = true;
  77177. /**
  77178. * An event triggered when the configuration changes and requires Shader to Update some parameters.
  77179. */
  77180. this.onUpdateParameters = new BABYLON.Observable();
  77181. }
  77182. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorCurvesEnabled", {
  77183. /**
  77184. * Gets wether the color curves effect is enabled.
  77185. */
  77186. get: function () {
  77187. return this._colorCurvesEnabled;
  77188. },
  77189. /**
  77190. * Sets wether the color curves effect is enabled.
  77191. */
  77192. set: function (value) {
  77193. if (this._colorCurvesEnabled === value) {
  77194. return;
  77195. }
  77196. this._colorCurvesEnabled = value;
  77197. this._updateParameters();
  77198. },
  77199. enumerable: true,
  77200. configurable: true
  77201. });
  77202. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingEnabled", {
  77203. /**
  77204. * Gets wether the color grading effect is enabled.
  77205. */
  77206. get: function () {
  77207. return this._colorGradingEnabled;
  77208. },
  77209. /**
  77210. * Sets wether the color grading effect is enabled.
  77211. */
  77212. set: function (value) {
  77213. if (this._colorGradingEnabled === value) {
  77214. return;
  77215. }
  77216. this._colorGradingEnabled = value;
  77217. this._updateParameters();
  77218. },
  77219. enumerable: true,
  77220. configurable: true
  77221. });
  77222. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingWithGreenDepth", {
  77223. /**
  77224. * Gets wether the color grading effect is using a green depth for the 3d Texture.
  77225. */
  77226. get: function () {
  77227. return this._colorGradingWithGreenDepth;
  77228. },
  77229. /**
  77230. * Sets wether the color grading effect is using a green depth for the 3d Texture.
  77231. */
  77232. set: function (value) {
  77233. if (this._colorGradingWithGreenDepth === value) {
  77234. return;
  77235. }
  77236. this._colorGradingWithGreenDepth = value;
  77237. this._updateParameters();
  77238. },
  77239. enumerable: true,
  77240. configurable: true
  77241. });
  77242. Object.defineProperty(ImageProcessingConfiguration.prototype, "colorGradingBGR", {
  77243. /**
  77244. * Gets wether the color grading texture contains BGR values.
  77245. */
  77246. get: function () {
  77247. return this._colorGradingBGR;
  77248. },
  77249. /**
  77250. * Sets wether the color grading texture contains BGR values.
  77251. */
  77252. set: function (value) {
  77253. if (this._colorGradingBGR === value) {
  77254. return;
  77255. }
  77256. this._colorGradingBGR = value;
  77257. this._updateParameters();
  77258. },
  77259. enumerable: true,
  77260. configurable: true
  77261. });
  77262. Object.defineProperty(ImageProcessingConfiguration.prototype, "exposure", {
  77263. /**
  77264. * Gets the Exposure used in the effect.
  77265. */
  77266. get: function () {
  77267. return this._exposure;
  77268. },
  77269. /**
  77270. * Sets the Exposure used in the effect.
  77271. */
  77272. set: function (value) {
  77273. if (this._exposure === value) {
  77274. return;
  77275. }
  77276. this._exposure = value;
  77277. this._updateParameters();
  77278. },
  77279. enumerable: true,
  77280. configurable: true
  77281. });
  77282. Object.defineProperty(ImageProcessingConfiguration.prototype, "toneMappingEnabled", {
  77283. /**
  77284. * Gets wether the tone mapping effect is enabled.
  77285. */
  77286. get: function () {
  77287. return this._toneMappingEnabled;
  77288. },
  77289. /**
  77290. * Sets wether the tone mapping effect is enabled.
  77291. */
  77292. set: function (value) {
  77293. if (this._toneMappingEnabled === value) {
  77294. return;
  77295. }
  77296. this._toneMappingEnabled = value;
  77297. this._updateParameters();
  77298. },
  77299. enumerable: true,
  77300. configurable: true
  77301. });
  77302. Object.defineProperty(ImageProcessingConfiguration.prototype, "contrast", {
  77303. /**
  77304. * Gets the contrast used in the effect.
  77305. */
  77306. get: function () {
  77307. return this._contrast;
  77308. },
  77309. /**
  77310. * Sets the contrast used in the effect.
  77311. */
  77312. set: function (value) {
  77313. if (this._contrast === value) {
  77314. return;
  77315. }
  77316. this._contrast = value;
  77317. this._updateParameters();
  77318. },
  77319. enumerable: true,
  77320. configurable: true
  77321. });
  77322. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteBlendMode", {
  77323. /**
  77324. * Gets the vignette blend mode allowing different kind of effect.
  77325. */
  77326. get: function () {
  77327. return this._vignetteBlendMode;
  77328. },
  77329. /**
  77330. * Sets the vignette blend mode allowing different kind of effect.
  77331. */
  77332. set: function (value) {
  77333. if (this._vignetteBlendMode === value) {
  77334. return;
  77335. }
  77336. this._vignetteBlendMode = value;
  77337. this._updateParameters();
  77338. },
  77339. enumerable: true,
  77340. configurable: true
  77341. });
  77342. Object.defineProperty(ImageProcessingConfiguration.prototype, "vignetteEnabled", {
  77343. /**
  77344. * Gets wether the vignette effect is enabled.
  77345. */
  77346. get: function () {
  77347. return this._vignetteEnabled;
  77348. },
  77349. /**
  77350. * Sets wether the vignette effect is enabled.
  77351. */
  77352. set: function (value) {
  77353. if (this._vignetteEnabled === value) {
  77354. return;
  77355. }
  77356. this._vignetteEnabled = value;
  77357. this._updateParameters();
  77358. },
  77359. enumerable: true,
  77360. configurable: true
  77361. });
  77362. Object.defineProperty(ImageProcessingConfiguration.prototype, "applyByPostProcess", {
  77363. /**
  77364. * Gets wether the image processing is applied through a post process or not.
  77365. */
  77366. get: function () {
  77367. return this._applyByPostProcess;
  77368. },
  77369. /**
  77370. * Sets wether the image processing is applied through a post process or not.
  77371. */
  77372. set: function (value) {
  77373. if (this._applyByPostProcess === value) {
  77374. return;
  77375. }
  77376. this._applyByPostProcess = value;
  77377. this._updateParameters();
  77378. },
  77379. enumerable: true,
  77380. configurable: true
  77381. });
  77382. Object.defineProperty(ImageProcessingConfiguration.prototype, "isEnabled", {
  77383. /**
  77384. * Gets wether the image processing is enabled or not.
  77385. */
  77386. get: function () {
  77387. return this._isEnabled;
  77388. },
  77389. /**
  77390. * Sets wether the image processing is enabled or not.
  77391. */
  77392. set: function (value) {
  77393. if (this._isEnabled === value) {
  77394. return;
  77395. }
  77396. this._isEnabled = value;
  77397. this._updateParameters();
  77398. },
  77399. enumerable: true,
  77400. configurable: true
  77401. });
  77402. /**
  77403. * Method called each time the image processing information changes requires to recompile the effect.
  77404. */
  77405. ImageProcessingConfiguration.prototype._updateParameters = function () {
  77406. this.onUpdateParameters.notifyObservers(this);
  77407. };
  77408. ImageProcessingConfiguration.prototype.getClassName = function () {
  77409. return "ImageProcessingConfiguration";
  77410. };
  77411. /**
  77412. * Prepare the list of uniforms associated with the Image Processing effects.
  77413. * @param uniformsList The list of uniforms used in the effect
  77414. * @param defines the list of defines currently in use
  77415. */
  77416. ImageProcessingConfiguration.PrepareUniforms = function (uniforms, defines) {
  77417. if (defines.EXPOSURE) {
  77418. uniforms.push("exposureLinear");
  77419. }
  77420. if (defines.CONTRAST) {
  77421. uniforms.push("contrast");
  77422. }
  77423. if (defines.COLORGRADING) {
  77424. uniforms.push("colorTransformSettings");
  77425. }
  77426. if (defines.VIGNETTE) {
  77427. uniforms.push("vInverseScreenSize");
  77428. uniforms.push("vignetteSettings1");
  77429. uniforms.push("vignetteSettings2");
  77430. }
  77431. if (defines.COLORCURVES) {
  77432. BABYLON.ColorCurves.PrepareUniforms(uniforms);
  77433. }
  77434. };
  77435. /**
  77436. * Prepare the list of samplers associated with the Image Processing effects.
  77437. * @param uniformsList The list of uniforms used in the effect
  77438. * @param defines the list of defines currently in use
  77439. */
  77440. ImageProcessingConfiguration.PrepareSamplers = function (samplersList, defines) {
  77441. if (defines.COLORGRADING) {
  77442. samplersList.push("txColorTransform");
  77443. }
  77444. };
  77445. /**
  77446. * Prepare the list of defines associated to the shader.
  77447. * @param defines the list of defines to complete
  77448. */
  77449. ImageProcessingConfiguration.prototype.prepareDefines = function (defines, forPostProcess) {
  77450. if (forPostProcess === void 0) { forPostProcess = false; }
  77451. if (forPostProcess !== this.applyByPostProcess || !this._isEnabled) {
  77452. defines.VIGNETTE = false;
  77453. defines.TONEMAPPING = false;
  77454. defines.CONTRAST = false;
  77455. defines.EXPOSURE = false;
  77456. defines.COLORCURVES = false;
  77457. defines.COLORGRADING = false;
  77458. defines.COLORGRADING3D = false;
  77459. defines.IMAGEPROCESSING = false;
  77460. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess && this._isEnabled;
  77461. return;
  77462. }
  77463. defines.VIGNETTE = this.vignetteEnabled;
  77464. defines.VIGNETTEBLENDMODEMULTIPLY = (this.vignetteBlendMode === ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY);
  77465. defines.VIGNETTEBLENDMODEOPAQUE = !defines.VIGNETTEBLENDMODEMULTIPLY;
  77466. defines.TONEMAPPING = this.toneMappingEnabled;
  77467. defines.CONTRAST = (this.contrast !== 1.0);
  77468. defines.EXPOSURE = (this.exposure !== 1.0);
  77469. defines.COLORCURVES = (this.colorCurvesEnabled && !!this.colorCurves);
  77470. defines.COLORGRADING = (this.colorGradingEnabled && !!this.colorGradingTexture);
  77471. if (defines.COLORGRADING) {
  77472. defines.COLORGRADING3D = this.colorGradingTexture.is3D;
  77473. }
  77474. else {
  77475. defines.COLORGRADING3D = false;
  77476. }
  77477. defines.SAMPLER3DGREENDEPTH = this.colorGradingWithGreenDepth;
  77478. defines.SAMPLER3DBGRMAP = this.colorGradingBGR;
  77479. defines.IMAGEPROCESSINGPOSTPROCESS = this.applyByPostProcess;
  77480. defines.IMAGEPROCESSING = defines.VIGNETTE || defines.TONEMAPPING || defines.CONTRAST || defines.EXPOSURE || defines.COLORCURVES || defines.COLORGRADING;
  77481. };
  77482. /**
  77483. * Returns true if all the image processing information are ready.
  77484. */
  77485. ImageProcessingConfiguration.prototype.isReady = function () {
  77486. // Color Grading texure can not be none blocking.
  77487. return !this.colorGradingEnabled || !this.colorGradingTexture || this.colorGradingTexture.isReady();
  77488. };
  77489. /**
  77490. * Binds the image processing to the shader.
  77491. * @param effect The effect to bind to
  77492. */
  77493. ImageProcessingConfiguration.prototype.bind = function (effect, aspectRatio) {
  77494. if (aspectRatio === void 0) { aspectRatio = 1; }
  77495. // Color Curves
  77496. if (this._colorCurvesEnabled && this.colorCurves) {
  77497. BABYLON.ColorCurves.Bind(this.colorCurves, effect);
  77498. }
  77499. // Vignette
  77500. if (this._vignetteEnabled) {
  77501. var inverseWidth = 1 / effect.getEngine().getRenderWidth();
  77502. var inverseHeight = 1 / effect.getEngine().getRenderHeight();
  77503. effect.setFloat2("vInverseScreenSize", inverseWidth, inverseHeight);
  77504. var vignetteScaleY = Math.tan(this.vignetteCameraFov * 0.5);
  77505. var vignetteScaleX = vignetteScaleY * aspectRatio;
  77506. var vignetteScaleGeometricMean = Math.sqrt(vignetteScaleX * vignetteScaleY);
  77507. vignetteScaleX = BABYLON.Tools.Mix(vignetteScaleX, vignetteScaleGeometricMean, this.vignetteStretch);
  77508. vignetteScaleY = BABYLON.Tools.Mix(vignetteScaleY, vignetteScaleGeometricMean, this.vignetteStretch);
  77509. effect.setFloat4("vignetteSettings1", vignetteScaleX, vignetteScaleY, -vignetteScaleX * this.vignetteCentreX, -vignetteScaleY * this.vignetteCentreY);
  77510. var vignettePower = -2.0 * this.vignetteWeight;
  77511. effect.setFloat4("vignetteSettings2", this.vignetteColor.r, this.vignetteColor.g, this.vignetteColor.b, vignettePower);
  77512. }
  77513. // Exposure
  77514. effect.setFloat("exposureLinear", this.exposure);
  77515. // Contrast
  77516. effect.setFloat("contrast", this.contrast);
  77517. // Color transform settings
  77518. if (this.colorGradingTexture) {
  77519. effect.setTexture("txColorTransform", this.colorGradingTexture);
  77520. var textureSize = this.colorGradingTexture.getSize().height;
  77521. effect.setFloat4("colorTransformSettings", (textureSize - 1) / textureSize, // textureScale
  77522. 0.5 / textureSize, // textureOffset
  77523. textureSize, // textureSize
  77524. this.colorGradingTexture.level // weight
  77525. );
  77526. }
  77527. };
  77528. /**
  77529. * Clones the current image processing instance.
  77530. * @return The cloned image processing
  77531. */
  77532. ImageProcessingConfiguration.prototype.clone = function () {
  77533. return BABYLON.SerializationHelper.Clone(function () { return new ImageProcessingConfiguration(); }, this);
  77534. };
  77535. /**
  77536. * Serializes the current image processing instance to a json representation.
  77537. * @return a JSON representation
  77538. */
  77539. ImageProcessingConfiguration.prototype.serialize = function () {
  77540. return BABYLON.SerializationHelper.Serialize(this);
  77541. };
  77542. /**
  77543. * Parses the image processing from a json representation.
  77544. * @param source the JSON source to parse
  77545. * @return The parsed image processing
  77546. */
  77547. ImageProcessingConfiguration.Parse = function (source) {
  77548. return BABYLON.SerializationHelper.Parse(function () { return new ImageProcessingConfiguration(); }, source, null, null);
  77549. };
  77550. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_MULTIPLY", {
  77551. /**
  77552. * Used to apply the vignette as a mix with the pixel color.
  77553. */
  77554. get: function () {
  77555. return this._VIGNETTEMODE_MULTIPLY;
  77556. },
  77557. enumerable: true,
  77558. configurable: true
  77559. });
  77560. Object.defineProperty(ImageProcessingConfiguration, "VIGNETTEMODE_OPAQUE", {
  77561. /**
  77562. * Used to apply the vignette as a replacement of the pixel color.
  77563. */
  77564. get: function () {
  77565. return this._VIGNETTEMODE_OPAQUE;
  77566. },
  77567. enumerable: true,
  77568. configurable: true
  77569. });
  77570. // Static constants associated to the image processing.
  77571. ImageProcessingConfiguration._VIGNETTEMODE_MULTIPLY = 0;
  77572. ImageProcessingConfiguration._VIGNETTEMODE_OPAQUE = 1;
  77573. __decorate([
  77574. BABYLON.serializeAsColorCurves()
  77575. ], ImageProcessingConfiguration.prototype, "colorCurves", void 0);
  77576. __decorate([
  77577. BABYLON.serialize()
  77578. ], ImageProcessingConfiguration.prototype, "_colorCurvesEnabled", void 0);
  77579. __decorate([
  77580. BABYLON.serializeAsTexture()
  77581. ], ImageProcessingConfiguration.prototype, "colorGradingTexture", void 0);
  77582. __decorate([
  77583. BABYLON.serialize()
  77584. ], ImageProcessingConfiguration.prototype, "_colorGradingEnabled", void 0);
  77585. __decorate([
  77586. BABYLON.serialize()
  77587. ], ImageProcessingConfiguration.prototype, "_colorGradingWithGreenDepth", void 0);
  77588. __decorate([
  77589. BABYLON.serialize()
  77590. ], ImageProcessingConfiguration.prototype, "_colorGradingBGR", void 0);
  77591. __decorate([
  77592. BABYLON.serialize()
  77593. ], ImageProcessingConfiguration.prototype, "_exposure", void 0);
  77594. __decorate([
  77595. BABYLON.serialize()
  77596. ], ImageProcessingConfiguration.prototype, "_toneMappingEnabled", void 0);
  77597. __decorate([
  77598. BABYLON.serialize()
  77599. ], ImageProcessingConfiguration.prototype, "_contrast", void 0);
  77600. __decorate([
  77601. BABYLON.serialize()
  77602. ], ImageProcessingConfiguration.prototype, "vignetteStretch", void 0);
  77603. __decorate([
  77604. BABYLON.serialize()
  77605. ], ImageProcessingConfiguration.prototype, "vignetteCentreX", void 0);
  77606. __decorate([
  77607. BABYLON.serialize()
  77608. ], ImageProcessingConfiguration.prototype, "vignetteCentreY", void 0);
  77609. __decorate([
  77610. BABYLON.serialize()
  77611. ], ImageProcessingConfiguration.prototype, "vignetteWeight", void 0);
  77612. __decorate([
  77613. BABYLON.serializeAsColor4()
  77614. ], ImageProcessingConfiguration.prototype, "vignetteColor", void 0);
  77615. __decorate([
  77616. BABYLON.serialize()
  77617. ], ImageProcessingConfiguration.prototype, "vignetteCameraFov", void 0);
  77618. __decorate([
  77619. BABYLON.serialize()
  77620. ], ImageProcessingConfiguration.prototype, "_vignetteBlendMode", void 0);
  77621. __decorate([
  77622. BABYLON.serialize()
  77623. ], ImageProcessingConfiguration.prototype, "_vignetteEnabled", void 0);
  77624. __decorate([
  77625. BABYLON.serialize()
  77626. ], ImageProcessingConfiguration.prototype, "_applyByPostProcess", void 0);
  77627. __decorate([
  77628. BABYLON.serialize()
  77629. ], ImageProcessingConfiguration.prototype, "_isEnabled", void 0);
  77630. return ImageProcessingConfiguration;
  77631. }());
  77632. BABYLON.ImageProcessingConfiguration = ImageProcessingConfiguration;
  77633. })(BABYLON || (BABYLON = {}));
  77634. //# sourceMappingURL=babylon.imageProcessingConfiguration.js.map
  77635. var BABYLON;
  77636. (function (BABYLON) {
  77637. /**
  77638. * This represents a color grading texture. This acts as a lookup table LUT, useful during post process
  77639. * It can help converting any input color in a desired output one. This can then be used to create effects
  77640. * from sepia, black and white to sixties or futuristic rendering...
  77641. *
  77642. * The only supported format is currently 3dl.
  77643. * More information on LUT: https://en.wikipedia.org/wiki/3D_lookup_table/
  77644. */
  77645. var ColorGradingTexture = /** @class */ (function (_super) {
  77646. __extends(ColorGradingTexture, _super);
  77647. /**
  77648. * Instantiates a ColorGradingTexture from the following parameters.
  77649. *
  77650. * @param url The location of the color gradind data (currently only supporting 3dl)
  77651. * @param scene The scene the texture will be used in
  77652. */
  77653. function ColorGradingTexture(url, scene) {
  77654. var _this = _super.call(this, scene) || this;
  77655. if (!url) {
  77656. return _this;
  77657. }
  77658. _this._engine = scene.getEngine();
  77659. _this._textureMatrix = BABYLON.Matrix.Identity();
  77660. _this.name = url;
  77661. _this.url = url;
  77662. _this.hasAlpha = false;
  77663. _this.isCube = false;
  77664. _this.is3D = _this._engine.webGLVersion > 1;
  77665. _this.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77666. _this.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77667. _this.wrapR = BABYLON.Texture.CLAMP_ADDRESSMODE;
  77668. _this.anisotropicFilteringLevel = 1;
  77669. _this._texture = _this._getFromCache(url, true);
  77670. if (!_this._texture) {
  77671. if (!scene.useDelayedTextureLoading) {
  77672. _this.loadTexture();
  77673. }
  77674. else {
  77675. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  77676. }
  77677. }
  77678. return _this;
  77679. }
  77680. /**
  77681. * Returns the texture matrix used in most of the material.
  77682. * This is not used in color grading but keep for troubleshooting purpose (easily swap diffuse by colorgrading to look in).
  77683. */
  77684. ColorGradingTexture.prototype.getTextureMatrix = function () {
  77685. return this._textureMatrix;
  77686. };
  77687. /**
  77688. * Occurs when the file being loaded is a .3dl LUT file.
  77689. */
  77690. ColorGradingTexture.prototype.load3dlTexture = function () {
  77691. var engine = this._engine;
  77692. var texture;
  77693. if (engine.webGLVersion === 1) {
  77694. texture = engine.createRawTexture(null, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77695. }
  77696. else {
  77697. texture = engine.createRawTexture3D(null, 1, 1, 1, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  77698. }
  77699. this._texture = texture;
  77700. var callback = function (text) {
  77701. if (typeof text !== "string") {
  77702. return;
  77703. }
  77704. var data = null;
  77705. var tempData = null;
  77706. var line;
  77707. var lines = text.split('\n');
  77708. var size = 0, pixelIndexW = 0, pixelIndexH = 0, pixelIndexSlice = 0;
  77709. var maxColor = 0;
  77710. for (var i = 0; i < lines.length; i++) {
  77711. line = lines[i];
  77712. if (!ColorGradingTexture._noneEmptyLineRegex.test(line))
  77713. continue;
  77714. if (line.indexOf('#') === 0)
  77715. continue;
  77716. var words = line.split(" ");
  77717. if (size === 0) {
  77718. // Number of space + one
  77719. size = words.length;
  77720. data = new Uint8Array(size * size * size * 4); // volume texture of side size and rgb 8
  77721. tempData = new Float32Array(size * size * size * 4);
  77722. continue;
  77723. }
  77724. if (size != 0) {
  77725. var r = Math.max(parseInt(words[0]), 0);
  77726. var g = Math.max(parseInt(words[1]), 0);
  77727. var b = Math.max(parseInt(words[2]), 0);
  77728. maxColor = Math.max(r, maxColor);
  77729. maxColor = Math.max(g, maxColor);
  77730. maxColor = Math.max(b, maxColor);
  77731. var pixelStorageIndex = (pixelIndexW + pixelIndexSlice * size + pixelIndexH * size * size) * 4;
  77732. if (tempData) {
  77733. tempData[pixelStorageIndex + 0] = r;
  77734. tempData[pixelStorageIndex + 1] = g;
  77735. tempData[pixelStorageIndex + 2] = b;
  77736. }
  77737. pixelIndexSlice++;
  77738. if (pixelIndexSlice % size == 0) {
  77739. pixelIndexH++;
  77740. pixelIndexSlice = 0;
  77741. if (pixelIndexH % size == 0) {
  77742. pixelIndexW++;
  77743. pixelIndexH = 0;
  77744. }
  77745. }
  77746. }
  77747. }
  77748. if (tempData && data) {
  77749. for (var i = 0; i < tempData.length; i++) {
  77750. if (i > 0 && (i + 1) % 4 === 0) {
  77751. data[i] = 255;
  77752. }
  77753. else {
  77754. var value = tempData[i];
  77755. data[i] = (value / maxColor * 255);
  77756. }
  77757. }
  77758. }
  77759. if (texture.is3D) {
  77760. texture.updateSize(size, size, size);
  77761. engine.updateRawTexture3D(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77762. }
  77763. else {
  77764. texture.updateSize(size * size, size);
  77765. engine.updateRawTexture(texture, data, BABYLON.Engine.TEXTUREFORMAT_RGBA, false);
  77766. }
  77767. };
  77768. var scene = this.getScene();
  77769. if (scene) {
  77770. scene._loadFile(this.url, callback);
  77771. }
  77772. else {
  77773. this._engine._loadFile(this.url, callback);
  77774. }
  77775. return this._texture;
  77776. };
  77777. /**
  77778. * Starts the loading process of the texture.
  77779. */
  77780. ColorGradingTexture.prototype.loadTexture = function () {
  77781. if (this.url && this.url.toLocaleLowerCase().indexOf(".3dl") == (this.url.length - 4)) {
  77782. this.load3dlTexture();
  77783. }
  77784. };
  77785. /**
  77786. * Clones the color gradind texture.
  77787. */
  77788. ColorGradingTexture.prototype.clone = function () {
  77789. var newTexture = new ColorGradingTexture(this.url, this.getScene());
  77790. // Base texture
  77791. newTexture.level = this.level;
  77792. return newTexture;
  77793. };
  77794. /**
  77795. * Called during delayed load for textures.
  77796. */
  77797. ColorGradingTexture.prototype.delayLoad = function () {
  77798. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  77799. return;
  77800. }
  77801. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  77802. this._texture = this._getFromCache(this.url, true);
  77803. if (!this._texture) {
  77804. this.loadTexture();
  77805. }
  77806. };
  77807. /**
  77808. * Parses a color grading texture serialized by Babylon.
  77809. * @param parsedTexture The texture information being parsedTexture
  77810. * @param scene The scene to load the texture in
  77811. * @param rootUrl The root url of the data assets to load
  77812. * @return A color gradind texture
  77813. */
  77814. ColorGradingTexture.Parse = function (parsedTexture, scene, rootUrl) {
  77815. var texture = null;
  77816. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  77817. texture = new ColorGradingTexture(parsedTexture.name, scene);
  77818. texture.name = parsedTexture.name;
  77819. texture.level = parsedTexture.level;
  77820. }
  77821. return texture;
  77822. };
  77823. /**
  77824. * Serializes the LUT texture to json format.
  77825. */
  77826. ColorGradingTexture.prototype.serialize = function () {
  77827. if (!this.name) {
  77828. return null;
  77829. }
  77830. var serializationObject = {};
  77831. serializationObject.name = this.name;
  77832. serializationObject.level = this.level;
  77833. serializationObject.customType = "BABYLON.ColorGradingTexture";
  77834. return serializationObject;
  77835. };
  77836. /**
  77837. * Empty line regex stored for GC.
  77838. */
  77839. ColorGradingTexture._noneEmptyLineRegex = /\S+/;
  77840. return ColorGradingTexture;
  77841. }(BABYLON.BaseTexture));
  77842. BABYLON.ColorGradingTexture = ColorGradingTexture;
  77843. })(BABYLON || (BABYLON = {}));
  77844. //# sourceMappingURL=babylon.colorGradingTexture.js.map
  77845. var BABYLON;
  77846. (function (BABYLON) {
  77847. /**
  77848. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  77849. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  77850. * 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;
  77851. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  77852. */
  77853. var ColorCurves = /** @class */ (function () {
  77854. function ColorCurves() {
  77855. this._dirty = true;
  77856. this._tempColor = new BABYLON.Color4(0, 0, 0, 0);
  77857. this._globalCurve = new BABYLON.Color4(0, 0, 0, 0);
  77858. this._highlightsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77859. this._midtonesCurve = new BABYLON.Color4(0, 0, 0, 0);
  77860. this._shadowsCurve = new BABYLON.Color4(0, 0, 0, 0);
  77861. this._positiveCurve = new BABYLON.Color4(0, 0, 0, 0);
  77862. this._negativeCurve = new BABYLON.Color4(0, 0, 0, 0);
  77863. this._globalHue = 30;
  77864. this._globalDensity = 0;
  77865. this._globalSaturation = 0;
  77866. this._globalExposure = 0;
  77867. this._highlightsHue = 30;
  77868. this._highlightsDensity = 0;
  77869. this._highlightsSaturation = 0;
  77870. this._highlightsExposure = 0;
  77871. this._midtonesHue = 30;
  77872. this._midtonesDensity = 0;
  77873. this._midtonesSaturation = 0;
  77874. this._midtonesExposure = 0;
  77875. this._shadowsHue = 30;
  77876. this._shadowsDensity = 0;
  77877. this._shadowsSaturation = 0;
  77878. this._shadowsExposure = 0;
  77879. }
  77880. Object.defineProperty(ColorCurves.prototype, "globalHue", {
  77881. /**
  77882. * Gets the global Hue value.
  77883. * 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).
  77884. */
  77885. get: function () {
  77886. return this._globalHue;
  77887. },
  77888. /**
  77889. * Sets the global Hue value.
  77890. * 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).
  77891. */
  77892. set: function (value) {
  77893. this._globalHue = value;
  77894. this._dirty = true;
  77895. },
  77896. enumerable: true,
  77897. configurable: true
  77898. });
  77899. Object.defineProperty(ColorCurves.prototype, "globalDensity", {
  77900. /**
  77901. * Gets the global Density value.
  77902. * 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.
  77903. * Values less than zero provide a filter of opposite hue.
  77904. */
  77905. get: function () {
  77906. return this._globalDensity;
  77907. },
  77908. /**
  77909. * Sets the global Density value.
  77910. * 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.
  77911. * Values less than zero provide a filter of opposite hue.
  77912. */
  77913. set: function (value) {
  77914. this._globalDensity = value;
  77915. this._dirty = true;
  77916. },
  77917. enumerable: true,
  77918. configurable: true
  77919. });
  77920. Object.defineProperty(ColorCurves.prototype, "globalSaturation", {
  77921. /**
  77922. * Gets the global Saturation value.
  77923. * 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.
  77924. */
  77925. get: function () {
  77926. return this._globalSaturation;
  77927. },
  77928. /**
  77929. * Sets the global Saturation value.
  77930. * 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.
  77931. */
  77932. set: function (value) {
  77933. this._globalSaturation = value;
  77934. this._dirty = true;
  77935. },
  77936. enumerable: true,
  77937. configurable: true
  77938. });
  77939. Object.defineProperty(ColorCurves.prototype, "globalExposure", {
  77940. /**
  77941. * Gets the global Exposure value.
  77942. * 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.
  77943. */
  77944. get: function () {
  77945. return this._globalExposure;
  77946. },
  77947. /**
  77948. * Sets the global Exposure value.
  77949. * 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.
  77950. */
  77951. set: function (value) {
  77952. this._globalExposure = value;
  77953. this._dirty = true;
  77954. },
  77955. enumerable: true,
  77956. configurable: true
  77957. });
  77958. Object.defineProperty(ColorCurves.prototype, "highlightsHue", {
  77959. /**
  77960. * Gets the highlights Hue value.
  77961. * 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).
  77962. */
  77963. get: function () {
  77964. return this._highlightsHue;
  77965. },
  77966. /**
  77967. * Sets the highlights Hue value.
  77968. * 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).
  77969. */
  77970. set: function (value) {
  77971. this._highlightsHue = value;
  77972. this._dirty = true;
  77973. },
  77974. enumerable: true,
  77975. configurable: true
  77976. });
  77977. Object.defineProperty(ColorCurves.prototype, "highlightsDensity", {
  77978. /**
  77979. * Gets the highlights Density value.
  77980. * 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.
  77981. * Values less than zero provide a filter of opposite hue.
  77982. */
  77983. get: function () {
  77984. return this._highlightsDensity;
  77985. },
  77986. /**
  77987. * Sets the highlights Density value.
  77988. * 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.
  77989. * Values less than zero provide a filter of opposite hue.
  77990. */
  77991. set: function (value) {
  77992. this._highlightsDensity = value;
  77993. this._dirty = true;
  77994. },
  77995. enumerable: true,
  77996. configurable: true
  77997. });
  77998. Object.defineProperty(ColorCurves.prototype, "highlightsSaturation", {
  77999. /**
  78000. * Gets the highlights Saturation value.
  78001. * 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.
  78002. */
  78003. get: function () {
  78004. return this._highlightsSaturation;
  78005. },
  78006. /**
  78007. * Sets the highlights Saturation value.
  78008. * 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.
  78009. */
  78010. set: function (value) {
  78011. this._highlightsSaturation = value;
  78012. this._dirty = true;
  78013. },
  78014. enumerable: true,
  78015. configurable: true
  78016. });
  78017. Object.defineProperty(ColorCurves.prototype, "highlightsExposure", {
  78018. /**
  78019. * Gets the highlights Exposure value.
  78020. * 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.
  78021. */
  78022. get: function () {
  78023. return this._highlightsExposure;
  78024. },
  78025. /**
  78026. * Sets the highlights Exposure value.
  78027. * 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.
  78028. */
  78029. set: function (value) {
  78030. this._highlightsExposure = value;
  78031. this._dirty = true;
  78032. },
  78033. enumerable: true,
  78034. configurable: true
  78035. });
  78036. Object.defineProperty(ColorCurves.prototype, "midtonesHue", {
  78037. /**
  78038. * Gets the midtones Hue value.
  78039. * 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).
  78040. */
  78041. get: function () {
  78042. return this._midtonesHue;
  78043. },
  78044. /**
  78045. * Sets the midtones Hue value.
  78046. * 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).
  78047. */
  78048. set: function (value) {
  78049. this._midtonesHue = value;
  78050. this._dirty = true;
  78051. },
  78052. enumerable: true,
  78053. configurable: true
  78054. });
  78055. Object.defineProperty(ColorCurves.prototype, "midtonesDensity", {
  78056. /**
  78057. * Gets the midtones Density value.
  78058. * 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.
  78059. * Values less than zero provide a filter of opposite hue.
  78060. */
  78061. get: function () {
  78062. return this._midtonesDensity;
  78063. },
  78064. /**
  78065. * Sets the midtones Density value.
  78066. * 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.
  78067. * Values less than zero provide a filter of opposite hue.
  78068. */
  78069. set: function (value) {
  78070. this._midtonesDensity = value;
  78071. this._dirty = true;
  78072. },
  78073. enumerable: true,
  78074. configurable: true
  78075. });
  78076. Object.defineProperty(ColorCurves.prototype, "midtonesSaturation", {
  78077. /**
  78078. * Gets the midtones Saturation value.
  78079. * 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.
  78080. */
  78081. get: function () {
  78082. return this._midtonesSaturation;
  78083. },
  78084. /**
  78085. * Sets the midtones Saturation value.
  78086. * 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.
  78087. */
  78088. set: function (value) {
  78089. this._midtonesSaturation = value;
  78090. this._dirty = true;
  78091. },
  78092. enumerable: true,
  78093. configurable: true
  78094. });
  78095. Object.defineProperty(ColorCurves.prototype, "midtonesExposure", {
  78096. /**
  78097. * Gets the midtones Exposure value.
  78098. * 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.
  78099. */
  78100. get: function () {
  78101. return this._midtonesExposure;
  78102. },
  78103. /**
  78104. * Sets the midtones Exposure value.
  78105. * 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.
  78106. */
  78107. set: function (value) {
  78108. this._midtonesExposure = value;
  78109. this._dirty = true;
  78110. },
  78111. enumerable: true,
  78112. configurable: true
  78113. });
  78114. Object.defineProperty(ColorCurves.prototype, "shadowsHue", {
  78115. /**
  78116. * Gets the shadows Hue value.
  78117. * 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).
  78118. */
  78119. get: function () {
  78120. return this._shadowsHue;
  78121. },
  78122. /**
  78123. * Sets the shadows Hue value.
  78124. * 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).
  78125. */
  78126. set: function (value) {
  78127. this._shadowsHue = value;
  78128. this._dirty = true;
  78129. },
  78130. enumerable: true,
  78131. configurable: true
  78132. });
  78133. Object.defineProperty(ColorCurves.prototype, "shadowsDensity", {
  78134. /**
  78135. * Gets the shadows Density value.
  78136. * 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.
  78137. * Values less than zero provide a filter of opposite hue.
  78138. */
  78139. get: function () {
  78140. return this._shadowsDensity;
  78141. },
  78142. /**
  78143. * Sets the shadows Density value.
  78144. * 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.
  78145. * Values less than zero provide a filter of opposite hue.
  78146. */
  78147. set: function (value) {
  78148. this._shadowsDensity = value;
  78149. this._dirty = true;
  78150. },
  78151. enumerable: true,
  78152. configurable: true
  78153. });
  78154. Object.defineProperty(ColorCurves.prototype, "shadowsSaturation", {
  78155. /**
  78156. * Gets the shadows Saturation value.
  78157. * 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.
  78158. */
  78159. get: function () {
  78160. return this._shadowsSaturation;
  78161. },
  78162. /**
  78163. * Sets the shadows Saturation value.
  78164. * 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.
  78165. */
  78166. set: function (value) {
  78167. this._shadowsSaturation = value;
  78168. this._dirty = true;
  78169. },
  78170. enumerable: true,
  78171. configurable: true
  78172. });
  78173. Object.defineProperty(ColorCurves.prototype, "shadowsExposure", {
  78174. /**
  78175. * Gets the shadows Exposure value.
  78176. * 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.
  78177. */
  78178. get: function () {
  78179. return this._shadowsExposure;
  78180. },
  78181. /**
  78182. * Sets the shadows Exposure value.
  78183. * 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.
  78184. */
  78185. set: function (value) {
  78186. this._shadowsExposure = value;
  78187. this._dirty = true;
  78188. },
  78189. enumerable: true,
  78190. configurable: true
  78191. });
  78192. ColorCurves.prototype.getClassName = function () {
  78193. return "ColorCurves";
  78194. };
  78195. /**
  78196. * Binds the color curves to the shader.
  78197. * @param colorCurves The color curve to bind
  78198. * @param effect The effect to bind to
  78199. */
  78200. ColorCurves.Bind = function (colorCurves, effect, positiveUniform, neutralUniform, negativeUniform) {
  78201. if (positiveUniform === void 0) { positiveUniform = "vCameraColorCurvePositive"; }
  78202. if (neutralUniform === void 0) { neutralUniform = "vCameraColorCurveNeutral"; }
  78203. if (negativeUniform === void 0) { negativeUniform = "vCameraColorCurveNegative"; }
  78204. if (colorCurves._dirty) {
  78205. colorCurves._dirty = false;
  78206. // Fill in global info.
  78207. colorCurves.getColorGradingDataToRef(colorCurves._globalHue, colorCurves._globalDensity, colorCurves._globalSaturation, colorCurves._globalExposure, colorCurves._globalCurve);
  78208. // Compute highlights info.
  78209. colorCurves.getColorGradingDataToRef(colorCurves._highlightsHue, colorCurves._highlightsDensity, colorCurves._highlightsSaturation, colorCurves._highlightsExposure, colorCurves._tempColor);
  78210. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._highlightsCurve);
  78211. // Compute midtones info.
  78212. colorCurves.getColorGradingDataToRef(colorCurves._midtonesHue, colorCurves._midtonesDensity, colorCurves._midtonesSaturation, colorCurves._midtonesExposure, colorCurves._tempColor);
  78213. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._midtonesCurve);
  78214. // Compute shadows info.
  78215. colorCurves.getColorGradingDataToRef(colorCurves._shadowsHue, colorCurves._shadowsDensity, colorCurves._shadowsSaturation, colorCurves._shadowsExposure, colorCurves._tempColor);
  78216. colorCurves._tempColor.multiplyToRef(colorCurves._globalCurve, colorCurves._shadowsCurve);
  78217. // Compute deltas (neutral is midtones).
  78218. colorCurves._highlightsCurve.subtractToRef(colorCurves._midtonesCurve, colorCurves._positiveCurve);
  78219. colorCurves._midtonesCurve.subtractToRef(colorCurves._shadowsCurve, colorCurves._negativeCurve);
  78220. }
  78221. if (effect) {
  78222. effect.setFloat4(positiveUniform, colorCurves._positiveCurve.r, colorCurves._positiveCurve.g, colorCurves._positiveCurve.b, colorCurves._positiveCurve.a);
  78223. effect.setFloat4(neutralUniform, colorCurves._midtonesCurve.r, colorCurves._midtonesCurve.g, colorCurves._midtonesCurve.b, colorCurves._midtonesCurve.a);
  78224. effect.setFloat4(negativeUniform, colorCurves._negativeCurve.r, colorCurves._negativeCurve.g, colorCurves._negativeCurve.b, colorCurves._negativeCurve.a);
  78225. }
  78226. };
  78227. /**
  78228. * Prepare the list of uniforms associated with the ColorCurves effects.
  78229. * @param uniformsList The list of uniforms used in the effect
  78230. */
  78231. ColorCurves.PrepareUniforms = function (uniformsList) {
  78232. uniformsList.push("vCameraColorCurveNeutral", "vCameraColorCurvePositive", "vCameraColorCurveNegative");
  78233. };
  78234. /**
  78235. * Returns color grading data based on a hue, density, saturation and exposure value.
  78236. * @param filterHue The hue of the color filter.
  78237. * @param filterDensity The density of the color filter.
  78238. * @param saturation The saturation.
  78239. * @param exposure The exposure.
  78240. * @param result The result data container.
  78241. */
  78242. ColorCurves.prototype.getColorGradingDataToRef = function (hue, density, saturation, exposure, result) {
  78243. if (hue == null) {
  78244. return;
  78245. }
  78246. hue = ColorCurves.clamp(hue, 0, 360);
  78247. density = ColorCurves.clamp(density, -100, 100);
  78248. saturation = ColorCurves.clamp(saturation, -100, 100);
  78249. exposure = ColorCurves.clamp(exposure, -100, 100);
  78250. // Remap the slider/config filter density with non-linear mapping and also scale by half
  78251. // so that the maximum filter density is only 50% control. This provides fine control
  78252. // for small values and reasonable range.
  78253. density = ColorCurves.applyColorGradingSliderNonlinear(density);
  78254. density *= 0.5;
  78255. exposure = ColorCurves.applyColorGradingSliderNonlinear(exposure);
  78256. if (density < 0) {
  78257. density *= -1;
  78258. hue = (hue + 180) % 360;
  78259. }
  78260. ColorCurves.fromHSBToRef(hue, density, 50 + 0.25 * exposure, result);
  78261. result.scaleToRef(2, result);
  78262. result.a = 1 + 0.01 * saturation;
  78263. };
  78264. /**
  78265. * Takes an input slider value and returns an adjusted value that provides extra control near the centre.
  78266. * @param value The input slider value in range [-100,100].
  78267. * @returns Adjusted value.
  78268. */
  78269. ColorCurves.applyColorGradingSliderNonlinear = function (value) {
  78270. value /= 100;
  78271. var x = Math.abs(value);
  78272. x = Math.pow(x, 2);
  78273. if (value < 0) {
  78274. x *= -1;
  78275. }
  78276. x *= 100;
  78277. return x;
  78278. };
  78279. /**
  78280. * Returns an RGBA Color4 based on Hue, Saturation and Brightness (also referred to as value, HSV).
  78281. * @param hue The hue (H) input.
  78282. * @param saturation The saturation (S) input.
  78283. * @param brightness The brightness (B) input.
  78284. * @result An RGBA color represented as Vector4.
  78285. */
  78286. ColorCurves.fromHSBToRef = function (hue, saturation, brightness, result) {
  78287. var h = ColorCurves.clamp(hue, 0, 360);
  78288. var s = ColorCurves.clamp(saturation / 100, 0, 1);
  78289. var v = ColorCurves.clamp(brightness / 100, 0, 1);
  78290. if (s === 0) {
  78291. result.r = v;
  78292. result.g = v;
  78293. result.b = v;
  78294. }
  78295. else {
  78296. // sector 0 to 5
  78297. h /= 60;
  78298. var i = Math.floor(h);
  78299. // fractional part of h
  78300. var f = h - i;
  78301. var p = v * (1 - s);
  78302. var q = v * (1 - s * f);
  78303. var t = v * (1 - s * (1 - f));
  78304. switch (i) {
  78305. case 0:
  78306. result.r = v;
  78307. result.g = t;
  78308. result.b = p;
  78309. break;
  78310. case 1:
  78311. result.r = q;
  78312. result.g = v;
  78313. result.b = p;
  78314. break;
  78315. case 2:
  78316. result.r = p;
  78317. result.g = v;
  78318. result.b = t;
  78319. break;
  78320. case 3:
  78321. result.r = p;
  78322. result.g = q;
  78323. result.b = v;
  78324. break;
  78325. case 4:
  78326. result.r = t;
  78327. result.g = p;
  78328. result.b = v;
  78329. break;
  78330. default: // case 5:
  78331. result.r = v;
  78332. result.g = p;
  78333. result.b = q;
  78334. break;
  78335. }
  78336. }
  78337. result.a = 1;
  78338. };
  78339. /**
  78340. * Returns a value clamped between min and max
  78341. * @param value The value to clamp
  78342. * @param min The minimum of value
  78343. * @param max The maximum of value
  78344. * @returns The clamped value.
  78345. */
  78346. ColorCurves.clamp = function (value, min, max) {
  78347. return Math.min(Math.max(value, min), max);
  78348. };
  78349. /**
  78350. * Clones the current color curve instance.
  78351. * @return The cloned curves
  78352. */
  78353. ColorCurves.prototype.clone = function () {
  78354. return BABYLON.SerializationHelper.Clone(function () { return new ColorCurves(); }, this);
  78355. };
  78356. /**
  78357. * Serializes the current color curve instance to a json representation.
  78358. * @return a JSON representation
  78359. */
  78360. ColorCurves.prototype.serialize = function () {
  78361. return BABYLON.SerializationHelper.Serialize(this);
  78362. };
  78363. /**
  78364. * Parses the color curve from a json representation.
  78365. * @param source the JSON source to parse
  78366. * @return The parsed curves
  78367. */
  78368. ColorCurves.Parse = function (source) {
  78369. return BABYLON.SerializationHelper.Parse(function () { return new ColorCurves(); }, source, null, null);
  78370. };
  78371. __decorate([
  78372. BABYLON.serialize()
  78373. ], ColorCurves.prototype, "_globalHue", void 0);
  78374. __decorate([
  78375. BABYLON.serialize()
  78376. ], ColorCurves.prototype, "_globalDensity", void 0);
  78377. __decorate([
  78378. BABYLON.serialize()
  78379. ], ColorCurves.prototype, "_globalSaturation", void 0);
  78380. __decorate([
  78381. BABYLON.serialize()
  78382. ], ColorCurves.prototype, "_globalExposure", void 0);
  78383. __decorate([
  78384. BABYLON.serialize()
  78385. ], ColorCurves.prototype, "_highlightsHue", void 0);
  78386. __decorate([
  78387. BABYLON.serialize()
  78388. ], ColorCurves.prototype, "_highlightsDensity", void 0);
  78389. __decorate([
  78390. BABYLON.serialize()
  78391. ], ColorCurves.prototype, "_highlightsSaturation", void 0);
  78392. __decorate([
  78393. BABYLON.serialize()
  78394. ], ColorCurves.prototype, "_highlightsExposure", void 0);
  78395. __decorate([
  78396. BABYLON.serialize()
  78397. ], ColorCurves.prototype, "_midtonesHue", void 0);
  78398. __decorate([
  78399. BABYLON.serialize()
  78400. ], ColorCurves.prototype, "_midtonesDensity", void 0);
  78401. __decorate([
  78402. BABYLON.serialize()
  78403. ], ColorCurves.prototype, "_midtonesSaturation", void 0);
  78404. __decorate([
  78405. BABYLON.serialize()
  78406. ], ColorCurves.prototype, "_midtonesExposure", void 0);
  78407. return ColorCurves;
  78408. }());
  78409. BABYLON.ColorCurves = ColorCurves;
  78410. })(BABYLON || (BABYLON = {}));
  78411. //# sourceMappingURL=babylon.colorCurves.js.map
  78412. var BABYLON;
  78413. (function (BABYLON) {
  78414. var RefractionPostProcess = /** @class */ (function (_super) {
  78415. __extends(RefractionPostProcess, _super);
  78416. function RefractionPostProcess(name, refractionTextureUrl, color, depth, colorLevel, options, camera, samplingMode, engine, reusable) {
  78417. var _this = _super.call(this, name, "refraction", ["baseColor", "depth", "colorLevel"], ["refractionSampler"], options, camera, samplingMode, engine, reusable) || this;
  78418. _this.color = color;
  78419. _this.depth = depth;
  78420. _this.colorLevel = colorLevel;
  78421. _this._ownRefractionTexture = true;
  78422. _this.onActivateObservable.add(function (cam) {
  78423. _this._refTexture = _this._refTexture || new BABYLON.Texture(refractionTextureUrl, cam.getScene());
  78424. });
  78425. _this.onApplyObservable.add(function (effect) {
  78426. effect.setColor3("baseColor", _this.color);
  78427. effect.setFloat("depth", _this.depth);
  78428. effect.setFloat("colorLevel", _this.colorLevel);
  78429. effect.setTexture("refractionSampler", _this._refTexture);
  78430. });
  78431. return _this;
  78432. }
  78433. Object.defineProperty(RefractionPostProcess.prototype, "refractionTexture", {
  78434. /**
  78435. * Gets or sets the refraction texture
  78436. * Please note that you are responsible for disposing the texture if you set it manually
  78437. */
  78438. get: function () {
  78439. return this._refTexture;
  78440. },
  78441. set: function (value) {
  78442. if (this._refTexture && this._ownRefractionTexture) {
  78443. this._refTexture.dispose();
  78444. }
  78445. this._refTexture = value;
  78446. this._ownRefractionTexture = false;
  78447. },
  78448. enumerable: true,
  78449. configurable: true
  78450. });
  78451. // Methods
  78452. RefractionPostProcess.prototype.dispose = function (camera) {
  78453. if (this._refTexture && this._ownRefractionTexture) {
  78454. this._refTexture.dispose();
  78455. this._refTexture = null;
  78456. }
  78457. _super.prototype.dispose.call(this, camera);
  78458. };
  78459. return RefractionPostProcess;
  78460. }(BABYLON.PostProcess));
  78461. BABYLON.RefractionPostProcess = RefractionPostProcess;
  78462. })(BABYLON || (BABYLON = {}));
  78463. //# sourceMappingURL=babylon.refractionPostProcess.js.map
  78464. var BABYLON;
  78465. (function (BABYLON) {
  78466. var BlackAndWhitePostProcess = /** @class */ (function (_super) {
  78467. __extends(BlackAndWhitePostProcess, _super);
  78468. function BlackAndWhitePostProcess(name, options, camera, samplingMode, engine, reusable) {
  78469. var _this = _super.call(this, name, "blackAndWhite", ["degree"], null, options, camera, samplingMode, engine, reusable) || this;
  78470. _this.degree = 1;
  78471. _this.onApplyObservable.add(function (effect) {
  78472. effect.setFloat("degree", _this.degree);
  78473. });
  78474. return _this;
  78475. }
  78476. return BlackAndWhitePostProcess;
  78477. }(BABYLON.PostProcess));
  78478. BABYLON.BlackAndWhitePostProcess = BlackAndWhitePostProcess;
  78479. })(BABYLON || (BABYLON = {}));
  78480. //# sourceMappingURL=babylon.blackAndWhitePostProcess.js.map
  78481. var BABYLON;
  78482. (function (BABYLON) {
  78483. /**
  78484. * The ConvolutionPostProcess applies a 3x3 kernel to every pixel of the
  78485. * input texture to perform effects such as edge detection or sharpening
  78486. * See http://en.wikipedia.org/wiki/Kernel_(image_processing)
  78487. */
  78488. var ConvolutionPostProcess = /** @class */ (function (_super) {
  78489. __extends(ConvolutionPostProcess, _super);
  78490. /**
  78491. * Creates a new instance ConvolutionPostProcess
  78492. * @param name The name of the effect.
  78493. * @param kernel Array of 9 values corrisponding to the 3x3 kernel to be applied
  78494. * @param options The required width/height ratio to downsize to before computing the render pass.
  78495. * @param camera The camera to apply the render pass to.
  78496. * @param samplingMode The sampling mode to be used when computing the pass. (default: 0)
  78497. * @param engine The engine which the post process will be applied. (default: current engine)
  78498. * @param reusable If the post process can be reused on the same frame. (default: false)
  78499. * @param textureType Type of textures used when performing the post process. (default: 0)
  78500. */
  78501. function ConvolutionPostProcess(name, /** Array of 9 values corrisponding to the 3x3 kernel to be applied */ kernel, options, camera, samplingMode, engine, reusable, textureType) {
  78502. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  78503. var _this = _super.call(this, name, "convolution", ["kernel", "screenSize"], null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  78504. _this.kernel = kernel;
  78505. _this.onApply = function (effect) {
  78506. effect.setFloat2("screenSize", _this.width, _this.height);
  78507. effect.setArray("kernel", _this.kernel);
  78508. };
  78509. return _this;
  78510. }
  78511. // Statics
  78512. /**
  78513. * Edge detection 0 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78514. */
  78515. ConvolutionPostProcess.EdgeDetect0Kernel = [1, 0, -1, 0, 0, 0, -1, 0, 1];
  78516. /**
  78517. * Edge detection 1 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78518. */
  78519. ConvolutionPostProcess.EdgeDetect1Kernel = [0, 1, 0, 1, -4, 1, 0, 1, 0];
  78520. /**
  78521. * Edge detection 2 see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78522. */
  78523. ConvolutionPostProcess.EdgeDetect2Kernel = [-1, -1, -1, -1, 8, -1, -1, -1, -1];
  78524. /**
  78525. * Kernel to sharpen an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78526. */
  78527. ConvolutionPostProcess.SharpenKernel = [0, -1, 0, -1, 5, -1, 0, -1, 0];
  78528. /**
  78529. * Kernel to emboss an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78530. */
  78531. ConvolutionPostProcess.EmbossKernel = [-2, -1, 0, -1, 1, 1, 0, 1, 2];
  78532. /**
  78533. * Kernel to blur an image see https://en.wikipedia.org/wiki/Kernel_(image_processing)
  78534. */
  78535. ConvolutionPostProcess.GaussianKernel = [0, 1, 0, 1, 1, 1, 0, 1, 0];
  78536. return ConvolutionPostProcess;
  78537. }(BABYLON.PostProcess));
  78538. BABYLON.ConvolutionPostProcess = ConvolutionPostProcess;
  78539. })(BABYLON || (BABYLON = {}));
  78540. //# sourceMappingURL=babylon.convolutionPostProcess.js.map
  78541. var BABYLON;
  78542. (function (BABYLON) {
  78543. var FilterPostProcess = /** @class */ (function (_super) {
  78544. __extends(FilterPostProcess, _super);
  78545. function FilterPostProcess(name, kernelMatrix, options, camera, samplingMode, engine, reusable) {
  78546. var _this = _super.call(this, name, "filter", ["kernelMatrix"], null, options, camera, samplingMode, engine, reusable) || this;
  78547. _this.kernelMatrix = kernelMatrix;
  78548. _this.onApply = function (effect) {
  78549. effect.setMatrix("kernelMatrix", _this.kernelMatrix);
  78550. };
  78551. return _this;
  78552. }
  78553. return FilterPostProcess;
  78554. }(BABYLON.PostProcess));
  78555. BABYLON.FilterPostProcess = FilterPostProcess;
  78556. })(BABYLON || (BABYLON = {}));
  78557. //# sourceMappingURL=babylon.filterPostProcess.js.map
  78558. var BABYLON;
  78559. (function (BABYLON) {
  78560. // Inspired by http://http.developer.nvidia.com/GPUGems3/gpugems3_ch13.html
  78561. var VolumetricLightScatteringPostProcess = /** @class */ (function (_super) {
  78562. __extends(VolumetricLightScatteringPostProcess, _super);
  78563. /**
  78564. * @constructor
  78565. * @param {string} name - The post-process name
  78566. * @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)
  78567. * @param {BABYLON.Camera} camera - The camera that the post-process will be attached to
  78568. * @param {BABYLON.Mesh} mesh - The mesh used to create the light scattering
  78569. * @param {number} samples - The post-process quality, default 100
  78570. * @param {number} samplingMode - The post-process filtering mode
  78571. * @param {BABYLON.Engine} engine - The babylon engine
  78572. * @param {boolean} reusable - If the post-process is reusable
  78573. * @param {BABYLON.Scene} scene - The constructor needs a scene reference to initialize internal components. If "camera" is null (RenderPipelineà, "scene" must be provided
  78574. */
  78575. function VolumetricLightScatteringPostProcess(name, ratio, camera, mesh, samples, samplingMode, engine, reusable, scene) {
  78576. if (samples === void 0) { samples = 100; }
  78577. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  78578. 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;
  78579. _this._screenCoordinates = BABYLON.Vector2.Zero();
  78580. /**
  78581. * Custom position of the mesh. Used if "useCustomMeshPosition" is set to "true"
  78582. */
  78583. _this.customMeshPosition = BABYLON.Vector3.Zero();
  78584. /**
  78585. * Set if the post-process should use a custom position for the light source (true) or the internal mesh position (false)
  78586. */
  78587. _this.useCustomMeshPosition = false;
  78588. /**
  78589. * If the post-process should inverse the light scattering direction
  78590. */
  78591. _this.invert = true;
  78592. /**
  78593. * Array containing the excluded meshes not rendered in the internal pass
  78594. */
  78595. _this.excludedMeshes = new Array();
  78596. /**
  78597. * Controls the overall intensity of the post-process
  78598. */
  78599. _this.exposure = 0.3;
  78600. /**
  78601. * Dissipates each sample's contribution in range [0, 1]
  78602. */
  78603. _this.decay = 0.96815;
  78604. /**
  78605. * Controls the overall intensity of each sample
  78606. */
  78607. _this.weight = 0.58767;
  78608. /**
  78609. * Controls the density of each sample
  78610. */
  78611. _this.density = 0.926;
  78612. scene = ((camera === null) ? scene : camera.getScene()); // parameter "scene" can be null.
  78613. engine = scene.getEngine();
  78614. _this._viewPort = new BABYLON.Viewport(0, 0, 1, 1).toGlobal(engine.getRenderWidth(), engine.getRenderHeight());
  78615. // Configure mesh
  78616. _this.mesh = ((mesh !== null) ? mesh : VolumetricLightScatteringPostProcess.CreateDefaultMesh("VolumetricLightScatteringMesh", scene));
  78617. // Configure
  78618. _this._createPass(scene, ratio.passRatio || ratio);
  78619. _this.onActivate = function (camera) {
  78620. if (!_this.isSupported) {
  78621. _this.dispose(camera);
  78622. }
  78623. _this.onActivate = null;
  78624. };
  78625. _this.onApplyObservable.add(function (effect) {
  78626. _this._updateMeshScreenCoordinates(scene);
  78627. effect.setTexture("lightScatteringSampler", _this._volumetricLightScatteringRTT);
  78628. effect.setFloat("exposure", _this.exposure);
  78629. effect.setFloat("decay", _this.decay);
  78630. effect.setFloat("weight", _this.weight);
  78631. effect.setFloat("density", _this.density);
  78632. effect.setVector2("meshPositionOnScreen", _this._screenCoordinates);
  78633. });
  78634. return _this;
  78635. }
  78636. Object.defineProperty(VolumetricLightScatteringPostProcess.prototype, "useDiffuseColor", {
  78637. get: function () {
  78638. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78639. return false;
  78640. },
  78641. set: function (useDiffuseColor) {
  78642. BABYLON.Tools.Warn("VolumetricLightScatteringPostProcess.useDiffuseColor is no longer used, use the mesh material directly instead");
  78643. },
  78644. enumerable: true,
  78645. configurable: true
  78646. });
  78647. VolumetricLightScatteringPostProcess.prototype.getClassName = function () {
  78648. return "VolumetricLightScatteringPostProcess";
  78649. };
  78650. VolumetricLightScatteringPostProcess.prototype._isReady = function (subMesh, useInstances) {
  78651. var mesh = subMesh.getMesh();
  78652. // Render this.mesh as default
  78653. if (mesh === this.mesh && mesh.material) {
  78654. return mesh.material.isReady(mesh);
  78655. }
  78656. var defines = [];
  78657. var attribs = [BABYLON.VertexBuffer.PositionKind];
  78658. var material = subMesh.getMaterial();
  78659. // Alpha test
  78660. if (material) {
  78661. if (material.needAlphaTesting()) {
  78662. defines.push("#define ALPHATEST");
  78663. }
  78664. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  78665. attribs.push(BABYLON.VertexBuffer.UVKind);
  78666. defines.push("#define UV1");
  78667. }
  78668. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  78669. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  78670. defines.push("#define UV2");
  78671. }
  78672. }
  78673. // Bones
  78674. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  78675. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  78676. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  78677. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  78678. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  78679. }
  78680. else {
  78681. defines.push("#define NUM_BONE_INFLUENCERS 0");
  78682. }
  78683. // Instances
  78684. if (useInstances) {
  78685. defines.push("#define INSTANCES");
  78686. attribs.push("world0");
  78687. attribs.push("world1");
  78688. attribs.push("world2");
  78689. attribs.push("world3");
  78690. }
  78691. // Get correct effect
  78692. var join = defines.join("\n");
  78693. if (this._cachedDefines !== join) {
  78694. this._cachedDefines = join;
  78695. this._volumetricLightScatteringPass = mesh.getScene().getEngine().createEffect({ vertexElement: "depth", fragmentElement: "volumetricLightScatteringPass" }, attribs, ["world", "mBones", "viewProjection", "diffuseMatrix"], ["diffuseSampler"], join);
  78696. }
  78697. return this._volumetricLightScatteringPass.isReady();
  78698. };
  78699. /**
  78700. * Sets the new light position for light scattering effect
  78701. * @param {BABYLON.Vector3} The new custom light position
  78702. */
  78703. VolumetricLightScatteringPostProcess.prototype.setCustomMeshPosition = function (position) {
  78704. this.customMeshPosition = position;
  78705. };
  78706. /**
  78707. * Returns the light position for light scattering effect
  78708. * @return {BABYLON.Vector3} The custom light position
  78709. */
  78710. VolumetricLightScatteringPostProcess.prototype.getCustomMeshPosition = function () {
  78711. return this.customMeshPosition;
  78712. };
  78713. /**
  78714. * Disposes the internal assets and detaches the post-process from the camera
  78715. */
  78716. VolumetricLightScatteringPostProcess.prototype.dispose = function (camera) {
  78717. var rttIndex = camera.getScene().customRenderTargets.indexOf(this._volumetricLightScatteringRTT);
  78718. if (rttIndex !== -1) {
  78719. camera.getScene().customRenderTargets.splice(rttIndex, 1);
  78720. }
  78721. this._volumetricLightScatteringRTT.dispose();
  78722. _super.prototype.dispose.call(this, camera);
  78723. };
  78724. /**
  78725. * Returns the render target texture used by the post-process
  78726. * @return {BABYLON.RenderTargetTexture} The render target texture used by the post-process
  78727. */
  78728. VolumetricLightScatteringPostProcess.prototype.getPass = function () {
  78729. return this._volumetricLightScatteringRTT;
  78730. };
  78731. // Private methods
  78732. VolumetricLightScatteringPostProcess.prototype._meshExcluded = function (mesh) {
  78733. if (this.excludedMeshes.length > 0 && this.excludedMeshes.indexOf(mesh) !== -1) {
  78734. return true;
  78735. }
  78736. return false;
  78737. };
  78738. VolumetricLightScatteringPostProcess.prototype._createPass = function (scene, ratio) {
  78739. var _this = this;
  78740. var engine = scene.getEngine();
  78741. this._volumetricLightScatteringRTT = new BABYLON.RenderTargetTexture("volumetricLightScatteringMap", { width: engine.getRenderWidth() * ratio, height: engine.getRenderHeight() * ratio }, scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  78742. this._volumetricLightScatteringRTT.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78743. this._volumetricLightScatteringRTT.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78744. this._volumetricLightScatteringRTT.renderList = null;
  78745. this._volumetricLightScatteringRTT.renderParticles = false;
  78746. this._volumetricLightScatteringRTT.ignoreCameraViewport = true;
  78747. var camera = this.getCamera();
  78748. if (camera) {
  78749. camera.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78750. }
  78751. else {
  78752. scene.customRenderTargets.push(this._volumetricLightScatteringRTT);
  78753. }
  78754. // Custom render function for submeshes
  78755. var renderSubMesh = function (subMesh) {
  78756. var mesh = subMesh.getRenderingMesh();
  78757. if (_this._meshExcluded(mesh)) {
  78758. return;
  78759. }
  78760. var material = subMesh.getMaterial();
  78761. if (!material) {
  78762. return;
  78763. }
  78764. var scene = mesh.getScene();
  78765. var engine = scene.getEngine();
  78766. // Culling
  78767. engine.setState(material.backFaceCulling);
  78768. // Managing instances
  78769. var batch = mesh._getInstancesRenderList(subMesh._id);
  78770. if (batch.mustReturn) {
  78771. return;
  78772. }
  78773. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null);
  78774. if (_this._isReady(subMesh, hardwareInstancedRendering)) {
  78775. var effect = _this._volumetricLightScatteringPass;
  78776. if (mesh === _this.mesh) {
  78777. if (subMesh.effect) {
  78778. effect = subMesh.effect;
  78779. }
  78780. else {
  78781. effect = material.getEffect();
  78782. }
  78783. }
  78784. engine.enableEffect(effect);
  78785. mesh._bind(subMesh, effect, BABYLON.Material.TriangleFillMode);
  78786. if (mesh === _this.mesh) {
  78787. material.bind(mesh.getWorldMatrix(), mesh);
  78788. }
  78789. else {
  78790. _this._volumetricLightScatteringPass.setMatrix("viewProjection", scene.getTransformMatrix());
  78791. // Alpha test
  78792. if (material && material.needAlphaTesting()) {
  78793. var alphaTexture = material.getAlphaTestTexture();
  78794. _this._volumetricLightScatteringPass.setTexture("diffuseSampler", alphaTexture);
  78795. if (alphaTexture) {
  78796. _this._volumetricLightScatteringPass.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  78797. }
  78798. }
  78799. // Bones
  78800. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  78801. _this._volumetricLightScatteringPass.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  78802. }
  78803. }
  78804. // Draw
  78805. mesh._processRendering(subMesh, _this._volumetricLightScatteringPass, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return effect.setMatrix("world", world); });
  78806. }
  78807. };
  78808. // Render target texture callbacks
  78809. var savedSceneClearColor;
  78810. var sceneClearColor = new BABYLON.Color4(0.0, 0.0, 0.0, 1.0);
  78811. this._volumetricLightScatteringRTT.onBeforeRenderObservable.add(function () {
  78812. savedSceneClearColor = scene.clearColor;
  78813. scene.clearColor = sceneClearColor;
  78814. });
  78815. this._volumetricLightScatteringRTT.onAfterRenderObservable.add(function () {
  78816. scene.clearColor = savedSceneClearColor;
  78817. });
  78818. this._volumetricLightScatteringRTT.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  78819. var engine = scene.getEngine();
  78820. var index;
  78821. if (depthOnlySubMeshes.length) {
  78822. engine.setColorWrite(false);
  78823. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  78824. renderSubMesh(depthOnlySubMeshes.data[index]);
  78825. }
  78826. engine.setColorWrite(true);
  78827. }
  78828. for (index = 0; index < opaqueSubMeshes.length; index++) {
  78829. renderSubMesh(opaqueSubMeshes.data[index]);
  78830. }
  78831. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  78832. renderSubMesh(alphaTestSubMeshes.data[index]);
  78833. }
  78834. if (transparentSubMeshes.length) {
  78835. // Sort sub meshes
  78836. for (index = 0; index < transparentSubMeshes.length; index++) {
  78837. var submesh = transparentSubMeshes.data[index];
  78838. var boundingInfo = submesh.getBoundingInfo();
  78839. if (boundingInfo && scene.activeCamera) {
  78840. submesh._alphaIndex = submesh.getMesh().alphaIndex;
  78841. submesh._distanceToCamera = boundingInfo.boundingSphere.centerWorld.subtract(scene.activeCamera.position).length();
  78842. }
  78843. }
  78844. var sortedArray = transparentSubMeshes.data.slice(0, transparentSubMeshes.length);
  78845. sortedArray.sort(function (a, b) {
  78846. // Alpha index first
  78847. if (a._alphaIndex > b._alphaIndex) {
  78848. return 1;
  78849. }
  78850. if (a._alphaIndex < b._alphaIndex) {
  78851. return -1;
  78852. }
  78853. // Then distance to camera
  78854. if (a._distanceToCamera < b._distanceToCamera) {
  78855. return 1;
  78856. }
  78857. if (a._distanceToCamera > b._distanceToCamera) {
  78858. return -1;
  78859. }
  78860. return 0;
  78861. });
  78862. // Render sub meshes
  78863. engine.setAlphaMode(BABYLON.Engine.ALPHA_COMBINE);
  78864. for (index = 0; index < sortedArray.length; index++) {
  78865. renderSubMesh(sortedArray[index]);
  78866. }
  78867. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  78868. }
  78869. };
  78870. };
  78871. VolumetricLightScatteringPostProcess.prototype._updateMeshScreenCoordinates = function (scene) {
  78872. var transform = scene.getTransformMatrix();
  78873. var meshPosition;
  78874. if (this.useCustomMeshPosition) {
  78875. meshPosition = this.customMeshPosition;
  78876. }
  78877. else if (this.attachedNode) {
  78878. meshPosition = this.attachedNode.position;
  78879. }
  78880. else {
  78881. meshPosition = this.mesh.parent ? this.mesh.getAbsolutePosition() : this.mesh.position;
  78882. }
  78883. var pos = BABYLON.Vector3.Project(meshPosition, BABYLON.Matrix.Identity(), transform, this._viewPort);
  78884. this._screenCoordinates.x = pos.x / this._viewPort.width;
  78885. this._screenCoordinates.y = pos.y / this._viewPort.height;
  78886. if (this.invert)
  78887. this._screenCoordinates.y = 1.0 - this._screenCoordinates.y;
  78888. };
  78889. // Static methods
  78890. /**
  78891. * Creates a default mesh for the Volumeric Light Scattering post-process
  78892. * @param {string} The mesh name
  78893. * @param {BABYLON.Scene} The scene where to create the mesh
  78894. * @return {BABYLON.Mesh} the default mesh
  78895. */
  78896. VolumetricLightScatteringPostProcess.CreateDefaultMesh = function (name, scene) {
  78897. var mesh = BABYLON.Mesh.CreatePlane(name, 1, scene);
  78898. mesh.billboardMode = BABYLON.AbstractMesh.BILLBOARDMODE_ALL;
  78899. var material = new BABYLON.StandardMaterial(name + "Material", scene);
  78900. material.emissiveColor = new BABYLON.Color3(1, 1, 1);
  78901. mesh.material = material;
  78902. return mesh;
  78903. };
  78904. __decorate([
  78905. BABYLON.serializeAsVector3()
  78906. ], VolumetricLightScatteringPostProcess.prototype, "customMeshPosition", void 0);
  78907. __decorate([
  78908. BABYLON.serialize()
  78909. ], VolumetricLightScatteringPostProcess.prototype, "useCustomMeshPosition", void 0);
  78910. __decorate([
  78911. BABYLON.serialize()
  78912. ], VolumetricLightScatteringPostProcess.prototype, "invert", void 0);
  78913. __decorate([
  78914. BABYLON.serializeAsMeshReference()
  78915. ], VolumetricLightScatteringPostProcess.prototype, "mesh", void 0);
  78916. __decorate([
  78917. BABYLON.serialize()
  78918. ], VolumetricLightScatteringPostProcess.prototype, "excludedMeshes", void 0);
  78919. __decorate([
  78920. BABYLON.serialize()
  78921. ], VolumetricLightScatteringPostProcess.prototype, "exposure", void 0);
  78922. __decorate([
  78923. BABYLON.serialize()
  78924. ], VolumetricLightScatteringPostProcess.prototype, "decay", void 0);
  78925. __decorate([
  78926. BABYLON.serialize()
  78927. ], VolumetricLightScatteringPostProcess.prototype, "weight", void 0);
  78928. __decorate([
  78929. BABYLON.serialize()
  78930. ], VolumetricLightScatteringPostProcess.prototype, "density", void 0);
  78931. return VolumetricLightScatteringPostProcess;
  78932. }(BABYLON.PostProcess));
  78933. BABYLON.VolumetricLightScatteringPostProcess = VolumetricLightScatteringPostProcess;
  78934. })(BABYLON || (BABYLON = {}));
  78935. //# sourceMappingURL=babylon.volumetricLightScatteringPostProcess.js.map
  78936. //
  78937. // This post-process allows the modification of rendered colors by using
  78938. // a 'look-up table' (LUT). This effect is also called Color Grading.
  78939. //
  78940. // The object needs to be provided an url to a texture containing the color
  78941. // look-up table: the texture must be 256 pixels wide and 16 pixels high.
  78942. // Use an image editing software to tweak the LUT to match your needs.
  78943. //
  78944. // For an example of a color LUT, see here:
  78945. // http://udn.epicgames.com/Three/rsrc/Three/ColorGrading/RGBTable16x1.png
  78946. // For explanations on color grading, see here:
  78947. // http://udn.epicgames.com/Three/ColorGrading.html
  78948. //
  78949. var BABYLON;
  78950. (function (BABYLON) {
  78951. var ColorCorrectionPostProcess = /** @class */ (function (_super) {
  78952. __extends(ColorCorrectionPostProcess, _super);
  78953. function ColorCorrectionPostProcess(name, colorTableUrl, options, camera, samplingMode, engine, reusable) {
  78954. var _this = _super.call(this, name, 'colorCorrection', null, ['colorTable'], options, camera, samplingMode, engine, reusable) || this;
  78955. _this._colorTableTexture = new BABYLON.Texture(colorTableUrl, camera.getScene(), true, false, BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  78956. _this._colorTableTexture.anisotropicFilteringLevel = 1;
  78957. _this._colorTableTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78958. _this._colorTableTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  78959. _this.onApply = function (effect) {
  78960. effect.setTexture("colorTable", _this._colorTableTexture);
  78961. };
  78962. return _this;
  78963. }
  78964. return ColorCorrectionPostProcess;
  78965. }(BABYLON.PostProcess));
  78966. BABYLON.ColorCorrectionPostProcess = ColorCorrectionPostProcess;
  78967. })(BABYLON || (BABYLON = {}));
  78968. //# sourceMappingURL=babylon.colorCorrectionPostProcess.js.map
  78969. var BABYLON;
  78970. (function (BABYLON) {
  78971. /** Defines operator used for tonemapping */
  78972. var TonemappingOperator;
  78973. (function (TonemappingOperator) {
  78974. /** Hable */
  78975. TonemappingOperator[TonemappingOperator["Hable"] = 0] = "Hable";
  78976. /** Reinhard */
  78977. TonemappingOperator[TonemappingOperator["Reinhard"] = 1] = "Reinhard";
  78978. /** HejiDawson */
  78979. TonemappingOperator[TonemappingOperator["HejiDawson"] = 2] = "HejiDawson";
  78980. /** Photographic */
  78981. TonemappingOperator[TonemappingOperator["Photographic"] = 3] = "Photographic";
  78982. })(TonemappingOperator = BABYLON.TonemappingOperator || (BABYLON.TonemappingOperator = {}));
  78983. ;
  78984. /**
  78985. * Defines a post process to apply tone mapping
  78986. */
  78987. var TonemapPostProcess = /** @class */ (function (_super) {
  78988. __extends(TonemapPostProcess, _super);
  78989. /**
  78990. * Creates a new TonemapPostProcess
  78991. * @param name defines the name of the postprocess
  78992. * @param _operator defines the operator to use
  78993. * @param exposureAdjustment defines the required exposure adjustement
  78994. * @param camera defines the camera to use (can be null)
  78995. * @param samplingMode defines the required sampling mode (BABYLON.Texture.BILINEAR_SAMPLINGMODE by default)
  78996. * @param engine defines the hosting engine (can be ignore if camera is set)
  78997. * @param textureFormat defines the texture format to use (BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT by default)
  78998. */
  78999. function TonemapPostProcess(name, _operator,
  79000. /** Defines the required exposure adjustement */
  79001. exposureAdjustment, camera, samplingMode, engine, textureFormat) {
  79002. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  79003. if (textureFormat === void 0) { textureFormat = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79004. var _this = _super.call(this, name, "tonemap", ["_ExposureAdjustment"], null, 1.0, camera, samplingMode, engine, true, null, textureFormat) || this;
  79005. _this._operator = _operator;
  79006. _this.exposureAdjustment = exposureAdjustment;
  79007. var defines = "#define ";
  79008. if (_this._operator === TonemappingOperator.Hable)
  79009. defines += "HABLE_TONEMAPPING";
  79010. else if (_this._operator === TonemappingOperator.Reinhard)
  79011. defines += "REINHARD_TONEMAPPING";
  79012. else if (_this._operator === TonemappingOperator.HejiDawson)
  79013. defines += "OPTIMIZED_HEJIDAWSON_TONEMAPPING";
  79014. else if (_this._operator === TonemappingOperator.Photographic)
  79015. defines += "PHOTOGRAPHIC_TONEMAPPING";
  79016. //sadly a second call to create the effect.
  79017. _this.updateEffect(defines);
  79018. _this.onApply = function (effect) {
  79019. effect.setFloat("_ExposureAdjustment", _this.exposureAdjustment);
  79020. };
  79021. return _this;
  79022. }
  79023. return TonemapPostProcess;
  79024. }(BABYLON.PostProcess));
  79025. BABYLON.TonemapPostProcess = TonemapPostProcess;
  79026. })(BABYLON || (BABYLON = {}));
  79027. //# sourceMappingURL=babylon.tonemapPostProcess.js.map
  79028. var BABYLON;
  79029. (function (BABYLON) {
  79030. var DisplayPassPostProcess = /** @class */ (function (_super) {
  79031. __extends(DisplayPassPostProcess, _super);
  79032. function DisplayPassPostProcess(name, options, camera, samplingMode, engine, reusable) {
  79033. return _super.call(this, name, "displayPass", ["passSampler"], ["passSampler"], options, camera, samplingMode, engine, reusable) || this;
  79034. }
  79035. return DisplayPassPostProcess;
  79036. }(BABYLON.PostProcess));
  79037. BABYLON.DisplayPassPostProcess = DisplayPassPostProcess;
  79038. })(BABYLON || (BABYLON = {}));
  79039. //# sourceMappingURL=babylon.displayPassPostProcess.js.map
  79040. var BABYLON;
  79041. (function (BABYLON) {
  79042. var HighlightsPostProcess = /** @class */ (function (_super) {
  79043. __extends(HighlightsPostProcess, _super);
  79044. function HighlightsPostProcess(name, options, camera, samplingMode, engine, reusable, textureType) {
  79045. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79046. return _super.call(this, name, "highlights", null, null, options, camera, samplingMode, engine, reusable, null, textureType) || this;
  79047. }
  79048. return HighlightsPostProcess;
  79049. }(BABYLON.PostProcess));
  79050. BABYLON.HighlightsPostProcess = HighlightsPostProcess;
  79051. })(BABYLON || (BABYLON = {}));
  79052. //# sourceMappingURL=babylon.highlightsPostProcess.js.map
  79053. var BABYLON;
  79054. (function (BABYLON) {
  79055. var ImageProcessingPostProcess = /** @class */ (function (_super) {
  79056. __extends(ImageProcessingPostProcess, _super);
  79057. function ImageProcessingPostProcess(name, options, camera, samplingMode, engine, reusable, textureType, imageProcessingConfiguration) {
  79058. if (camera === void 0) { camera = null; }
  79059. if (textureType === void 0) { textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT; }
  79060. var _this = _super.call(this, name, "imageProcessing", [], [], options, camera, samplingMode, engine, reusable, null, textureType, "postprocess", null, true) || this;
  79061. _this._fromLinearSpace = true;
  79062. /**
  79063. * Defines cache preventing GC.
  79064. */
  79065. _this._defines = {
  79066. IMAGEPROCESSING: false,
  79067. VIGNETTE: false,
  79068. VIGNETTEBLENDMODEMULTIPLY: false,
  79069. VIGNETTEBLENDMODEOPAQUE: false,
  79070. TONEMAPPING: false,
  79071. CONTRAST: false,
  79072. COLORCURVES: false,
  79073. COLORGRADING: false,
  79074. COLORGRADING3D: false,
  79075. FROMLINEARSPACE: false,
  79076. SAMPLER3DGREENDEPTH: false,
  79077. SAMPLER3DBGRMAP: false,
  79078. IMAGEPROCESSINGPOSTPROCESS: false,
  79079. EXPOSURE: false,
  79080. };
  79081. // Setup the configuration as forced by the constructor. This would then not force the
  79082. // scene materials output in linear space and let untouched the default forward pass.
  79083. if (imageProcessingConfiguration) {
  79084. imageProcessingConfiguration.applyByPostProcess = true;
  79085. _this._attachImageProcessingConfiguration(imageProcessingConfiguration, true);
  79086. // This will cause the shader to be compiled
  79087. _this.fromLinearSpace = false;
  79088. }
  79089. // Setup the default processing configuration to the scene.
  79090. else {
  79091. _this._attachImageProcessingConfiguration(null, true);
  79092. _this.imageProcessingConfiguration.applyByPostProcess = true;
  79093. }
  79094. _this.onApply = function (effect) {
  79095. _this.imageProcessingConfiguration.bind(effect, _this.aspectRatio);
  79096. };
  79097. return _this;
  79098. }
  79099. Object.defineProperty(ImageProcessingPostProcess.prototype, "imageProcessingConfiguration", {
  79100. /**
  79101. * Gets the image processing configuration used either in this material.
  79102. */
  79103. get: function () {
  79104. return this._imageProcessingConfiguration;
  79105. },
  79106. /**
  79107. * Sets the Default image processing configuration used either in the this material.
  79108. *
  79109. * If sets to null, the scene one is in use.
  79110. */
  79111. set: function (value) {
  79112. this._attachImageProcessingConfiguration(value);
  79113. },
  79114. enumerable: true,
  79115. configurable: true
  79116. });
  79117. /**
  79118. * Attaches a new image processing configuration to the PBR Material.
  79119. * @param configuration
  79120. */
  79121. ImageProcessingPostProcess.prototype._attachImageProcessingConfiguration = function (configuration, doNotBuild) {
  79122. var _this = this;
  79123. if (doNotBuild === void 0) { doNotBuild = false; }
  79124. if (configuration === this._imageProcessingConfiguration) {
  79125. return;
  79126. }
  79127. // Detaches observer.
  79128. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79129. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79130. }
  79131. // Pick the scene configuration if needed.
  79132. if (!configuration) {
  79133. var scene = null;
  79134. var engine = this.getEngine();
  79135. var camera = this.getCamera();
  79136. if (camera) {
  79137. scene = camera.getScene();
  79138. }
  79139. else if (engine && engine.scenes) {
  79140. var scenes = engine.scenes;
  79141. scene = scenes[scenes.length - 1];
  79142. }
  79143. else {
  79144. scene = BABYLON.Engine.LastCreatedScene;
  79145. }
  79146. this._imageProcessingConfiguration = scene.imageProcessingConfiguration;
  79147. }
  79148. else {
  79149. this._imageProcessingConfiguration = configuration;
  79150. }
  79151. // Attaches observer.
  79152. if (this._imageProcessingConfiguration) {
  79153. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  79154. _this._updateParameters();
  79155. });
  79156. }
  79157. // Ensure the effect will be rebuilt.
  79158. if (!doNotBuild) {
  79159. this._updateParameters();
  79160. }
  79161. };
  79162. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurves", {
  79163. /**
  79164. * Gets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79165. */
  79166. get: function () {
  79167. return this.imageProcessingConfiguration.colorCurves;
  79168. },
  79169. /**
  79170. * Sets Color curves setup used in the effect if colorCurvesEnabled is set to true .
  79171. */
  79172. set: function (value) {
  79173. this.imageProcessingConfiguration.colorCurves = value;
  79174. },
  79175. enumerable: true,
  79176. configurable: true
  79177. });
  79178. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorCurvesEnabled", {
  79179. /**
  79180. * Gets wether the color curves effect is enabled.
  79181. */
  79182. get: function () {
  79183. return this.imageProcessingConfiguration.colorCurvesEnabled;
  79184. },
  79185. /**
  79186. * Sets wether the color curves effect is enabled.
  79187. */
  79188. set: function (value) {
  79189. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  79190. },
  79191. enumerable: true,
  79192. configurable: true
  79193. });
  79194. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingTexture", {
  79195. /**
  79196. * Gets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79197. */
  79198. get: function () {
  79199. return this.imageProcessingConfiguration.colorGradingTexture;
  79200. },
  79201. /**
  79202. * Sets Color grading LUT texture used in the effect if colorGradingEnabled is set to true.
  79203. */
  79204. set: function (value) {
  79205. this.imageProcessingConfiguration.colorGradingTexture = value;
  79206. },
  79207. enumerable: true,
  79208. configurable: true
  79209. });
  79210. Object.defineProperty(ImageProcessingPostProcess.prototype, "colorGradingEnabled", {
  79211. /**
  79212. * Gets wether the color grading effect is enabled.
  79213. */
  79214. get: function () {
  79215. return this.imageProcessingConfiguration.colorGradingEnabled;
  79216. },
  79217. /**
  79218. * Gets wether the color grading effect is enabled.
  79219. */
  79220. set: function (value) {
  79221. this.imageProcessingConfiguration.colorGradingEnabled = value;
  79222. },
  79223. enumerable: true,
  79224. configurable: true
  79225. });
  79226. Object.defineProperty(ImageProcessingPostProcess.prototype, "exposure", {
  79227. /**
  79228. * Gets exposure used in the effect.
  79229. */
  79230. get: function () {
  79231. return this.imageProcessingConfiguration.exposure;
  79232. },
  79233. /**
  79234. * Sets exposure used in the effect.
  79235. */
  79236. set: function (value) {
  79237. this.imageProcessingConfiguration.exposure = value;
  79238. },
  79239. enumerable: true,
  79240. configurable: true
  79241. });
  79242. Object.defineProperty(ImageProcessingPostProcess.prototype, "toneMappingEnabled", {
  79243. /**
  79244. * Gets wether tonemapping is enabled or not.
  79245. */
  79246. get: function () {
  79247. return this._imageProcessingConfiguration.toneMappingEnabled;
  79248. },
  79249. /**
  79250. * Sets wether tonemapping is enabled or not
  79251. */
  79252. set: function (value) {
  79253. this._imageProcessingConfiguration.toneMappingEnabled = value;
  79254. },
  79255. enumerable: true,
  79256. configurable: true
  79257. });
  79258. ;
  79259. ;
  79260. Object.defineProperty(ImageProcessingPostProcess.prototype, "contrast", {
  79261. /**
  79262. * Gets contrast used in the effect.
  79263. */
  79264. get: function () {
  79265. return this.imageProcessingConfiguration.contrast;
  79266. },
  79267. /**
  79268. * Sets contrast used in the effect.
  79269. */
  79270. set: function (value) {
  79271. this.imageProcessingConfiguration.contrast = value;
  79272. },
  79273. enumerable: true,
  79274. configurable: true
  79275. });
  79276. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteStretch", {
  79277. /**
  79278. * Gets Vignette stretch size.
  79279. */
  79280. get: function () {
  79281. return this.imageProcessingConfiguration.vignetteStretch;
  79282. },
  79283. /**
  79284. * Sets Vignette stretch size.
  79285. */
  79286. set: function (value) {
  79287. this.imageProcessingConfiguration.vignetteStretch = value;
  79288. },
  79289. enumerable: true,
  79290. configurable: true
  79291. });
  79292. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreX", {
  79293. /**
  79294. * Gets Vignette centre X Offset.
  79295. */
  79296. get: function () {
  79297. return this.imageProcessingConfiguration.vignetteCentreX;
  79298. },
  79299. /**
  79300. * Sets Vignette centre X Offset.
  79301. */
  79302. set: function (value) {
  79303. this.imageProcessingConfiguration.vignetteCentreX = value;
  79304. },
  79305. enumerable: true,
  79306. configurable: true
  79307. });
  79308. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCentreY", {
  79309. /**
  79310. * Gets Vignette centre Y Offset.
  79311. */
  79312. get: function () {
  79313. return this.imageProcessingConfiguration.vignetteCentreY;
  79314. },
  79315. /**
  79316. * Sets Vignette centre Y Offset.
  79317. */
  79318. set: function (value) {
  79319. this.imageProcessingConfiguration.vignetteCentreY = value;
  79320. },
  79321. enumerable: true,
  79322. configurable: true
  79323. });
  79324. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteWeight", {
  79325. /**
  79326. * Gets Vignette weight or intensity of the vignette effect.
  79327. */
  79328. get: function () {
  79329. return this.imageProcessingConfiguration.vignetteWeight;
  79330. },
  79331. /**
  79332. * Sets Vignette weight or intensity of the vignette effect.
  79333. */
  79334. set: function (value) {
  79335. this.imageProcessingConfiguration.vignetteWeight = value;
  79336. },
  79337. enumerable: true,
  79338. configurable: true
  79339. });
  79340. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteColor", {
  79341. /**
  79342. * Gets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79343. * if vignetteEnabled is set to true.
  79344. */
  79345. get: function () {
  79346. return this.imageProcessingConfiguration.vignetteColor;
  79347. },
  79348. /**
  79349. * Sets Color of the vignette applied on the screen through the chosen blend mode (vignetteBlendMode)
  79350. * if vignetteEnabled is set to true.
  79351. */
  79352. set: function (value) {
  79353. this.imageProcessingConfiguration.vignetteColor = value;
  79354. },
  79355. enumerable: true,
  79356. configurable: true
  79357. });
  79358. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteCameraFov", {
  79359. /**
  79360. * Gets Camera field of view used by the Vignette effect.
  79361. */
  79362. get: function () {
  79363. return this.imageProcessingConfiguration.vignetteCameraFov;
  79364. },
  79365. /**
  79366. * Sets Camera field of view used by the Vignette effect.
  79367. */
  79368. set: function (value) {
  79369. this.imageProcessingConfiguration.vignetteCameraFov = value;
  79370. },
  79371. enumerable: true,
  79372. configurable: true
  79373. });
  79374. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteBlendMode", {
  79375. /**
  79376. * Gets the vignette blend mode allowing different kind of effect.
  79377. */
  79378. get: function () {
  79379. return this.imageProcessingConfiguration.vignetteBlendMode;
  79380. },
  79381. /**
  79382. * Sets the vignette blend mode allowing different kind of effect.
  79383. */
  79384. set: function (value) {
  79385. this.imageProcessingConfiguration.vignetteBlendMode = value;
  79386. },
  79387. enumerable: true,
  79388. configurable: true
  79389. });
  79390. Object.defineProperty(ImageProcessingPostProcess.prototype, "vignetteEnabled", {
  79391. /**
  79392. * Gets wether the vignette effect is enabled.
  79393. */
  79394. get: function () {
  79395. return this.imageProcessingConfiguration.vignetteEnabled;
  79396. },
  79397. /**
  79398. * Sets wether the vignette effect is enabled.
  79399. */
  79400. set: function (value) {
  79401. this.imageProcessingConfiguration.vignetteEnabled = value;
  79402. },
  79403. enumerable: true,
  79404. configurable: true
  79405. });
  79406. Object.defineProperty(ImageProcessingPostProcess.prototype, "fromLinearSpace", {
  79407. /**
  79408. * Gets wether the input of the processing is in Gamma or Linear Space.
  79409. */
  79410. get: function () {
  79411. return this._fromLinearSpace;
  79412. },
  79413. /**
  79414. * Sets wether the input of the processing is in Gamma or Linear Space.
  79415. */
  79416. set: function (value) {
  79417. if (this._fromLinearSpace === value) {
  79418. return;
  79419. }
  79420. this._fromLinearSpace = value;
  79421. this._updateParameters();
  79422. },
  79423. enumerable: true,
  79424. configurable: true
  79425. });
  79426. ImageProcessingPostProcess.prototype.getClassName = function () {
  79427. return "ImageProcessingPostProcess";
  79428. };
  79429. ImageProcessingPostProcess.prototype._updateParameters = function () {
  79430. this._defines.FROMLINEARSPACE = this._fromLinearSpace;
  79431. this.imageProcessingConfiguration.prepareDefines(this._defines, true);
  79432. var defines = "";
  79433. for (var define in this._defines) {
  79434. if (this._defines[define]) {
  79435. defines += "#define " + define + ";\r\n";
  79436. }
  79437. }
  79438. var samplers = ["textureSampler"];
  79439. var uniforms = ["scale"];
  79440. if (BABYLON.ImageProcessingConfiguration) {
  79441. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, this._defines);
  79442. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, this._defines);
  79443. }
  79444. this.updateEffect(defines, uniforms, samplers);
  79445. };
  79446. ImageProcessingPostProcess.prototype.dispose = function (camera) {
  79447. _super.prototype.dispose.call(this, camera);
  79448. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  79449. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  79450. }
  79451. if (this._imageProcessingConfiguration) {
  79452. this.imageProcessingConfiguration.applyByPostProcess = false;
  79453. }
  79454. };
  79455. __decorate([
  79456. BABYLON.serialize()
  79457. ], ImageProcessingPostProcess.prototype, "_fromLinearSpace", void 0);
  79458. return ImageProcessingPostProcess;
  79459. }(BABYLON.PostProcess));
  79460. BABYLON.ImageProcessingPostProcess = ImageProcessingPostProcess;
  79461. })(BABYLON || (BABYLON = {}));
  79462. //# sourceMappingURL=babylon.imageProcessingPostProcess.js.map
  79463. var BABYLON;
  79464. (function (BABYLON) {
  79465. /**
  79466. * Class used to store bone information
  79467. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  79468. */
  79469. var Bone = /** @class */ (function (_super) {
  79470. __extends(Bone, _super);
  79471. /**
  79472. * Create a new bone
  79473. * @param name defines the bone name
  79474. * @param skeleton defines the parent skeleton
  79475. * @param parentBone defines the parent (can be null if the bone is the root)
  79476. * @param localMatrix defines the local matrix
  79477. * @param restPose defines the rest pose matrix
  79478. * @param baseMatrix defines the base matrix
  79479. * @param index defines index of the bone in the hiearchy
  79480. */
  79481. function Bone(
  79482. /**
  79483. * defines the bone name
  79484. */
  79485. name, skeleton, parentBone, localMatrix, restPose, baseMatrix, index) {
  79486. if (parentBone === void 0) { parentBone = null; }
  79487. if (localMatrix === void 0) { localMatrix = null; }
  79488. if (restPose === void 0) { restPose = null; }
  79489. if (baseMatrix === void 0) { baseMatrix = null; }
  79490. if (index === void 0) { index = null; }
  79491. var _this = _super.call(this, name, skeleton.getScene()) || this;
  79492. _this.name = name;
  79493. /**
  79494. * Gets the list of child bones
  79495. */
  79496. _this.children = new Array();
  79497. /** Gets the animations associated with this bone */
  79498. _this.animations = new Array();
  79499. /**
  79500. * @hidden Internal only
  79501. * Set this value to map this bone to a different index in the transform matrices
  79502. * Set this value to -1 to exclude the bone from the transform matrices
  79503. */
  79504. _this._index = null;
  79505. _this._absoluteTransform = new BABYLON.Matrix();
  79506. _this._invertedAbsoluteTransform = new BABYLON.Matrix();
  79507. _this._scalingDeterminant = 1;
  79508. _this._worldTransform = new BABYLON.Matrix();
  79509. _this._needToDecompose = true;
  79510. _this._needToCompose = false;
  79511. _this._skeleton = skeleton;
  79512. _this._localMatrix = localMatrix ? localMatrix.clone() : BABYLON.Matrix.Identity();
  79513. _this._restPose = restPose ? restPose : _this._localMatrix.clone();
  79514. _this._baseMatrix = baseMatrix ? baseMatrix : _this._localMatrix.clone();
  79515. _this._index = index;
  79516. skeleton.bones.push(_this);
  79517. _this.setParent(parentBone, false);
  79518. if (baseMatrix || localMatrix) {
  79519. _this._updateDifferenceMatrix();
  79520. }
  79521. return _this;
  79522. }
  79523. Object.defineProperty(Bone.prototype, "_matrix", {
  79524. /** @hidden */
  79525. get: function () {
  79526. this._compose();
  79527. return this._localMatrix;
  79528. },
  79529. /** @hidden */
  79530. set: function (value) {
  79531. this._localMatrix.copyFrom(value);
  79532. this._needToDecompose = true;
  79533. },
  79534. enumerable: true,
  79535. configurable: true
  79536. });
  79537. // Members
  79538. /**
  79539. * Gets the parent skeleton
  79540. * @returns a skeleton
  79541. */
  79542. Bone.prototype.getSkeleton = function () {
  79543. return this._skeleton;
  79544. };
  79545. /**
  79546. * Gets parent bone
  79547. * @returns a bone or null if the bone is the root of the bone hierarchy
  79548. */
  79549. Bone.prototype.getParent = function () {
  79550. return this._parent;
  79551. };
  79552. /**
  79553. * Sets the parent bone
  79554. * @param parent defines the parent (can be null if the bone is the root)
  79555. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79556. */
  79557. Bone.prototype.setParent = function (parent, updateDifferenceMatrix) {
  79558. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79559. if (this._parent === parent) {
  79560. return;
  79561. }
  79562. if (this._parent) {
  79563. var index = this._parent.children.indexOf(this);
  79564. if (index !== -1) {
  79565. this._parent.children.splice(index, 1);
  79566. }
  79567. }
  79568. this._parent = parent;
  79569. if (this._parent) {
  79570. this._parent.children.push(this);
  79571. }
  79572. if (updateDifferenceMatrix) {
  79573. this._updateDifferenceMatrix();
  79574. }
  79575. this.markAsDirty();
  79576. };
  79577. /**
  79578. * Gets the local matrix
  79579. * @returns a matrix
  79580. */
  79581. Bone.prototype.getLocalMatrix = function () {
  79582. this._compose();
  79583. return this._localMatrix;
  79584. };
  79585. /**
  79586. * Gets the base matrix (initial matrix which remains unchanged)
  79587. * @returns a matrix
  79588. */
  79589. Bone.prototype.getBaseMatrix = function () {
  79590. return this._baseMatrix;
  79591. };
  79592. /**
  79593. * Gets the rest pose matrix
  79594. * @returns a matrix
  79595. */
  79596. Bone.prototype.getRestPose = function () {
  79597. return this._restPose;
  79598. };
  79599. /**
  79600. * Gets a matrix used to store world matrix (ie. the matrix sent to shaders)
  79601. */
  79602. Bone.prototype.getWorldMatrix = function () {
  79603. return this._worldTransform;
  79604. };
  79605. /**
  79606. * Sets the local matrix to rest pose matrix
  79607. */
  79608. Bone.prototype.returnToRest = function () {
  79609. this.updateMatrix(this._restPose.clone());
  79610. };
  79611. /**
  79612. * Gets the inverse of the absolute transform matrix.
  79613. * This matrix will be multiplied by local matrix to get the difference matrix (ie. the difference between original state and current state)
  79614. * @returns a matrix
  79615. */
  79616. Bone.prototype.getInvertedAbsoluteTransform = function () {
  79617. return this._invertedAbsoluteTransform;
  79618. };
  79619. /**
  79620. * Gets the absolute transform matrix (ie base matrix * parent world matrix)
  79621. * @returns a matrix
  79622. */
  79623. Bone.prototype.getAbsoluteTransform = function () {
  79624. return this._absoluteTransform;
  79625. };
  79626. Object.defineProperty(Bone.prototype, "position", {
  79627. // Properties (matches AbstractMesh properties)
  79628. /** Gets or sets current position (in local space) */
  79629. get: function () {
  79630. this._decompose();
  79631. return this._localPosition;
  79632. },
  79633. set: function (newPosition) {
  79634. this._decompose();
  79635. this._localPosition.copyFrom(newPosition);
  79636. this._markAsDirtyAndCompose();
  79637. },
  79638. enumerable: true,
  79639. configurable: true
  79640. });
  79641. Object.defineProperty(Bone.prototype, "rotation", {
  79642. /** Gets or sets current rotation (in local space) */
  79643. get: function () {
  79644. return this.getRotation();
  79645. },
  79646. set: function (newRotation) {
  79647. this.setRotation(newRotation);
  79648. },
  79649. enumerable: true,
  79650. configurable: true
  79651. });
  79652. Object.defineProperty(Bone.prototype, "rotationQuaternion", {
  79653. /** Gets or sets current rotation quaternion (in local space) */
  79654. get: function () {
  79655. this._decompose();
  79656. return this._localRotation;
  79657. },
  79658. set: function (newRotation) {
  79659. this.setRotationQuaternion(newRotation);
  79660. },
  79661. enumerable: true,
  79662. configurable: true
  79663. });
  79664. Object.defineProperty(Bone.prototype, "scaling", {
  79665. /** Gets or sets current scaling (in local space) */
  79666. get: function () {
  79667. return this.getScale();
  79668. },
  79669. set: function (newScaling) {
  79670. this.setScale(newScaling);
  79671. },
  79672. enumerable: true,
  79673. configurable: true
  79674. });
  79675. Object.defineProperty(Bone.prototype, "animationPropertiesOverride", {
  79676. /**
  79677. * Gets the animation properties override
  79678. */
  79679. get: function () {
  79680. return this._skeleton.animationPropertiesOverride;
  79681. },
  79682. enumerable: true,
  79683. configurable: true
  79684. });
  79685. // Methods
  79686. Bone.prototype._decompose = function () {
  79687. if (!this._needToDecompose) {
  79688. return;
  79689. }
  79690. this._needToDecompose = false;
  79691. if (!this._localScaling) {
  79692. this._localScaling = BABYLON.Vector3.Zero();
  79693. this._localRotation = BABYLON.Quaternion.Zero();
  79694. this._localPosition = BABYLON.Vector3.Zero();
  79695. }
  79696. this._localMatrix.decompose(this._localScaling, this._localRotation, this._localPosition);
  79697. };
  79698. Bone.prototype._compose = function () {
  79699. if (!this._needToCompose) {
  79700. return;
  79701. }
  79702. this._needToCompose = false;
  79703. BABYLON.Matrix.ComposeToRef(this._localScaling, this._localRotation, this._localPosition, this._localMatrix);
  79704. };
  79705. /**
  79706. * Update the base and local matrices
  79707. * @param matrix defines the new base or local matrix
  79708. * @param updateDifferenceMatrix defines if the difference matrix must be updated
  79709. * @param updateLocalMatrix defines if the local matrix should be updated
  79710. */
  79711. Bone.prototype.updateMatrix = function (matrix, updateDifferenceMatrix, updateLocalMatrix) {
  79712. if (updateDifferenceMatrix === void 0) { updateDifferenceMatrix = true; }
  79713. if (updateLocalMatrix === void 0) { updateLocalMatrix = true; }
  79714. this._baseMatrix.copyFrom(matrix);
  79715. if (updateDifferenceMatrix) {
  79716. this._updateDifferenceMatrix();
  79717. }
  79718. if (updateLocalMatrix) {
  79719. this._localMatrix.copyFrom(matrix);
  79720. this._markAsDirtyAndDecompose();
  79721. }
  79722. else {
  79723. this.markAsDirty();
  79724. }
  79725. };
  79726. /** @hidden */
  79727. Bone.prototype._updateDifferenceMatrix = function (rootMatrix, updateChildren) {
  79728. if (updateChildren === void 0) { updateChildren = true; }
  79729. if (!rootMatrix) {
  79730. rootMatrix = this._baseMatrix;
  79731. }
  79732. if (this._parent) {
  79733. rootMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  79734. }
  79735. else {
  79736. this._absoluteTransform.copyFrom(rootMatrix);
  79737. }
  79738. this._absoluteTransform.invertToRef(this._invertedAbsoluteTransform);
  79739. if (updateChildren) {
  79740. for (var index = 0; index < this.children.length; index++) {
  79741. this.children[index]._updateDifferenceMatrix();
  79742. }
  79743. }
  79744. this._scalingDeterminant = (this._absoluteTransform.determinant() < 0 ? -1 : 1);
  79745. };
  79746. /**
  79747. * Flag the bone as dirty (Forcing it to update everything)
  79748. */
  79749. Bone.prototype.markAsDirty = function () {
  79750. this._currentRenderId++;
  79751. this._childRenderId++;
  79752. this._skeleton._markAsDirty();
  79753. };
  79754. Bone.prototype._markAsDirtyAndCompose = function () {
  79755. this.markAsDirty();
  79756. this._needToCompose = true;
  79757. };
  79758. Bone.prototype._markAsDirtyAndDecompose = function () {
  79759. this.markAsDirty();
  79760. this._needToDecompose = true;
  79761. };
  79762. /**
  79763. * Copy an animation range from another bone
  79764. * @param source defines the source bone
  79765. * @param rangeName defines the range name to copy
  79766. * @param frameOffset defines the frame offset
  79767. * @param rescaleAsRequired defines if rescaling must be applied if required
  79768. * @param skelDimensionsRatio defines the scaling ratio
  79769. * @returns true if operation was successful
  79770. */
  79771. Bone.prototype.copyAnimationRange = function (source, rangeName, frameOffset, rescaleAsRequired, skelDimensionsRatio) {
  79772. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  79773. if (skelDimensionsRatio === void 0) { skelDimensionsRatio = null; }
  79774. // all animation may be coming from a library skeleton, so may need to create animation
  79775. if (this.animations.length === 0) {
  79776. this.animations.push(new BABYLON.Animation(this.name, "_matrix", source.animations[0].framePerSecond, BABYLON.Animation.ANIMATIONTYPE_MATRIX, 0));
  79777. this.animations[0].setKeys([]);
  79778. }
  79779. // get animation info / verify there is such a range from the source bone
  79780. var sourceRange = source.animations[0].getRange(rangeName);
  79781. if (!sourceRange) {
  79782. return false;
  79783. }
  79784. var from = sourceRange.from;
  79785. var to = sourceRange.to;
  79786. var sourceKeys = source.animations[0].getKeys();
  79787. // rescaling prep
  79788. var sourceBoneLength = source.length;
  79789. var sourceParent = source.getParent();
  79790. var parent = this.getParent();
  79791. var parentScalingReqd = rescaleAsRequired && sourceParent && sourceBoneLength && this.length && sourceBoneLength !== this.length;
  79792. var parentRatio = parentScalingReqd && parent && sourceParent ? parent.length / sourceParent.length : 1;
  79793. var dimensionsScalingReqd = rescaleAsRequired && !parent && skelDimensionsRatio && (skelDimensionsRatio.x !== 1 || skelDimensionsRatio.y !== 1 || skelDimensionsRatio.z !== 1);
  79794. var destKeys = this.animations[0].getKeys();
  79795. // loop vars declaration
  79796. var orig;
  79797. var origTranslation;
  79798. var mat;
  79799. for (var key = 0, nKeys = sourceKeys.length; key < nKeys; key++) {
  79800. orig = sourceKeys[key];
  79801. if (orig.frame >= from && orig.frame <= to) {
  79802. if (rescaleAsRequired) {
  79803. mat = orig.value.clone();
  79804. // scale based on parent ratio, when bone has parent
  79805. if (parentScalingReqd) {
  79806. origTranslation = mat.getTranslation();
  79807. mat.setTranslation(origTranslation.scaleInPlace(parentRatio));
  79808. // scale based on skeleton dimension ratio when root bone, and value is passed
  79809. }
  79810. else if (dimensionsScalingReqd && skelDimensionsRatio) {
  79811. origTranslation = mat.getTranslation();
  79812. mat.setTranslation(origTranslation.multiplyInPlace(skelDimensionsRatio));
  79813. // use original when root bone, and no data for skelDimensionsRatio
  79814. }
  79815. else {
  79816. mat = orig.value;
  79817. }
  79818. }
  79819. else {
  79820. mat = orig.value;
  79821. }
  79822. destKeys.push({ frame: orig.frame + frameOffset, value: mat });
  79823. }
  79824. }
  79825. this.animations[0].createRange(rangeName, from + frameOffset, to + frameOffset);
  79826. return true;
  79827. };
  79828. /**
  79829. * Translate the bone in local or world space
  79830. * @param vec The amount to translate the bone
  79831. * @param space The space that the translation is in
  79832. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79833. */
  79834. Bone.prototype.translate = function (vec, space, mesh) {
  79835. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79836. var lm = this.getLocalMatrix();
  79837. if (space == BABYLON.Space.LOCAL) {
  79838. lm.m[12] += vec.x;
  79839. lm.m[13] += vec.y;
  79840. lm.m[14] += vec.z;
  79841. }
  79842. else {
  79843. var wm = null;
  79844. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79845. if (mesh) {
  79846. wm = mesh.getWorldMatrix();
  79847. }
  79848. this._skeleton.computeAbsoluteTransforms();
  79849. var tmat = Bone._tmpMats[0];
  79850. var tvec = Bone._tmpVecs[0];
  79851. if (this._parent) {
  79852. if (mesh && wm) {
  79853. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79854. tmat.multiplyToRef(wm, tmat);
  79855. }
  79856. else {
  79857. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79858. }
  79859. }
  79860. tmat.m[12] = 0;
  79861. tmat.m[13] = 0;
  79862. tmat.m[14] = 0;
  79863. tmat.invert();
  79864. BABYLON.Vector3.TransformCoordinatesToRef(vec, tmat, tvec);
  79865. lm.m[12] += tvec.x;
  79866. lm.m[13] += tvec.y;
  79867. lm.m[14] += tvec.z;
  79868. }
  79869. this._markAsDirtyAndDecompose();
  79870. };
  79871. /**
  79872. * Set the postion of the bone in local or world space
  79873. * @param position The position to set the bone
  79874. * @param space The space that the position is in
  79875. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79876. */
  79877. Bone.prototype.setPosition = function (position, space, mesh) {
  79878. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79879. var lm = this.getLocalMatrix();
  79880. if (space == BABYLON.Space.LOCAL) {
  79881. lm.m[12] = position.x;
  79882. lm.m[13] = position.y;
  79883. lm.m[14] = position.z;
  79884. }
  79885. else {
  79886. var wm = null;
  79887. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  79888. if (mesh) {
  79889. wm = mesh.getWorldMatrix();
  79890. }
  79891. this._skeleton.computeAbsoluteTransforms();
  79892. var tmat = Bone._tmpMats[0];
  79893. var vec = Bone._tmpVecs[0];
  79894. if (this._parent) {
  79895. if (mesh && wm) {
  79896. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79897. tmat.multiplyToRef(wm, tmat);
  79898. }
  79899. else {
  79900. tmat.copyFrom(this._parent.getAbsoluteTransform());
  79901. }
  79902. }
  79903. tmat.invert();
  79904. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, vec);
  79905. lm.m[12] = vec.x;
  79906. lm.m[13] = vec.y;
  79907. lm.m[14] = vec.z;
  79908. }
  79909. this._markAsDirtyAndDecompose();
  79910. };
  79911. /**
  79912. * Set the absolute position of the bone (world space)
  79913. * @param position The position to set the bone
  79914. * @param mesh The mesh that this bone is attached to
  79915. */
  79916. Bone.prototype.setAbsolutePosition = function (position, mesh) {
  79917. this.setPosition(position, BABYLON.Space.WORLD, mesh);
  79918. };
  79919. /**
  79920. * Scale the bone on the x, y and z axes (in local space)
  79921. * @param x The amount to scale the bone on the x axis
  79922. * @param y The amount to scale the bone on the y axis
  79923. * @param z The amount to scale the bone on the z axis
  79924. * @param scaleChildren sets this to true if children of the bone should be scaled as well (false by default)
  79925. */
  79926. Bone.prototype.scale = function (x, y, z, scaleChildren) {
  79927. if (scaleChildren === void 0) { scaleChildren = false; }
  79928. var locMat = this.getLocalMatrix();
  79929. // Apply new scaling on top of current local matrix
  79930. var scaleMat = Bone._tmpMats[0];
  79931. BABYLON.Matrix.ScalingToRef(x, y, z, scaleMat);
  79932. scaleMat.multiplyToRef(locMat, locMat);
  79933. // Invert scaling matrix and apply the inverse to all children
  79934. scaleMat.invert();
  79935. for (var _i = 0, _a = this.children; _i < _a.length; _i++) {
  79936. var child = _a[_i];
  79937. var cm = child.getLocalMatrix();
  79938. cm.multiplyToRef(scaleMat, cm);
  79939. cm.m[12] *= x;
  79940. cm.m[13] *= y;
  79941. cm.m[14] *= z;
  79942. child._markAsDirtyAndDecompose();
  79943. }
  79944. this._markAsDirtyAndDecompose();
  79945. if (scaleChildren) {
  79946. for (var _b = 0, _c = this.children; _b < _c.length; _b++) {
  79947. var child = _c[_b];
  79948. child.scale(x, y, z, scaleChildren);
  79949. }
  79950. }
  79951. };
  79952. /**
  79953. * Set the bone scaling in local space
  79954. * @param scale defines the scaling vector
  79955. */
  79956. Bone.prototype.setScale = function (scale) {
  79957. this._decompose();
  79958. this._localScaling.copyFrom(scale);
  79959. this._markAsDirtyAndCompose();
  79960. };
  79961. /**
  79962. * Gets the current scaling in local space
  79963. * @returns the current scaling vector
  79964. */
  79965. Bone.prototype.getScale = function () {
  79966. this._decompose();
  79967. return this._localScaling;
  79968. };
  79969. /**
  79970. * Gets the current scaling in local space and stores it in a target vector
  79971. * @param result defines the target vector
  79972. */
  79973. Bone.prototype.getScaleToRef = function (result) {
  79974. this._decompose();
  79975. result.copyFrom(this._localScaling);
  79976. };
  79977. /**
  79978. * Set the yaw, pitch, and roll of the bone in local or world space
  79979. * @param yaw The rotation of the bone on the y axis
  79980. * @param pitch The rotation of the bone on the x axis
  79981. * @param roll The rotation of the bone on the z axis
  79982. * @param space The space that the axes of rotation are in
  79983. * @param mesh The mesh that this bone is attached to. This is only used in world space
  79984. */
  79985. Bone.prototype.setYawPitchRoll = function (yaw, pitch, roll, space, mesh) {
  79986. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  79987. if (space === BABYLON.Space.LOCAL) {
  79988. var quat = Bone._tmpQuat;
  79989. BABYLON.Quaternion.RotationYawPitchRollToRef(yaw, pitch, roll, quat);
  79990. this.setRotationQuaternion(quat, space, mesh);
  79991. return;
  79992. }
  79993. var rotMatInv = Bone._tmpMats[0];
  79994. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  79995. return;
  79996. }
  79997. var rotMat = Bone._tmpMats[1];
  79998. BABYLON.Matrix.RotationYawPitchRollToRef(yaw, pitch, roll, rotMat);
  79999. rotMatInv.multiplyToRef(rotMat, rotMat);
  80000. this._rotateWithMatrix(rotMat, space, mesh);
  80001. };
  80002. /**
  80003. * Add a rotation to the bone on an axis in local or world space
  80004. * @param axis The axis to rotate the bone on
  80005. * @param amount The amount to rotate the bone
  80006. * @param space The space that the axis is in
  80007. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80008. */
  80009. Bone.prototype.rotate = function (axis, amount, space, mesh) {
  80010. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80011. var rmat = Bone._tmpMats[0];
  80012. rmat.m[12] = 0;
  80013. rmat.m[13] = 0;
  80014. rmat.m[14] = 0;
  80015. BABYLON.Matrix.RotationAxisToRef(axis, amount, rmat);
  80016. this._rotateWithMatrix(rmat, space, mesh);
  80017. };
  80018. /**
  80019. * Set the rotation of the bone to a particular axis angle in local or world space
  80020. * @param axis The axis to rotate the bone on
  80021. * @param angle The angle that the bone should be rotated to
  80022. * @param space The space that the axis is in
  80023. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80024. */
  80025. Bone.prototype.setAxisAngle = function (axis, angle, space, mesh) {
  80026. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80027. if (space === BABYLON.Space.LOCAL) {
  80028. var quat = Bone._tmpQuat;
  80029. BABYLON.Quaternion.RotationAxisToRef(axis, angle, quat);
  80030. this.setRotationQuaternion(quat, space, mesh);
  80031. return;
  80032. }
  80033. var rotMatInv = Bone._tmpMats[0];
  80034. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80035. return;
  80036. }
  80037. var rotMat = Bone._tmpMats[1];
  80038. BABYLON.Matrix.RotationAxisToRef(axis, angle, rotMat);
  80039. rotMatInv.multiplyToRef(rotMat, rotMat);
  80040. this._rotateWithMatrix(rotMat, space, mesh);
  80041. };
  80042. /**
  80043. * Set the euler rotation of the bone in local of world space
  80044. * @param rotation The euler rotation that the bone should be set to
  80045. * @param space The space that the rotation is in
  80046. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80047. */
  80048. Bone.prototype.setRotation = function (rotation, space, mesh) {
  80049. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80050. this.setYawPitchRoll(rotation.y, rotation.x, rotation.z, space, mesh);
  80051. };
  80052. /**
  80053. * Set the quaternion rotation of the bone in local of world space
  80054. * @param quat The quaternion rotation that the bone should be set to
  80055. * @param space The space that the rotation is in
  80056. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80057. */
  80058. Bone.prototype.setRotationQuaternion = function (quat, space, mesh) {
  80059. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80060. if (space === BABYLON.Space.LOCAL) {
  80061. this._decompose();
  80062. this._localRotation.copyFrom(quat);
  80063. this._markAsDirtyAndCompose();
  80064. return;
  80065. }
  80066. var rotMatInv = Bone._tmpMats[0];
  80067. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80068. return;
  80069. }
  80070. var rotMat = Bone._tmpMats[1];
  80071. BABYLON.Matrix.FromQuaternionToRef(quat, rotMat);
  80072. rotMatInv.multiplyToRef(rotMat, rotMat);
  80073. this._rotateWithMatrix(rotMat, space, mesh);
  80074. };
  80075. /**
  80076. * Set the rotation matrix of the bone in local of world space
  80077. * @param rotMat The rotation matrix that the bone should be set to
  80078. * @param space The space that the rotation is in
  80079. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80080. */
  80081. Bone.prototype.setRotationMatrix = function (rotMat, space, mesh) {
  80082. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80083. if (space === BABYLON.Space.LOCAL) {
  80084. var quat = Bone._tmpQuat;
  80085. BABYLON.Quaternion.FromRotationMatrixToRef(rotMat, quat);
  80086. this.setRotationQuaternion(quat, space, mesh);
  80087. return;
  80088. }
  80089. var rotMatInv = Bone._tmpMats[0];
  80090. if (!this._getNegativeRotationToRef(rotMatInv, mesh)) {
  80091. return;
  80092. }
  80093. var rotMat2 = Bone._tmpMats[1];
  80094. rotMat2.copyFrom(rotMat);
  80095. rotMatInv.multiplyToRef(rotMat, rotMat2);
  80096. this._rotateWithMatrix(rotMat2, space, mesh);
  80097. };
  80098. Bone.prototype._rotateWithMatrix = function (rmat, space, mesh) {
  80099. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80100. var lmat = this.getLocalMatrix();
  80101. var lx = lmat.m[12];
  80102. var ly = lmat.m[13];
  80103. var lz = lmat.m[14];
  80104. var parent = this.getParent();
  80105. var parentScale = Bone._tmpMats[3];
  80106. var parentScaleInv = Bone._tmpMats[4];
  80107. if (parent && space == BABYLON.Space.WORLD) {
  80108. if (mesh) {
  80109. parentScale.copyFrom(mesh.getWorldMatrix());
  80110. parent.getAbsoluteTransform().multiplyToRef(parentScale, parentScale);
  80111. }
  80112. else {
  80113. parentScale.copyFrom(parent.getAbsoluteTransform());
  80114. }
  80115. parentScaleInv.copyFrom(parentScale);
  80116. parentScaleInv.invert();
  80117. lmat.multiplyToRef(parentScale, lmat);
  80118. lmat.multiplyToRef(rmat, lmat);
  80119. lmat.multiplyToRef(parentScaleInv, lmat);
  80120. }
  80121. else {
  80122. if (space == BABYLON.Space.WORLD && mesh) {
  80123. parentScale.copyFrom(mesh.getWorldMatrix());
  80124. parentScaleInv.copyFrom(parentScale);
  80125. parentScaleInv.invert();
  80126. lmat.multiplyToRef(parentScale, lmat);
  80127. lmat.multiplyToRef(rmat, lmat);
  80128. lmat.multiplyToRef(parentScaleInv, lmat);
  80129. }
  80130. else {
  80131. lmat.multiplyToRef(rmat, lmat);
  80132. }
  80133. }
  80134. lmat.m[12] = lx;
  80135. lmat.m[13] = ly;
  80136. lmat.m[14] = lz;
  80137. this.computeAbsoluteTransforms();
  80138. this._markAsDirtyAndDecompose();
  80139. };
  80140. Bone.prototype._getNegativeRotationToRef = function (rotMatInv, mesh) {
  80141. var scaleMatrix = Bone._tmpMats[2];
  80142. rotMatInv.copyFrom(this.getAbsoluteTransform());
  80143. if (mesh) {
  80144. rotMatInv.multiplyToRef(mesh.getWorldMatrix(), rotMatInv);
  80145. BABYLON.Matrix.ScalingToRef(mesh.scaling.x, mesh.scaling.y, mesh.scaling.z, scaleMatrix);
  80146. }
  80147. rotMatInv.invert();
  80148. if (isNaN(rotMatInv.m[0])) {
  80149. // Matrix failed to invert.
  80150. // This can happen if scale is zero for example.
  80151. return false;
  80152. }
  80153. scaleMatrix.m[0] *= this._scalingDeterminant;
  80154. rotMatInv.multiplyToRef(scaleMatrix, rotMatInv);
  80155. return true;
  80156. };
  80157. /**
  80158. * Get the position of the bone in local or world space
  80159. * @param space The space that the returned position is in
  80160. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80161. * @returns The position of the bone
  80162. */
  80163. Bone.prototype.getPosition = function (space, mesh) {
  80164. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80165. if (mesh === void 0) { mesh = null; }
  80166. var pos = BABYLON.Vector3.Zero();
  80167. this.getPositionToRef(space, mesh, pos);
  80168. return pos;
  80169. };
  80170. /**
  80171. * Copy the position of the bone to a vector3 in local or world space
  80172. * @param space The space that the returned position is in
  80173. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80174. * @param result The vector3 to copy the position to
  80175. */
  80176. Bone.prototype.getPositionToRef = function (space, mesh, result) {
  80177. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80178. if (space == BABYLON.Space.LOCAL) {
  80179. var lm = this.getLocalMatrix();
  80180. result.x = lm.m[12];
  80181. result.y = lm.m[13];
  80182. result.z = lm.m[14];
  80183. }
  80184. else {
  80185. var wm = null;
  80186. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80187. if (mesh) {
  80188. wm = mesh.getWorldMatrix();
  80189. }
  80190. this._skeleton.computeAbsoluteTransforms();
  80191. var tmat = Bone._tmpMats[0];
  80192. if (mesh && wm) {
  80193. tmat.copyFrom(this.getAbsoluteTransform());
  80194. tmat.multiplyToRef(wm, tmat);
  80195. }
  80196. else {
  80197. tmat = this.getAbsoluteTransform();
  80198. }
  80199. result.x = tmat.m[12];
  80200. result.y = tmat.m[13];
  80201. result.z = tmat.m[14];
  80202. }
  80203. };
  80204. /**
  80205. * Get the absolute position of the bone (world space)
  80206. * @param mesh The mesh that this bone is attached to
  80207. * @returns The absolute position of the bone
  80208. */
  80209. Bone.prototype.getAbsolutePosition = function (mesh) {
  80210. if (mesh === void 0) { mesh = null; }
  80211. var pos = BABYLON.Vector3.Zero();
  80212. this.getPositionToRef(BABYLON.Space.WORLD, mesh, pos);
  80213. return pos;
  80214. };
  80215. /**
  80216. * Copy the absolute position of the bone (world space) to the result param
  80217. * @param mesh The mesh that this bone is attached to
  80218. * @param result The vector3 to copy the absolute position to
  80219. */
  80220. Bone.prototype.getAbsolutePositionToRef = function (mesh, result) {
  80221. this.getPositionToRef(BABYLON.Space.WORLD, mesh, result);
  80222. };
  80223. /**
  80224. * Compute the absolute transforms of this bone and its children
  80225. */
  80226. Bone.prototype.computeAbsoluteTransforms = function () {
  80227. this._compose();
  80228. if (this._parent) {
  80229. this._localMatrix.multiplyToRef(this._parent._absoluteTransform, this._absoluteTransform);
  80230. }
  80231. else {
  80232. this._absoluteTransform.copyFrom(this._localMatrix);
  80233. var poseMatrix = this._skeleton.getPoseMatrix();
  80234. if (poseMatrix) {
  80235. this._absoluteTransform.multiplyToRef(poseMatrix, this._absoluteTransform);
  80236. }
  80237. }
  80238. var children = this.children;
  80239. var len = children.length;
  80240. for (var i = 0; i < len; i++) {
  80241. children[i].computeAbsoluteTransforms();
  80242. }
  80243. };
  80244. /**
  80245. * Get the world direction from an axis that is in the local space of the bone
  80246. * @param localAxis The local direction that is used to compute the world direction
  80247. * @param mesh The mesh that this bone is attached to
  80248. * @returns The world direction
  80249. */
  80250. Bone.prototype.getDirection = function (localAxis, mesh) {
  80251. if (mesh === void 0) { mesh = null; }
  80252. var result = BABYLON.Vector3.Zero();
  80253. this.getDirectionToRef(localAxis, mesh, result);
  80254. return result;
  80255. };
  80256. /**
  80257. * Copy the world direction to a vector3 from an axis that is in the local space of the bone
  80258. * @param localAxis The local direction that is used to compute the world direction
  80259. * @param mesh The mesh that this bone is attached to
  80260. * @param result The vector3 that the world direction will be copied to
  80261. */
  80262. Bone.prototype.getDirectionToRef = function (localAxis, mesh, result) {
  80263. if (mesh === void 0) { mesh = null; }
  80264. var wm = null;
  80265. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80266. if (mesh) {
  80267. wm = mesh.getWorldMatrix();
  80268. }
  80269. this._skeleton.computeAbsoluteTransforms();
  80270. var mat = Bone._tmpMats[0];
  80271. mat.copyFrom(this.getAbsoluteTransform());
  80272. if (mesh && wm) {
  80273. mat.multiplyToRef(wm, mat);
  80274. }
  80275. BABYLON.Vector3.TransformNormalToRef(localAxis, mat, result);
  80276. result.normalize();
  80277. };
  80278. /**
  80279. * Get the euler rotation of the bone in local or world space
  80280. * @param space The space that the rotation should be in
  80281. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80282. * @returns The euler rotation
  80283. */
  80284. Bone.prototype.getRotation = function (space, mesh) {
  80285. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80286. if (mesh === void 0) { mesh = null; }
  80287. var result = BABYLON.Vector3.Zero();
  80288. this.getRotationToRef(space, mesh, result);
  80289. return result;
  80290. };
  80291. /**
  80292. * Copy the euler rotation of the bone to a vector3. The rotation can be in either local or world space
  80293. * @param space The space that the rotation should be in
  80294. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80295. * @param result The vector3 that the rotation should be copied to
  80296. */
  80297. Bone.prototype.getRotationToRef = function (space, mesh, result) {
  80298. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80299. if (mesh === void 0) { mesh = null; }
  80300. var quat = Bone._tmpQuat;
  80301. this.getRotationQuaternionToRef(space, mesh, quat);
  80302. quat.toEulerAnglesToRef(result);
  80303. };
  80304. /**
  80305. * Get the quaternion rotation of the bone in either local or world space
  80306. * @param space The space that the rotation should be in
  80307. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80308. * @returns The quaternion rotation
  80309. */
  80310. Bone.prototype.getRotationQuaternion = function (space, mesh) {
  80311. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80312. if (mesh === void 0) { mesh = null; }
  80313. var result = BABYLON.Quaternion.Identity();
  80314. this.getRotationQuaternionToRef(space, mesh, result);
  80315. return result;
  80316. };
  80317. /**
  80318. * Copy the quaternion rotation of the bone to a quaternion. The rotation can be in either local or world space
  80319. * @param space The space that the rotation should be in
  80320. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80321. * @param result The quaternion that the rotation should be copied to
  80322. */
  80323. Bone.prototype.getRotationQuaternionToRef = function (space, mesh, result) {
  80324. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80325. if (mesh === void 0) { mesh = null; }
  80326. if (space == BABYLON.Space.LOCAL) {
  80327. this._decompose();
  80328. result.copyFrom(this._localRotation);
  80329. }
  80330. else {
  80331. var mat = Bone._tmpMats[0];
  80332. var amat = this.getAbsoluteTransform();
  80333. if (mesh) {
  80334. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80335. }
  80336. else {
  80337. mat.copyFrom(amat);
  80338. }
  80339. mat.m[0] *= this._scalingDeterminant;
  80340. mat.m[1] *= this._scalingDeterminant;
  80341. mat.m[2] *= this._scalingDeterminant;
  80342. mat.decompose(undefined, result, undefined);
  80343. }
  80344. };
  80345. /**
  80346. * Get the rotation matrix of the bone in local or world space
  80347. * @param space The space that the rotation should be in
  80348. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80349. * @returns The rotation matrix
  80350. */
  80351. Bone.prototype.getRotationMatrix = function (space, mesh) {
  80352. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80353. var result = BABYLON.Matrix.Identity();
  80354. this.getRotationMatrixToRef(space, mesh, result);
  80355. return result;
  80356. };
  80357. /**
  80358. * Copy the rotation matrix of the bone to a matrix. The rotation can be in either local or world space
  80359. * @param space The space that the rotation should be in
  80360. * @param mesh The mesh that this bone is attached to. This is only used in world space
  80361. * @param result The quaternion that the rotation should be copied to
  80362. */
  80363. Bone.prototype.getRotationMatrixToRef = function (space, mesh, result) {
  80364. if (space === void 0) { space = BABYLON.Space.LOCAL; }
  80365. if (space == BABYLON.Space.LOCAL) {
  80366. this.getLocalMatrix().getRotationMatrixToRef(result);
  80367. }
  80368. else {
  80369. var mat = Bone._tmpMats[0];
  80370. var amat = this.getAbsoluteTransform();
  80371. if (mesh) {
  80372. amat.multiplyToRef(mesh.getWorldMatrix(), mat);
  80373. }
  80374. else {
  80375. mat.copyFrom(amat);
  80376. }
  80377. mat.m[0] *= this._scalingDeterminant;
  80378. mat.m[1] *= this._scalingDeterminant;
  80379. mat.m[2] *= this._scalingDeterminant;
  80380. mat.getRotationMatrixToRef(result);
  80381. }
  80382. };
  80383. /**
  80384. * Get the world position of a point that is in the local space of the bone
  80385. * @param position The local position
  80386. * @param mesh The mesh that this bone is attached to
  80387. * @returns The world position
  80388. */
  80389. Bone.prototype.getAbsolutePositionFromLocal = function (position, mesh) {
  80390. if (mesh === void 0) { mesh = null; }
  80391. var result = BABYLON.Vector3.Zero();
  80392. this.getAbsolutePositionFromLocalToRef(position, mesh, result);
  80393. return result;
  80394. };
  80395. /**
  80396. * Get the world position of a point that is in the local space of the bone and copy it to the result param
  80397. * @param position The local position
  80398. * @param mesh The mesh that this bone is attached to
  80399. * @param result The vector3 that the world position should be copied to
  80400. */
  80401. Bone.prototype.getAbsolutePositionFromLocalToRef = function (position, mesh, result) {
  80402. if (mesh === void 0) { mesh = null; }
  80403. var wm = null;
  80404. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80405. if (mesh) {
  80406. wm = mesh.getWorldMatrix();
  80407. }
  80408. this._skeleton.computeAbsoluteTransforms();
  80409. var tmat = Bone._tmpMats[0];
  80410. if (mesh && wm) {
  80411. tmat.copyFrom(this.getAbsoluteTransform());
  80412. tmat.multiplyToRef(wm, tmat);
  80413. }
  80414. else {
  80415. tmat = this.getAbsoluteTransform();
  80416. }
  80417. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80418. };
  80419. /**
  80420. * Get the local position of a point that is in world space
  80421. * @param position The world position
  80422. * @param mesh The mesh that this bone is attached to
  80423. * @returns The local position
  80424. */
  80425. Bone.prototype.getLocalPositionFromAbsolute = function (position, mesh) {
  80426. if (mesh === void 0) { mesh = null; }
  80427. var result = BABYLON.Vector3.Zero();
  80428. this.getLocalPositionFromAbsoluteToRef(position, mesh, result);
  80429. return result;
  80430. };
  80431. /**
  80432. * Get the local position of a point that is in world space and copy it to the result param
  80433. * @param position The world position
  80434. * @param mesh The mesh that this bone is attached to
  80435. * @param result The vector3 that the local position should be copied to
  80436. */
  80437. Bone.prototype.getLocalPositionFromAbsoluteToRef = function (position, mesh, result) {
  80438. if (mesh === void 0) { mesh = null; }
  80439. var wm = null;
  80440. //mesh.getWorldMatrix() needs to be called before skeleton.computeAbsoluteTransforms()
  80441. if (mesh) {
  80442. wm = mesh.getWorldMatrix();
  80443. }
  80444. this._skeleton.computeAbsoluteTransforms();
  80445. var tmat = Bone._tmpMats[0];
  80446. tmat.copyFrom(this.getAbsoluteTransform());
  80447. if (mesh && wm) {
  80448. tmat.multiplyToRef(wm, tmat);
  80449. }
  80450. tmat.invert();
  80451. BABYLON.Vector3.TransformCoordinatesToRef(position, tmat, result);
  80452. };
  80453. Bone._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80454. Bone._tmpQuat = BABYLON.Quaternion.Identity();
  80455. Bone._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80456. return Bone;
  80457. }(BABYLON.Node));
  80458. BABYLON.Bone = Bone;
  80459. })(BABYLON || (BABYLON = {}));
  80460. //# sourceMappingURL=babylon.bone.js.map
  80461. var BABYLON;
  80462. (function (BABYLON) {
  80463. /**
  80464. * Class used to apply inverse kinematics to bones
  80465. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#boneikcontroller
  80466. */
  80467. var BoneIKController = /** @class */ (function () {
  80468. /**
  80469. * Creates a new BoneIKController
  80470. * @param mesh defines the mesh to control
  80471. * @param bone defines the bone to control
  80472. * @param options defines options to set up the controller
  80473. */
  80474. function BoneIKController(mesh, bone, options) {
  80475. /**
  80476. * Gets or sets the target position
  80477. */
  80478. this.targetPosition = BABYLON.Vector3.Zero();
  80479. /**
  80480. * Gets or sets the pole target position
  80481. */
  80482. this.poleTargetPosition = BABYLON.Vector3.Zero();
  80483. /**
  80484. * Gets or sets the pole target local offset
  80485. */
  80486. this.poleTargetLocalOffset = BABYLON.Vector3.Zero();
  80487. /**
  80488. * Gets or sets the pole angle
  80489. */
  80490. this.poleAngle = 0;
  80491. /**
  80492. * 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)
  80493. */
  80494. this.slerpAmount = 1;
  80495. this._bone1Quat = BABYLON.Quaternion.Identity();
  80496. this._bone1Mat = BABYLON.Matrix.Identity();
  80497. this._bone2Ang = Math.PI;
  80498. this._maxAngle = Math.PI;
  80499. this._rightHandedSystem = false;
  80500. this._bendAxis = BABYLON.Vector3.Right();
  80501. this._slerping = false;
  80502. this._adjustRoll = 0;
  80503. this._bone2 = bone;
  80504. this._bone1 = bone.getParent();
  80505. if (!this._bone1) {
  80506. return;
  80507. }
  80508. this.mesh = mesh;
  80509. var bonePos = bone.getPosition();
  80510. if (bone.getAbsoluteTransform().determinant() > 0) {
  80511. this._rightHandedSystem = true;
  80512. this._bendAxis.x = 0;
  80513. this._bendAxis.y = 0;
  80514. this._bendAxis.z = -1;
  80515. if (bonePos.x > bonePos.y && bonePos.x > bonePos.z) {
  80516. this._adjustRoll = Math.PI * .5;
  80517. this._bendAxis.z = 1;
  80518. }
  80519. }
  80520. if (this._bone1.length) {
  80521. var boneScale1 = this._bone1.getScale();
  80522. var boneScale2 = this._bone2.getScale();
  80523. this._bone1Length = this._bone1.length * boneScale1.y * this.mesh.scaling.y;
  80524. this._bone2Length = this._bone2.length * boneScale2.y * this.mesh.scaling.y;
  80525. }
  80526. else if (this._bone1.children[0]) {
  80527. mesh.computeWorldMatrix(true);
  80528. var pos1 = this._bone2.children[0].getAbsolutePosition(mesh);
  80529. var pos2 = this._bone2.getAbsolutePosition(mesh);
  80530. var pos3 = this._bone1.getAbsolutePosition(mesh);
  80531. this._bone1Length = BABYLON.Vector3.Distance(pos1, pos2);
  80532. this._bone2Length = BABYLON.Vector3.Distance(pos2, pos3);
  80533. }
  80534. this._bone1.getRotationMatrixToRef(BABYLON.Space.WORLD, mesh, this._bone1Mat);
  80535. this.maxAngle = Math.PI;
  80536. if (options) {
  80537. if (options.targetMesh) {
  80538. this.targetMesh = options.targetMesh;
  80539. this.targetMesh.computeWorldMatrix(true);
  80540. }
  80541. if (options.poleTargetMesh) {
  80542. this.poleTargetMesh = options.poleTargetMesh;
  80543. this.poleTargetMesh.computeWorldMatrix(true);
  80544. }
  80545. else if (options.poleTargetBone) {
  80546. this.poleTargetBone = options.poleTargetBone;
  80547. }
  80548. else if (this._bone1.getParent()) {
  80549. this.poleTargetBone = this._bone1.getParent();
  80550. }
  80551. if (options.poleTargetLocalOffset) {
  80552. this.poleTargetLocalOffset.copyFrom(options.poleTargetLocalOffset);
  80553. }
  80554. if (options.poleAngle) {
  80555. this.poleAngle = options.poleAngle;
  80556. }
  80557. if (options.bendAxis) {
  80558. this._bendAxis.copyFrom(options.bendAxis);
  80559. }
  80560. if (options.maxAngle) {
  80561. this.maxAngle = options.maxAngle;
  80562. }
  80563. if (options.slerpAmount) {
  80564. this.slerpAmount = options.slerpAmount;
  80565. }
  80566. }
  80567. }
  80568. Object.defineProperty(BoneIKController.prototype, "maxAngle", {
  80569. /**
  80570. * Gets or sets maximum allowed angle
  80571. */
  80572. get: function () {
  80573. return this._maxAngle;
  80574. },
  80575. set: function (value) {
  80576. this._setMaxAngle(value);
  80577. },
  80578. enumerable: true,
  80579. configurable: true
  80580. });
  80581. BoneIKController.prototype._setMaxAngle = function (ang) {
  80582. if (ang < 0) {
  80583. ang = 0;
  80584. }
  80585. if (ang > Math.PI || ang == undefined) {
  80586. ang = Math.PI;
  80587. }
  80588. this._maxAngle = ang;
  80589. var a = this._bone1Length;
  80590. var b = this._bone2Length;
  80591. this._maxReach = Math.sqrt(a * a + b * b - 2 * a * b * Math.cos(ang));
  80592. };
  80593. /**
  80594. * Force the controller to update the bones
  80595. */
  80596. BoneIKController.prototype.update = function () {
  80597. var bone1 = this._bone1;
  80598. if (!bone1) {
  80599. return;
  80600. }
  80601. var target = this.targetPosition;
  80602. var poleTarget = this.poleTargetPosition;
  80603. var mat1 = BoneIKController._tmpMats[0];
  80604. var mat2 = BoneIKController._tmpMats[1];
  80605. if (this.targetMesh) {
  80606. target.copyFrom(this.targetMesh.getAbsolutePosition());
  80607. }
  80608. if (this.poleTargetBone) {
  80609. this.poleTargetBone.getAbsolutePositionFromLocalToRef(this.poleTargetLocalOffset, this.mesh, poleTarget);
  80610. }
  80611. else if (this.poleTargetMesh) {
  80612. BABYLON.Vector3.TransformCoordinatesToRef(this.poleTargetLocalOffset, this.poleTargetMesh.getWorldMatrix(), poleTarget);
  80613. }
  80614. var bonePos = BoneIKController._tmpVecs[0];
  80615. var zaxis = BoneIKController._tmpVecs[1];
  80616. var xaxis = BoneIKController._tmpVecs[2];
  80617. var yaxis = BoneIKController._tmpVecs[3];
  80618. var upAxis = BoneIKController._tmpVecs[4];
  80619. var _tmpQuat = BoneIKController._tmpQuat;
  80620. bone1.getAbsolutePositionToRef(this.mesh, bonePos);
  80621. poleTarget.subtractToRef(bonePos, upAxis);
  80622. if (upAxis.x == 0 && upAxis.y == 0 && upAxis.z == 0) {
  80623. upAxis.y = 1;
  80624. }
  80625. else {
  80626. upAxis.normalize();
  80627. }
  80628. target.subtractToRef(bonePos, yaxis);
  80629. yaxis.normalize();
  80630. BABYLON.Vector3.CrossToRef(yaxis, upAxis, zaxis);
  80631. zaxis.normalize();
  80632. BABYLON.Vector3.CrossToRef(yaxis, zaxis, xaxis);
  80633. xaxis.normalize();
  80634. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, mat1);
  80635. var a = this._bone1Length;
  80636. var b = this._bone2Length;
  80637. var c = BABYLON.Vector3.Distance(bonePos, target);
  80638. if (this._maxReach > 0) {
  80639. c = Math.min(this._maxReach, c);
  80640. }
  80641. var acosa = (b * b + c * c - a * a) / (2 * b * c);
  80642. var acosb = (c * c + a * a - b * b) / (2 * c * a);
  80643. if (acosa > 1) {
  80644. acosa = 1;
  80645. }
  80646. if (acosb > 1) {
  80647. acosb = 1;
  80648. }
  80649. if (acosa < -1) {
  80650. acosa = -1;
  80651. }
  80652. if (acosb < -1) {
  80653. acosb = -1;
  80654. }
  80655. var angA = Math.acos(acosa);
  80656. var angB = Math.acos(acosb);
  80657. var angC = -angA - angB;
  80658. if (this._rightHandedSystem) {
  80659. BABYLON.Matrix.RotationYawPitchRollToRef(0, 0, this._adjustRoll, mat2);
  80660. mat2.multiplyToRef(mat1, mat1);
  80661. BABYLON.Matrix.RotationAxisToRef(this._bendAxis, angB, mat2);
  80662. mat2.multiplyToRef(mat1, mat1);
  80663. }
  80664. else {
  80665. var _tmpVec = BoneIKController._tmpVecs[5];
  80666. _tmpVec.copyFrom(this._bendAxis);
  80667. _tmpVec.x *= -1;
  80668. BABYLON.Matrix.RotationAxisToRef(_tmpVec, -angB, mat2);
  80669. mat2.multiplyToRef(mat1, mat1);
  80670. }
  80671. if (this.poleAngle) {
  80672. BABYLON.Matrix.RotationAxisToRef(yaxis, this.poleAngle, mat2);
  80673. mat1.multiplyToRef(mat2, mat1);
  80674. }
  80675. if (this._bone1) {
  80676. if (this.slerpAmount < 1) {
  80677. if (!this._slerping) {
  80678. BABYLON.Quaternion.FromRotationMatrixToRef(this._bone1Mat, this._bone1Quat);
  80679. }
  80680. BABYLON.Quaternion.FromRotationMatrixToRef(mat1, _tmpQuat);
  80681. BABYLON.Quaternion.SlerpToRef(this._bone1Quat, _tmpQuat, this.slerpAmount, this._bone1Quat);
  80682. angC = this._bone2Ang * (1.0 - this.slerpAmount) + angC * this.slerpAmount;
  80683. this._bone1.setRotationQuaternion(this._bone1Quat, BABYLON.Space.WORLD, this.mesh);
  80684. this._slerping = true;
  80685. }
  80686. else {
  80687. this._bone1.setRotationMatrix(mat1, BABYLON.Space.WORLD, this.mesh);
  80688. this._bone1Mat.copyFrom(mat1);
  80689. this._slerping = false;
  80690. }
  80691. }
  80692. this._bone2.setAxisAngle(this._bendAxis, angC, BABYLON.Space.LOCAL);
  80693. this._bone2Ang = angC;
  80694. };
  80695. BoneIKController._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  80696. BoneIKController._tmpQuat = BABYLON.Quaternion.Identity();
  80697. BoneIKController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  80698. return BoneIKController;
  80699. }());
  80700. BABYLON.BoneIKController = BoneIKController;
  80701. })(BABYLON || (BABYLON = {}));
  80702. //# sourceMappingURL=babylon.boneIKController.js.map
  80703. var BABYLON;
  80704. (function (BABYLON) {
  80705. /**
  80706. * Class used to make a bone look toward a point in space
  80707. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons#bonelookcontroller
  80708. */
  80709. var BoneLookController = /** @class */ (function () {
  80710. /**
  80711. * Create a BoneLookController
  80712. * @param mesh the mesh that the bone belongs to
  80713. * @param bone the bone that will be looking to the target
  80714. * @param target the target Vector3 to look at
  80715. * @param settings optional settings:
  80716. * * maxYaw: the maximum angle the bone will yaw to
  80717. * * minYaw: the minimum angle the bone will yaw to
  80718. * * maxPitch: the maximum angle the bone will pitch to
  80719. * * minPitch: the minimum angle the bone will yaw to
  80720. * * slerpAmount: set the between 0 and 1 to make the bone slerp to the target.
  80721. * * upAxis: the up axis of the coordinate system
  80722. * * upAxisSpace: the space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD.
  80723. * * yawAxis: set yawAxis if the bone does not yaw on the y axis
  80724. * * pitchAxis: set pitchAxis if the bone does not pitch on the x axis
  80725. * * adjustYaw: used to make an adjustment to the yaw of the bone
  80726. * * adjustPitch: used to make an adjustment to the pitch of the bone
  80727. * * adjustRoll: used to make an adjustment to the roll of the bone
  80728. **/
  80729. function BoneLookController(mesh, bone, target, options) {
  80730. /**
  80731. * The up axis of the coordinate system that is used when the bone is rotated
  80732. */
  80733. this.upAxis = BABYLON.Vector3.Up();
  80734. /**
  80735. * The space that the up axis is in - BABYLON.Space.BONE, BABYLON.Space.LOCAL (default), or BABYLON.Space.WORLD
  80736. */
  80737. this.upAxisSpace = BABYLON.Space.LOCAL;
  80738. /**
  80739. * Used to make an adjustment to the yaw of the bone
  80740. */
  80741. this.adjustYaw = 0;
  80742. /**
  80743. * Used to make an adjustment to the pitch of the bone
  80744. */
  80745. this.adjustPitch = 0;
  80746. /**
  80747. * Used to make an adjustment to the roll of the bone
  80748. */
  80749. this.adjustRoll = 0;
  80750. /**
  80751. * 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)
  80752. */
  80753. this.slerpAmount = 1;
  80754. this._boneQuat = BABYLON.Quaternion.Identity();
  80755. this._slerping = false;
  80756. this._firstFrameSkipped = false;
  80757. this._fowardAxis = BABYLON.Vector3.Forward();
  80758. this.mesh = mesh;
  80759. this.bone = bone;
  80760. this.target = target;
  80761. if (options) {
  80762. if (options.adjustYaw) {
  80763. this.adjustYaw = options.adjustYaw;
  80764. }
  80765. if (options.adjustPitch) {
  80766. this.adjustPitch = options.adjustPitch;
  80767. }
  80768. if (options.adjustRoll) {
  80769. this.adjustRoll = options.adjustRoll;
  80770. }
  80771. if (options.maxYaw != null) {
  80772. this.maxYaw = options.maxYaw;
  80773. }
  80774. else {
  80775. this.maxYaw = Math.PI;
  80776. }
  80777. if (options.minYaw != null) {
  80778. this.minYaw = options.minYaw;
  80779. }
  80780. else {
  80781. this.minYaw = -Math.PI;
  80782. }
  80783. if (options.maxPitch != null) {
  80784. this.maxPitch = options.maxPitch;
  80785. }
  80786. else {
  80787. this.maxPitch = Math.PI;
  80788. }
  80789. if (options.minPitch != null) {
  80790. this.minPitch = options.minPitch;
  80791. }
  80792. else {
  80793. this.minPitch = -Math.PI;
  80794. }
  80795. if (options.slerpAmount != null) {
  80796. this.slerpAmount = options.slerpAmount;
  80797. }
  80798. if (options.upAxis != null) {
  80799. this.upAxis = options.upAxis;
  80800. }
  80801. if (options.upAxisSpace != null) {
  80802. this.upAxisSpace = options.upAxisSpace;
  80803. }
  80804. if (options.yawAxis != null || options.pitchAxis != null) {
  80805. var newYawAxis = BABYLON.Axis.Y;
  80806. var newPitchAxis = BABYLON.Axis.X;
  80807. if (options.yawAxis != null) {
  80808. newYawAxis = options.yawAxis.clone();
  80809. newYawAxis.normalize();
  80810. }
  80811. if (options.pitchAxis != null) {
  80812. newPitchAxis = options.pitchAxis.clone();
  80813. newPitchAxis.normalize();
  80814. }
  80815. var newRollAxis = BABYLON.Vector3.Cross(newPitchAxis, newYawAxis);
  80816. this._transformYawPitch = BABYLON.Matrix.Identity();
  80817. BABYLON.Matrix.FromXYZAxesToRef(newPitchAxis, newYawAxis, newRollAxis, this._transformYawPitch);
  80818. this._transformYawPitchInv = this._transformYawPitch.clone();
  80819. this._transformYawPitch.invert();
  80820. }
  80821. }
  80822. if (!bone.getParent() && this.upAxisSpace == BABYLON.Space.BONE) {
  80823. this.upAxisSpace = BABYLON.Space.LOCAL;
  80824. }
  80825. }
  80826. Object.defineProperty(BoneLookController.prototype, "minYaw", {
  80827. /**
  80828. * Gets or sets the minimum yaw angle that the bone can look to
  80829. */
  80830. get: function () {
  80831. return this._minYaw;
  80832. },
  80833. set: function (value) {
  80834. this._minYaw = value;
  80835. this._minYawSin = Math.sin(value);
  80836. this._minYawCos = Math.cos(value);
  80837. if (this._maxYaw != null) {
  80838. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80839. this._yawRange = this._maxYaw - this._minYaw;
  80840. }
  80841. },
  80842. enumerable: true,
  80843. configurable: true
  80844. });
  80845. Object.defineProperty(BoneLookController.prototype, "maxYaw", {
  80846. /**
  80847. * Gets or sets the maximum yaw angle that the bone can look to
  80848. */
  80849. get: function () {
  80850. return this._maxYaw;
  80851. },
  80852. set: function (value) {
  80853. this._maxYaw = value;
  80854. this._maxYawSin = Math.sin(value);
  80855. this._maxYawCos = Math.cos(value);
  80856. if (this._minYaw != null) {
  80857. this._midYawConstraint = this._getAngleDiff(this._minYaw, this._maxYaw) * .5 + this._minYaw;
  80858. this._yawRange = this._maxYaw - this._minYaw;
  80859. }
  80860. },
  80861. enumerable: true,
  80862. configurable: true
  80863. });
  80864. Object.defineProperty(BoneLookController.prototype, "minPitch", {
  80865. /**
  80866. * Gets or sets the minimum pitch angle that the bone can look to
  80867. */
  80868. get: function () {
  80869. return this._minPitch;
  80870. },
  80871. set: function (value) {
  80872. this._minPitch = value;
  80873. this._minPitchTan = Math.tan(value);
  80874. },
  80875. enumerable: true,
  80876. configurable: true
  80877. });
  80878. Object.defineProperty(BoneLookController.prototype, "maxPitch", {
  80879. /**
  80880. * Gets or sets the maximum pitch angle that the bone can look to
  80881. */
  80882. get: function () {
  80883. return this._maxPitch;
  80884. },
  80885. set: function (value) {
  80886. this._maxPitch = value;
  80887. this._maxPitchTan = Math.tan(value);
  80888. },
  80889. enumerable: true,
  80890. configurable: true
  80891. });
  80892. /**
  80893. * Update the bone to look at the target. This should be called before the scene is rendered (use scene.registerBeforeRender())
  80894. */
  80895. BoneLookController.prototype.update = function () {
  80896. //skip the first frame when slerping so that the mesh rotation is correct
  80897. if (this.slerpAmount < 1 && !this._firstFrameSkipped) {
  80898. this._firstFrameSkipped = true;
  80899. return;
  80900. }
  80901. var bone = this.bone;
  80902. var bonePos = BoneLookController._tmpVecs[0];
  80903. bone.getAbsolutePositionToRef(this.mesh, bonePos);
  80904. var target = this.target;
  80905. var _tmpMat1 = BoneLookController._tmpMats[0];
  80906. var _tmpMat2 = BoneLookController._tmpMats[1];
  80907. var mesh = this.mesh;
  80908. var parentBone = bone.getParent();
  80909. var upAxis = BoneLookController._tmpVecs[1];
  80910. upAxis.copyFrom(this.upAxis);
  80911. if (this.upAxisSpace == BABYLON.Space.BONE && parentBone) {
  80912. if (this._transformYawPitch) {
  80913. BABYLON.Vector3.TransformCoordinatesToRef(upAxis, this._transformYawPitchInv, upAxis);
  80914. }
  80915. parentBone.getDirectionToRef(upAxis, this.mesh, upAxis);
  80916. }
  80917. else if (this.upAxisSpace == BABYLON.Space.LOCAL) {
  80918. mesh.getDirectionToRef(upAxis, upAxis);
  80919. if (mesh.scaling.x != 1 || mesh.scaling.y != 1 || mesh.scaling.z != 1) {
  80920. upAxis.normalize();
  80921. }
  80922. }
  80923. var checkYaw = false;
  80924. var checkPitch = false;
  80925. if (this._maxYaw != Math.PI || this._minYaw != -Math.PI) {
  80926. checkYaw = true;
  80927. }
  80928. if (this._maxPitch != Math.PI || this._minPitch != -Math.PI) {
  80929. checkPitch = true;
  80930. }
  80931. if (checkYaw || checkPitch) {
  80932. var spaceMat = BoneLookController._tmpMats[2];
  80933. var spaceMatInv = BoneLookController._tmpMats[3];
  80934. if (this.upAxisSpace == BABYLON.Space.BONE && upAxis.y == 1 && parentBone) {
  80935. parentBone.getRotationMatrixToRef(BABYLON.Space.WORLD, this.mesh, spaceMat);
  80936. }
  80937. else if (this.upAxisSpace == BABYLON.Space.LOCAL && upAxis.y == 1 && !parentBone) {
  80938. spaceMat.copyFrom(mesh.getWorldMatrix());
  80939. }
  80940. else {
  80941. var forwardAxis = BoneLookController._tmpVecs[2];
  80942. forwardAxis.copyFrom(this._fowardAxis);
  80943. if (this._transformYawPitch) {
  80944. BABYLON.Vector3.TransformCoordinatesToRef(forwardAxis, this._transformYawPitchInv, forwardAxis);
  80945. }
  80946. if (parentBone) {
  80947. parentBone.getDirectionToRef(forwardAxis, this.mesh, forwardAxis);
  80948. }
  80949. else {
  80950. mesh.getDirectionToRef(forwardAxis, forwardAxis);
  80951. }
  80952. var rightAxis = BABYLON.Vector3.Cross(upAxis, forwardAxis);
  80953. rightAxis.normalize();
  80954. var forwardAxis = BABYLON.Vector3.Cross(rightAxis, upAxis);
  80955. BABYLON.Matrix.FromXYZAxesToRef(rightAxis, upAxis, forwardAxis, spaceMat);
  80956. }
  80957. spaceMat.invertToRef(spaceMatInv);
  80958. var xzlen = null;
  80959. if (checkPitch) {
  80960. var localTarget = BoneLookController._tmpVecs[3];
  80961. target.subtractToRef(bonePos, localTarget);
  80962. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80963. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80964. var pitch = Math.atan2(localTarget.y, xzlen);
  80965. var newPitch = pitch;
  80966. if (pitch > this._maxPitch) {
  80967. localTarget.y = this._maxPitchTan * xzlen;
  80968. newPitch = this._maxPitch;
  80969. }
  80970. else if (pitch < this._minPitch) {
  80971. localTarget.y = this._minPitchTan * xzlen;
  80972. newPitch = this._minPitch;
  80973. }
  80974. if (pitch != newPitch) {
  80975. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  80976. localTarget.addInPlace(bonePos);
  80977. target = localTarget;
  80978. }
  80979. }
  80980. if (checkYaw) {
  80981. var localTarget = BoneLookController._tmpVecs[4];
  80982. target.subtractToRef(bonePos, localTarget);
  80983. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMatInv, localTarget);
  80984. var yaw = Math.atan2(localTarget.x, localTarget.z);
  80985. var newYaw = yaw;
  80986. if (yaw > this._maxYaw || yaw < this._minYaw) {
  80987. if (xzlen == null) {
  80988. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  80989. }
  80990. if (this._yawRange > Math.PI) {
  80991. if (this._isAngleBetween(yaw, this._maxYaw, this._midYawConstraint)) {
  80992. localTarget.z = this._maxYawCos * xzlen;
  80993. localTarget.x = this._maxYawSin * xzlen;
  80994. newYaw = this._maxYaw;
  80995. }
  80996. else if (this._isAngleBetween(yaw, this._midYawConstraint, this._minYaw)) {
  80997. localTarget.z = this._minYawCos * xzlen;
  80998. localTarget.x = this._minYawSin * xzlen;
  80999. newYaw = this._minYaw;
  81000. }
  81001. }
  81002. else {
  81003. if (yaw > this._maxYaw) {
  81004. localTarget.z = this._maxYawCos * xzlen;
  81005. localTarget.x = this._maxYawSin * xzlen;
  81006. newYaw = this._maxYaw;
  81007. }
  81008. else if (yaw < this._minYaw) {
  81009. localTarget.z = this._minYawCos * xzlen;
  81010. localTarget.x = this._minYawSin * xzlen;
  81011. newYaw = this._minYaw;
  81012. }
  81013. }
  81014. }
  81015. if (this._slerping && this._yawRange > Math.PI) {
  81016. //are we going to be crossing into the min/max region?
  81017. var boneFwd = BoneLookController._tmpVecs[8];
  81018. boneFwd.copyFrom(BABYLON.Axis.Z);
  81019. if (this._transformYawPitch) {
  81020. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, this._transformYawPitchInv, boneFwd);
  81021. }
  81022. var boneRotMat = BoneLookController._tmpMats[4];
  81023. this._boneQuat.toRotationMatrix(boneRotMat);
  81024. this.mesh.getWorldMatrix().multiplyToRef(boneRotMat, boneRotMat);
  81025. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, boneRotMat, boneFwd);
  81026. BABYLON.Vector3.TransformCoordinatesToRef(boneFwd, spaceMatInv, boneFwd);
  81027. var boneYaw = Math.atan2(boneFwd.x, boneFwd.z);
  81028. var angBtwTar = this._getAngleBetween(boneYaw, yaw);
  81029. var angBtwMidYaw = this._getAngleBetween(boneYaw, this._midYawConstraint);
  81030. if (angBtwTar > angBtwMidYaw) {
  81031. if (xzlen == null) {
  81032. xzlen = Math.sqrt(localTarget.x * localTarget.x + localTarget.z * localTarget.z);
  81033. }
  81034. var angBtwMax = this._getAngleBetween(boneYaw, this._maxYaw);
  81035. var angBtwMin = this._getAngleBetween(boneYaw, this._minYaw);
  81036. if (angBtwMin < angBtwMax) {
  81037. newYaw = boneYaw + Math.PI * .75;
  81038. localTarget.z = Math.cos(newYaw) * xzlen;
  81039. localTarget.x = Math.sin(newYaw) * xzlen;
  81040. }
  81041. else {
  81042. newYaw = boneYaw - Math.PI * .75;
  81043. localTarget.z = Math.cos(newYaw) * xzlen;
  81044. localTarget.x = Math.sin(newYaw) * xzlen;
  81045. }
  81046. }
  81047. }
  81048. if (yaw != newYaw) {
  81049. BABYLON.Vector3.TransformCoordinatesToRef(localTarget, spaceMat, localTarget);
  81050. localTarget.addInPlace(bonePos);
  81051. target = localTarget;
  81052. }
  81053. }
  81054. }
  81055. var zaxis = BoneLookController._tmpVecs[5];
  81056. var xaxis = BoneLookController._tmpVecs[6];
  81057. var yaxis = BoneLookController._tmpVecs[7];
  81058. var _tmpQuat = BoneLookController._tmpQuat;
  81059. target.subtractToRef(bonePos, zaxis);
  81060. zaxis.normalize();
  81061. BABYLON.Vector3.CrossToRef(upAxis, zaxis, xaxis);
  81062. xaxis.normalize();
  81063. BABYLON.Vector3.CrossToRef(zaxis, xaxis, yaxis);
  81064. yaxis.normalize();
  81065. BABYLON.Matrix.FromXYZAxesToRef(xaxis, yaxis, zaxis, _tmpMat1);
  81066. if (xaxis.x === 0 && xaxis.y === 0 && xaxis.z === 0) {
  81067. return;
  81068. }
  81069. if (yaxis.x === 0 && yaxis.y === 0 && yaxis.z === 0) {
  81070. return;
  81071. }
  81072. if (zaxis.x === 0 && zaxis.y === 0 && zaxis.z === 0) {
  81073. return;
  81074. }
  81075. if (this.adjustYaw || this.adjustPitch || this.adjustRoll) {
  81076. BABYLON.Matrix.RotationYawPitchRollToRef(this.adjustYaw, this.adjustPitch, this.adjustRoll, _tmpMat2);
  81077. _tmpMat2.multiplyToRef(_tmpMat1, _tmpMat1);
  81078. }
  81079. if (this.slerpAmount < 1) {
  81080. if (!this._slerping) {
  81081. this.bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, this.mesh, this._boneQuat);
  81082. }
  81083. if (this._transformYawPitch) {
  81084. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81085. }
  81086. BABYLON.Quaternion.FromRotationMatrixToRef(_tmpMat1, _tmpQuat);
  81087. BABYLON.Quaternion.SlerpToRef(this._boneQuat, _tmpQuat, this.slerpAmount, this._boneQuat);
  81088. this.bone.setRotationQuaternion(this._boneQuat, BABYLON.Space.WORLD, this.mesh);
  81089. this._slerping = true;
  81090. }
  81091. else {
  81092. if (this._transformYawPitch) {
  81093. this._transformYawPitch.multiplyToRef(_tmpMat1, _tmpMat1);
  81094. }
  81095. this.bone.setRotationMatrix(_tmpMat1, BABYLON.Space.WORLD, this.mesh);
  81096. this._slerping = false;
  81097. }
  81098. };
  81099. BoneLookController.prototype._getAngleDiff = function (ang1, ang2) {
  81100. var angDiff = ang2 - ang1;
  81101. angDiff %= Math.PI * 2;
  81102. if (angDiff > Math.PI) {
  81103. angDiff -= Math.PI * 2;
  81104. }
  81105. else if (angDiff < -Math.PI) {
  81106. angDiff += Math.PI * 2;
  81107. }
  81108. return angDiff;
  81109. };
  81110. BoneLookController.prototype._getAngleBetween = function (ang1, ang2) {
  81111. ang1 %= (2 * Math.PI);
  81112. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81113. ang2 %= (2 * Math.PI);
  81114. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81115. var ab = 0;
  81116. if (ang1 < ang2) {
  81117. ab = ang2 - ang1;
  81118. }
  81119. else {
  81120. ab = ang1 - ang2;
  81121. }
  81122. if (ab > Math.PI) {
  81123. ab = Math.PI * 2 - ab;
  81124. }
  81125. return ab;
  81126. };
  81127. BoneLookController.prototype._isAngleBetween = function (ang, ang1, ang2) {
  81128. ang %= (2 * Math.PI);
  81129. ang = (ang < 0) ? ang + (2 * Math.PI) : ang;
  81130. ang1 %= (2 * Math.PI);
  81131. ang1 = (ang1 < 0) ? ang1 + (2 * Math.PI) : ang1;
  81132. ang2 %= (2 * Math.PI);
  81133. ang2 = (ang2 < 0) ? ang2 + (2 * Math.PI) : ang2;
  81134. if (ang1 < ang2) {
  81135. if (ang > ang1 && ang < ang2) {
  81136. return true;
  81137. }
  81138. }
  81139. else {
  81140. if (ang > ang2 && ang < ang1) {
  81141. return true;
  81142. }
  81143. }
  81144. return false;
  81145. };
  81146. 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()];
  81147. BoneLookController._tmpQuat = BABYLON.Quaternion.Identity();
  81148. BoneLookController._tmpMats = [BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity(), BABYLON.Matrix.Identity()];
  81149. return BoneLookController;
  81150. }());
  81151. BABYLON.BoneLookController = BoneLookController;
  81152. })(BABYLON || (BABYLON = {}));
  81153. //# sourceMappingURL=babylon.boneLookController.js.map
  81154. var BABYLON;
  81155. (function (BABYLON) {
  81156. /**
  81157. * Class used to handle skinning animations
  81158. * @see http://doc.babylonjs.com/how_to/how_to_use_bones_and_skeletons
  81159. */
  81160. var Skeleton = /** @class */ (function () {
  81161. /**
  81162. * Creates a new skeleton
  81163. * @param name defines the skeleton name
  81164. * @param id defines the skeleton Id
  81165. * @param scene defines the hosting scene
  81166. */
  81167. function Skeleton(
  81168. /** defines the skeleton name */
  81169. name,
  81170. /** defines the skeleton Id */
  81171. id, scene) {
  81172. this.name = name;
  81173. this.id = id;
  81174. /**
  81175. * Gets the list of child bones
  81176. */
  81177. this.bones = new Array();
  81178. /**
  81179. * Gets a boolean indicating if the root matrix is provided by meshes or by the current skeleton (this is the default value)
  81180. */
  81181. this.needInitialSkinMatrix = false;
  81182. this._isDirty = true;
  81183. this._meshesWithPoseMatrix = new Array();
  81184. this._identity = BABYLON.Matrix.Identity();
  81185. this._ranges = {};
  81186. this._lastAbsoluteTransformsUpdateId = -1;
  81187. /**
  81188. * Specifies if the skeleton should be serialized
  81189. */
  81190. this.doNotSerialize = false;
  81191. this._animationPropertiesOverride = null;
  81192. // Events
  81193. /**
  81194. * An observable triggered before computing the skeleton's matrices
  81195. */
  81196. this.onBeforeComputeObservable = new BABYLON.Observable();
  81197. this.bones = [];
  81198. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  81199. scene.skeletons.push(this);
  81200. //make sure it will recalculate the matrix next time prepare is called.
  81201. this._isDirty = true;
  81202. }
  81203. Object.defineProperty(Skeleton.prototype, "animationPropertiesOverride", {
  81204. /**
  81205. * Gets or sets the animation properties override
  81206. */
  81207. get: function () {
  81208. if (!this._animationPropertiesOverride) {
  81209. return this._scene.animationPropertiesOverride;
  81210. }
  81211. return this._animationPropertiesOverride;
  81212. },
  81213. set: function (value) {
  81214. this._animationPropertiesOverride = value;
  81215. },
  81216. enumerable: true,
  81217. configurable: true
  81218. });
  81219. // Members
  81220. /**
  81221. * Gets the list of transform matrices to send to shaders (one matrix per bone)
  81222. * @param mesh defines the mesh to use to get the root matrix (if needInitialSkinMatrix === true)
  81223. * @returns a Float32Array containing matrices data
  81224. */
  81225. Skeleton.prototype.getTransformMatrices = function (mesh) {
  81226. if (this.needInitialSkinMatrix && mesh._bonesTransformMatrices) {
  81227. return mesh._bonesTransformMatrices;
  81228. }
  81229. if (!this._transformMatrices) {
  81230. this.prepare();
  81231. }
  81232. return this._transformMatrices;
  81233. };
  81234. /**
  81235. * Gets the current hosting scene
  81236. * @returns a scene object
  81237. */
  81238. Skeleton.prototype.getScene = function () {
  81239. return this._scene;
  81240. };
  81241. // Methods
  81242. /**
  81243. * Gets a string representing the current skeleton data
  81244. * @param fullDetails defines a boolean indicating if we want a verbose version
  81245. * @returns a string representing the current skeleton data
  81246. */
  81247. Skeleton.prototype.toString = function (fullDetails) {
  81248. var ret = "Name: " + this.name + ", nBones: " + this.bones.length;
  81249. ret += ", nAnimationRanges: " + (this._ranges ? Object.keys(this._ranges).length : "none");
  81250. if (fullDetails) {
  81251. ret += ", Ranges: {";
  81252. var first = true;
  81253. for (var name_1 in this._ranges) {
  81254. if (first) {
  81255. ret += ", ";
  81256. first = false;
  81257. }
  81258. ret += name_1;
  81259. }
  81260. ret += "}";
  81261. }
  81262. return ret;
  81263. };
  81264. /**
  81265. * Get bone's index searching by name
  81266. * @param name defines bone's name to search for
  81267. * @return the indice of the bone. Returns -1 if not found
  81268. */
  81269. Skeleton.prototype.getBoneIndexByName = function (name) {
  81270. for (var boneIndex = 0, cache = this.bones.length; boneIndex < cache; boneIndex++) {
  81271. if (this.bones[boneIndex].name === name) {
  81272. return boneIndex;
  81273. }
  81274. }
  81275. return -1;
  81276. };
  81277. /**
  81278. * Creater a new animation range
  81279. * @param name defines the name of the range
  81280. * @param from defines the start key
  81281. * @param to defines the end key
  81282. */
  81283. Skeleton.prototype.createAnimationRange = function (name, from, to) {
  81284. // check name not already in use
  81285. if (!this._ranges[name]) {
  81286. this._ranges[name] = new BABYLON.AnimationRange(name, from, to);
  81287. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81288. if (this.bones[i].animations[0]) {
  81289. this.bones[i].animations[0].createRange(name, from, to);
  81290. }
  81291. }
  81292. }
  81293. };
  81294. /**
  81295. * Delete a specific animation range
  81296. * @param name defines the name of the range
  81297. * @param deleteFrames defines if frames must be removed as well
  81298. */
  81299. Skeleton.prototype.deleteAnimationRange = function (name, deleteFrames) {
  81300. if (deleteFrames === void 0) { deleteFrames = true; }
  81301. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81302. if (this.bones[i].animations[0]) {
  81303. this.bones[i].animations[0].deleteRange(name, deleteFrames);
  81304. }
  81305. }
  81306. this._ranges[name] = null; // said much faster than 'delete this._range[name]'
  81307. };
  81308. /**
  81309. * Gets a specific animation range
  81310. * @param name defines the name of the range to look for
  81311. * @returns the requested animation range or null if not found
  81312. */
  81313. Skeleton.prototype.getAnimationRange = function (name) {
  81314. return this._ranges[name];
  81315. };
  81316. /**
  81317. * Gets the list of all animation ranges defined on this skeleton
  81318. * @returns an array
  81319. */
  81320. Skeleton.prototype.getAnimationRanges = function () {
  81321. var animationRanges = [];
  81322. var name;
  81323. var i = 0;
  81324. for (name in this._ranges) {
  81325. animationRanges[i] = this._ranges[name];
  81326. i++;
  81327. }
  81328. return animationRanges;
  81329. };
  81330. /**
  81331. * Copy animation range from a source skeleton.
  81332. * This is not for a complete retargeting, only between very similar skeleton's with only possible bone length differences
  81333. * @param source defines the source skeleton
  81334. * @param name defines the name of the range to copy
  81335. * @param rescaleAsRequired defines if rescaling must be applied if required
  81336. * @returns true if operation was successful
  81337. */
  81338. Skeleton.prototype.copyAnimationRange = function (source, name, rescaleAsRequired) {
  81339. if (rescaleAsRequired === void 0) { rescaleAsRequired = false; }
  81340. if (this._ranges[name] || !source.getAnimationRange(name)) {
  81341. return false;
  81342. }
  81343. var ret = true;
  81344. var frameOffset = this._getHighestAnimationFrame() + 1;
  81345. // make a dictionary of source skeleton's bones, so exact same order or doublely nested loop is not required
  81346. var boneDict = {};
  81347. var sourceBones = source.bones;
  81348. var nBones;
  81349. var i;
  81350. for (i = 0, nBones = sourceBones.length; i < nBones; i++) {
  81351. boneDict[sourceBones[i].name] = sourceBones[i];
  81352. }
  81353. if (this.bones.length !== sourceBones.length) {
  81354. BABYLON.Tools.Warn("copyAnimationRange: this rig has " + this.bones.length + " bones, while source as " + sourceBones.length);
  81355. ret = false;
  81356. }
  81357. var skelDimensionsRatio = (rescaleAsRequired && this.dimensionsAtRest && source.dimensionsAtRest) ? this.dimensionsAtRest.divide(source.dimensionsAtRest) : null;
  81358. for (i = 0, nBones = this.bones.length; i < nBones; i++) {
  81359. var boneName = this.bones[i].name;
  81360. var sourceBone = boneDict[boneName];
  81361. if (sourceBone) {
  81362. ret = ret && this.bones[i].copyAnimationRange(sourceBone, name, frameOffset, rescaleAsRequired, skelDimensionsRatio);
  81363. }
  81364. else {
  81365. BABYLON.Tools.Warn("copyAnimationRange: not same rig, missing source bone " + boneName);
  81366. ret = false;
  81367. }
  81368. }
  81369. // do not call createAnimationRange(), since it also is done to bones, which was already done
  81370. var range = source.getAnimationRange(name);
  81371. if (range) {
  81372. this._ranges[name] = new BABYLON.AnimationRange(name, range.from + frameOffset, range.to + frameOffset);
  81373. }
  81374. return ret;
  81375. };
  81376. /**
  81377. * Forces the skeleton to go to rest pose
  81378. */
  81379. Skeleton.prototype.returnToRest = function () {
  81380. for (var index = 0; index < this.bones.length; index++) {
  81381. this.bones[index].returnToRest();
  81382. }
  81383. };
  81384. Skeleton.prototype._getHighestAnimationFrame = function () {
  81385. var ret = 0;
  81386. for (var i = 0, nBones = this.bones.length; i < nBones; i++) {
  81387. if (this.bones[i].animations[0]) {
  81388. var highest = this.bones[i].animations[0].getHighestFrame();
  81389. if (ret < highest) {
  81390. ret = highest;
  81391. }
  81392. }
  81393. }
  81394. return ret;
  81395. };
  81396. /**
  81397. * Begin a specific animation range
  81398. * @param name defines the name of the range to start
  81399. * @param loop defines if looping must be turned on (false by default)
  81400. * @param speedRatio defines the speed ratio to apply (1 by default)
  81401. * @param onAnimationEnd defines a callback which will be called when animation will end
  81402. * @returns a new animatable
  81403. */
  81404. Skeleton.prototype.beginAnimation = function (name, loop, speedRatio, onAnimationEnd) {
  81405. var range = this.getAnimationRange(name);
  81406. if (!range) {
  81407. return null;
  81408. }
  81409. return this._scene.beginAnimation(this, range.from, range.to, loop, speedRatio, onAnimationEnd);
  81410. };
  81411. /** @hidden */
  81412. Skeleton.prototype._markAsDirty = function () {
  81413. this._isDirty = true;
  81414. };
  81415. /** @hidden */
  81416. Skeleton.prototype._registerMeshWithPoseMatrix = function (mesh) {
  81417. this._meshesWithPoseMatrix.push(mesh);
  81418. };
  81419. /** @hidden */
  81420. Skeleton.prototype._unregisterMeshWithPoseMatrix = function (mesh) {
  81421. var index = this._meshesWithPoseMatrix.indexOf(mesh);
  81422. if (index > -1) {
  81423. this._meshesWithPoseMatrix.splice(index, 1);
  81424. }
  81425. };
  81426. /** @hidden */
  81427. Skeleton.prototype._computeTransformMatrices = function (targetMatrix, initialSkinMatrix) {
  81428. this.onBeforeComputeObservable.notifyObservers(this);
  81429. for (var index = 0; index < this.bones.length; index++) {
  81430. var bone = this.bones[index];
  81431. var parentBone = bone.getParent();
  81432. if (parentBone) {
  81433. bone.getLocalMatrix().multiplyToRef(parentBone.getWorldMatrix(), bone.getWorldMatrix());
  81434. }
  81435. else {
  81436. if (initialSkinMatrix) {
  81437. bone.getLocalMatrix().multiplyToRef(initialSkinMatrix, bone.getWorldMatrix());
  81438. }
  81439. else {
  81440. bone.getWorldMatrix().copyFrom(bone.getLocalMatrix());
  81441. }
  81442. }
  81443. if (bone._index !== -1) {
  81444. var mappedIndex = bone._index === null ? index : bone._index;
  81445. bone.getInvertedAbsoluteTransform().multiplyToArray(bone.getWorldMatrix(), targetMatrix, mappedIndex * 16);
  81446. }
  81447. }
  81448. this._identity.copyToArray(targetMatrix, this.bones.length * 16);
  81449. };
  81450. /**
  81451. * Build all resources required to render a skeleton
  81452. */
  81453. Skeleton.prototype.prepare = function () {
  81454. if (!this._isDirty) {
  81455. return;
  81456. }
  81457. if (this.needInitialSkinMatrix) {
  81458. for (var index = 0; index < this._meshesWithPoseMatrix.length; index++) {
  81459. var mesh = this._meshesWithPoseMatrix[index];
  81460. var poseMatrix = mesh.getPoseMatrix();
  81461. if (!mesh._bonesTransformMatrices || mesh._bonesTransformMatrices.length !== 16 * (this.bones.length + 1)) {
  81462. mesh._bonesTransformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81463. }
  81464. if (this._synchronizedWithMesh !== mesh) {
  81465. this._synchronizedWithMesh = mesh;
  81466. // Prepare bones
  81467. for (var boneIndex = 0; boneIndex < this.bones.length; boneIndex++) {
  81468. var bone = this.bones[boneIndex];
  81469. if (!bone.getParent()) {
  81470. var matrix = bone.getBaseMatrix();
  81471. matrix.multiplyToRef(poseMatrix, BABYLON.Tmp.Matrix[1]);
  81472. bone._updateDifferenceMatrix(BABYLON.Tmp.Matrix[1]);
  81473. }
  81474. }
  81475. }
  81476. this._computeTransformMatrices(mesh._bonesTransformMatrices, poseMatrix);
  81477. }
  81478. }
  81479. else {
  81480. if (!this._transformMatrices || this._transformMatrices.length !== 16 * (this.bones.length + 1)) {
  81481. this._transformMatrices = new Float32Array(16 * (this.bones.length + 1));
  81482. }
  81483. this._computeTransformMatrices(this._transformMatrices, null);
  81484. }
  81485. this._isDirty = false;
  81486. this._scene._activeBones.addCount(this.bones.length, false);
  81487. };
  81488. /**
  81489. * Gets the list of animatables currently running for this skeleton
  81490. * @returns an array of animatables
  81491. */
  81492. Skeleton.prototype.getAnimatables = function () {
  81493. if (!this._animatables || this._animatables.length !== this.bones.length) {
  81494. this._animatables = [];
  81495. for (var index = 0; index < this.bones.length; index++) {
  81496. this._animatables.push(this.bones[index]);
  81497. }
  81498. }
  81499. return this._animatables;
  81500. };
  81501. /**
  81502. * Clone the current skeleton
  81503. * @param name defines the name of the new skeleton
  81504. * @param id defines the id of the enw skeleton
  81505. * @returns the new skeleton
  81506. */
  81507. Skeleton.prototype.clone = function (name, id) {
  81508. var result = new Skeleton(name, id || name, this._scene);
  81509. result.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81510. for (var index = 0; index < this.bones.length; index++) {
  81511. var source = this.bones[index];
  81512. var parentBone = null;
  81513. var parent_1 = source.getParent();
  81514. if (parent_1) {
  81515. var parentIndex = this.bones.indexOf(parent_1);
  81516. parentBone = result.bones[parentIndex];
  81517. }
  81518. var bone = new BABYLON.Bone(source.name, result, parentBone, source.getBaseMatrix().clone(), source.getRestPose().clone());
  81519. BABYLON.Tools.DeepCopy(source.animations, bone.animations);
  81520. }
  81521. if (this._ranges) {
  81522. result._ranges = {};
  81523. for (var rangeName in this._ranges) {
  81524. var range = this._ranges[rangeName];
  81525. if (range) {
  81526. result._ranges[rangeName] = range.clone();
  81527. }
  81528. }
  81529. }
  81530. this._isDirty = true;
  81531. return result;
  81532. };
  81533. /**
  81534. * Enable animation blending for this skeleton
  81535. * @param blendingSpeed defines the blending speed to apply
  81536. * @see http://doc.babylonjs.com/babylon101/animations#animation-blending
  81537. */
  81538. Skeleton.prototype.enableBlending = function (blendingSpeed) {
  81539. if (blendingSpeed === void 0) { blendingSpeed = 0.01; }
  81540. this.bones.forEach(function (bone) {
  81541. bone.animations.forEach(function (animation) {
  81542. animation.enableBlending = true;
  81543. animation.blendingSpeed = blendingSpeed;
  81544. });
  81545. });
  81546. };
  81547. /**
  81548. * Releases all resources associated with the current skeleton
  81549. */
  81550. Skeleton.prototype.dispose = function () {
  81551. this._meshesWithPoseMatrix = [];
  81552. // Animations
  81553. this.getScene().stopAnimation(this);
  81554. // Remove from scene
  81555. this.getScene().removeSkeleton(this);
  81556. };
  81557. /**
  81558. * Serialize the skeleton in a JSON object
  81559. * @returns a JSON object
  81560. */
  81561. Skeleton.prototype.serialize = function () {
  81562. var serializationObject = {};
  81563. serializationObject.name = this.name;
  81564. serializationObject.id = this.id;
  81565. if (this.dimensionsAtRest) {
  81566. serializationObject.dimensionsAtRest = this.dimensionsAtRest.asArray();
  81567. }
  81568. serializationObject.bones = [];
  81569. serializationObject.needInitialSkinMatrix = this.needInitialSkinMatrix;
  81570. for (var index = 0; index < this.bones.length; index++) {
  81571. var bone = this.bones[index];
  81572. var parent_2 = bone.getParent();
  81573. var serializedBone = {
  81574. parentBoneIndex: parent_2 ? this.bones.indexOf(parent_2) : -1,
  81575. name: bone.name,
  81576. matrix: bone.getBaseMatrix().toArray(),
  81577. rest: bone.getRestPose().toArray()
  81578. };
  81579. serializationObject.bones.push(serializedBone);
  81580. if (bone.length) {
  81581. serializedBone.length = bone.length;
  81582. }
  81583. if (bone.metadata) {
  81584. serializedBone.metadata = bone.metadata;
  81585. }
  81586. if (bone.animations && bone.animations.length > 0) {
  81587. serializedBone.animation = bone.animations[0].serialize();
  81588. }
  81589. serializationObject.ranges = [];
  81590. for (var name in this._ranges) {
  81591. var source = this._ranges[name];
  81592. if (!source) {
  81593. continue;
  81594. }
  81595. var range = {};
  81596. range.name = name;
  81597. range.from = source.from;
  81598. range.to = source.to;
  81599. serializationObject.ranges.push(range);
  81600. }
  81601. }
  81602. return serializationObject;
  81603. };
  81604. /**
  81605. * Creates a new skeleton from serialized data
  81606. * @param parsedSkeleton defines the serialized data
  81607. * @param scene defines the hosting scene
  81608. * @returns a new skeleton
  81609. */
  81610. Skeleton.Parse = function (parsedSkeleton, scene) {
  81611. var skeleton = new Skeleton(parsedSkeleton.name, parsedSkeleton.id, scene);
  81612. if (parsedSkeleton.dimensionsAtRest) {
  81613. skeleton.dimensionsAtRest = BABYLON.Vector3.FromArray(parsedSkeleton.dimensionsAtRest);
  81614. }
  81615. skeleton.needInitialSkinMatrix = parsedSkeleton.needInitialSkinMatrix;
  81616. var index;
  81617. for (index = 0; index < parsedSkeleton.bones.length; index++) {
  81618. var parsedBone = parsedSkeleton.bones[index];
  81619. var parentBone = null;
  81620. if (parsedBone.parentBoneIndex > -1) {
  81621. parentBone = skeleton.bones[parsedBone.parentBoneIndex];
  81622. }
  81623. var rest = parsedBone.rest ? BABYLON.Matrix.FromArray(parsedBone.rest) : null;
  81624. var bone = new BABYLON.Bone(parsedBone.name, skeleton, parentBone, BABYLON.Matrix.FromArray(parsedBone.matrix), rest);
  81625. if (parsedBone.length) {
  81626. bone.length = parsedBone.length;
  81627. }
  81628. if (parsedBone.metadata) {
  81629. bone.metadata = parsedBone.metadata;
  81630. }
  81631. if (parsedBone.animation) {
  81632. bone.animations.push(BABYLON.Animation.Parse(parsedBone.animation));
  81633. }
  81634. }
  81635. // placed after bones, so createAnimationRange can cascade down
  81636. if (parsedSkeleton.ranges) {
  81637. for (index = 0; index < parsedSkeleton.ranges.length; index++) {
  81638. var data = parsedSkeleton.ranges[index];
  81639. skeleton.createAnimationRange(data.name, data.from, data.to);
  81640. }
  81641. }
  81642. return skeleton;
  81643. };
  81644. /**
  81645. * Compute all node absolute transforms
  81646. * @param forceUpdate defines if computation must be done even if cache is up to date
  81647. */
  81648. Skeleton.prototype.computeAbsoluteTransforms = function (forceUpdate) {
  81649. if (forceUpdate === void 0) { forceUpdate = false; }
  81650. var renderId = this._scene.getRenderId();
  81651. if (this._lastAbsoluteTransformsUpdateId != renderId || forceUpdate) {
  81652. this.bones[0].computeAbsoluteTransforms();
  81653. this._lastAbsoluteTransformsUpdateId = renderId;
  81654. }
  81655. };
  81656. /**
  81657. * Gets the root pose matrix
  81658. * @returns a matrix
  81659. */
  81660. Skeleton.prototype.getPoseMatrix = function () {
  81661. var poseMatrix = null;
  81662. if (this._meshesWithPoseMatrix.length > 0) {
  81663. poseMatrix = this._meshesWithPoseMatrix[0].getPoseMatrix();
  81664. }
  81665. return poseMatrix;
  81666. };
  81667. /**
  81668. * Sorts bones per internal index
  81669. */
  81670. Skeleton.prototype.sortBones = function () {
  81671. var bones = new Array();
  81672. var visited = new Array(this.bones.length);
  81673. for (var index = 0; index < this.bones.length; index++) {
  81674. this._sortBones(index, bones, visited);
  81675. }
  81676. this.bones = bones;
  81677. };
  81678. Skeleton.prototype._sortBones = function (index, bones, visited) {
  81679. if (visited[index]) {
  81680. return;
  81681. }
  81682. visited[index] = true;
  81683. var bone = this.bones[index];
  81684. if (bone._index === undefined) {
  81685. bone._index = index;
  81686. }
  81687. var parentBone = bone.getParent();
  81688. if (parentBone) {
  81689. this._sortBones(this.bones.indexOf(parentBone), bones, visited);
  81690. }
  81691. bones.push(bone);
  81692. };
  81693. return Skeleton;
  81694. }());
  81695. BABYLON.Skeleton = Skeleton;
  81696. })(BABYLON || (BABYLON = {}));
  81697. //# sourceMappingURL=babylon.skeleton.js.map
  81698. var BABYLON;
  81699. (function (BABYLON) {
  81700. var SphericalPolynomial = /** @class */ (function () {
  81701. function SphericalPolynomial() {
  81702. this.x = BABYLON.Vector3.Zero();
  81703. this.y = BABYLON.Vector3.Zero();
  81704. this.z = BABYLON.Vector3.Zero();
  81705. this.xx = BABYLON.Vector3.Zero();
  81706. this.yy = BABYLON.Vector3.Zero();
  81707. this.zz = BABYLON.Vector3.Zero();
  81708. this.xy = BABYLON.Vector3.Zero();
  81709. this.yz = BABYLON.Vector3.Zero();
  81710. this.zx = BABYLON.Vector3.Zero();
  81711. }
  81712. SphericalPolynomial.prototype.addAmbient = function (color) {
  81713. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81714. this.xx = this.xx.add(colorVector);
  81715. this.yy = this.yy.add(colorVector);
  81716. this.zz = this.zz.add(colorVector);
  81717. };
  81718. SphericalPolynomial.getSphericalPolynomialFromHarmonics = function (harmonics) {
  81719. var result = new SphericalPolynomial();
  81720. result.x = harmonics.L11.scale(1.02333);
  81721. result.y = harmonics.L1_1.scale(1.02333);
  81722. result.z = harmonics.L10.scale(1.02333);
  81723. result.xx = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).add(harmonics.L22.scale(0.429043));
  81724. result.yy = harmonics.L00.scale(0.886277).subtract(harmonics.L20.scale(0.247708)).subtract(harmonics.L22.scale(0.429043));
  81725. result.zz = harmonics.L00.scale(0.886277).add(harmonics.L20.scale(0.495417));
  81726. result.yz = harmonics.L2_1.scale(0.858086);
  81727. result.zx = harmonics.L21.scale(0.858086);
  81728. result.xy = harmonics.L2_2.scale(0.858086);
  81729. result.scale(1.0 / Math.PI);
  81730. return result;
  81731. };
  81732. SphericalPolynomial.prototype.scale = function (scale) {
  81733. this.x = this.x.scale(scale);
  81734. this.y = this.y.scale(scale);
  81735. this.z = this.z.scale(scale);
  81736. this.xx = this.xx.scale(scale);
  81737. this.yy = this.yy.scale(scale);
  81738. this.zz = this.zz.scale(scale);
  81739. this.yz = this.yz.scale(scale);
  81740. this.zx = this.zx.scale(scale);
  81741. this.xy = this.xy.scale(scale);
  81742. };
  81743. return SphericalPolynomial;
  81744. }());
  81745. BABYLON.SphericalPolynomial = SphericalPolynomial;
  81746. var SphericalHarmonics = /** @class */ (function () {
  81747. function SphericalHarmonics() {
  81748. this.L00 = BABYLON.Vector3.Zero();
  81749. this.L1_1 = BABYLON.Vector3.Zero();
  81750. this.L10 = BABYLON.Vector3.Zero();
  81751. this.L11 = BABYLON.Vector3.Zero();
  81752. this.L2_2 = BABYLON.Vector3.Zero();
  81753. this.L2_1 = BABYLON.Vector3.Zero();
  81754. this.L20 = BABYLON.Vector3.Zero();
  81755. this.L21 = BABYLON.Vector3.Zero();
  81756. this.L22 = BABYLON.Vector3.Zero();
  81757. }
  81758. SphericalHarmonics.prototype.addLight = function (direction, color, deltaSolidAngle) {
  81759. var colorVector = new BABYLON.Vector3(color.r, color.g, color.b);
  81760. var c = colorVector.scale(deltaSolidAngle);
  81761. this.L00 = this.L00.add(c.scale(0.282095));
  81762. this.L1_1 = this.L1_1.add(c.scale(0.488603 * direction.y));
  81763. this.L10 = this.L10.add(c.scale(0.488603 * direction.z));
  81764. this.L11 = this.L11.add(c.scale(0.488603 * direction.x));
  81765. this.L2_2 = this.L2_2.add(c.scale(1.092548 * direction.x * direction.y));
  81766. this.L2_1 = this.L2_1.add(c.scale(1.092548 * direction.y * direction.z));
  81767. this.L21 = this.L21.add(c.scale(1.092548 * direction.x * direction.z));
  81768. this.L20 = this.L20.add(c.scale(0.315392 * (3.0 * direction.z * direction.z - 1.0)));
  81769. this.L22 = this.L22.add(c.scale(0.546274 * (direction.x * direction.x - direction.y * direction.y)));
  81770. };
  81771. SphericalHarmonics.prototype.scale = function (scale) {
  81772. this.L00 = this.L00.scale(scale);
  81773. this.L1_1 = this.L1_1.scale(scale);
  81774. this.L10 = this.L10.scale(scale);
  81775. this.L11 = this.L11.scale(scale);
  81776. this.L2_2 = this.L2_2.scale(scale);
  81777. this.L2_1 = this.L2_1.scale(scale);
  81778. this.L20 = this.L20.scale(scale);
  81779. this.L21 = this.L21.scale(scale);
  81780. this.L22 = this.L22.scale(scale);
  81781. };
  81782. SphericalHarmonics.prototype.convertIncidentRadianceToIrradiance = function () {
  81783. // Convert from incident radiance (Li) to irradiance (E) by applying convolution with the cosine-weighted hemisphere.
  81784. //
  81785. // E_lm = A_l * L_lm
  81786. //
  81787. // In spherical harmonics this convolution amounts to scaling factors for each frequency band.
  81788. // This corresponds to equation 5 in "An Efficient Representation for Irradiance Environment Maps", where
  81789. // the scaling factors are given in equation 9.
  81790. // Constant (Band 0)
  81791. this.L00 = this.L00.scale(3.141593);
  81792. // Linear (Band 1)
  81793. this.L1_1 = this.L1_1.scale(2.094395);
  81794. this.L10 = this.L10.scale(2.094395);
  81795. this.L11 = this.L11.scale(2.094395);
  81796. // Quadratic (Band 2)
  81797. this.L2_2 = this.L2_2.scale(0.785398);
  81798. this.L2_1 = this.L2_1.scale(0.785398);
  81799. this.L20 = this.L20.scale(0.785398);
  81800. this.L21 = this.L21.scale(0.785398);
  81801. this.L22 = this.L22.scale(0.785398);
  81802. };
  81803. SphericalHarmonics.prototype.convertIrradianceToLambertianRadiance = function () {
  81804. // Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  81805. // L = (1/pi) * E * rho
  81806. //
  81807. // This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  81808. this.scale(1.0 / Math.PI);
  81809. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  81810. // (The pixel shader must apply albedo after texture fetches, etc).
  81811. };
  81812. SphericalHarmonics.getsphericalHarmonicsFromPolynomial = function (polynomial) {
  81813. var result = new SphericalHarmonics();
  81814. result.L00 = polynomial.xx.scale(0.376127).add(polynomial.yy.scale(0.376127)).add(polynomial.zz.scale(0.376126));
  81815. result.L1_1 = polynomial.y.scale(0.977204);
  81816. result.L10 = polynomial.z.scale(0.977204);
  81817. result.L11 = polynomial.x.scale(0.977204);
  81818. result.L2_2 = polynomial.xy.scale(1.16538);
  81819. result.L2_1 = polynomial.yz.scale(1.16538);
  81820. result.L20 = polynomial.zz.scale(1.34567).subtract(polynomial.xx.scale(0.672834)).subtract(polynomial.yy.scale(0.672834));
  81821. result.L21 = polynomial.zx.scale(1.16538);
  81822. result.L22 = polynomial.xx.scale(1.16538).subtract(polynomial.yy.scale(1.16538));
  81823. result.scale(Math.PI);
  81824. return result;
  81825. };
  81826. return SphericalHarmonics;
  81827. }());
  81828. BABYLON.SphericalHarmonics = SphericalHarmonics;
  81829. })(BABYLON || (BABYLON = {}));
  81830. //# sourceMappingURL=babylon.sphericalPolynomial.js.map
  81831. var BABYLON;
  81832. (function (BABYLON) {
  81833. var FileFaceOrientation = /** @class */ (function () {
  81834. function FileFaceOrientation(name, worldAxisForNormal, worldAxisForFileX, worldAxisForFileY) {
  81835. this.name = name;
  81836. this.worldAxisForNormal = worldAxisForNormal;
  81837. this.worldAxisForFileX = worldAxisForFileX;
  81838. this.worldAxisForFileY = worldAxisForFileY;
  81839. }
  81840. return FileFaceOrientation;
  81841. }());
  81842. ;
  81843. /**
  81844. * Helper class dealing with the extraction of spherical polynomial dataArray
  81845. * from a cube map.
  81846. */
  81847. var CubeMapToSphericalPolynomialTools = /** @class */ (function () {
  81848. function CubeMapToSphericalPolynomialTools() {
  81849. }
  81850. /**
  81851. * Converts a texture to the according Spherical Polynomial data.
  81852. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81853. *
  81854. * @param texture The texture to extract the information from.
  81855. * @return The Spherical Polynomial data.
  81856. */
  81857. CubeMapToSphericalPolynomialTools.ConvertCubeMapTextureToSphericalPolynomial = function (texture) {
  81858. if (!texture.isCube) {
  81859. // Only supports cube Textures currently.
  81860. return null;
  81861. }
  81862. var size = texture.getSize().width;
  81863. var right = texture.readPixels(0);
  81864. var left = texture.readPixels(1);
  81865. var up;
  81866. var down;
  81867. if (texture.isRenderTarget) {
  81868. up = texture.readPixels(3);
  81869. down = texture.readPixels(2);
  81870. }
  81871. else {
  81872. up = texture.readPixels(2);
  81873. down = texture.readPixels(3);
  81874. }
  81875. var front = texture.readPixels(4);
  81876. var back = texture.readPixels(5);
  81877. var gammaSpace = texture.gammaSpace;
  81878. // Always read as RGBA.
  81879. var format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  81880. var type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  81881. if (texture.textureType && texture.textureType !== BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81882. type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  81883. }
  81884. var cubeInfo = {
  81885. size: size,
  81886. right: right,
  81887. left: left,
  81888. up: up,
  81889. down: down,
  81890. front: front,
  81891. back: back,
  81892. format: format,
  81893. type: type,
  81894. gammaSpace: gammaSpace,
  81895. };
  81896. return this.ConvertCubeMapToSphericalPolynomial(cubeInfo);
  81897. };
  81898. /**
  81899. * Converts a cubemap to the according Spherical Polynomial data.
  81900. * This extracts the first 3 orders only as they are the only one used in the lighting.
  81901. *
  81902. * @param cubeInfo The Cube map to extract the information from.
  81903. * @return The Spherical Polynomial data.
  81904. */
  81905. CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial = function (cubeInfo) {
  81906. var sphericalHarmonics = new BABYLON.SphericalHarmonics();
  81907. var totalSolidAngle = 0.0;
  81908. // The (u,v) range is [-1,+1], so the distance between each texel is 2/Size.
  81909. var du = 2.0 / cubeInfo.size;
  81910. var dv = du;
  81911. // The (u,v) of the first texel is half a texel from the corner (-1,-1).
  81912. var minUV = du * 0.5 - 1.0;
  81913. for (var faceIndex = 0; faceIndex < 6; faceIndex++) {
  81914. var fileFace = this.FileFaces[faceIndex];
  81915. var dataArray = cubeInfo[fileFace.name];
  81916. var v = minUV;
  81917. // TODO: we could perform the summation directly into a SphericalPolynomial (SP), which is more efficient than SphericalHarmonic (SH).
  81918. // This is possible because during the summation we do not need the SH-specific properties, e.g. orthogonality.
  81919. // Because SP is still linear, so summation is fine in that basis.
  81920. var stride = cubeInfo.format === BABYLON.Engine.TEXTUREFORMAT_RGBA ? 4 : 3;
  81921. for (var y = 0; y < cubeInfo.size; y++) {
  81922. var u = minUV;
  81923. for (var x = 0; x < cubeInfo.size; x++) {
  81924. // World direction (not normalised)
  81925. var worldDirection = fileFace.worldAxisForFileX.scale(u).add(fileFace.worldAxisForFileY.scale(v)).add(fileFace.worldAxisForNormal);
  81926. worldDirection.normalize();
  81927. var deltaSolidAngle = Math.pow(1.0 + u * u + v * v, -3.0 / 2.0);
  81928. var r = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 0];
  81929. var g = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 1];
  81930. var b = dataArray[(y * cubeInfo.size * stride) + (x * stride) + 2];
  81931. // Handle Integer types.
  81932. if (cubeInfo.type === BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT) {
  81933. r /= 255;
  81934. g /= 255;
  81935. b /= 255;
  81936. }
  81937. // Handle Gamma space textures.
  81938. if (cubeInfo.gammaSpace) {
  81939. r = Math.pow(BABYLON.Scalar.Clamp(r), BABYLON.ToLinearSpace);
  81940. g = Math.pow(BABYLON.Scalar.Clamp(g), BABYLON.ToLinearSpace);
  81941. b = Math.pow(BABYLON.Scalar.Clamp(b), BABYLON.ToLinearSpace);
  81942. }
  81943. var color = new BABYLON.Color3(r, g, b);
  81944. sphericalHarmonics.addLight(worldDirection, color, deltaSolidAngle);
  81945. totalSolidAngle += deltaSolidAngle;
  81946. u += du;
  81947. }
  81948. v += dv;
  81949. }
  81950. }
  81951. // Solid angle for entire sphere is 4*pi
  81952. var sphereSolidAngle = 4.0 * Math.PI;
  81953. // Adjust the solid angle to allow for how many faces we processed.
  81954. var facesProcessed = 6.0;
  81955. var expectedSolidAngle = sphereSolidAngle * facesProcessed / 6.0;
  81956. // Adjust the harmonics so that the accumulated solid angle matches the expected solid angle.
  81957. // This is needed because the numerical integration over the cube uses a
  81958. // small angle approximation of solid angle for each texel (see deltaSolidAngle),
  81959. // and also to compensate for accumulative error due to float precision in the summation.
  81960. var correctionFactor = expectedSolidAngle / totalSolidAngle;
  81961. sphericalHarmonics.scale(correctionFactor);
  81962. sphericalHarmonics.convertIncidentRadianceToIrradiance();
  81963. sphericalHarmonics.convertIrradianceToLambertianRadiance();
  81964. return BABYLON.SphericalPolynomial.getSphericalPolynomialFromHarmonics(sphericalHarmonics);
  81965. };
  81966. CubeMapToSphericalPolynomialTools.FileFaces = [
  81967. new FileFaceOrientation("right", new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(0, -1, 0)),
  81968. new FileFaceOrientation("left", new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(0, -1, 0)),
  81969. new FileFaceOrientation("up", new BABYLON.Vector3(0, 1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, 1)),
  81970. new FileFaceOrientation("down", new BABYLON.Vector3(0, -1, 0), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, 0, -1)),
  81971. new FileFaceOrientation("front", new BABYLON.Vector3(0, 0, 1), new BABYLON.Vector3(1, 0, 0), new BABYLON.Vector3(0, -1, 0)),
  81972. new FileFaceOrientation("back", new BABYLON.Vector3(0, 0, -1), new BABYLON.Vector3(-1, 0, 0), new BABYLON.Vector3(0, -1, 0)) // -Z bottom
  81973. ];
  81974. return CubeMapToSphericalPolynomialTools;
  81975. }());
  81976. BABYLON.CubeMapToSphericalPolynomialTools = CubeMapToSphericalPolynomialTools;
  81977. })(BABYLON || (BABYLON = {}));
  81978. //# sourceMappingURL=babylon.cubemapToSphericalPolynomial.js.map
  81979. var BABYLON;
  81980. (function (BABYLON) {
  81981. /**
  81982. * Helper class usefull to convert panorama picture to their cubemap representation in 6 faces.
  81983. */
  81984. var PanoramaToCubeMapTools = /** @class */ (function () {
  81985. function PanoramaToCubeMapTools() {
  81986. }
  81987. /**
  81988. * Converts a panorma stored in RGB right to left up to down format into a cubemap (6 faces).
  81989. *
  81990. * @param float32Array The source data.
  81991. * @param inputWidth The width of the input panorama.
  81992. * @param inputhHeight The height of the input panorama.
  81993. * @param size The willing size of the generated cubemap (each faces will be size * size pixels)
  81994. * @return The cubemap data
  81995. */
  81996. PanoramaToCubeMapTools.ConvertPanoramaToCubemap = function (float32Array, inputWidth, inputHeight, size) {
  81997. if (!float32Array) {
  81998. throw "ConvertPanoramaToCubemap: input cannot be null";
  81999. }
  82000. if (float32Array.length != inputWidth * inputHeight * 3) {
  82001. throw "ConvertPanoramaToCubemap: input size is wrong";
  82002. }
  82003. var textureFront = this.CreateCubemapTexture(size, this.FACE_FRONT, float32Array, inputWidth, inputHeight);
  82004. var textureBack = this.CreateCubemapTexture(size, this.FACE_BACK, float32Array, inputWidth, inputHeight);
  82005. var textureLeft = this.CreateCubemapTexture(size, this.FACE_LEFT, float32Array, inputWidth, inputHeight);
  82006. var textureRight = this.CreateCubemapTexture(size, this.FACE_RIGHT, float32Array, inputWidth, inputHeight);
  82007. var textureUp = this.CreateCubemapTexture(size, this.FACE_UP, float32Array, inputWidth, inputHeight);
  82008. var textureDown = this.CreateCubemapTexture(size, this.FACE_DOWN, float32Array, inputWidth, inputHeight);
  82009. return {
  82010. front: textureFront,
  82011. back: textureBack,
  82012. left: textureLeft,
  82013. right: textureRight,
  82014. up: textureUp,
  82015. down: textureDown,
  82016. size: size,
  82017. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  82018. format: BABYLON.Engine.TEXTUREFORMAT_RGB,
  82019. gammaSpace: false,
  82020. };
  82021. };
  82022. PanoramaToCubeMapTools.CreateCubemapTexture = function (texSize, faceData, float32Array, inputWidth, inputHeight) {
  82023. var buffer = new ArrayBuffer(texSize * texSize * 4 * 3);
  82024. var textureArray = new Float32Array(buffer);
  82025. var rotDX1 = faceData[1].subtract(faceData[0]).scale(1 / texSize);
  82026. var rotDX2 = faceData[3].subtract(faceData[2]).scale(1 / texSize);
  82027. var dy = 1 / texSize;
  82028. var fy = 0;
  82029. for (var y = 0; y < texSize; y++) {
  82030. var xv1 = faceData[0];
  82031. var xv2 = faceData[2];
  82032. for (var x = 0; x < texSize; x++) {
  82033. var v = xv2.subtract(xv1).scale(fy).add(xv1);
  82034. v.normalize();
  82035. var color = this.CalcProjectionSpherical(v, float32Array, inputWidth, inputHeight);
  82036. // 3 channels per pixels
  82037. textureArray[y * texSize * 3 + (x * 3) + 0] = color.r;
  82038. textureArray[y * texSize * 3 + (x * 3) + 1] = color.g;
  82039. textureArray[y * texSize * 3 + (x * 3) + 2] = color.b;
  82040. xv1 = xv1.add(rotDX1);
  82041. xv2 = xv2.add(rotDX2);
  82042. }
  82043. fy += dy;
  82044. }
  82045. return textureArray;
  82046. };
  82047. PanoramaToCubeMapTools.CalcProjectionSpherical = function (vDir, float32Array, inputWidth, inputHeight) {
  82048. var theta = Math.atan2(vDir.z, vDir.x);
  82049. var phi = Math.acos(vDir.y);
  82050. while (theta < -Math.PI)
  82051. theta += 2 * Math.PI;
  82052. while (theta > Math.PI)
  82053. theta -= 2 * Math.PI;
  82054. var dx = theta / Math.PI;
  82055. var dy = phi / Math.PI;
  82056. // recenter.
  82057. dx = dx * 0.5 + 0.5;
  82058. var px = Math.round(dx * inputWidth);
  82059. if (px < 0)
  82060. px = 0;
  82061. else if (px >= inputWidth)
  82062. px = inputWidth - 1;
  82063. var py = Math.round(dy * inputHeight);
  82064. if (py < 0)
  82065. py = 0;
  82066. else if (py >= inputHeight)
  82067. py = inputHeight - 1;
  82068. var inputY = (inputHeight - py - 1);
  82069. var r = float32Array[inputY * inputWidth * 3 + (px * 3) + 0];
  82070. var g = float32Array[inputY * inputWidth * 3 + (px * 3) + 1];
  82071. var b = float32Array[inputY * inputWidth * 3 + (px * 3) + 2];
  82072. return {
  82073. r: r,
  82074. g: g,
  82075. b: b
  82076. };
  82077. };
  82078. PanoramaToCubeMapTools.FACE_FRONT = [
  82079. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82080. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82081. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82082. new BABYLON.Vector3(1.0, 1.0, -1.0)
  82083. ];
  82084. PanoramaToCubeMapTools.FACE_BACK = [
  82085. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82086. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82087. new BABYLON.Vector3(1.0, 1.0, 1.0),
  82088. new BABYLON.Vector3(-1.0, 1.0, 1.0)
  82089. ];
  82090. PanoramaToCubeMapTools.FACE_RIGHT = [
  82091. new BABYLON.Vector3(1.0, -1.0, -1.0),
  82092. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82093. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82094. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82095. ];
  82096. PanoramaToCubeMapTools.FACE_LEFT = [
  82097. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82098. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82099. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82100. new BABYLON.Vector3(-1.0, 1.0, -1.0)
  82101. ];
  82102. PanoramaToCubeMapTools.FACE_DOWN = [
  82103. new BABYLON.Vector3(-1.0, 1.0, -1.0),
  82104. new BABYLON.Vector3(1.0, 1.0, -1.0),
  82105. new BABYLON.Vector3(-1.0, 1.0, 1.0),
  82106. new BABYLON.Vector3(1.0, 1.0, 1.0)
  82107. ];
  82108. PanoramaToCubeMapTools.FACE_UP = [
  82109. new BABYLON.Vector3(-1.0, -1.0, 1.0),
  82110. new BABYLON.Vector3(1.0, -1.0, 1.0),
  82111. new BABYLON.Vector3(-1.0, -1.0, -1.0),
  82112. new BABYLON.Vector3(1.0, -1.0, -1.0)
  82113. ];
  82114. return PanoramaToCubeMapTools;
  82115. }());
  82116. BABYLON.PanoramaToCubeMapTools = PanoramaToCubeMapTools;
  82117. })(BABYLON || (BABYLON = {}));
  82118. //# sourceMappingURL=babylon.panoramaToCubemap.js.map
  82119. var BABYLON;
  82120. (function (BABYLON) {
  82121. ;
  82122. /**
  82123. * This groups tools to convert HDR texture to native colors array.
  82124. */
  82125. var HDRTools = /** @class */ (function () {
  82126. function HDRTools() {
  82127. }
  82128. HDRTools.Ldexp = function (mantissa, exponent) {
  82129. if (exponent > 1023) {
  82130. return mantissa * Math.pow(2, 1023) * Math.pow(2, exponent - 1023);
  82131. }
  82132. if (exponent < -1074) {
  82133. return mantissa * Math.pow(2, -1074) * Math.pow(2, exponent + 1074);
  82134. }
  82135. return mantissa * Math.pow(2, exponent);
  82136. };
  82137. HDRTools.Rgbe2float = function (float32array, red, green, blue, exponent, index) {
  82138. if (exponent > 0) { /*nonzero pixel*/
  82139. exponent = this.Ldexp(1.0, exponent - (128 + 8));
  82140. float32array[index + 0] = red * exponent;
  82141. float32array[index + 1] = green * exponent;
  82142. float32array[index + 2] = blue * exponent;
  82143. }
  82144. else {
  82145. float32array[index + 0] = 0;
  82146. float32array[index + 1] = 0;
  82147. float32array[index + 2] = 0;
  82148. }
  82149. };
  82150. HDRTools.readStringLine = function (uint8array, startIndex) {
  82151. var line = "";
  82152. var character = "";
  82153. for (var i = startIndex; i < uint8array.length - startIndex; i++) {
  82154. character = String.fromCharCode(uint8array[i]);
  82155. if (character == "\n") {
  82156. break;
  82157. }
  82158. line += character;
  82159. }
  82160. return line;
  82161. };
  82162. /**
  82163. * Reads header information from an RGBE texture stored in a native array.
  82164. * More information on this format are available here:
  82165. * https://en.wikipedia.org/wiki/RGBE_image_format
  82166. *
  82167. * @param uint8array The binary file stored in native array.
  82168. * @return The header information.
  82169. */
  82170. HDRTools.RGBE_ReadHeader = function (uint8array) {
  82171. var height = 0;
  82172. var width = 0;
  82173. var line = this.readStringLine(uint8array, 0);
  82174. if (line[0] != '#' || line[1] != '?') {
  82175. throw "Bad HDR Format.";
  82176. }
  82177. var endOfHeader = false;
  82178. var findFormat = false;
  82179. var lineIndex = 0;
  82180. do {
  82181. lineIndex += (line.length + 1);
  82182. line = this.readStringLine(uint8array, lineIndex);
  82183. if (line == "FORMAT=32-bit_rle_rgbe") {
  82184. findFormat = true;
  82185. }
  82186. else if (line.length == 0) {
  82187. endOfHeader = true;
  82188. }
  82189. } while (!endOfHeader);
  82190. if (!findFormat) {
  82191. throw "HDR Bad header format, unsupported FORMAT";
  82192. }
  82193. lineIndex += (line.length + 1);
  82194. line = this.readStringLine(uint8array, lineIndex);
  82195. var sizeRegexp = /^\-Y (.*) \+X (.*)$/g;
  82196. var match = sizeRegexp.exec(line);
  82197. // TODO. Support +Y and -X if needed.
  82198. if (!match || match.length < 3) {
  82199. throw "HDR Bad header format, no size";
  82200. }
  82201. width = parseInt(match[2]);
  82202. height = parseInt(match[1]);
  82203. if (width < 8 || width > 0x7fff) {
  82204. throw "HDR Bad header format, unsupported size";
  82205. }
  82206. lineIndex += (line.length + 1);
  82207. return {
  82208. height: height,
  82209. width: width,
  82210. dataPosition: lineIndex
  82211. };
  82212. };
  82213. /**
  82214. * Returns the cubemap information (each faces texture data) extracted from an RGBE texture.
  82215. * This RGBE texture needs to store the information as a panorama.
  82216. *
  82217. * More information on this format are available here:
  82218. * https://en.wikipedia.org/wiki/RGBE_image_format
  82219. *
  82220. * @param buffer The binary file stored in an array buffer.
  82221. * @param size The expected size of the extracted cubemap.
  82222. * @return The Cube Map information.
  82223. */
  82224. HDRTools.GetCubeMapTextureData = function (buffer, size) {
  82225. var uint8array = new Uint8Array(buffer);
  82226. var hdrInfo = this.RGBE_ReadHeader(uint8array);
  82227. var data = this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82228. var cubeMapData = BABYLON.PanoramaToCubeMapTools.ConvertPanoramaToCubemap(data, hdrInfo.width, hdrInfo.height, size);
  82229. return cubeMapData;
  82230. };
  82231. /**
  82232. * Returns the pixels data extracted from an RGBE texture.
  82233. * This pixels will be stored left to right up to down in the R G B order in one array.
  82234. *
  82235. * More information on this format are available here:
  82236. * https://en.wikipedia.org/wiki/RGBE_image_format
  82237. *
  82238. * @param uint8array The binary file stored in an array buffer.
  82239. * @param hdrInfo The header information of the file.
  82240. * @return The pixels data in RGB right to left up to down order.
  82241. */
  82242. HDRTools.RGBE_ReadPixels = function (uint8array, hdrInfo) {
  82243. // Keep for multi format supports.
  82244. return this.RGBE_ReadPixels_RLE(uint8array, hdrInfo);
  82245. };
  82246. HDRTools.RGBE_ReadPixels_RLE = function (uint8array, hdrInfo) {
  82247. var num_scanlines = hdrInfo.height;
  82248. var scanline_width = hdrInfo.width;
  82249. var a, b, c, d, count;
  82250. var dataIndex = hdrInfo.dataPosition;
  82251. var index = 0, endIndex = 0, i = 0;
  82252. var scanLineArrayBuffer = new ArrayBuffer(scanline_width * 4); // four channel R G B E
  82253. var scanLineArray = new Uint8Array(scanLineArrayBuffer);
  82254. // 3 channels of 4 bytes per pixel in float.
  82255. var resultBuffer = new ArrayBuffer(hdrInfo.width * hdrInfo.height * 4 * 3);
  82256. var resultArray = new Float32Array(resultBuffer);
  82257. // read in each successive scanline
  82258. while (num_scanlines > 0) {
  82259. a = uint8array[dataIndex++];
  82260. b = uint8array[dataIndex++];
  82261. c = uint8array[dataIndex++];
  82262. d = uint8array[dataIndex++];
  82263. if (a != 2 || b != 2 || (c & 0x80)) {
  82264. // this file is not run length encoded
  82265. throw "HDR Bad header format, not RLE";
  82266. }
  82267. if (((c << 8) | d) != scanline_width) {
  82268. throw "HDR Bad header format, wrong scan line width";
  82269. }
  82270. index = 0;
  82271. // read each of the four channels for the scanline into the buffer
  82272. for (i = 0; i < 4; i++) {
  82273. endIndex = (i + 1) * scanline_width;
  82274. while (index < endIndex) {
  82275. a = uint8array[dataIndex++];
  82276. b = uint8array[dataIndex++];
  82277. if (a > 128) {
  82278. // a run of the same value
  82279. count = a - 128;
  82280. if ((count == 0) || (count > endIndex - index)) {
  82281. throw "HDR Bad Format, bad scanline data (run)";
  82282. }
  82283. while (count-- > 0) {
  82284. scanLineArray[index++] = b;
  82285. }
  82286. }
  82287. else {
  82288. // a non-run
  82289. count = a;
  82290. if ((count == 0) || (count > endIndex - index)) {
  82291. throw "HDR Bad Format, bad scanline data (non-run)";
  82292. }
  82293. scanLineArray[index++] = b;
  82294. if (--count > 0) {
  82295. for (var j = 0; j < count; j++) {
  82296. scanLineArray[index++] = uint8array[dataIndex++];
  82297. }
  82298. }
  82299. }
  82300. }
  82301. }
  82302. // now convert data from buffer into floats
  82303. for (i = 0; i < scanline_width; i++) {
  82304. a = scanLineArray[i];
  82305. b = scanLineArray[i + scanline_width];
  82306. c = scanLineArray[i + 2 * scanline_width];
  82307. d = scanLineArray[i + 3 * scanline_width];
  82308. this.Rgbe2float(resultArray, a, b, c, d, (hdrInfo.height - num_scanlines) * scanline_width * 3 + i * 3);
  82309. }
  82310. num_scanlines--;
  82311. }
  82312. return resultArray;
  82313. };
  82314. return HDRTools;
  82315. }());
  82316. BABYLON.HDRTools = HDRTools;
  82317. })(BABYLON || (BABYLON = {}));
  82318. //# sourceMappingURL=babylon.hdr.js.map
  82319. var BABYLON;
  82320. (function (BABYLON) {
  82321. /**
  82322. * Sets of helpers addressing the serialization and deserialization of environment texture
  82323. * stored in a BabylonJS env file.
  82324. * Those files are usually stored as .env files.
  82325. */
  82326. var EnvironmentTextureTools = /** @class */ (function () {
  82327. function EnvironmentTextureTools() {
  82328. }
  82329. /**
  82330. * Gets the environment info from an env file.
  82331. * @param data The array buffer containing the .env bytes.
  82332. * @returns the environment file info (the json header) if successfully parsed.
  82333. */
  82334. EnvironmentTextureTools.GetEnvInfo = function (data) {
  82335. var dataView = new DataView(data);
  82336. var pos = 0;
  82337. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82338. if (dataView.getUint8(pos++) !== EnvironmentTextureTools._MagicBytes[i]) {
  82339. BABYLON.Tools.Error('Not a babylon environment map');
  82340. return null;
  82341. }
  82342. }
  82343. // Read json manifest - collect characters up to null terminator
  82344. var manifestString = '';
  82345. var charCode = 0x00;
  82346. while ((charCode = dataView.getUint8(pos++))) {
  82347. manifestString += String.fromCharCode(charCode);
  82348. }
  82349. var manifest = JSON.parse(manifestString);
  82350. if (manifest.specular) {
  82351. // Extend the header with the position of the payload.
  82352. manifest.specular.specularDataPosition = pos;
  82353. }
  82354. return manifest;
  82355. };
  82356. /**
  82357. * Creates an environment texture from a loaded cube texture.
  82358. * @param texture defines the cube texture to convert in env file
  82359. * @return a promise containing the environment data if succesfull.
  82360. */
  82361. EnvironmentTextureTools.CreateEnvTextureAsync = function (texture) {
  82362. var _this = this;
  82363. var internalTexture = texture.getInternalTexture();
  82364. if (!internalTexture) {
  82365. return Promise.reject("The cube texture is invalid.");
  82366. }
  82367. if (!texture._prefiltered) {
  82368. return Promise.reject("The cube texture is invalid (not prefiltered).");
  82369. }
  82370. var engine = internalTexture.getEngine();
  82371. if (engine && engine.premultipliedAlpha) {
  82372. return Promise.reject("Env texture can only be created when the engine is created with the premultipliedAlpha option set to false.");
  82373. }
  82374. var canvas = engine.getRenderingCanvas();
  82375. if (!canvas) {
  82376. return Promise.reject("Env texture can only be created when the engine is associated to a canvas.");
  82377. }
  82378. var textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82379. if (!engine.getCaps().textureFloatRender) {
  82380. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82381. if (!engine.getCaps().textureHalfFloatRender) {
  82382. return Promise.reject("Env texture can only be created when the browser supports half float or full float rendering.");
  82383. }
  82384. }
  82385. var cubeWidth = internalTexture.width;
  82386. var hostingScene = new BABYLON.Scene(engine);
  82387. var specularTextures = {};
  82388. var promises = [];
  82389. // Read and collect all mipmaps data from the cube.
  82390. var mipmapsCount = BABYLON.Scalar.Log2(internalTexture.width);
  82391. mipmapsCount = Math.round(mipmapsCount);
  82392. var _loop_1 = function (i) {
  82393. var faceWidth = Math.pow(2, mipmapsCount - i);
  82394. var _loop_2 = function (face) {
  82395. var data = texture.readPixels(face, i);
  82396. // Creates a temp texture with the face data.
  82397. var tempTexture = engine.createRawTexture(data, faceWidth, faceWidth, BABYLON.Engine.TEXTUREFORMAT_RGBA, false, false, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, textureType);
  82398. // And rgbdEncode them.
  82399. var promise = new Promise(function (resolve, reject) {
  82400. var rgbdPostProcess = new BABYLON.PostProcess("rgbdEncode", "rgbdEncode", null, null, 1, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, undefined, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, undefined, null, false);
  82401. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82402. rgbdPostProcess.onApply = function (effect) {
  82403. effect._bindTexture("textureSampler", tempTexture);
  82404. };
  82405. // As the process needs to happen on the main canvas, keep track of the current size
  82406. var currentW = engine.getRenderWidth();
  82407. var currentH = engine.getRenderHeight();
  82408. // Set the desired size for the texture
  82409. engine.setSize(faceWidth, faceWidth);
  82410. hostingScene.postProcessManager.directRender([rgbdPostProcess], null);
  82411. // Reading datas from WebGL
  82412. BABYLON.Tools.ToBlob(canvas, function (blob) {
  82413. var fileReader = new FileReader();
  82414. fileReader.onload = function (event) {
  82415. var arrayBuffer = event.target.result;
  82416. specularTextures[i * 6 + face] = arrayBuffer;
  82417. resolve();
  82418. };
  82419. fileReader.readAsArrayBuffer(blob);
  82420. });
  82421. // Reapply the previous canvas size
  82422. engine.setSize(currentW, currentH);
  82423. });
  82424. });
  82425. promises.push(promise);
  82426. };
  82427. // All faces of the cube.
  82428. for (var face = 0; face < 6; face++) {
  82429. _loop_2(face);
  82430. }
  82431. };
  82432. for (var i = 0; i <= mipmapsCount; i++) {
  82433. _loop_1(i);
  82434. }
  82435. // Once all the textures haves been collected as RGBD stored in PNGs
  82436. return Promise.all(promises).then(function () {
  82437. // We can delete the hosting scene keeping track of all the creation objects
  82438. hostingScene.dispose();
  82439. // Creates the json header for the env texture
  82440. var info = {
  82441. version: 1,
  82442. width: cubeWidth,
  82443. irradiance: _this._CreateEnvTextureIrradiance(texture),
  82444. specular: {
  82445. mipmaps: []
  82446. }
  82447. };
  82448. // Sets the specular image data information
  82449. var position = 0;
  82450. for (var i = 0; i <= mipmapsCount; i++) {
  82451. for (var face = 0; face < 6; face++) {
  82452. var byteLength = specularTextures[i * 6 + face].byteLength;
  82453. info.specular.mipmaps.push({
  82454. length: byteLength,
  82455. position: position
  82456. });
  82457. position += byteLength;
  82458. }
  82459. }
  82460. // Encode the JSON as an array buffer
  82461. var infoString = JSON.stringify(info);
  82462. var infoBuffer = new ArrayBuffer(infoString.length + 1);
  82463. var infoView = new Uint8Array(infoBuffer); // Limited to ascii subset matching unicode.
  82464. for (var i = 0, strLen = infoString.length; i < strLen; i++) {
  82465. infoView[i] = infoString.charCodeAt(i);
  82466. }
  82467. // Ends up with a null terminator for easier parsing
  82468. infoView[infoString.length] = 0x00;
  82469. // Computes the final required size and creates the storage
  82470. var totalSize = EnvironmentTextureTools._MagicBytes.length + position + infoBuffer.byteLength;
  82471. var finalBuffer = new ArrayBuffer(totalSize);
  82472. var finalBufferView = new Uint8Array(finalBuffer);
  82473. var dataView = new DataView(finalBuffer);
  82474. // Copy the magic bytes identifying the file in
  82475. var pos = 0;
  82476. for (var i = 0; i < EnvironmentTextureTools._MagicBytes.length; i++) {
  82477. dataView.setUint8(pos++, EnvironmentTextureTools._MagicBytes[i]);
  82478. }
  82479. // Add the json info
  82480. finalBufferView.set(new Uint8Array(infoBuffer), pos);
  82481. pos += infoBuffer.byteLength;
  82482. // Finally inserts the texture data
  82483. for (var i = 0; i <= mipmapsCount; i++) {
  82484. for (var face = 0; face < 6; face++) {
  82485. var dataBuffer = specularTextures[i * 6 + face];
  82486. finalBufferView.set(new Uint8Array(dataBuffer), pos);
  82487. pos += dataBuffer.byteLength;
  82488. }
  82489. }
  82490. // Voila
  82491. return finalBuffer;
  82492. });
  82493. };
  82494. /**
  82495. * Creates a JSON representation of the spherical data.
  82496. * @param texture defines the texture containing the polynomials
  82497. * @return the JSON representation of the spherical info
  82498. */
  82499. EnvironmentTextureTools._CreateEnvTextureIrradiance = function (texture) {
  82500. var polynmials = texture.sphericalPolynomial;
  82501. if (polynmials == null) {
  82502. return null;
  82503. }
  82504. return {
  82505. polynomials: true,
  82506. x: [polynmials.x.x, polynmials.x.y, polynmials.x.z],
  82507. y: [polynmials.y.x, polynmials.y.y, polynmials.y.z],
  82508. z: [polynmials.z.x, polynmials.z.y, polynmials.z.z],
  82509. xx: [polynmials.xx.x, polynmials.xx.y, polynmials.xx.z],
  82510. yy: [polynmials.yy.x, polynmials.yy.y, polynmials.yy.z],
  82511. zz: [polynmials.zz.x, polynmials.zz.y, polynmials.zz.z],
  82512. yz: [polynmials.yz.x, polynmials.yz.y, polynmials.yz.z],
  82513. zx: [polynmials.zx.x, polynmials.zx.y, polynmials.zx.z],
  82514. xy: [polynmials.xy.x, polynmials.xy.y, polynmials.xy.z]
  82515. };
  82516. };
  82517. /**
  82518. * Uploads the texture info contained in the env file to te GPU.
  82519. * @param texture defines the internal texture to upload to
  82520. * @param arrayBuffer defines the buffer cotaining the data to load
  82521. * @param info defines the texture info retrieved through the GetEnvInfo method
  82522. * @returns a promise
  82523. */
  82524. EnvironmentTextureTools.UploadLevelsAsync = function (texture, arrayBuffer, info) {
  82525. if (info.version !== 1) {
  82526. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82527. }
  82528. var specularInfo = info.specular;
  82529. if (!specularInfo) {
  82530. // Nothing else parsed so far
  82531. return Promise.resolve();
  82532. }
  82533. // Double checks the enclosed info
  82534. var mipmapsCount = BABYLON.Scalar.Log2(info.width);
  82535. mipmapsCount = Math.round(mipmapsCount) + 1;
  82536. if (specularInfo.mipmaps.length !== 6 * mipmapsCount) {
  82537. BABYLON.Tools.Warn('Unsupported specular mipmaps number "' + specularInfo.mipmaps.length + '"');
  82538. }
  82539. // Gets everything ready.
  82540. var engine = texture.getEngine();
  82541. var expandTexture = false;
  82542. var generateNonLODTextures = false;
  82543. var rgbdPostProcess = null;
  82544. var cubeRtt = null;
  82545. var lodTextures = null;
  82546. var caps = engine.getCaps();
  82547. texture.format = BABYLON.Engine.TEXTUREFORMAT_RGBA;
  82548. texture.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  82549. texture.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  82550. // Add extra process if texture lod is not supported
  82551. if (!caps.textureLOD) {
  82552. expandTexture = false;
  82553. generateNonLODTextures = true;
  82554. lodTextures = {};
  82555. }
  82556. // in webgl 1 there are no ways to either render or copy lod level information for float textures.
  82557. else if (engine.webGLVersion < 2) {
  82558. expandTexture = false;
  82559. }
  82560. // If half float available we can uncompress the texture
  82561. else if (caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering) {
  82562. expandTexture = true;
  82563. texture.type = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  82564. }
  82565. // If full float available we can uncompress the texture
  82566. else if (caps.textureFloatRender && caps.textureFloatLinearFiltering) {
  82567. expandTexture = true;
  82568. texture.type = BABYLON.Engine.TEXTURETYPE_FLOAT;
  82569. }
  82570. // Expand the texture if possible
  82571. if (expandTexture) {
  82572. // Simply run through the decode PP
  82573. rgbdPostProcess = new BABYLON.PostProcess("rgbdDecode", "rgbdDecode", null, null, 1, null, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, engine, false, undefined, texture.type, undefined, null, false);
  82574. texture._isRGBD = false;
  82575. texture.invertY = false;
  82576. cubeRtt = engine.createRenderTargetCubeTexture(texture.width, {
  82577. generateDepthBuffer: false,
  82578. generateMipMaps: true,
  82579. generateStencilBuffer: false,
  82580. samplingMode: BABYLON.Texture.TRILINEAR_SAMPLINGMODE,
  82581. type: texture.type,
  82582. format: BABYLON.Engine.TEXTUREFORMAT_RGBA
  82583. });
  82584. }
  82585. else {
  82586. texture._isRGBD = true;
  82587. texture.invertY = true;
  82588. // In case of missing support, applies the same patch than DDS files.
  82589. if (generateNonLODTextures) {
  82590. var mipSlices = 3;
  82591. var scale = texture._lodGenerationScale;
  82592. var offset = texture._lodGenerationOffset;
  82593. for (var i = 0; i < mipSlices; i++) {
  82594. //compute LOD from even spacing in smoothness (matching shader calculation)
  82595. var smoothness = i / (mipSlices - 1);
  82596. var roughness = 1 - smoothness;
  82597. var minLODIndex = offset; // roughness = 0
  82598. var maxLODIndex = BABYLON.Scalar.Log2(info.width) * scale + offset; // roughness = 1
  82599. var lodIndex = minLODIndex + (maxLODIndex - minLODIndex) * roughness;
  82600. var mipmapIndex = Math.round(Math.min(Math.max(lodIndex, 0), maxLODIndex));
  82601. var glTextureFromLod = new BABYLON.InternalTexture(engine, BABYLON.InternalTexture.DATASOURCE_TEMP);
  82602. glTextureFromLod.isCube = true;
  82603. glTextureFromLod.invertY = true;
  82604. glTextureFromLod.generateMipMaps = false;
  82605. engine.updateTextureSamplingMode(BABYLON.Texture.LINEAR_LINEAR, glTextureFromLod);
  82606. // Wrap in a base texture for easy binding.
  82607. var lodTexture = new BABYLON.BaseTexture(null);
  82608. lodTexture.isCube = true;
  82609. lodTexture._texture = glTextureFromLod;
  82610. lodTextures[mipmapIndex] = lodTexture;
  82611. switch (i) {
  82612. case 0:
  82613. texture._lodTextureLow = lodTexture;
  82614. break;
  82615. case 1:
  82616. texture._lodTextureMid = lodTexture;
  82617. break;
  82618. case 2:
  82619. texture._lodTextureHigh = lodTexture;
  82620. break;
  82621. }
  82622. }
  82623. }
  82624. }
  82625. var promises = [];
  82626. var _loop_3 = function (i) {
  82627. var _loop_4 = function (face) {
  82628. // Retrieves the face data
  82629. var imageData = specularInfo.mipmaps[i * 6 + face];
  82630. var bytes = new Uint8Array(arrayBuffer, specularInfo.specularDataPosition + imageData.position, imageData.length);
  82631. // Constructs an image element from bytes
  82632. var blob = new Blob([bytes], { type: 'image/png' });
  82633. var url = URL.createObjectURL(blob);
  82634. var image = new Image();
  82635. image.src = url;
  82636. // Enqueue promise to upload to the texture.
  82637. var promise = new Promise(function (resolve, reject) {
  82638. ;
  82639. image.onload = function () {
  82640. if (expandTexture) {
  82641. var tempTexture_1 = engine.createTexture(null, true, true, null, BABYLON.Texture.NEAREST_SAMPLINGMODE, null, function (message) {
  82642. reject(message);
  82643. }, image);
  82644. rgbdPostProcess.getEffect().executeWhenCompiled(function () {
  82645. // Uncompress the data to a RTT
  82646. rgbdPostProcess.onApply = function (effect) {
  82647. effect._bindTexture("textureSampler", tempTexture_1);
  82648. effect.setFloat2("scale", 1, 1);
  82649. };
  82650. engine.scenes[0].postProcessManager.directRender([rgbdPostProcess], cubeRtt, true, face, i);
  82651. // Cleanup
  82652. engine.restoreDefaultFramebuffer();
  82653. tempTexture_1.dispose();
  82654. window.URL.revokeObjectURL(url);
  82655. resolve();
  82656. });
  82657. }
  82658. else {
  82659. engine._uploadImageToTexture(texture, face, i, image);
  82660. // Upload the face to the none lod texture support
  82661. if (generateNonLODTextures) {
  82662. var lodTexture = lodTextures[i];
  82663. if (lodTexture) {
  82664. engine._uploadImageToTexture(lodTexture._texture, face, 0, image);
  82665. }
  82666. }
  82667. resolve();
  82668. }
  82669. };
  82670. image.onerror = function (error) {
  82671. reject(error);
  82672. };
  82673. });
  82674. promises.push(promise);
  82675. };
  82676. // All faces
  82677. for (var face = 0; face < 6; face++) {
  82678. _loop_4(face);
  82679. }
  82680. };
  82681. // All mipmaps
  82682. for (var i = 0; i < mipmapsCount; i++) {
  82683. _loop_3(i);
  82684. }
  82685. // Once all done, finishes the cleanup and return
  82686. return Promise.all(promises).then(function () {
  82687. // Relase temp RTT.
  82688. if (cubeRtt) {
  82689. engine._releaseFramebufferObjects(cubeRtt);
  82690. cubeRtt._swapAndDie(texture);
  82691. }
  82692. // Relase temp Post Process.
  82693. if (rgbdPostProcess) {
  82694. rgbdPostProcess.dispose();
  82695. }
  82696. // Flag internal texture as ready in case they are in use.
  82697. if (generateNonLODTextures) {
  82698. if (texture._lodTextureHigh && texture._lodTextureHigh._texture) {
  82699. texture._lodTextureHigh._texture.isReady = true;
  82700. }
  82701. if (texture._lodTextureMid && texture._lodTextureMid._texture) {
  82702. texture._lodTextureMid._texture.isReady = true;
  82703. }
  82704. if (texture._lodTextureLow && texture._lodTextureLow._texture) {
  82705. texture._lodTextureLow._texture.isReady = true;
  82706. }
  82707. }
  82708. });
  82709. };
  82710. /**
  82711. * Uploads spherical polynomials information to the texture.
  82712. * @param texture defines the texture we are trying to upload the information to
  82713. * @param arrayBuffer defines the array buffer holding the data
  82714. * @param info defines the environment texture info retrieved through the GetEnvInfo method
  82715. */
  82716. EnvironmentTextureTools.UploadPolynomials = function (texture, arrayBuffer, info) {
  82717. if (info.version !== 1) {
  82718. BABYLON.Tools.Warn('Unsupported babylon environment map version "' + info.version + '"');
  82719. }
  82720. var irradianceInfo = info.irradiance;
  82721. if (!irradianceInfo) {
  82722. return;
  82723. }
  82724. //harmonics now represent radiance
  82725. texture._sphericalPolynomial = new BABYLON.SphericalPolynomial();
  82726. if (irradianceInfo.polynomials) {
  82727. EnvironmentTextureTools._UploadSP(irradianceInfo, texture._sphericalPolynomial);
  82728. }
  82729. else {
  82730. // convert From SH to SP.
  82731. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance(irradianceInfo);
  82732. EnvironmentTextureTools._ConvertSHToSP(irradianceInfo, texture._sphericalPolynomial);
  82733. }
  82734. };
  82735. /**
  82736. * Upload spherical polynomial coefficients to the texture
  82737. * @param polynmials Spherical polynmial coefficients (9)
  82738. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82739. */
  82740. EnvironmentTextureTools._UploadSP = function (polynmials, outPolynomialCoefficents) {
  82741. outPolynomialCoefficents.x.x = polynmials.x[0];
  82742. outPolynomialCoefficents.x.y = polynmials.x[1];
  82743. outPolynomialCoefficents.x.z = polynmials.x[2];
  82744. outPolynomialCoefficents.y.x = polynmials.y[0];
  82745. outPolynomialCoefficents.y.y = polynmials.y[1];
  82746. outPolynomialCoefficents.y.z = polynmials.y[2];
  82747. outPolynomialCoefficents.z.x = polynmials.z[0];
  82748. outPolynomialCoefficents.z.y = polynmials.z[1];
  82749. outPolynomialCoefficents.z.z = polynmials.z[2];
  82750. //xx
  82751. outPolynomialCoefficents.xx.x = polynmials.xx[0];
  82752. outPolynomialCoefficents.xx.y = polynmials.xx[1];
  82753. outPolynomialCoefficents.xx.z = polynmials.xx[2];
  82754. outPolynomialCoefficents.yy.x = polynmials.yy[0];
  82755. outPolynomialCoefficents.yy.y = polynmials.yy[1];
  82756. outPolynomialCoefficents.yy.z = polynmials.yy[2];
  82757. outPolynomialCoefficents.zz.x = polynmials.zz[0];
  82758. outPolynomialCoefficents.zz.y = polynmials.zz[1];
  82759. outPolynomialCoefficents.zz.z = polynmials.zz[2];
  82760. //yz
  82761. outPolynomialCoefficents.yz.x = polynmials.yz[0];
  82762. outPolynomialCoefficents.yz.y = polynmials.yz[1];
  82763. outPolynomialCoefficents.yz.z = polynmials.yz[2];
  82764. outPolynomialCoefficents.zx.x = polynmials.zx[0];
  82765. outPolynomialCoefficents.zx.y = polynmials.zx[1];
  82766. outPolynomialCoefficents.zx.z = polynmials.zx[2];
  82767. outPolynomialCoefficents.xy.x = polynmials.xy[0];
  82768. outPolynomialCoefficents.xy.y = polynmials.xy[1];
  82769. outPolynomialCoefficents.xy.z = polynmials.xy[2];
  82770. };
  82771. /**
  82772. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  82773. * L = (1/pi) * E * rho
  82774. *
  82775. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  82776. * @param harmonics Spherical harmonic coefficients (9)
  82777. */
  82778. EnvironmentTextureTools._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  82779. var scaleFactor = 1 / Math.PI;
  82780. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  82781. // (The pixel shader must apply albedo after texture fetches, etc).
  82782. harmonics.l00[0] *= scaleFactor;
  82783. harmonics.l00[1] *= scaleFactor;
  82784. harmonics.l00[2] *= scaleFactor;
  82785. harmonics.l1_1[0] *= scaleFactor;
  82786. harmonics.l1_1[1] *= scaleFactor;
  82787. harmonics.l1_1[2] *= scaleFactor;
  82788. harmonics.l10[0] *= scaleFactor;
  82789. harmonics.l10[1] *= scaleFactor;
  82790. harmonics.l10[2] *= scaleFactor;
  82791. harmonics.l11[0] *= scaleFactor;
  82792. harmonics.l11[1] *= scaleFactor;
  82793. harmonics.l11[2] *= scaleFactor;
  82794. harmonics.l2_2[0] *= scaleFactor;
  82795. harmonics.l2_2[1] *= scaleFactor;
  82796. harmonics.l2_2[2] *= scaleFactor;
  82797. harmonics.l2_1[0] *= scaleFactor;
  82798. harmonics.l2_1[1] *= scaleFactor;
  82799. harmonics.l2_1[2] *= scaleFactor;
  82800. harmonics.l20[0] *= scaleFactor;
  82801. harmonics.l20[1] *= scaleFactor;
  82802. harmonics.l20[2] *= scaleFactor;
  82803. harmonics.l21[0] *= scaleFactor;
  82804. harmonics.l21[1] *= scaleFactor;
  82805. harmonics.l21[2] *= scaleFactor;
  82806. harmonics.l22[0] *= scaleFactor;
  82807. harmonics.l22[1] *= scaleFactor;
  82808. harmonics.l22[2] *= scaleFactor;
  82809. };
  82810. /**
  82811. * Convert spherical harmonics to spherical polynomial coefficients
  82812. * @param harmonics Spherical harmonic coefficients (9)
  82813. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  82814. */
  82815. EnvironmentTextureTools._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  82816. var rPi = 1 / Math.PI;
  82817. //x
  82818. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  82819. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  82820. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  82821. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  82822. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  82823. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  82824. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  82825. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  82826. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  82827. //xx
  82828. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  82829. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  82830. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  82831. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  82832. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  82833. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  82834. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  82835. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  82836. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  82837. //yz
  82838. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  82839. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  82840. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  82841. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  82842. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  82843. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  82844. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  82845. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  82846. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  82847. };
  82848. /**
  82849. * Magic number identifying the env file.
  82850. */
  82851. EnvironmentTextureTools._MagicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  82852. return EnvironmentTextureTools;
  82853. }());
  82854. BABYLON.EnvironmentTextureTools = EnvironmentTextureTools;
  82855. })(BABYLON || (BABYLON = {}));
  82856. //# sourceMappingURL=babylon.environmentTextureTools.js.map
  82857. var BABYLON;
  82858. (function (BABYLON) {
  82859. /**
  82860. * This represents a texture coming from an HDR input.
  82861. *
  82862. * The only supported format is currently panorama picture stored in RGBE format.
  82863. * Example of such files can be found on HDRLib: http://hdrlib.com/
  82864. */
  82865. var HDRCubeTexture = /** @class */ (function (_super) {
  82866. __extends(HDRCubeTexture, _super);
  82867. /**
  82868. * Instantiates an HDRTexture from the following parameters.
  82869. *
  82870. * @param url The location of the HDR raw data (Panorama stored in RGBE format)
  82871. * @param scene The scene the texture will be used in
  82872. * @param size The cubemap desired size (the more it increases the longer the generation will be)
  82873. * @param noMipmap Forces to not generate the mipmap if true
  82874. * @param generateHarmonics Specifies whether you want to extract the polynomial harmonics during the generation process
  82875. * @param gammaSpace Specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space)
  82876. * @param reserved Reserved flag for internal use.
  82877. */
  82878. function HDRCubeTexture(url, scene, size, noMipmap, generateHarmonics, gammaSpace, reserved, onLoad, onError) {
  82879. if (noMipmap === void 0) { noMipmap = false; }
  82880. if (generateHarmonics === void 0) { generateHarmonics = true; }
  82881. if (gammaSpace === void 0) { gammaSpace = false; }
  82882. if (reserved === void 0) { reserved = false; }
  82883. if (onLoad === void 0) { onLoad = null; }
  82884. if (onError === void 0) { onError = null; }
  82885. var _this = _super.call(this, scene) || this;
  82886. _this._generateHarmonics = true;
  82887. _this._onLoad = null;
  82888. _this._onError = null;
  82889. /**
  82890. * The texture coordinates mode. As this texture is stored in a cube format, please modify carefully.
  82891. */
  82892. _this.coordinatesMode = BABYLON.Texture.CUBIC_MODE;
  82893. _this._isBlocking = true;
  82894. _this._rotationY = 0;
  82895. /**
  82896. * Gets or sets the center of the bounding box associated with the cube texture
  82897. * It must define where the camera used to render the texture was set
  82898. */
  82899. _this.boundingBoxPosition = BABYLON.Vector3.Zero();
  82900. if (!url) {
  82901. return _this;
  82902. }
  82903. _this.name = url;
  82904. _this.url = url;
  82905. _this.hasAlpha = false;
  82906. _this.isCube = true;
  82907. _this._textureMatrix = BABYLON.Matrix.Identity();
  82908. _this._onLoad = onLoad;
  82909. _this._onError = onError;
  82910. _this.gammaSpace = gammaSpace;
  82911. _this._noMipmap = noMipmap;
  82912. _this._size = size;
  82913. _this._texture = _this._getFromCache(url, _this._noMipmap);
  82914. if (!_this._texture) {
  82915. if (!scene.useDelayedTextureLoading) {
  82916. _this.loadTexture();
  82917. }
  82918. else {
  82919. _this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_NOTLOADED;
  82920. }
  82921. }
  82922. return _this;
  82923. }
  82924. Object.defineProperty(HDRCubeTexture.prototype, "isBlocking", {
  82925. /**
  82926. * Gets wether or not the texture is blocking during loading.
  82927. */
  82928. get: function () {
  82929. return this._isBlocking;
  82930. },
  82931. /**
  82932. * Sets wether or not the texture is blocking during loading.
  82933. */
  82934. set: function (value) {
  82935. this._isBlocking = value;
  82936. },
  82937. enumerable: true,
  82938. configurable: true
  82939. });
  82940. Object.defineProperty(HDRCubeTexture.prototype, "rotationY", {
  82941. /**
  82942. * Gets texture matrix rotation angle around Y axis radians.
  82943. */
  82944. get: function () {
  82945. return this._rotationY;
  82946. },
  82947. /**
  82948. * Sets texture matrix rotation angle around Y axis in radians.
  82949. */
  82950. set: function (value) {
  82951. this._rotationY = value;
  82952. this.setReflectionTextureMatrix(BABYLON.Matrix.RotationY(this._rotationY));
  82953. },
  82954. enumerable: true,
  82955. configurable: true
  82956. });
  82957. Object.defineProperty(HDRCubeTexture.prototype, "boundingBoxSize", {
  82958. get: function () {
  82959. return this._boundingBoxSize;
  82960. },
  82961. /**
  82962. * Gets or sets the size of the bounding box associated with the cube texture
  82963. * When defined, the cubemap will switch to local mode
  82964. * @see https://community.arm.com/graphics/b/blog/posts/reflections-based-on-local-cubemaps-in-unity
  82965. * @example https://www.babylonjs-playground.com/#RNASML
  82966. */
  82967. set: function (value) {
  82968. if (this._boundingBoxSize && this._boundingBoxSize.equals(value)) {
  82969. return;
  82970. }
  82971. this._boundingBoxSize = value;
  82972. var scene = this.getScene();
  82973. if (scene) {
  82974. scene.markAllMaterialsAsDirty(BABYLON.Material.TextureDirtyFlag);
  82975. }
  82976. },
  82977. enumerable: true,
  82978. configurable: true
  82979. });
  82980. /**
  82981. * Occurs when the file is raw .hdr file.
  82982. */
  82983. HDRCubeTexture.prototype.loadTexture = function () {
  82984. var _this = this;
  82985. var callback = function (buffer) {
  82986. _this.lodGenerationOffset = 0.0;
  82987. _this.lodGenerationScale = 0.8;
  82988. var scene = _this.getScene();
  82989. if (!scene) {
  82990. return null;
  82991. }
  82992. // Extract the raw linear data.
  82993. var data = BABYLON.HDRTools.GetCubeMapTextureData(buffer, _this._size);
  82994. // Generate harmonics if needed.
  82995. if (_this._generateHarmonics) {
  82996. var sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial(data);
  82997. _this.sphericalPolynomial = sphericalPolynomial;
  82998. }
  82999. var results = [];
  83000. var byteArray = null;
  83001. // Push each faces.
  83002. for (var j = 0; j < 6; j++) {
  83003. // Create uintarray fallback.
  83004. if (!scene.getEngine().getCaps().textureFloat) {
  83005. // 3 channels of 1 bytes per pixel in bytes.
  83006. var byteBuffer = new ArrayBuffer(_this._size * _this._size * 3);
  83007. byteArray = new Uint8Array(byteBuffer);
  83008. }
  83009. var dataFace = (data[HDRCubeTexture._facesMapping[j]]);
  83010. // If special cases.
  83011. if (_this.gammaSpace || byteArray) {
  83012. for (var i = 0; i < _this._size * _this._size; i++) {
  83013. // Put in gamma space if requested.
  83014. if (_this.gammaSpace) {
  83015. dataFace[(i * 3) + 0] = Math.pow(dataFace[(i * 3) + 0], BABYLON.ToGammaSpace);
  83016. dataFace[(i * 3) + 1] = Math.pow(dataFace[(i * 3) + 1], BABYLON.ToGammaSpace);
  83017. dataFace[(i * 3) + 2] = Math.pow(dataFace[(i * 3) + 2], BABYLON.ToGammaSpace);
  83018. }
  83019. // Convert to int texture for fallback.
  83020. if (byteArray) {
  83021. var r = Math.max(dataFace[(i * 3) + 0] * 255, 0);
  83022. var g = Math.max(dataFace[(i * 3) + 1] * 255, 0);
  83023. var b = Math.max(dataFace[(i * 3) + 2] * 255, 0);
  83024. // May use luminance instead if the result is not accurate.
  83025. var max = Math.max(Math.max(r, g), b);
  83026. if (max > 255) {
  83027. var scale = 255 / max;
  83028. r *= scale;
  83029. g *= scale;
  83030. b *= scale;
  83031. }
  83032. byteArray[(i * 3) + 0] = r;
  83033. byteArray[(i * 3) + 1] = g;
  83034. byteArray[(i * 3) + 2] = b;
  83035. }
  83036. }
  83037. }
  83038. if (byteArray) {
  83039. results.push(byteArray);
  83040. }
  83041. else {
  83042. results.push(dataFace);
  83043. }
  83044. }
  83045. return results;
  83046. };
  83047. var scene = this.getScene();
  83048. if (scene) {
  83049. this._texture = scene.getEngine().createRawCubeTextureFromUrl(this.url, scene, this._size, BABYLON.Engine.TEXTUREFORMAT_RGB, scene.getEngine().getCaps().textureFloat ? BABYLON.Engine.TEXTURETYPE_FLOAT : BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, this._noMipmap, callback, null, this._onLoad, this._onError);
  83050. }
  83051. };
  83052. HDRCubeTexture.prototype.clone = function () {
  83053. var scene = this.getScene();
  83054. if (!scene) {
  83055. return this;
  83056. }
  83057. var newTexture = new HDRCubeTexture(this.url, scene, this._size, this._noMipmap, this._generateHarmonics, this.gammaSpace);
  83058. // Base texture
  83059. newTexture.level = this.level;
  83060. newTexture.wrapU = this.wrapU;
  83061. newTexture.wrapV = this.wrapV;
  83062. newTexture.coordinatesIndex = this.coordinatesIndex;
  83063. newTexture.coordinatesMode = this.coordinatesMode;
  83064. return newTexture;
  83065. };
  83066. // Methods
  83067. HDRCubeTexture.prototype.delayLoad = function () {
  83068. if (this.delayLoadState !== BABYLON.Engine.DELAYLOADSTATE_NOTLOADED) {
  83069. return;
  83070. }
  83071. this.delayLoadState = BABYLON.Engine.DELAYLOADSTATE_LOADED;
  83072. this._texture = this._getFromCache(this.url, this._noMipmap);
  83073. if (!this._texture) {
  83074. this.loadTexture();
  83075. }
  83076. };
  83077. HDRCubeTexture.prototype.getReflectionTextureMatrix = function () {
  83078. return this._textureMatrix;
  83079. };
  83080. HDRCubeTexture.prototype.setReflectionTextureMatrix = function (value) {
  83081. this._textureMatrix = value;
  83082. };
  83083. HDRCubeTexture.Parse = function (parsedTexture, scene, rootUrl) {
  83084. var texture = null;
  83085. if (parsedTexture.name && !parsedTexture.isRenderTarget) {
  83086. texture = new HDRCubeTexture(rootUrl + parsedTexture.name, scene, parsedTexture.size, parsedTexture.noMipmap, parsedTexture.generateHarmonics, parsedTexture.useInGammaSpace);
  83087. texture.name = parsedTexture.name;
  83088. texture.hasAlpha = parsedTexture.hasAlpha;
  83089. texture.level = parsedTexture.level;
  83090. texture.coordinatesMode = parsedTexture.coordinatesMode;
  83091. texture.isBlocking = parsedTexture.isBlocking;
  83092. }
  83093. if (texture) {
  83094. if (parsedTexture.boundingBoxPosition) {
  83095. texture.boundingBoxPosition = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxPosition);
  83096. }
  83097. if (parsedTexture.boundingBoxSize) {
  83098. texture.boundingBoxSize = BABYLON.Vector3.FromArray(parsedTexture.boundingBoxSize);
  83099. }
  83100. if (parsedTexture.rotationY) {
  83101. texture.rotationY = parsedTexture.rotationY;
  83102. }
  83103. }
  83104. return texture;
  83105. };
  83106. HDRCubeTexture.prototype.serialize = function () {
  83107. if (!this.name) {
  83108. return null;
  83109. }
  83110. var serializationObject = {};
  83111. serializationObject.name = this.name;
  83112. serializationObject.hasAlpha = this.hasAlpha;
  83113. serializationObject.isCube = true;
  83114. serializationObject.level = this.level;
  83115. serializationObject.size = this._size;
  83116. serializationObject.coordinatesMode = this.coordinatesMode;
  83117. serializationObject.useInGammaSpace = this.gammaSpace;
  83118. serializationObject.generateHarmonics = this._generateHarmonics;
  83119. serializationObject.customType = "BABYLON.HDRCubeTexture";
  83120. serializationObject.noMipmap = this._noMipmap;
  83121. serializationObject.isBlocking = this._isBlocking;
  83122. serializationObject.rotationY = this._rotationY;
  83123. return serializationObject;
  83124. };
  83125. HDRCubeTexture._facesMapping = [
  83126. "right",
  83127. "left",
  83128. "up",
  83129. "down",
  83130. "front",
  83131. "back"
  83132. ];
  83133. return HDRCubeTexture;
  83134. }(BABYLON.BaseTexture));
  83135. BABYLON.HDRCubeTexture = HDRCubeTexture;
  83136. })(BABYLON || (BABYLON = {}));
  83137. //# sourceMappingURL=babylon.hdrCubeTexture.js.map
  83138. var BABYLON;
  83139. (function (BABYLON) {
  83140. var IndexedVector2 = /** @class */ (function (_super) {
  83141. __extends(IndexedVector2, _super);
  83142. function IndexedVector2(original, index) {
  83143. var _this = _super.call(this, original.x, original.y) || this;
  83144. _this.index = index;
  83145. return _this;
  83146. }
  83147. return IndexedVector2;
  83148. }(BABYLON.Vector2));
  83149. var PolygonPoints = /** @class */ (function () {
  83150. function PolygonPoints() {
  83151. this.elements = new Array();
  83152. }
  83153. PolygonPoints.prototype.add = function (originalPoints) {
  83154. var _this = this;
  83155. var result = new Array();
  83156. originalPoints.forEach(function (point) {
  83157. if (result.length === 0 || !point.equalsWithEpsilon(result[0])) {
  83158. var newPoint = new IndexedVector2(point, _this.elements.length);
  83159. result.push(newPoint);
  83160. _this.elements.push(newPoint);
  83161. }
  83162. });
  83163. return result;
  83164. };
  83165. PolygonPoints.prototype.computeBounds = function () {
  83166. var lmin = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83167. var lmax = new BABYLON.Vector2(this.elements[0].x, this.elements[0].y);
  83168. this.elements.forEach(function (point) {
  83169. // x
  83170. if (point.x < lmin.x) {
  83171. lmin.x = point.x;
  83172. }
  83173. else if (point.x > lmax.x) {
  83174. lmax.x = point.x;
  83175. }
  83176. // y
  83177. if (point.y < lmin.y) {
  83178. lmin.y = point.y;
  83179. }
  83180. else if (point.y > lmax.y) {
  83181. lmax.y = point.y;
  83182. }
  83183. });
  83184. return {
  83185. min: lmin,
  83186. max: lmax,
  83187. width: lmax.x - lmin.x,
  83188. height: lmax.y - lmin.y
  83189. };
  83190. };
  83191. return PolygonPoints;
  83192. }());
  83193. var Polygon = /** @class */ (function () {
  83194. function Polygon() {
  83195. }
  83196. Polygon.Rectangle = function (xmin, ymin, xmax, ymax) {
  83197. return [
  83198. new BABYLON.Vector2(xmin, ymin),
  83199. new BABYLON.Vector2(xmax, ymin),
  83200. new BABYLON.Vector2(xmax, ymax),
  83201. new BABYLON.Vector2(xmin, ymax)
  83202. ];
  83203. };
  83204. Polygon.Circle = function (radius, cx, cy, numberOfSides) {
  83205. if (cx === void 0) { cx = 0; }
  83206. if (cy === void 0) { cy = 0; }
  83207. if (numberOfSides === void 0) { numberOfSides = 32; }
  83208. var result = new Array();
  83209. var angle = 0;
  83210. var increment = (Math.PI * 2) / numberOfSides;
  83211. for (var i = 0; i < numberOfSides; i++) {
  83212. result.push(new BABYLON.Vector2(cx + Math.cos(angle) * radius, cy + Math.sin(angle) * radius));
  83213. angle -= increment;
  83214. }
  83215. return result;
  83216. };
  83217. Polygon.Parse = function (input) {
  83218. var floats = input.split(/[^-+eE\.\d]+/).map(parseFloat).filter(function (val) { return (!isNaN(val)); });
  83219. var i, result = [];
  83220. for (i = 0; i < (floats.length & 0x7FFFFFFE); i += 2) {
  83221. result.push(new BABYLON.Vector2(floats[i], floats[i + 1]));
  83222. }
  83223. return result;
  83224. };
  83225. Polygon.StartingAt = function (x, y) {
  83226. return BABYLON.Path2.StartingAt(x, y);
  83227. };
  83228. return Polygon;
  83229. }());
  83230. BABYLON.Polygon = Polygon;
  83231. var PolygonMeshBuilder = /** @class */ (function () {
  83232. function PolygonMeshBuilder(name, contours, scene) {
  83233. this._points = new PolygonPoints();
  83234. this._outlinepoints = new PolygonPoints();
  83235. this._holes = new Array();
  83236. this._epoints = new Array();
  83237. this._eholes = new Array();
  83238. this._name = name;
  83239. this._scene = scene;
  83240. var points;
  83241. if (contours instanceof BABYLON.Path2) {
  83242. points = contours.getPoints();
  83243. }
  83244. else {
  83245. points = contours;
  83246. }
  83247. this._addToepoint(points);
  83248. this._points.add(points);
  83249. this._outlinepoints.add(points);
  83250. if (typeof earcut === 'undefined') {
  83251. BABYLON.Tools.Warn("Earcut was not found, the polygon will not be built.");
  83252. }
  83253. }
  83254. PolygonMeshBuilder.prototype._addToepoint = function (points) {
  83255. for (var _i = 0, points_1 = points; _i < points_1.length; _i++) {
  83256. var p = points_1[_i];
  83257. this._epoints.push(p.x, p.y);
  83258. }
  83259. };
  83260. PolygonMeshBuilder.prototype.addHole = function (hole) {
  83261. this._points.add(hole);
  83262. var holepoints = new PolygonPoints();
  83263. holepoints.add(hole);
  83264. this._holes.push(holepoints);
  83265. this._eholes.push(this._epoints.length / 2);
  83266. this._addToepoint(hole);
  83267. return this;
  83268. };
  83269. PolygonMeshBuilder.prototype.build = function (updatable, depth) {
  83270. var _this = this;
  83271. if (updatable === void 0) { updatable = false; }
  83272. if (depth === void 0) { depth = 0; }
  83273. var result = new BABYLON.Mesh(this._name, this._scene);
  83274. var normals = new Array();
  83275. var positions = new Array();
  83276. var uvs = new Array();
  83277. var bounds = this._points.computeBounds();
  83278. this._points.elements.forEach(function (p) {
  83279. normals.push(0, 1.0, 0);
  83280. positions.push(p.x, 0, p.y);
  83281. uvs.push((p.x - bounds.min.x) / bounds.width, (p.y - bounds.min.y) / bounds.height);
  83282. });
  83283. var indices = new Array();
  83284. var res = earcut(this._epoints, this._eholes, 2);
  83285. for (var i = 0; i < res.length; i++) {
  83286. indices.push(res[i]);
  83287. }
  83288. if (depth > 0) {
  83289. var positionscount = (positions.length / 3); //get the current pointcount
  83290. this._points.elements.forEach(function (p) {
  83291. normals.push(0, -1.0, 0);
  83292. positions.push(p.x, -depth, p.y);
  83293. uvs.push(1 - (p.x - bounds.min.x) / bounds.width, 1 - (p.y - bounds.min.y) / bounds.height);
  83294. });
  83295. var totalCount = indices.length;
  83296. for (var i = 0; i < totalCount; i += 3) {
  83297. var i0 = indices[i + 0];
  83298. var i1 = indices[i + 1];
  83299. var i2 = indices[i + 2];
  83300. indices.push(i2 + positionscount);
  83301. indices.push(i1 + positionscount);
  83302. indices.push(i0 + positionscount);
  83303. }
  83304. //Add the sides
  83305. this.addSide(positions, normals, uvs, indices, bounds, this._outlinepoints, depth, false);
  83306. this._holes.forEach(function (hole) {
  83307. _this.addSide(positions, normals, uvs, indices, bounds, hole, depth, true);
  83308. });
  83309. }
  83310. result.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions, updatable);
  83311. result.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals, updatable);
  83312. result.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs, updatable);
  83313. result.setIndices(indices);
  83314. return result;
  83315. };
  83316. PolygonMeshBuilder.prototype.addSide = function (positions, normals, uvs, indices, bounds, points, depth, flip) {
  83317. var StartIndex = positions.length / 3;
  83318. var ulength = 0;
  83319. for (var i = 0; i < points.elements.length; i++) {
  83320. var p = points.elements[i];
  83321. var p1;
  83322. if ((i + 1) > points.elements.length - 1) {
  83323. p1 = points.elements[0];
  83324. }
  83325. else {
  83326. p1 = points.elements[i + 1];
  83327. }
  83328. positions.push(p.x, 0, p.y);
  83329. positions.push(p.x, -depth, p.y);
  83330. positions.push(p1.x, 0, p1.y);
  83331. positions.push(p1.x, -depth, p1.y);
  83332. var v1 = new BABYLON.Vector3(p.x, 0, p.y);
  83333. var v2 = new BABYLON.Vector3(p1.x, 0, p1.y);
  83334. var v3 = v2.subtract(v1);
  83335. var v4 = new BABYLON.Vector3(0, 1, 0);
  83336. var vn = BABYLON.Vector3.Cross(v3, v4);
  83337. vn = vn.normalize();
  83338. uvs.push(ulength / bounds.width, 0);
  83339. uvs.push(ulength / bounds.width, 1);
  83340. ulength += v3.length();
  83341. uvs.push((ulength / bounds.width), 0);
  83342. uvs.push((ulength / bounds.width), 1);
  83343. if (!flip) {
  83344. normals.push(-vn.x, -vn.y, -vn.z);
  83345. normals.push(-vn.x, -vn.y, -vn.z);
  83346. normals.push(-vn.x, -vn.y, -vn.z);
  83347. normals.push(-vn.x, -vn.y, -vn.z);
  83348. indices.push(StartIndex);
  83349. indices.push(StartIndex + 1);
  83350. indices.push(StartIndex + 2);
  83351. indices.push(StartIndex + 1);
  83352. indices.push(StartIndex + 3);
  83353. indices.push(StartIndex + 2);
  83354. }
  83355. else {
  83356. normals.push(vn.x, vn.y, vn.z);
  83357. normals.push(vn.x, vn.y, vn.z);
  83358. normals.push(vn.x, vn.y, vn.z);
  83359. normals.push(vn.x, vn.y, vn.z);
  83360. indices.push(StartIndex);
  83361. indices.push(StartIndex + 2);
  83362. indices.push(StartIndex + 1);
  83363. indices.push(StartIndex + 1);
  83364. indices.push(StartIndex + 2);
  83365. indices.push(StartIndex + 3);
  83366. }
  83367. StartIndex += 4;
  83368. }
  83369. ;
  83370. };
  83371. return PolygonMeshBuilder;
  83372. }());
  83373. BABYLON.PolygonMeshBuilder = PolygonMeshBuilder;
  83374. })(BABYLON || (BABYLON = {}));
  83375. //# sourceMappingURL=babylon.polygonMesh.js.map
  83376. var BABYLON;
  83377. (function (BABYLON) {
  83378. // Unique ID when we import meshes from Babylon to CSG
  83379. var currentCSGMeshId = 0;
  83380. // # class Vertex
  83381. // Represents a vertex of a polygon. Use your own vertex class instead of this
  83382. // one to provide additional features like texture coordinates and vertex
  83383. // colors. Custom vertex classes need to provide a `pos` property and `clone()`,
  83384. // `flip()`, and `interpolate()` methods that behave analogous to the ones
  83385. // defined by `BABYLON.CSG.Vertex`. This class provides `normal` so convenience
  83386. // functions like `BABYLON.CSG.sphere()` can return a smooth vertex normal, but `normal`
  83387. // is not used anywhere else.
  83388. // Same goes for uv, it allows to keep the original vertex uv coordinates of the 2 meshes
  83389. var Vertex = /** @class */ (function () {
  83390. function Vertex(pos, normal, uv) {
  83391. this.pos = pos;
  83392. this.normal = normal;
  83393. this.uv = uv;
  83394. }
  83395. Vertex.prototype.clone = function () {
  83396. return new Vertex(this.pos.clone(), this.normal.clone(), this.uv.clone());
  83397. };
  83398. // Invert all orientation-specific data (e.g. vertex normal). Called when the
  83399. // orientation of a polygon is flipped.
  83400. Vertex.prototype.flip = function () {
  83401. this.normal = this.normal.scale(-1);
  83402. };
  83403. // Create a new vertex between this vertex and `other` by linearly
  83404. // interpolating all properties using a parameter of `t`. Subclasses should
  83405. // override this to interpolate additional properties.
  83406. Vertex.prototype.interpolate = function (other, t) {
  83407. 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));
  83408. };
  83409. return Vertex;
  83410. }());
  83411. // # class Plane
  83412. // Represents a plane in 3D space.
  83413. var Plane = /** @class */ (function () {
  83414. function Plane(normal, w) {
  83415. this.normal = normal;
  83416. this.w = w;
  83417. }
  83418. Plane.FromPoints = function (a, b, c) {
  83419. var v0 = c.subtract(a);
  83420. var v1 = b.subtract(a);
  83421. if (v0.lengthSquared() === 0 || v1.lengthSquared() === 0) {
  83422. return null;
  83423. }
  83424. var n = BABYLON.Vector3.Normalize(BABYLON.Vector3.Cross(v0, v1));
  83425. return new Plane(n, BABYLON.Vector3.Dot(n, a));
  83426. };
  83427. Plane.prototype.clone = function () {
  83428. return new Plane(this.normal.clone(), this.w);
  83429. };
  83430. Plane.prototype.flip = function () {
  83431. this.normal.scaleInPlace(-1);
  83432. this.w = -this.w;
  83433. };
  83434. // Split `polygon` by this plane if needed, then put the polygon or polygon
  83435. // fragments in the appropriate lists. Coplanar polygons go into either
  83436. // `coplanarFront` or `coplanarBack` depending on their orientation with
  83437. // respect to this plane. Polygons in front or in back of this plane go into
  83438. // either `front` or `back`.
  83439. Plane.prototype.splitPolygon = function (polygon, coplanarFront, coplanarBack, front, back) {
  83440. var COPLANAR = 0;
  83441. var FRONT = 1;
  83442. var BACK = 2;
  83443. var SPANNING = 3;
  83444. // Classify each point as well as the entire polygon into one of the above
  83445. // four classes.
  83446. var polygonType = 0;
  83447. var types = [];
  83448. var i;
  83449. var t;
  83450. for (i = 0; i < polygon.vertices.length; i++) {
  83451. t = BABYLON.Vector3.Dot(this.normal, polygon.vertices[i].pos) - this.w;
  83452. var type = (t < -Plane.EPSILON) ? BACK : (t > Plane.EPSILON) ? FRONT : COPLANAR;
  83453. polygonType |= type;
  83454. types.push(type);
  83455. }
  83456. // Put the polygon in the correct list, splitting it when necessary.
  83457. switch (polygonType) {
  83458. case COPLANAR:
  83459. (BABYLON.Vector3.Dot(this.normal, polygon.plane.normal) > 0 ? coplanarFront : coplanarBack).push(polygon);
  83460. break;
  83461. case FRONT:
  83462. front.push(polygon);
  83463. break;
  83464. case BACK:
  83465. back.push(polygon);
  83466. break;
  83467. case SPANNING:
  83468. var f = [], b = [];
  83469. for (i = 0; i < polygon.vertices.length; i++) {
  83470. var j = (i + 1) % polygon.vertices.length;
  83471. var ti = types[i], tj = types[j];
  83472. var vi = polygon.vertices[i], vj = polygon.vertices[j];
  83473. if (ti !== BACK)
  83474. f.push(vi);
  83475. if (ti !== FRONT)
  83476. b.push(ti !== BACK ? vi.clone() : vi);
  83477. if ((ti | tj) === SPANNING) {
  83478. t = (this.w - BABYLON.Vector3.Dot(this.normal, vi.pos)) / BABYLON.Vector3.Dot(this.normal, vj.pos.subtract(vi.pos));
  83479. var v = vi.interpolate(vj, t);
  83480. f.push(v);
  83481. b.push(v.clone());
  83482. }
  83483. }
  83484. var poly;
  83485. if (f.length >= 3) {
  83486. poly = new Polygon(f, polygon.shared);
  83487. if (poly.plane)
  83488. front.push(poly);
  83489. }
  83490. if (b.length >= 3) {
  83491. poly = new Polygon(b, polygon.shared);
  83492. if (poly.plane)
  83493. back.push(poly);
  83494. }
  83495. break;
  83496. }
  83497. };
  83498. // `BABYLON.CSG.Plane.EPSILON` is the tolerance used by `splitPolygon()` to decide if a
  83499. // point is on the plane.
  83500. Plane.EPSILON = 1e-5;
  83501. return Plane;
  83502. }());
  83503. // # class Polygon
  83504. // Represents a convex polygon. The vertices used to initialize a polygon must
  83505. // be coplanar and form a convex loop.
  83506. //
  83507. // Each convex polygon has a `shared` property, which is shared between all
  83508. // polygons that are clones of each other or were split from the same polygon.
  83509. // This can be used to define per-polygon properties (such as surface color).
  83510. var Polygon = /** @class */ (function () {
  83511. function Polygon(vertices, shared) {
  83512. this.vertices = vertices;
  83513. this.shared = shared;
  83514. this.plane = Plane.FromPoints(vertices[0].pos, vertices[1].pos, vertices[2].pos);
  83515. }
  83516. Polygon.prototype.clone = function () {
  83517. var vertices = this.vertices.map(function (v) { return v.clone(); });
  83518. return new Polygon(vertices, this.shared);
  83519. };
  83520. Polygon.prototype.flip = function () {
  83521. this.vertices.reverse().map(function (v) { v.flip(); });
  83522. this.plane.flip();
  83523. };
  83524. return Polygon;
  83525. }());
  83526. // # class Node
  83527. // Holds a node in a BSP tree. A BSP tree is built from a collection of polygons
  83528. // by picking a polygon to split along. That polygon (and all other coplanar
  83529. // polygons) are added directly to that node and the other polygons are added to
  83530. // the front and/or back subtrees. This is not a leafy BSP tree since there is
  83531. // no distinction between internal and leaf nodes.
  83532. var Node = /** @class */ (function () {
  83533. function Node(polygons) {
  83534. this.plane = null;
  83535. this.front = null;
  83536. this.back = null;
  83537. this.polygons = new Array();
  83538. if (polygons) {
  83539. this.build(polygons);
  83540. }
  83541. }
  83542. Node.prototype.clone = function () {
  83543. var node = new Node();
  83544. node.plane = this.plane && this.plane.clone();
  83545. node.front = this.front && this.front.clone();
  83546. node.back = this.back && this.back.clone();
  83547. node.polygons = this.polygons.map(function (p) { return p.clone(); });
  83548. return node;
  83549. };
  83550. // Convert solid space to empty space and empty space to solid space.
  83551. Node.prototype.invert = function () {
  83552. for (var i = 0; i < this.polygons.length; i++) {
  83553. this.polygons[i].flip();
  83554. }
  83555. if (this.plane) {
  83556. this.plane.flip();
  83557. }
  83558. if (this.front) {
  83559. this.front.invert();
  83560. }
  83561. if (this.back) {
  83562. this.back.invert();
  83563. }
  83564. var temp = this.front;
  83565. this.front = this.back;
  83566. this.back = temp;
  83567. };
  83568. // Recursively remove all polygons in `polygons` that are inside this BSP
  83569. // tree.
  83570. Node.prototype.clipPolygons = function (polygons) {
  83571. if (!this.plane)
  83572. return polygons.slice();
  83573. var front = new Array(), back = new Array();
  83574. for (var i = 0; i < polygons.length; i++) {
  83575. this.plane.splitPolygon(polygons[i], front, back, front, back);
  83576. }
  83577. if (this.front) {
  83578. front = this.front.clipPolygons(front);
  83579. }
  83580. if (this.back) {
  83581. back = this.back.clipPolygons(back);
  83582. }
  83583. else {
  83584. back = [];
  83585. }
  83586. return front.concat(back);
  83587. };
  83588. // Remove all polygons in this BSP tree that are inside the other BSP tree
  83589. // `bsp`.
  83590. Node.prototype.clipTo = function (bsp) {
  83591. this.polygons = bsp.clipPolygons(this.polygons);
  83592. if (this.front)
  83593. this.front.clipTo(bsp);
  83594. if (this.back)
  83595. this.back.clipTo(bsp);
  83596. };
  83597. // Return a list of all polygons in this BSP tree.
  83598. Node.prototype.allPolygons = function () {
  83599. var polygons = this.polygons.slice();
  83600. if (this.front)
  83601. polygons = polygons.concat(this.front.allPolygons());
  83602. if (this.back)
  83603. polygons = polygons.concat(this.back.allPolygons());
  83604. return polygons;
  83605. };
  83606. // Build a BSP tree out of `polygons`. When called on an existing tree, the
  83607. // new polygons are filtered down to the bottom of the tree and become new
  83608. // nodes there. Each set of polygons is partitioned using the first polygon
  83609. // (no heuristic is used to pick a good split).
  83610. Node.prototype.build = function (polygons) {
  83611. if (!polygons.length)
  83612. return;
  83613. if (!this.plane)
  83614. this.plane = polygons[0].plane.clone();
  83615. var front = new Array(), back = new Array();
  83616. for (var i = 0; i < polygons.length; i++) {
  83617. this.plane.splitPolygon(polygons[i], this.polygons, this.polygons, front, back);
  83618. }
  83619. if (front.length) {
  83620. if (!this.front)
  83621. this.front = new Node();
  83622. this.front.build(front);
  83623. }
  83624. if (back.length) {
  83625. if (!this.back)
  83626. this.back = new Node();
  83627. this.back.build(back);
  83628. }
  83629. };
  83630. return Node;
  83631. }());
  83632. var CSG = /** @class */ (function () {
  83633. function CSG() {
  83634. this.polygons = new Array();
  83635. }
  83636. // Convert BABYLON.Mesh to BABYLON.CSG
  83637. CSG.FromMesh = function (mesh) {
  83638. var vertex, normal, uv, position, polygon, polygons = new Array(), vertices;
  83639. var matrix, meshPosition, meshRotation, meshRotationQuaternion = null, meshScaling;
  83640. if (mesh instanceof BABYLON.Mesh) {
  83641. mesh.computeWorldMatrix(true);
  83642. matrix = mesh.getWorldMatrix();
  83643. meshPosition = mesh.position.clone();
  83644. meshRotation = mesh.rotation.clone();
  83645. if (mesh.rotationQuaternion) {
  83646. meshRotationQuaternion = mesh.rotationQuaternion.clone();
  83647. }
  83648. meshScaling = mesh.scaling.clone();
  83649. }
  83650. else {
  83651. throw 'BABYLON.CSG: Wrong Mesh type, must be BABYLON.Mesh';
  83652. }
  83653. var indices = mesh.getIndices(), positions = mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind), normals = mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind), uvs = mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  83654. var subMeshes = mesh.subMeshes;
  83655. for (var sm = 0, sml = subMeshes.length; sm < sml; sm++) {
  83656. for (var i = subMeshes[sm].indexStart, il = subMeshes[sm].indexCount + subMeshes[sm].indexStart; i < il; i += 3) {
  83657. vertices = [];
  83658. for (var j = 0; j < 3; j++) {
  83659. var sourceNormal = new BABYLON.Vector3(normals[indices[i + j] * 3], normals[indices[i + j] * 3 + 1], normals[indices[i + j] * 3 + 2]);
  83660. uv = new BABYLON.Vector2(uvs[indices[i + j] * 2], uvs[indices[i + j] * 2 + 1]);
  83661. var sourcePosition = new BABYLON.Vector3(positions[indices[i + j] * 3], positions[indices[i + j] * 3 + 1], positions[indices[i + j] * 3 + 2]);
  83662. position = BABYLON.Vector3.TransformCoordinates(sourcePosition, matrix);
  83663. normal = BABYLON.Vector3.TransformNormal(sourceNormal, matrix);
  83664. vertex = new Vertex(position, normal, uv);
  83665. vertices.push(vertex);
  83666. }
  83667. polygon = new Polygon(vertices, { subMeshId: sm, meshId: currentCSGMeshId, materialIndex: subMeshes[sm].materialIndex });
  83668. // To handle the case of degenerated triangle
  83669. // polygon.plane == null <=> the polygon does not represent 1 single plane <=> the triangle is degenerated
  83670. if (polygon.plane)
  83671. polygons.push(polygon);
  83672. }
  83673. }
  83674. var csg = CSG.FromPolygons(polygons);
  83675. csg.matrix = matrix;
  83676. csg.position = meshPosition;
  83677. csg.rotation = meshRotation;
  83678. csg.scaling = meshScaling;
  83679. csg.rotationQuaternion = meshRotationQuaternion;
  83680. currentCSGMeshId++;
  83681. return csg;
  83682. };
  83683. // Construct a BABYLON.CSG solid from a list of `BABYLON.CSG.Polygon` instances.
  83684. CSG.FromPolygons = function (polygons) {
  83685. var csg = new CSG();
  83686. csg.polygons = polygons;
  83687. return csg;
  83688. };
  83689. CSG.prototype.clone = function () {
  83690. var csg = new CSG();
  83691. csg.polygons = this.polygons.map(function (p) { return p.clone(); });
  83692. csg.copyTransformAttributes(this);
  83693. return csg;
  83694. };
  83695. CSG.prototype.union = function (csg) {
  83696. var a = new Node(this.clone().polygons);
  83697. var b = new Node(csg.clone().polygons);
  83698. a.clipTo(b);
  83699. b.clipTo(a);
  83700. b.invert();
  83701. b.clipTo(a);
  83702. b.invert();
  83703. a.build(b.allPolygons());
  83704. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83705. };
  83706. CSG.prototype.unionInPlace = function (csg) {
  83707. var a = new Node(this.polygons);
  83708. var b = new Node(csg.polygons);
  83709. a.clipTo(b);
  83710. b.clipTo(a);
  83711. b.invert();
  83712. b.clipTo(a);
  83713. b.invert();
  83714. a.build(b.allPolygons());
  83715. this.polygons = a.allPolygons();
  83716. };
  83717. CSG.prototype.subtract = function (csg) {
  83718. var a = new Node(this.clone().polygons);
  83719. var b = new Node(csg.clone().polygons);
  83720. a.invert();
  83721. a.clipTo(b);
  83722. b.clipTo(a);
  83723. b.invert();
  83724. b.clipTo(a);
  83725. b.invert();
  83726. a.build(b.allPolygons());
  83727. a.invert();
  83728. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83729. };
  83730. CSG.prototype.subtractInPlace = function (csg) {
  83731. var a = new Node(this.polygons);
  83732. var b = new Node(csg.polygons);
  83733. a.invert();
  83734. a.clipTo(b);
  83735. b.clipTo(a);
  83736. b.invert();
  83737. b.clipTo(a);
  83738. b.invert();
  83739. a.build(b.allPolygons());
  83740. a.invert();
  83741. this.polygons = a.allPolygons();
  83742. };
  83743. CSG.prototype.intersect = function (csg) {
  83744. var a = new Node(this.clone().polygons);
  83745. var b = new Node(csg.clone().polygons);
  83746. a.invert();
  83747. b.clipTo(a);
  83748. b.invert();
  83749. a.clipTo(b);
  83750. b.clipTo(a);
  83751. a.build(b.allPolygons());
  83752. a.invert();
  83753. return CSG.FromPolygons(a.allPolygons()).copyTransformAttributes(this);
  83754. };
  83755. CSG.prototype.intersectInPlace = function (csg) {
  83756. var a = new Node(this.polygons);
  83757. var b = new Node(csg.polygons);
  83758. a.invert();
  83759. b.clipTo(a);
  83760. b.invert();
  83761. a.clipTo(b);
  83762. b.clipTo(a);
  83763. a.build(b.allPolygons());
  83764. a.invert();
  83765. this.polygons = a.allPolygons();
  83766. };
  83767. // Return a new BABYLON.CSG solid with solid and empty space switched. This solid is
  83768. // not modified.
  83769. CSG.prototype.inverse = function () {
  83770. var csg = this.clone();
  83771. csg.inverseInPlace();
  83772. return csg;
  83773. };
  83774. CSG.prototype.inverseInPlace = function () {
  83775. this.polygons.map(function (p) { p.flip(); });
  83776. };
  83777. // This is used to keep meshes transformations so they can be restored
  83778. // when we build back a Babylon Mesh
  83779. // NB : All CSG operations are performed in world coordinates
  83780. CSG.prototype.copyTransformAttributes = function (csg) {
  83781. this.matrix = csg.matrix;
  83782. this.position = csg.position;
  83783. this.rotation = csg.rotation;
  83784. this.scaling = csg.scaling;
  83785. this.rotationQuaternion = csg.rotationQuaternion;
  83786. return this;
  83787. };
  83788. // Build Raw mesh from CSG
  83789. // Coordinates here are in world space
  83790. CSG.prototype.buildMeshGeometry = function (name, scene, keepSubMeshes) {
  83791. var matrix = this.matrix.clone();
  83792. matrix.invert();
  83793. 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;
  83794. if (keepSubMeshes) {
  83795. // Sort Polygons, since subMeshes are indices range
  83796. polygons.sort(function (a, b) {
  83797. if (a.shared.meshId === b.shared.meshId) {
  83798. return a.shared.subMeshId - b.shared.subMeshId;
  83799. }
  83800. else {
  83801. return a.shared.meshId - b.shared.meshId;
  83802. }
  83803. });
  83804. }
  83805. for (var i = 0, il = polygons.length; i < il; i++) {
  83806. polygon = polygons[i];
  83807. // Building SubMeshes
  83808. if (!subMesh_dict[polygon.shared.meshId]) {
  83809. subMesh_dict[polygon.shared.meshId] = {};
  83810. }
  83811. if (!subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId]) {
  83812. subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId] = {
  83813. indexStart: +Infinity,
  83814. indexEnd: -Infinity,
  83815. materialIndex: polygon.shared.materialIndex
  83816. };
  83817. }
  83818. subMesh_obj = subMesh_dict[polygon.shared.meshId][polygon.shared.subMeshId];
  83819. for (var j = 2, jl = polygon.vertices.length; j < jl; j++) {
  83820. polygonIndices[0] = 0;
  83821. polygonIndices[1] = j - 1;
  83822. polygonIndices[2] = j;
  83823. for (var k = 0; k < 3; k++) {
  83824. vertex.copyFrom(polygon.vertices[polygonIndices[k]].pos);
  83825. normal.copyFrom(polygon.vertices[polygonIndices[k]].normal);
  83826. uv.copyFrom(polygon.vertices[polygonIndices[k]].uv);
  83827. var localVertex = BABYLON.Vector3.TransformCoordinates(vertex, matrix);
  83828. var localNormal = BABYLON.Vector3.TransformNormal(normal, matrix);
  83829. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z];
  83830. // Check if 2 points can be merged
  83831. if (!(typeof vertex_idx !== 'undefined' &&
  83832. normals[vertex_idx * 3] === localNormal.x &&
  83833. normals[vertex_idx * 3 + 1] === localNormal.y &&
  83834. normals[vertex_idx * 3 + 2] === localNormal.z &&
  83835. uvs[vertex_idx * 2] === uv.x &&
  83836. uvs[vertex_idx * 2 + 1] === uv.y)) {
  83837. vertices.push(localVertex.x, localVertex.y, localVertex.z);
  83838. uvs.push(uv.x, uv.y);
  83839. normals.push(normal.x, normal.y, normal.z);
  83840. vertex_idx = vertice_dict[localVertex.x + ',' + localVertex.y + ',' + localVertex.z] = (vertices.length / 3) - 1;
  83841. }
  83842. indices.push(vertex_idx);
  83843. subMesh_obj.indexStart = Math.min(currentIndex, subMesh_obj.indexStart);
  83844. subMesh_obj.indexEnd = Math.max(currentIndex, subMesh_obj.indexEnd);
  83845. currentIndex++;
  83846. }
  83847. }
  83848. }
  83849. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, vertices);
  83850. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  83851. mesh.setVerticesData(BABYLON.VertexBuffer.UVKind, uvs);
  83852. mesh.setIndices(indices, null);
  83853. if (keepSubMeshes) {
  83854. // We offset the materialIndex by the previous number of materials in the CSG mixed meshes
  83855. var materialIndexOffset = 0, materialMaxIndex;
  83856. mesh.subMeshes = new Array();
  83857. for (var m in subMesh_dict) {
  83858. materialMaxIndex = -1;
  83859. for (var sm in subMesh_dict[m]) {
  83860. subMesh_obj = subMesh_dict[m][sm];
  83861. BABYLON.SubMesh.CreateFromIndices(subMesh_obj.materialIndex + materialIndexOffset, subMesh_obj.indexStart, subMesh_obj.indexEnd - subMesh_obj.indexStart + 1, mesh);
  83862. materialMaxIndex = Math.max(subMesh_obj.materialIndex, materialMaxIndex);
  83863. }
  83864. materialIndexOffset += ++materialMaxIndex;
  83865. }
  83866. }
  83867. return mesh;
  83868. };
  83869. // Build Mesh from CSG taking material and transforms into account
  83870. CSG.prototype.toMesh = function (name, material, scene, keepSubMeshes) {
  83871. var mesh = this.buildMeshGeometry(name, scene, keepSubMeshes);
  83872. mesh.material = material;
  83873. mesh.position.copyFrom(this.position);
  83874. mesh.rotation.copyFrom(this.rotation);
  83875. if (this.rotationQuaternion) {
  83876. mesh.rotationQuaternion = this.rotationQuaternion.clone();
  83877. }
  83878. mesh.scaling.copyFrom(this.scaling);
  83879. mesh.computeWorldMatrix(true);
  83880. return mesh;
  83881. };
  83882. return CSG;
  83883. }());
  83884. BABYLON.CSG = CSG;
  83885. })(BABYLON || (BABYLON = {}));
  83886. //# sourceMappingURL=babylon.csg.js.map
  83887. var BABYLON;
  83888. (function (BABYLON) {
  83889. var LensFlare = /** @class */ (function () {
  83890. function LensFlare(size, position, color, imgUrl, system) {
  83891. this.size = size;
  83892. this.position = position;
  83893. this.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  83894. this.color = color || new BABYLON.Color3(1, 1, 1);
  83895. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, system.getScene(), true) : null;
  83896. this._system = system;
  83897. system.lensFlares.push(this);
  83898. }
  83899. LensFlare.AddFlare = function (size, position, color, imgUrl, system) {
  83900. return new LensFlare(size, position, color, imgUrl, system);
  83901. };
  83902. LensFlare.prototype.dispose = function () {
  83903. if (this.texture) {
  83904. this.texture.dispose();
  83905. }
  83906. // Remove from scene
  83907. var index = this._system.lensFlares.indexOf(this);
  83908. this._system.lensFlares.splice(index, 1);
  83909. };
  83910. ;
  83911. return LensFlare;
  83912. }());
  83913. BABYLON.LensFlare = LensFlare;
  83914. })(BABYLON || (BABYLON = {}));
  83915. //# sourceMappingURL=babylon.lensFlare.js.map
  83916. var BABYLON;
  83917. (function (BABYLON) {
  83918. var LensFlareSystem = /** @class */ (function () {
  83919. function LensFlareSystem(name, emitter, scene) {
  83920. this.name = name;
  83921. this.lensFlares = new Array();
  83922. this.borderLimit = 300;
  83923. this.viewportBorder = 0;
  83924. this.layerMask = 0x0FFFFFFF;
  83925. this._vertexBuffers = {};
  83926. this._isEnabled = true;
  83927. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  83928. this._emitter = emitter;
  83929. this.id = name;
  83930. scene.lensFlareSystems.push(this);
  83931. this.meshesSelectionPredicate = function (m) { return (scene.activeCamera && m.material && m.isVisible && m.isEnabled() && m.isBlocker && ((m.layerMask & scene.activeCamera.layerMask) != 0)); };
  83932. var engine = scene.getEngine();
  83933. // VBO
  83934. var vertices = [];
  83935. vertices.push(1, 1);
  83936. vertices.push(-1, 1);
  83937. vertices.push(-1, -1);
  83938. vertices.push(1, -1);
  83939. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  83940. // Indices
  83941. var indices = [];
  83942. indices.push(0);
  83943. indices.push(1);
  83944. indices.push(2);
  83945. indices.push(0);
  83946. indices.push(2);
  83947. indices.push(3);
  83948. this._indexBuffer = engine.createIndexBuffer(indices);
  83949. // Effects
  83950. this._effect = engine.createEffect("lensFlare", [BABYLON.VertexBuffer.PositionKind], ["color", "viewportMatrix"], ["textureSampler"], "");
  83951. }
  83952. Object.defineProperty(LensFlareSystem.prototype, "isEnabled", {
  83953. get: function () {
  83954. return this._isEnabled;
  83955. },
  83956. set: function (value) {
  83957. this._isEnabled = value;
  83958. },
  83959. enumerable: true,
  83960. configurable: true
  83961. });
  83962. LensFlareSystem.prototype.getScene = function () {
  83963. return this._scene;
  83964. };
  83965. LensFlareSystem.prototype.getEmitter = function () {
  83966. return this._emitter;
  83967. };
  83968. LensFlareSystem.prototype.setEmitter = function (newEmitter) {
  83969. this._emitter = newEmitter;
  83970. };
  83971. LensFlareSystem.prototype.getEmitterPosition = function () {
  83972. return this._emitter.getAbsolutePosition ? this._emitter.getAbsolutePosition() : this._emitter.position;
  83973. };
  83974. LensFlareSystem.prototype.computeEffectivePosition = function (globalViewport) {
  83975. var position = this.getEmitterPosition();
  83976. position = BABYLON.Vector3.Project(position, BABYLON.Matrix.Identity(), this._scene.getTransformMatrix(), globalViewport);
  83977. this._positionX = position.x;
  83978. this._positionY = position.y;
  83979. position = BABYLON.Vector3.TransformCoordinates(this.getEmitterPosition(), this._scene.getViewMatrix());
  83980. if (this.viewportBorder > 0) {
  83981. globalViewport.x -= this.viewportBorder;
  83982. globalViewport.y -= this.viewportBorder;
  83983. globalViewport.width += this.viewportBorder * 2;
  83984. globalViewport.height += this.viewportBorder * 2;
  83985. position.x += this.viewportBorder;
  83986. position.y += this.viewportBorder;
  83987. this._positionX += this.viewportBorder;
  83988. this._positionY += this.viewportBorder;
  83989. }
  83990. if (position.z > 0) {
  83991. if ((this._positionX > globalViewport.x) && (this._positionX < globalViewport.x + globalViewport.width)) {
  83992. if ((this._positionY > globalViewport.y) && (this._positionY < globalViewport.y + globalViewport.height))
  83993. return true;
  83994. }
  83995. return true;
  83996. }
  83997. return false;
  83998. };
  83999. LensFlareSystem.prototype._isVisible = function () {
  84000. if (!this._isEnabled || !this._scene.activeCamera) {
  84001. return false;
  84002. }
  84003. var emitterPosition = this.getEmitterPosition();
  84004. var direction = emitterPosition.subtract(this._scene.activeCamera.globalPosition);
  84005. var distance = direction.length();
  84006. direction.normalize();
  84007. var ray = new BABYLON.Ray(this._scene.activeCamera.globalPosition, direction);
  84008. var pickInfo = this._scene.pickWithRay(ray, this.meshesSelectionPredicate, true);
  84009. return !pickInfo || !pickInfo.hit || pickInfo.distance > distance;
  84010. };
  84011. LensFlareSystem.prototype.render = function () {
  84012. if (!this._effect.isReady() || !this._scene.activeCamera)
  84013. return false;
  84014. var engine = this._scene.getEngine();
  84015. var viewport = this._scene.activeCamera.viewport;
  84016. var globalViewport = viewport.toGlobal(engine.getRenderWidth(true), engine.getRenderHeight(true));
  84017. // Position
  84018. if (!this.computeEffectivePosition(globalViewport)) {
  84019. return false;
  84020. }
  84021. // Visibility
  84022. if (!this._isVisible()) {
  84023. return false;
  84024. }
  84025. // Intensity
  84026. var awayX;
  84027. var awayY;
  84028. if (this._positionX < this.borderLimit + globalViewport.x) {
  84029. awayX = this.borderLimit + globalViewport.x - this._positionX;
  84030. }
  84031. else if (this._positionX > globalViewport.x + globalViewport.width - this.borderLimit) {
  84032. awayX = this._positionX - globalViewport.x - globalViewport.width + this.borderLimit;
  84033. }
  84034. else {
  84035. awayX = 0;
  84036. }
  84037. if (this._positionY < this.borderLimit + globalViewport.y) {
  84038. awayY = this.borderLimit + globalViewport.y - this._positionY;
  84039. }
  84040. else if (this._positionY > globalViewport.y + globalViewport.height - this.borderLimit) {
  84041. awayY = this._positionY - globalViewport.y - globalViewport.height + this.borderLimit;
  84042. }
  84043. else {
  84044. awayY = 0;
  84045. }
  84046. var away = (awayX > awayY) ? awayX : awayY;
  84047. away -= this.viewportBorder;
  84048. if (away > this.borderLimit) {
  84049. away = this.borderLimit;
  84050. }
  84051. var intensity = 1.0 - (away / this.borderLimit);
  84052. if (intensity < 0) {
  84053. return false;
  84054. }
  84055. if (intensity > 1.0) {
  84056. intensity = 1.0;
  84057. }
  84058. if (this.viewportBorder > 0) {
  84059. globalViewport.x += this.viewportBorder;
  84060. globalViewport.y += this.viewportBorder;
  84061. globalViewport.width -= this.viewportBorder * 2;
  84062. globalViewport.height -= this.viewportBorder * 2;
  84063. this._positionX -= this.viewportBorder;
  84064. this._positionY -= this.viewportBorder;
  84065. }
  84066. // Position
  84067. var centerX = globalViewport.x + globalViewport.width / 2;
  84068. var centerY = globalViewport.y + globalViewport.height / 2;
  84069. var distX = centerX - this._positionX;
  84070. var distY = centerY - this._positionY;
  84071. // Effects
  84072. engine.enableEffect(this._effect);
  84073. engine.setState(false);
  84074. engine.setDepthBuffer(false);
  84075. // VBOs
  84076. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._effect);
  84077. // Flares
  84078. for (var index = 0; index < this.lensFlares.length; index++) {
  84079. var flare = this.lensFlares[index];
  84080. engine.setAlphaMode(flare.alphaMode);
  84081. var x = centerX - (distX * flare.position);
  84082. var y = centerY - (distY * flare.position);
  84083. var cw = flare.size;
  84084. var ch = flare.size * engine.getAspectRatio(this._scene.activeCamera, true);
  84085. var cx = 2 * (x / (globalViewport.width + globalViewport.x * 2)) - 1.0;
  84086. var cy = 1.0 - 2 * (y / (globalViewport.height + globalViewport.y * 2));
  84087. var viewportMatrix = BABYLON.Matrix.FromValues(cw / 2, 0, 0, 0, 0, ch / 2, 0, 0, 0, 0, 1, 0, cx, cy, 0, 1);
  84088. this._effect.setMatrix("viewportMatrix", viewportMatrix);
  84089. // Texture
  84090. this._effect.setTexture("textureSampler", flare.texture);
  84091. // Color
  84092. this._effect.setFloat4("color", flare.color.r * intensity, flare.color.g * intensity, flare.color.b * intensity, 1.0);
  84093. // Draw order
  84094. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  84095. }
  84096. engine.setDepthBuffer(true);
  84097. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  84098. return true;
  84099. };
  84100. LensFlareSystem.prototype.dispose = function () {
  84101. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  84102. if (vertexBuffer) {
  84103. vertexBuffer.dispose();
  84104. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  84105. }
  84106. if (this._indexBuffer) {
  84107. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  84108. this._indexBuffer = null;
  84109. }
  84110. while (this.lensFlares.length) {
  84111. this.lensFlares[0].dispose();
  84112. }
  84113. // Remove from scene
  84114. var index = this._scene.lensFlareSystems.indexOf(this);
  84115. this._scene.lensFlareSystems.splice(index, 1);
  84116. };
  84117. LensFlareSystem.Parse = function (parsedLensFlareSystem, scene, rootUrl) {
  84118. var emitter = scene.getLastEntryByID(parsedLensFlareSystem.emitterId);
  84119. var name = parsedLensFlareSystem.name || "lensFlareSystem#" + parsedLensFlareSystem.emitterId;
  84120. var lensFlareSystem = new LensFlareSystem(name, emitter, scene);
  84121. lensFlareSystem.id = parsedLensFlareSystem.id || name;
  84122. lensFlareSystem.borderLimit = parsedLensFlareSystem.borderLimit;
  84123. for (var index = 0; index < parsedLensFlareSystem.flares.length; index++) {
  84124. var parsedFlare = parsedLensFlareSystem.flares[index];
  84125. BABYLON.LensFlare.AddFlare(parsedFlare.size, parsedFlare.position, BABYLON.Color3.FromArray(parsedFlare.color), parsedFlare.textureName ? rootUrl + parsedFlare.textureName : "", lensFlareSystem);
  84126. }
  84127. return lensFlareSystem;
  84128. };
  84129. LensFlareSystem.prototype.serialize = function () {
  84130. var serializationObject = {};
  84131. serializationObject.id = this.id;
  84132. serializationObject.name = this.name;
  84133. serializationObject.emitterId = this.getEmitter().id;
  84134. serializationObject.borderLimit = this.borderLimit;
  84135. serializationObject.flares = [];
  84136. for (var index = 0; index < this.lensFlares.length; index++) {
  84137. var flare = this.lensFlares[index];
  84138. serializationObject.flares.push({
  84139. size: flare.size,
  84140. position: flare.position,
  84141. color: flare.color.asArray(),
  84142. textureName: BABYLON.Tools.GetFilename(flare.texture ? flare.texture.name : "")
  84143. });
  84144. }
  84145. return serializationObject;
  84146. };
  84147. return LensFlareSystem;
  84148. }());
  84149. BABYLON.LensFlareSystem = LensFlareSystem;
  84150. })(BABYLON || (BABYLON = {}));
  84151. //# sourceMappingURL=babylon.lensFlareSystem.js.map
  84152. var BABYLON;
  84153. (function (BABYLON) {
  84154. /**
  84155. * This is a holder class for the physics joint created by the physics plugin.
  84156. * It holds a set of functions to control the underlying joint.
  84157. */
  84158. var PhysicsJoint = /** @class */ (function () {
  84159. function PhysicsJoint(type, jointData) {
  84160. this.type = type;
  84161. this.jointData = jointData;
  84162. jointData.nativeParams = jointData.nativeParams || {};
  84163. }
  84164. Object.defineProperty(PhysicsJoint.prototype, "physicsJoint", {
  84165. get: function () {
  84166. return this._physicsJoint;
  84167. },
  84168. set: function (newJoint) {
  84169. if (this._physicsJoint) {
  84170. //remove from the wolrd
  84171. }
  84172. this._physicsJoint = newJoint;
  84173. },
  84174. enumerable: true,
  84175. configurable: true
  84176. });
  84177. Object.defineProperty(PhysicsJoint.prototype, "physicsPlugin", {
  84178. set: function (physicsPlugin) {
  84179. this._physicsPlugin = physicsPlugin;
  84180. },
  84181. enumerable: true,
  84182. configurable: true
  84183. });
  84184. /**
  84185. * Execute a function that is physics-plugin specific.
  84186. * @param {Function} func the function that will be executed.
  84187. * It accepts two parameters: the physics world and the physics joint.
  84188. */
  84189. PhysicsJoint.prototype.executeNativeFunction = function (func) {
  84190. func(this._physicsPlugin.world, this._physicsJoint);
  84191. };
  84192. //TODO check if the native joints are the same
  84193. //Joint Types
  84194. PhysicsJoint.DistanceJoint = 0;
  84195. PhysicsJoint.HingeJoint = 1;
  84196. PhysicsJoint.BallAndSocketJoint = 2;
  84197. PhysicsJoint.WheelJoint = 3;
  84198. PhysicsJoint.SliderJoint = 4;
  84199. //OIMO
  84200. PhysicsJoint.PrismaticJoint = 5;
  84201. //ENERGY FTW! (compare with this - http://ode-wiki.org/wiki/index.php?title=Manual:_Joint_Types_and_Functions)
  84202. PhysicsJoint.UniversalJoint = 6;
  84203. PhysicsJoint.Hinge2Joint = PhysicsJoint.WheelJoint;
  84204. //Cannon
  84205. //Similar to a Ball-Joint. Different in params
  84206. PhysicsJoint.PointToPointJoint = 8;
  84207. //Cannon only at the moment
  84208. PhysicsJoint.SpringJoint = 9;
  84209. PhysicsJoint.LockJoint = 10;
  84210. return PhysicsJoint;
  84211. }());
  84212. BABYLON.PhysicsJoint = PhysicsJoint;
  84213. /**
  84214. * A class representing a physics distance joint.
  84215. */
  84216. var DistanceJoint = /** @class */ (function (_super) {
  84217. __extends(DistanceJoint, _super);
  84218. function DistanceJoint(jointData) {
  84219. return _super.call(this, PhysicsJoint.DistanceJoint, jointData) || this;
  84220. }
  84221. /**
  84222. * Update the predefined distance.
  84223. */
  84224. DistanceJoint.prototype.updateDistance = function (maxDistance, minDistance) {
  84225. this._physicsPlugin.updateDistanceJoint(this, maxDistance, minDistance);
  84226. };
  84227. return DistanceJoint;
  84228. }(PhysicsJoint));
  84229. BABYLON.DistanceJoint = DistanceJoint;
  84230. var MotorEnabledJoint = /** @class */ (function (_super) {
  84231. __extends(MotorEnabledJoint, _super);
  84232. function MotorEnabledJoint(type, jointData) {
  84233. return _super.call(this, type, jointData) || this;
  84234. }
  84235. /**
  84236. * Set the motor values.
  84237. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84238. * @param {number} force the force to apply
  84239. * @param {number} maxForce max force for this motor.
  84240. */
  84241. MotorEnabledJoint.prototype.setMotor = function (force, maxForce) {
  84242. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84243. };
  84244. /**
  84245. * Set the motor's limits.
  84246. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84247. */
  84248. MotorEnabledJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84249. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84250. };
  84251. return MotorEnabledJoint;
  84252. }(PhysicsJoint));
  84253. BABYLON.MotorEnabledJoint = MotorEnabledJoint;
  84254. /**
  84255. * This class represents a single hinge physics joint
  84256. */
  84257. var HingeJoint = /** @class */ (function (_super) {
  84258. __extends(HingeJoint, _super);
  84259. function HingeJoint(jointData) {
  84260. return _super.call(this, PhysicsJoint.HingeJoint, jointData) || this;
  84261. }
  84262. /**
  84263. * Set the motor values.
  84264. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84265. * @param {number} force the force to apply
  84266. * @param {number} maxForce max force for this motor.
  84267. */
  84268. HingeJoint.prototype.setMotor = function (force, maxForce) {
  84269. this._physicsPlugin.setMotor(this, force || 0, maxForce);
  84270. };
  84271. /**
  84272. * Set the motor's limits.
  84273. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84274. */
  84275. HingeJoint.prototype.setLimit = function (upperLimit, lowerLimit) {
  84276. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit);
  84277. };
  84278. return HingeJoint;
  84279. }(MotorEnabledJoint));
  84280. BABYLON.HingeJoint = HingeJoint;
  84281. /**
  84282. * This class represents a dual hinge physics joint (same as wheel joint)
  84283. */
  84284. var Hinge2Joint = /** @class */ (function (_super) {
  84285. __extends(Hinge2Joint, _super);
  84286. function Hinge2Joint(jointData) {
  84287. return _super.call(this, PhysicsJoint.Hinge2Joint, jointData) || this;
  84288. }
  84289. /**
  84290. * Set the motor values.
  84291. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84292. * @param {number} force the force to apply
  84293. * @param {number} maxForce max force for this motor.
  84294. * @param {motorIndex} the motor's index, 0 or 1.
  84295. */
  84296. Hinge2Joint.prototype.setMotor = function (force, maxForce, motorIndex) {
  84297. if (motorIndex === void 0) { motorIndex = 0; }
  84298. this._physicsPlugin.setMotor(this, force || 0, maxForce, motorIndex);
  84299. };
  84300. /**
  84301. * Set the motor limits.
  84302. * Attention, this function is plugin specific. Engines won't react 100% the same.
  84303. * @param {number} upperLimit the upper limit
  84304. * @param {number} lowerLimit lower limit
  84305. * @param {motorIndex} the motor's index, 0 or 1.
  84306. */
  84307. Hinge2Joint.prototype.setLimit = function (upperLimit, lowerLimit, motorIndex) {
  84308. if (motorIndex === void 0) { motorIndex = 0; }
  84309. this._physicsPlugin.setLimit(this, upperLimit, lowerLimit, motorIndex);
  84310. };
  84311. return Hinge2Joint;
  84312. }(MotorEnabledJoint));
  84313. BABYLON.Hinge2Joint = Hinge2Joint;
  84314. })(BABYLON || (BABYLON = {}));
  84315. //# sourceMappingURL=babylon.physicsJoint.js.map
  84316. var BABYLON;
  84317. (function (BABYLON) {
  84318. var PhysicsImpostor = /** @class */ (function () {
  84319. function PhysicsImpostor(object, type, _options, _scene) {
  84320. if (_options === void 0) { _options = { mass: 0 }; }
  84321. var _this = this;
  84322. this.object = object;
  84323. this.type = type;
  84324. this._options = _options;
  84325. this._scene = _scene;
  84326. this._bodyUpdateRequired = false;
  84327. this._onBeforePhysicsStepCallbacks = new Array();
  84328. this._onAfterPhysicsStepCallbacks = new Array();
  84329. this._onPhysicsCollideCallbacks = [];
  84330. this._deltaPosition = BABYLON.Vector3.Zero();
  84331. this._isDisposed = false;
  84332. //temp variables for parent rotation calculations
  84333. //private _mats: Array<Matrix> = [new Matrix(), new Matrix()];
  84334. this._tmpQuat = new BABYLON.Quaternion();
  84335. this._tmpQuat2 = new BABYLON.Quaternion();
  84336. /**
  84337. * this function is executed by the physics engine.
  84338. */
  84339. this.beforeStep = function () {
  84340. if (!_this._physicsEngine) {
  84341. return;
  84342. }
  84343. _this.object.translate(_this._deltaPosition, -1);
  84344. _this._deltaRotationConjugated && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotationConjugated, _this.object.rotationQuaternion);
  84345. _this.object.computeWorldMatrix(false);
  84346. if (_this.object.parent && _this.object.rotationQuaternion) {
  84347. _this.getParentsRotation();
  84348. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this._tmpQuat);
  84349. }
  84350. else {
  84351. _this._tmpQuat.copyFrom(_this.object.rotationQuaternion || new BABYLON.Quaternion());
  84352. }
  84353. if (!_this._options.disableBidirectionalTransformation) {
  84354. _this.object.rotationQuaternion && _this._physicsEngine.getPhysicsPlugin().setPhysicsBodyTransformation(_this, /*bInfo.boundingBox.centerWorld*/ _this.object.getAbsolutePivotPoint(), _this._tmpQuat);
  84355. }
  84356. _this._onBeforePhysicsStepCallbacks.forEach(function (func) {
  84357. func(_this);
  84358. });
  84359. };
  84360. /**
  84361. * this function is executed by the physics engine.
  84362. */
  84363. this.afterStep = function () {
  84364. if (!_this._physicsEngine) {
  84365. return;
  84366. }
  84367. _this._onAfterPhysicsStepCallbacks.forEach(function (func) {
  84368. func(_this);
  84369. });
  84370. _this._physicsEngine.getPhysicsPlugin().setTransformationFromPhysicsBody(_this);
  84371. // object has now its world rotation. needs to be converted to local.
  84372. if (_this.object.parent && _this.object.rotationQuaternion) {
  84373. _this.getParentsRotation();
  84374. _this._tmpQuat.conjugateInPlace();
  84375. _this._tmpQuat.multiplyToRef(_this.object.rotationQuaternion, _this.object.rotationQuaternion);
  84376. }
  84377. // take the position set and make it the absolute position of this object.
  84378. _this.object.setAbsolutePosition(_this.object.position);
  84379. _this._deltaRotation && _this.object.rotationQuaternion && _this.object.rotationQuaternion.multiplyToRef(_this._deltaRotation, _this.object.rotationQuaternion);
  84380. _this.object.translate(_this._deltaPosition, 1);
  84381. };
  84382. /**
  84383. * Legacy collision detection event support
  84384. */
  84385. this.onCollideEvent = null;
  84386. //event and body object due to cannon's event-based architecture.
  84387. this.onCollide = function (e) {
  84388. if (!_this._onPhysicsCollideCallbacks.length && !_this.onCollideEvent) {
  84389. return;
  84390. }
  84391. if (!_this._physicsEngine) {
  84392. return;
  84393. }
  84394. var otherImpostor = _this._physicsEngine.getImpostorWithPhysicsBody(e.body);
  84395. if (otherImpostor) {
  84396. // Legacy collision detection event support
  84397. if (_this.onCollideEvent) {
  84398. _this.onCollideEvent(_this, otherImpostor);
  84399. }
  84400. _this._onPhysicsCollideCallbacks.filter(function (obj) {
  84401. return obj.otherImpostors.indexOf(otherImpostor) !== -1;
  84402. }).forEach(function (obj) {
  84403. obj.callback(_this, otherImpostor);
  84404. });
  84405. }
  84406. };
  84407. //sanity check!
  84408. if (!this.object) {
  84409. BABYLON.Tools.Error("No object was provided. A physics object is obligatory");
  84410. return;
  84411. }
  84412. //legacy support for old syntax.
  84413. if (!this._scene && object.getScene) {
  84414. this._scene = object.getScene();
  84415. }
  84416. if (!this._scene) {
  84417. return;
  84418. }
  84419. this._physicsEngine = this._scene.getPhysicsEngine();
  84420. if (!this._physicsEngine) {
  84421. BABYLON.Tools.Error("Physics not enabled. Please use scene.enablePhysics(...) before creating impostors.");
  84422. }
  84423. else {
  84424. //set the object's quaternion, if not set
  84425. if (!this.object.rotationQuaternion) {
  84426. if (this.object.rotation) {
  84427. this.object.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(this.object.rotation.y, this.object.rotation.x, this.object.rotation.z);
  84428. }
  84429. else {
  84430. this.object.rotationQuaternion = new BABYLON.Quaternion();
  84431. }
  84432. }
  84433. //default options params
  84434. this._options.mass = (_options.mass === void 0) ? 0 : _options.mass;
  84435. this._options.friction = (_options.friction === void 0) ? 0.2 : _options.friction;
  84436. this._options.restitution = (_options.restitution === void 0) ? 0.2 : _options.restitution;
  84437. this._joints = [];
  84438. //If the mesh has a parent, don't initialize the physicsBody. Instead wait for the parent to do that.
  84439. if (!this.object.parent || this._options.ignoreParent) {
  84440. this._init();
  84441. }
  84442. else if (this.object.parent.physicsImpostor) {
  84443. BABYLON.Tools.Warn("You must affect impostors to children before affecting impostor to parent.");
  84444. }
  84445. }
  84446. }
  84447. Object.defineProperty(PhysicsImpostor.prototype, "isDisposed", {
  84448. get: function () {
  84449. return this._isDisposed;
  84450. },
  84451. enumerable: true,
  84452. configurable: true
  84453. });
  84454. Object.defineProperty(PhysicsImpostor.prototype, "mass", {
  84455. get: function () {
  84456. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyMass(this) : 0;
  84457. },
  84458. set: function (value) {
  84459. this.setMass(value);
  84460. },
  84461. enumerable: true,
  84462. configurable: true
  84463. });
  84464. Object.defineProperty(PhysicsImpostor.prototype, "friction", {
  84465. get: function () {
  84466. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyFriction(this) : 0;
  84467. },
  84468. set: function (value) {
  84469. if (!this._physicsEngine) {
  84470. return;
  84471. }
  84472. this._physicsEngine.getPhysicsPlugin().setBodyFriction(this, value);
  84473. },
  84474. enumerable: true,
  84475. configurable: true
  84476. });
  84477. Object.defineProperty(PhysicsImpostor.prototype, "restitution", {
  84478. get: function () {
  84479. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getBodyRestitution(this) : 0;
  84480. },
  84481. set: function (value) {
  84482. if (!this._physicsEngine) {
  84483. return;
  84484. }
  84485. this._physicsEngine.getPhysicsPlugin().setBodyRestitution(this, value);
  84486. },
  84487. enumerable: true,
  84488. configurable: true
  84489. });
  84490. /**
  84491. * This function will completly initialize this impostor.
  84492. * It will create a new body - but only if this mesh has no parent.
  84493. * If it has, this impostor will not be used other than to define the impostor
  84494. * of the child mesh.
  84495. */
  84496. PhysicsImpostor.prototype._init = function () {
  84497. if (!this._physicsEngine) {
  84498. return;
  84499. }
  84500. this._physicsEngine.removeImpostor(this);
  84501. this.physicsBody = null;
  84502. this._parent = this._parent || this._getPhysicsParent();
  84503. if (!this._isDisposed && (!this.parent || this._options.ignoreParent)) {
  84504. this._physicsEngine.addImpostor(this);
  84505. }
  84506. };
  84507. PhysicsImpostor.prototype._getPhysicsParent = function () {
  84508. if (this.object.parent instanceof BABYLON.AbstractMesh) {
  84509. var parentMesh = this.object.parent;
  84510. return parentMesh.physicsImpostor;
  84511. }
  84512. return null;
  84513. };
  84514. /**
  84515. * Should a new body be generated.
  84516. */
  84517. PhysicsImpostor.prototype.isBodyInitRequired = function () {
  84518. return this._bodyUpdateRequired || (!this._physicsBody && !this._parent);
  84519. };
  84520. PhysicsImpostor.prototype.setScalingUpdated = function (updated) {
  84521. this.forceUpdate();
  84522. };
  84523. /**
  84524. * Force a regeneration of this or the parent's impostor's body.
  84525. * Use under cautious - This will remove all joints already implemented.
  84526. */
  84527. PhysicsImpostor.prototype.forceUpdate = function () {
  84528. this._init();
  84529. if (this.parent && !this._options.ignoreParent) {
  84530. this.parent.forceUpdate();
  84531. }
  84532. };
  84533. Object.defineProperty(PhysicsImpostor.prototype, "physicsBody", {
  84534. /*public get mesh(): AbstractMesh {
  84535. return this._mesh;
  84536. }*/
  84537. /**
  84538. * Gets the body that holds this impostor. Either its own, or its parent.
  84539. */
  84540. get: function () {
  84541. return (this._parent && !this._options.ignoreParent) ? this._parent.physicsBody : this._physicsBody;
  84542. },
  84543. /**
  84544. * Set the physics body. Used mainly by the physics engine/plugin
  84545. */
  84546. set: function (physicsBody) {
  84547. if (this._physicsBody && this._physicsEngine) {
  84548. this._physicsEngine.getPhysicsPlugin().removePhysicsBody(this);
  84549. }
  84550. this._physicsBody = physicsBody;
  84551. this.resetUpdateFlags();
  84552. },
  84553. enumerable: true,
  84554. configurable: true
  84555. });
  84556. Object.defineProperty(PhysicsImpostor.prototype, "parent", {
  84557. get: function () {
  84558. return !this._options.ignoreParent && this._parent ? this._parent : null;
  84559. },
  84560. set: function (value) {
  84561. this._parent = value;
  84562. },
  84563. enumerable: true,
  84564. configurable: true
  84565. });
  84566. PhysicsImpostor.prototype.resetUpdateFlags = function () {
  84567. this._bodyUpdateRequired = false;
  84568. };
  84569. PhysicsImpostor.prototype.getObjectExtendSize = function () {
  84570. if (this.object.getBoundingInfo) {
  84571. var q = this.object.rotationQuaternion;
  84572. //reset rotation
  84573. this.object.rotationQuaternion = PhysicsImpostor.IDENTITY_QUATERNION;
  84574. //calculate the world matrix with no rotation
  84575. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84576. var boundingInfo = this.object.getBoundingInfo();
  84577. var size = boundingInfo.boundingBox.extendSizeWorld.scale(2);
  84578. //bring back the rotation
  84579. this.object.rotationQuaternion = q;
  84580. //calculate the world matrix with the new rotation
  84581. this.object.computeWorldMatrix && this.object.computeWorldMatrix(true);
  84582. return size;
  84583. }
  84584. else {
  84585. return PhysicsImpostor.DEFAULT_OBJECT_SIZE;
  84586. }
  84587. };
  84588. PhysicsImpostor.prototype.getObjectCenter = function () {
  84589. if (this.object.getBoundingInfo) {
  84590. var boundingInfo = this.object.getBoundingInfo();
  84591. return boundingInfo.boundingBox.centerWorld;
  84592. }
  84593. else {
  84594. return this.object.position;
  84595. }
  84596. };
  84597. /**
  84598. * Get a specific parametes from the options parameter.
  84599. */
  84600. PhysicsImpostor.prototype.getParam = function (paramName) {
  84601. return this._options[paramName];
  84602. };
  84603. /**
  84604. * Sets a specific parameter in the options given to the physics plugin
  84605. */
  84606. PhysicsImpostor.prototype.setParam = function (paramName, value) {
  84607. this._options[paramName] = value;
  84608. this._bodyUpdateRequired = true;
  84609. };
  84610. /**
  84611. * Specifically change the body's mass option. Won't recreate the physics body object
  84612. */
  84613. PhysicsImpostor.prototype.setMass = function (mass) {
  84614. if (this.getParam("mass") !== mass) {
  84615. this.setParam("mass", mass);
  84616. }
  84617. if (this._physicsEngine) {
  84618. this._physicsEngine.getPhysicsPlugin().setBodyMass(this, mass);
  84619. }
  84620. };
  84621. PhysicsImpostor.prototype.getLinearVelocity = function () {
  84622. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getLinearVelocity(this) : BABYLON.Vector3.Zero();
  84623. };
  84624. PhysicsImpostor.prototype.setLinearVelocity = function (velocity) {
  84625. if (this._physicsEngine) {
  84626. this._physicsEngine.getPhysicsPlugin().setLinearVelocity(this, velocity);
  84627. }
  84628. };
  84629. PhysicsImpostor.prototype.getAngularVelocity = function () {
  84630. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getAngularVelocity(this) : BABYLON.Vector3.Zero();
  84631. };
  84632. PhysicsImpostor.prototype.setAngularVelocity = function (velocity) {
  84633. if (this._physicsEngine) {
  84634. this._physicsEngine.getPhysicsPlugin().setAngularVelocity(this, velocity);
  84635. }
  84636. };
  84637. /**
  84638. * Execute a function with the physics plugin native code.
  84639. * Provide a function the will have two variables - the world object and the physics body object.
  84640. */
  84641. PhysicsImpostor.prototype.executeNativeFunction = function (func) {
  84642. if (this._physicsEngine) {
  84643. func(this._physicsEngine.getPhysicsPlugin().world, this.physicsBody);
  84644. }
  84645. };
  84646. /**
  84647. * Register a function that will be executed before the physics world is stepping forward.
  84648. */
  84649. PhysicsImpostor.prototype.registerBeforePhysicsStep = function (func) {
  84650. this._onBeforePhysicsStepCallbacks.push(func);
  84651. };
  84652. PhysicsImpostor.prototype.unregisterBeforePhysicsStep = function (func) {
  84653. var index = this._onBeforePhysicsStepCallbacks.indexOf(func);
  84654. if (index > -1) {
  84655. this._onBeforePhysicsStepCallbacks.splice(index, 1);
  84656. }
  84657. else {
  84658. BABYLON.Tools.Warn("Function to remove was not found");
  84659. }
  84660. };
  84661. /**
  84662. * Register a function that will be executed after the physics step
  84663. */
  84664. PhysicsImpostor.prototype.registerAfterPhysicsStep = function (func) {
  84665. this._onAfterPhysicsStepCallbacks.push(func);
  84666. };
  84667. PhysicsImpostor.prototype.unregisterAfterPhysicsStep = function (func) {
  84668. var index = this._onAfterPhysicsStepCallbacks.indexOf(func);
  84669. if (index > -1) {
  84670. this._onAfterPhysicsStepCallbacks.splice(index, 1);
  84671. }
  84672. else {
  84673. BABYLON.Tools.Warn("Function to remove was not found");
  84674. }
  84675. };
  84676. /**
  84677. * register a function that will be executed when this impostor collides against a different body.
  84678. */
  84679. PhysicsImpostor.prototype.registerOnPhysicsCollide = function (collideAgainst, func) {
  84680. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84681. this._onPhysicsCollideCallbacks.push({ callback: func, otherImpostors: collidedAgainstList });
  84682. };
  84683. PhysicsImpostor.prototype.unregisterOnPhysicsCollide = function (collideAgainst, func) {
  84684. var collidedAgainstList = collideAgainst instanceof Array ? collideAgainst : [collideAgainst];
  84685. var index = -1;
  84686. var found = this._onPhysicsCollideCallbacks.some(function (cbDef, idx) {
  84687. if (cbDef.callback === func && cbDef.otherImpostors.length === collidedAgainstList.length) {
  84688. // chcek the arrays match
  84689. var sameList = cbDef.otherImpostors.every(function (impostor) {
  84690. return collidedAgainstList.indexOf(impostor) > -1;
  84691. });
  84692. if (sameList) {
  84693. index = idx;
  84694. }
  84695. return sameList;
  84696. }
  84697. return false;
  84698. });
  84699. if (found) {
  84700. this._onPhysicsCollideCallbacks.splice(index, 1);
  84701. }
  84702. else {
  84703. BABYLON.Tools.Warn("Function to remove was not found");
  84704. }
  84705. };
  84706. PhysicsImpostor.prototype.getParentsRotation = function () {
  84707. var parent = this.object.parent;
  84708. this._tmpQuat.copyFromFloats(0, 0, 0, 1);
  84709. while (parent) {
  84710. if (parent.rotationQuaternion) {
  84711. this._tmpQuat2.copyFrom(parent.rotationQuaternion);
  84712. }
  84713. else {
  84714. BABYLON.Quaternion.RotationYawPitchRollToRef(parent.rotation.y, parent.rotation.x, parent.rotation.z, this._tmpQuat2);
  84715. }
  84716. this._tmpQuat.multiplyToRef(this._tmpQuat2, this._tmpQuat);
  84717. parent = parent.parent;
  84718. }
  84719. return this._tmpQuat;
  84720. };
  84721. /**
  84722. * Apply a force
  84723. */
  84724. PhysicsImpostor.prototype.applyForce = function (force, contactPoint) {
  84725. if (this._physicsEngine) {
  84726. this._physicsEngine.getPhysicsPlugin().applyForce(this, force, contactPoint);
  84727. }
  84728. return this;
  84729. };
  84730. /**
  84731. * Apply an impulse
  84732. */
  84733. PhysicsImpostor.prototype.applyImpulse = function (force, contactPoint) {
  84734. if (this._physicsEngine) {
  84735. this._physicsEngine.getPhysicsPlugin().applyImpulse(this, force, contactPoint);
  84736. }
  84737. return this;
  84738. };
  84739. /**
  84740. * A help function to create a joint.
  84741. */
  84742. PhysicsImpostor.prototype.createJoint = function (otherImpostor, jointType, jointData) {
  84743. var joint = new BABYLON.PhysicsJoint(jointType, jointData);
  84744. this.addJoint(otherImpostor, joint);
  84745. return this;
  84746. };
  84747. /**
  84748. * Add a joint to this impostor with a different impostor.
  84749. */
  84750. PhysicsImpostor.prototype.addJoint = function (otherImpostor, joint) {
  84751. this._joints.push({
  84752. otherImpostor: otherImpostor,
  84753. joint: joint
  84754. });
  84755. if (this._physicsEngine) {
  84756. this._physicsEngine.addJoint(this, otherImpostor, joint);
  84757. }
  84758. return this;
  84759. };
  84760. /**
  84761. * Will keep this body still, in a sleep mode.
  84762. */
  84763. PhysicsImpostor.prototype.sleep = function () {
  84764. if (this._physicsEngine) {
  84765. this._physicsEngine.getPhysicsPlugin().sleepBody(this);
  84766. }
  84767. return this;
  84768. };
  84769. /**
  84770. * Wake the body up.
  84771. */
  84772. PhysicsImpostor.prototype.wakeUp = function () {
  84773. if (this._physicsEngine) {
  84774. this._physicsEngine.getPhysicsPlugin().wakeUpBody(this);
  84775. }
  84776. return this;
  84777. };
  84778. PhysicsImpostor.prototype.clone = function (newObject) {
  84779. if (!newObject)
  84780. return null;
  84781. return new PhysicsImpostor(newObject, this.type, this._options, this._scene);
  84782. };
  84783. PhysicsImpostor.prototype.dispose = function ( /*disposeChildren: boolean = true*/) {
  84784. var _this = this;
  84785. //no dispose if no physics engine is available.
  84786. if (!this._physicsEngine) {
  84787. return;
  84788. }
  84789. this._joints.forEach(function (j) {
  84790. if (_this._physicsEngine) {
  84791. _this._physicsEngine.removeJoint(_this, j.otherImpostor, j.joint);
  84792. }
  84793. });
  84794. //dispose the physics body
  84795. this._physicsEngine.removeImpostor(this);
  84796. if (this.parent) {
  84797. this.parent.forceUpdate();
  84798. }
  84799. else {
  84800. /*this._object.getChildMeshes().forEach(function(mesh) {
  84801. if (mesh.physicsImpostor) {
  84802. if (disposeChildren) {
  84803. mesh.physicsImpostor.dispose();
  84804. mesh.physicsImpostor = null;
  84805. }
  84806. }
  84807. })*/
  84808. }
  84809. this._isDisposed = true;
  84810. };
  84811. PhysicsImpostor.prototype.setDeltaPosition = function (position) {
  84812. this._deltaPosition.copyFrom(position);
  84813. };
  84814. PhysicsImpostor.prototype.setDeltaRotation = function (rotation) {
  84815. if (!this._deltaRotation) {
  84816. this._deltaRotation = new BABYLON.Quaternion();
  84817. }
  84818. this._deltaRotation.copyFrom(rotation);
  84819. this._deltaRotationConjugated = this._deltaRotation.conjugate();
  84820. };
  84821. PhysicsImpostor.prototype.getBoxSizeToRef = function (result) {
  84822. if (this._physicsEngine) {
  84823. this._physicsEngine.getPhysicsPlugin().getBoxSizeToRef(this, result);
  84824. }
  84825. return this;
  84826. };
  84827. PhysicsImpostor.prototype.getRadius = function () {
  84828. return this._physicsEngine ? this._physicsEngine.getPhysicsPlugin().getRadius(this) : 0;
  84829. };
  84830. /**
  84831. * Sync a bone with this impostor
  84832. * @param bone The bone to sync to the impostor.
  84833. * @param boneMesh The mesh that the bone is influencing.
  84834. * @param jointPivot The pivot of the joint / bone in local space.
  84835. * @param distToJoint Optional distance from the impostor to the joint.
  84836. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84837. */
  84838. PhysicsImpostor.prototype.syncBoneWithImpostor = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation) {
  84839. var tempVec = PhysicsImpostor._tmpVecs[0];
  84840. var mesh = this.object;
  84841. if (mesh.rotationQuaternion) {
  84842. if (adjustRotation) {
  84843. var tempQuat = PhysicsImpostor._tmpQuat;
  84844. mesh.rotationQuaternion.multiplyToRef(adjustRotation, tempQuat);
  84845. bone.setRotationQuaternion(tempQuat, BABYLON.Space.WORLD, boneMesh);
  84846. }
  84847. else {
  84848. bone.setRotationQuaternion(mesh.rotationQuaternion, BABYLON.Space.WORLD, boneMesh);
  84849. }
  84850. }
  84851. tempVec.x = 0;
  84852. tempVec.y = 0;
  84853. tempVec.z = 0;
  84854. if (jointPivot) {
  84855. tempVec.x = jointPivot.x;
  84856. tempVec.y = jointPivot.y;
  84857. tempVec.z = jointPivot.z;
  84858. bone.getDirectionToRef(tempVec, boneMesh, tempVec);
  84859. if (distToJoint === undefined || distToJoint === null) {
  84860. distToJoint = jointPivot.length();
  84861. }
  84862. tempVec.x *= distToJoint;
  84863. tempVec.y *= distToJoint;
  84864. tempVec.z *= distToJoint;
  84865. }
  84866. if (bone.getParent()) {
  84867. tempVec.addInPlace(mesh.getAbsolutePosition());
  84868. bone.setAbsolutePosition(tempVec, boneMesh);
  84869. }
  84870. else {
  84871. boneMesh.setAbsolutePosition(mesh.getAbsolutePosition());
  84872. boneMesh.position.x -= tempVec.x;
  84873. boneMesh.position.y -= tempVec.y;
  84874. boneMesh.position.z -= tempVec.z;
  84875. }
  84876. };
  84877. /**
  84878. * Sync impostor to a bone
  84879. * @param bone The bone that the impostor will be synced to.
  84880. * @param boneMesh The mesh that the bone is influencing.
  84881. * @param jointPivot The pivot of the joint / bone in local space.
  84882. * @param distToJoint Optional distance from the impostor to the joint.
  84883. * @param adjustRotation Optional quaternion for adjusting the local rotation of the bone.
  84884. * @param boneAxis Optional vector3 axis the bone is aligned with
  84885. */
  84886. PhysicsImpostor.prototype.syncImpostorWithBone = function (bone, boneMesh, jointPivot, distToJoint, adjustRotation, boneAxis) {
  84887. var mesh = this.object;
  84888. if (mesh.rotationQuaternion) {
  84889. if (adjustRotation) {
  84890. var tempQuat = PhysicsImpostor._tmpQuat;
  84891. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, tempQuat);
  84892. tempQuat.multiplyToRef(adjustRotation, mesh.rotationQuaternion);
  84893. }
  84894. else {
  84895. bone.getRotationQuaternionToRef(BABYLON.Space.WORLD, boneMesh, mesh.rotationQuaternion);
  84896. }
  84897. }
  84898. var pos = PhysicsImpostor._tmpVecs[0];
  84899. var boneDir = PhysicsImpostor._tmpVecs[1];
  84900. if (!boneAxis) {
  84901. boneAxis = PhysicsImpostor._tmpVecs[2];
  84902. boneAxis.x = 0;
  84903. boneAxis.y = 1;
  84904. boneAxis.z = 0;
  84905. }
  84906. bone.getDirectionToRef(boneAxis, boneMesh, boneDir);
  84907. bone.getAbsolutePositionToRef(boneMesh, pos);
  84908. if ((distToJoint === undefined || distToJoint === null) && jointPivot) {
  84909. distToJoint = jointPivot.length();
  84910. }
  84911. if (distToJoint !== undefined && distToJoint !== null) {
  84912. pos.x += boneDir.x * distToJoint;
  84913. pos.y += boneDir.y * distToJoint;
  84914. pos.z += boneDir.z * distToJoint;
  84915. }
  84916. mesh.setAbsolutePosition(pos);
  84917. };
  84918. PhysicsImpostor.DEFAULT_OBJECT_SIZE = new BABYLON.Vector3(1, 1, 1);
  84919. PhysicsImpostor.IDENTITY_QUATERNION = BABYLON.Quaternion.Identity();
  84920. PhysicsImpostor._tmpVecs = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  84921. PhysicsImpostor._tmpQuat = BABYLON.Quaternion.Identity();
  84922. //Impostor types
  84923. PhysicsImpostor.NoImpostor = 0;
  84924. PhysicsImpostor.SphereImpostor = 1;
  84925. PhysicsImpostor.BoxImpostor = 2;
  84926. PhysicsImpostor.PlaneImpostor = 3;
  84927. PhysicsImpostor.MeshImpostor = 4;
  84928. PhysicsImpostor.CylinderImpostor = 7;
  84929. PhysicsImpostor.ParticleImpostor = 8;
  84930. PhysicsImpostor.HeightmapImpostor = 9;
  84931. return PhysicsImpostor;
  84932. }());
  84933. BABYLON.PhysicsImpostor = PhysicsImpostor;
  84934. })(BABYLON || (BABYLON = {}));
  84935. //# sourceMappingURL=babylon.physicsImpostor.js.map
  84936. var BABYLON;
  84937. (function (BABYLON) {
  84938. var PhysicsEngine = /** @class */ (function () {
  84939. function PhysicsEngine(gravity, _physicsPlugin) {
  84940. if (_physicsPlugin === void 0) { _physicsPlugin = new BABYLON.CannonJSPlugin(); }
  84941. this._physicsPlugin = _physicsPlugin;
  84942. //new methods and parameters
  84943. this._impostors = [];
  84944. this._joints = [];
  84945. if (!this._physicsPlugin.isSupported()) {
  84946. throw new Error("Physics Engine " + this._physicsPlugin.name + " cannot be found. "
  84947. + "Please make sure it is included.");
  84948. }
  84949. gravity = gravity || new BABYLON.Vector3(0, -9.807, 0);
  84950. this.setGravity(gravity);
  84951. this.setTimeStep();
  84952. }
  84953. PhysicsEngine.prototype.setGravity = function (gravity) {
  84954. this.gravity = gravity;
  84955. this._physicsPlugin.setGravity(this.gravity);
  84956. };
  84957. /**
  84958. * Set the time step of the physics engine.
  84959. * default is 1/60.
  84960. * To slow it down, enter 1/600 for example.
  84961. * To speed it up, 1/30
  84962. * @param {number} newTimeStep the new timestep to apply to this world.
  84963. */
  84964. PhysicsEngine.prototype.setTimeStep = function (newTimeStep) {
  84965. if (newTimeStep === void 0) { newTimeStep = 1 / 60; }
  84966. this._physicsPlugin.setTimeStep(newTimeStep);
  84967. };
  84968. /**
  84969. * Get the time step of the physics engine.
  84970. */
  84971. PhysicsEngine.prototype.getTimeStep = function () {
  84972. return this._physicsPlugin.getTimeStep();
  84973. };
  84974. PhysicsEngine.prototype.dispose = function () {
  84975. this._impostors.forEach(function (impostor) {
  84976. impostor.dispose();
  84977. });
  84978. this._physicsPlugin.dispose();
  84979. };
  84980. PhysicsEngine.prototype.getPhysicsPluginName = function () {
  84981. return this._physicsPlugin.name;
  84982. };
  84983. /**
  84984. * Adding a new impostor for the impostor tracking.
  84985. * This will be done by the impostor itself.
  84986. * @param {PhysicsImpostor} impostor the impostor to add
  84987. */
  84988. PhysicsEngine.prototype.addImpostor = function (impostor) {
  84989. impostor.uniqueId = this._impostors.push(impostor);
  84990. //if no parent, generate the body
  84991. if (!impostor.parent) {
  84992. this._physicsPlugin.generatePhysicsBody(impostor);
  84993. }
  84994. };
  84995. /**
  84996. * Remove an impostor from the engine.
  84997. * This impostor and its mesh will not longer be updated by the physics engine.
  84998. * @param {PhysicsImpostor} impostor the impostor to remove
  84999. */
  85000. PhysicsEngine.prototype.removeImpostor = function (impostor) {
  85001. var index = this._impostors.indexOf(impostor);
  85002. if (index > -1) {
  85003. var removed = this._impostors.splice(index, 1);
  85004. //Is it needed?
  85005. if (removed.length) {
  85006. //this will also remove it from the world.
  85007. removed[0].physicsBody = null;
  85008. }
  85009. }
  85010. };
  85011. /**
  85012. * Add a joint to the physics engine
  85013. * @param {PhysicsImpostor} mainImpostor the main impostor to which the joint is added.
  85014. * @param {PhysicsImpostor} connectedImpostor the impostor that is connected to the main impostor using this joint
  85015. * @param {PhysicsJoint} the joint that will connect both impostors.
  85016. */
  85017. PhysicsEngine.prototype.addJoint = function (mainImpostor, connectedImpostor, joint) {
  85018. var impostorJoint = {
  85019. mainImpostor: mainImpostor,
  85020. connectedImpostor: connectedImpostor,
  85021. joint: joint
  85022. };
  85023. joint.physicsPlugin = this._physicsPlugin;
  85024. this._joints.push(impostorJoint);
  85025. this._physicsPlugin.generateJoint(impostorJoint);
  85026. };
  85027. PhysicsEngine.prototype.removeJoint = function (mainImpostor, connectedImpostor, joint) {
  85028. var matchingJoints = this._joints.filter(function (impostorJoint) {
  85029. return (impostorJoint.connectedImpostor === connectedImpostor
  85030. && impostorJoint.joint === joint
  85031. && impostorJoint.mainImpostor === mainImpostor);
  85032. });
  85033. if (matchingJoints.length) {
  85034. this._physicsPlugin.removeJoint(matchingJoints[0]);
  85035. //TODO remove it from the list as well
  85036. }
  85037. };
  85038. /**
  85039. * Called by the scene. no need to call it.
  85040. */
  85041. PhysicsEngine.prototype._step = function (delta) {
  85042. var _this = this;
  85043. //check if any mesh has no body / requires an update
  85044. this._impostors.forEach(function (impostor) {
  85045. if (impostor.isBodyInitRequired()) {
  85046. _this._physicsPlugin.generatePhysicsBody(impostor);
  85047. }
  85048. });
  85049. if (delta > 0.1) {
  85050. delta = 0.1;
  85051. }
  85052. else if (delta <= 0) {
  85053. delta = 1.0 / 60.0;
  85054. }
  85055. this._physicsPlugin.executeStep(delta, this._impostors);
  85056. };
  85057. PhysicsEngine.prototype.getPhysicsPlugin = function () {
  85058. return this._physicsPlugin;
  85059. };
  85060. PhysicsEngine.prototype.getImpostors = function () {
  85061. return this._impostors;
  85062. };
  85063. PhysicsEngine.prototype.getImpostorForPhysicsObject = function (object) {
  85064. for (var i = 0; i < this._impostors.length; ++i) {
  85065. if (this._impostors[i].object === object) {
  85066. return this._impostors[i];
  85067. }
  85068. }
  85069. return null;
  85070. };
  85071. PhysicsEngine.prototype.getImpostorWithPhysicsBody = function (body) {
  85072. for (var i = 0; i < this._impostors.length; ++i) {
  85073. if (this._impostors[i].physicsBody === body) {
  85074. return this._impostors[i];
  85075. }
  85076. }
  85077. return null;
  85078. };
  85079. // Statics
  85080. PhysicsEngine.Epsilon = 0.001;
  85081. return PhysicsEngine;
  85082. }());
  85083. BABYLON.PhysicsEngine = PhysicsEngine;
  85084. })(BABYLON || (BABYLON = {}));
  85085. //# sourceMappingURL=babylon.physicsEngine.js.map
  85086. var BABYLON;
  85087. (function (BABYLON) {
  85088. var PhysicsHelper = /** @class */ (function () {
  85089. function PhysicsHelper(scene) {
  85090. this._scene = scene;
  85091. this._physicsEngine = this._scene.getPhysicsEngine();
  85092. if (!this._physicsEngine) {
  85093. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you can use the methods.');
  85094. }
  85095. }
  85096. /**
  85097. * @param {Vector3} origin the origin of the explosion
  85098. * @param {number} radius the explosion radius
  85099. * @param {number} strength the explosion strength
  85100. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85101. */
  85102. PhysicsHelper.prototype.applyRadialExplosionImpulse = function (origin, radius, strength, falloff) {
  85103. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85104. if (!this._physicsEngine) {
  85105. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call this method.');
  85106. return null;
  85107. }
  85108. var impostors = this._physicsEngine.getImpostors();
  85109. if (impostors.length === 0) {
  85110. return null;
  85111. }
  85112. var event = new PhysicsRadialExplosionEvent(this._scene);
  85113. impostors.forEach(function (impostor) {
  85114. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85115. if (!impostorForceAndContactPoint) {
  85116. return;
  85117. }
  85118. impostor.applyImpulse(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85119. });
  85120. event.dispose(false);
  85121. return event;
  85122. };
  85123. /**
  85124. * @param {Vector3} origin the origin of the explosion
  85125. * @param {number} radius the explosion radius
  85126. * @param {number} strength the explosion strength
  85127. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85128. */
  85129. PhysicsHelper.prototype.applyRadialExplosionForce = function (origin, radius, strength, falloff) {
  85130. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85131. if (!this._physicsEngine) {
  85132. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85133. return null;
  85134. }
  85135. var impostors = this._physicsEngine.getImpostors();
  85136. if (impostors.length === 0) {
  85137. return null;
  85138. }
  85139. var event = new PhysicsRadialExplosionEvent(this._scene);
  85140. impostors.forEach(function (impostor) {
  85141. var impostorForceAndContactPoint = event.getImpostorForceAndContactPoint(impostor, origin, radius, strength, falloff);
  85142. if (!impostorForceAndContactPoint) {
  85143. return;
  85144. }
  85145. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85146. });
  85147. event.dispose(false);
  85148. return event;
  85149. };
  85150. /**
  85151. * @param {Vector3} origin the origin of the explosion
  85152. * @param {number} radius the explosion radius
  85153. * @param {number} strength the explosion strength
  85154. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear. Defaults to Constant
  85155. */
  85156. PhysicsHelper.prototype.gravitationalField = function (origin, radius, strength, falloff) {
  85157. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85158. if (!this._physicsEngine) {
  85159. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85160. return null;
  85161. }
  85162. var impostors = this._physicsEngine.getImpostors();
  85163. if (impostors.length === 0) {
  85164. return null;
  85165. }
  85166. var event = new PhysicsGravitationalFieldEvent(this, this._scene, origin, radius, strength, falloff);
  85167. event.dispose(false);
  85168. return event;
  85169. };
  85170. /**
  85171. * @param {Vector3} origin the origin of the updraft
  85172. * @param {number} radius the radius of the updraft
  85173. * @param {number} strength the strength of the updraft
  85174. * @param {number} height the height of the updraft
  85175. * @param {PhysicsUpdraftMode} updraftMode possible options: Center & Perpendicular. Defaults to Center
  85176. */
  85177. PhysicsHelper.prototype.updraft = function (origin, radius, strength, height, updraftMode) {
  85178. if (updraftMode === void 0) { updraftMode = PhysicsUpdraftMode.Center; }
  85179. if (!this._physicsEngine) {
  85180. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85181. return null;
  85182. }
  85183. if (this._physicsEngine.getImpostors().length === 0) {
  85184. return null;
  85185. }
  85186. var event = new PhysicsUpdraftEvent(this._scene, origin, radius, strength, height, updraftMode);
  85187. event.dispose(false);
  85188. return event;
  85189. };
  85190. /**
  85191. * @param {Vector3} origin the of the vortex
  85192. * @param {number} radius the radius of the vortex
  85193. * @param {number} strength the strength of the vortex
  85194. * @param {number} height the height of the vortex
  85195. */
  85196. PhysicsHelper.prototype.vortex = function (origin, radius, strength, height) {
  85197. if (!this._physicsEngine) {
  85198. BABYLON.Tools.Warn('Physics engine not enabled. Please enable the physics before you call the PhysicsHelper.');
  85199. return null;
  85200. }
  85201. if (this._physicsEngine.getImpostors().length === 0) {
  85202. return null;
  85203. }
  85204. var event = new PhysicsVortexEvent(this._scene, origin, radius, strength, height);
  85205. event.dispose(false);
  85206. return event;
  85207. };
  85208. return PhysicsHelper;
  85209. }());
  85210. BABYLON.PhysicsHelper = PhysicsHelper;
  85211. /***** Radial explosion *****/
  85212. var PhysicsRadialExplosionEvent = /** @class */ (function () {
  85213. function PhysicsRadialExplosionEvent(scene) {
  85214. this._sphereOptions = { segments: 32, diameter: 1 }; // TODO: make configurable
  85215. this._rays = [];
  85216. this._dataFetched = false; // check if the data has been fetched. If not, do cleanup
  85217. this._scene = scene;
  85218. }
  85219. /**
  85220. * Returns the data related to the radial explosion event (sphere & rays).
  85221. * @returns {PhysicsRadialExplosionEventData}
  85222. */
  85223. PhysicsRadialExplosionEvent.prototype.getData = function () {
  85224. this._dataFetched = true;
  85225. return {
  85226. sphere: this._sphere,
  85227. rays: this._rays,
  85228. };
  85229. };
  85230. /**
  85231. * Returns the force and contact point of the impostor or false, if the impostor is not affected by the force/impulse.
  85232. * @param impostor
  85233. * @param {Vector3} origin the origin of the explosion
  85234. * @param {number} radius the explosion radius
  85235. * @param {number} strength the explosion strength
  85236. * @param {PhysicsRadialImpulseFalloff} falloff possible options: Constant & Linear
  85237. * @returns {Nullable<PhysicsForceAndContactPoint>}
  85238. */
  85239. PhysicsRadialExplosionEvent.prototype.getImpostorForceAndContactPoint = function (impostor, origin, radius, strength, falloff) {
  85240. if (impostor.mass === 0) {
  85241. return null;
  85242. }
  85243. if (!this._intersectsWithSphere(impostor, origin, radius)) {
  85244. return null;
  85245. }
  85246. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85247. return null;
  85248. }
  85249. var impostorObjectCenter = impostor.getObjectCenter();
  85250. var direction = impostorObjectCenter.subtract(origin);
  85251. var ray = new BABYLON.Ray(origin, direction, radius);
  85252. this._rays.push(ray);
  85253. var hit = ray.intersectsMesh(impostor.object);
  85254. var contactPoint = hit.pickedPoint;
  85255. if (!contactPoint) {
  85256. return null;
  85257. }
  85258. var distanceFromOrigin = BABYLON.Vector3.Distance(origin, contactPoint);
  85259. if (distanceFromOrigin > radius) {
  85260. return null;
  85261. }
  85262. var multiplier = falloff === PhysicsRadialImpulseFalloff.Constant
  85263. ? strength
  85264. : strength * (1 - (distanceFromOrigin / radius));
  85265. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85266. return { force: force, contactPoint: contactPoint };
  85267. };
  85268. /**
  85269. * Disposes the sphere.
  85270. * @param {bolean} force
  85271. */
  85272. PhysicsRadialExplosionEvent.prototype.dispose = function (force) {
  85273. var _this = this;
  85274. if (force === void 0) { force = true; }
  85275. if (force) {
  85276. this._sphere.dispose();
  85277. }
  85278. else {
  85279. setTimeout(function () {
  85280. if (!_this._dataFetched) {
  85281. _this._sphere.dispose();
  85282. }
  85283. }, 0);
  85284. }
  85285. };
  85286. /*** Helpers ***/
  85287. PhysicsRadialExplosionEvent.prototype._prepareSphere = function () {
  85288. if (!this._sphere) {
  85289. this._sphere = BABYLON.MeshBuilder.CreateSphere("radialExplosionEventSphere", this._sphereOptions, this._scene);
  85290. this._sphere.isVisible = false;
  85291. }
  85292. };
  85293. PhysicsRadialExplosionEvent.prototype._intersectsWithSphere = function (impostor, origin, radius) {
  85294. var impostorObject = impostor.object;
  85295. this._prepareSphere();
  85296. this._sphere.position = origin;
  85297. this._sphere.scaling = new BABYLON.Vector3(radius * 2, radius * 2, radius * 2);
  85298. this._sphere._updateBoundingInfo();
  85299. this._sphere.computeWorldMatrix(true);
  85300. return this._sphere.intersectsMesh(impostorObject, true);
  85301. };
  85302. return PhysicsRadialExplosionEvent;
  85303. }());
  85304. BABYLON.PhysicsRadialExplosionEvent = PhysicsRadialExplosionEvent;
  85305. /***** Gravitational Field *****/
  85306. var PhysicsGravitationalFieldEvent = /** @class */ (function () {
  85307. function PhysicsGravitationalFieldEvent(physicsHelper, scene, origin, radius, strength, falloff) {
  85308. if (falloff === void 0) { falloff = PhysicsRadialImpulseFalloff.Constant; }
  85309. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85310. this._physicsHelper = physicsHelper;
  85311. this._scene = scene;
  85312. this._origin = origin;
  85313. this._radius = radius;
  85314. this._strength = strength;
  85315. this._falloff = falloff;
  85316. this._tickCallback = this._tick.bind(this);
  85317. }
  85318. /**
  85319. * Returns the data related to the gravitational field event (sphere).
  85320. * @returns {PhysicsGravitationalFieldEventData}
  85321. */
  85322. PhysicsGravitationalFieldEvent.prototype.getData = function () {
  85323. this._dataFetched = true;
  85324. return {
  85325. sphere: this._sphere,
  85326. };
  85327. };
  85328. /**
  85329. * Enables the gravitational field.
  85330. */
  85331. PhysicsGravitationalFieldEvent.prototype.enable = function () {
  85332. this._tickCallback.call(this);
  85333. this._scene.registerBeforeRender(this._tickCallback);
  85334. };
  85335. /**
  85336. * Disables the gravitational field.
  85337. */
  85338. PhysicsGravitationalFieldEvent.prototype.disable = function () {
  85339. this._scene.unregisterBeforeRender(this._tickCallback);
  85340. };
  85341. /**
  85342. * Disposes the sphere.
  85343. * @param {bolean} force
  85344. */
  85345. PhysicsGravitationalFieldEvent.prototype.dispose = function (force) {
  85346. var _this = this;
  85347. if (force === void 0) { force = true; }
  85348. if (force) {
  85349. this._sphere.dispose();
  85350. }
  85351. else {
  85352. setTimeout(function () {
  85353. if (!_this._dataFetched) {
  85354. _this._sphere.dispose();
  85355. }
  85356. }, 0);
  85357. }
  85358. };
  85359. PhysicsGravitationalFieldEvent.prototype._tick = function () {
  85360. // Since the params won't change, we fetch the event only once
  85361. if (this._sphere) {
  85362. this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85363. }
  85364. else {
  85365. var radialExplosionEvent = this._physicsHelper.applyRadialExplosionForce(this._origin, this._radius, this._strength * -1, this._falloff);
  85366. if (radialExplosionEvent) {
  85367. this._sphere = radialExplosionEvent.getData().sphere.clone('radialExplosionEventSphereClone');
  85368. }
  85369. }
  85370. };
  85371. return PhysicsGravitationalFieldEvent;
  85372. }());
  85373. BABYLON.PhysicsGravitationalFieldEvent = PhysicsGravitationalFieldEvent;
  85374. /***** Updraft *****/
  85375. var PhysicsUpdraftEvent = /** @class */ (function () {
  85376. function PhysicsUpdraftEvent(_scene, _origin, _radius, _strength, _height, _updraftMode) {
  85377. this._scene = _scene;
  85378. this._origin = _origin;
  85379. this._radius = _radius;
  85380. this._strength = _strength;
  85381. this._height = _height;
  85382. this._updraftMode = _updraftMode;
  85383. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85384. this._originDirection = BABYLON.Vector3.Zero(); // used if the updraftMode is perpendicular
  85385. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85386. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85387. this._physicsEngine = this._scene.getPhysicsEngine();
  85388. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85389. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85390. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85391. this._originDirection = this._origin.subtract(this._originTop).normalize();
  85392. }
  85393. this._tickCallback = this._tick.bind(this);
  85394. }
  85395. /**
  85396. * Returns the data related to the updraft event (cylinder).
  85397. * @returns {PhysicsUpdraftEventData}
  85398. */
  85399. PhysicsUpdraftEvent.prototype.getData = function () {
  85400. this._dataFetched = true;
  85401. return {
  85402. cylinder: this._cylinder,
  85403. };
  85404. };
  85405. /**
  85406. * Enables the updraft.
  85407. */
  85408. PhysicsUpdraftEvent.prototype.enable = function () {
  85409. this._tickCallback.call(this);
  85410. this._scene.registerBeforeRender(this._tickCallback);
  85411. };
  85412. /**
  85413. * Disables the cortex.
  85414. */
  85415. PhysicsUpdraftEvent.prototype.disable = function () {
  85416. this._scene.unregisterBeforeRender(this._tickCallback);
  85417. };
  85418. /**
  85419. * Disposes the sphere.
  85420. * @param {bolean} force
  85421. */
  85422. PhysicsUpdraftEvent.prototype.dispose = function (force) {
  85423. var _this = this;
  85424. if (force === void 0) { force = true; }
  85425. if (force) {
  85426. this._cylinder.dispose();
  85427. }
  85428. else {
  85429. setTimeout(function () {
  85430. if (!_this._dataFetched) {
  85431. _this._cylinder.dispose();
  85432. }
  85433. }, 0);
  85434. }
  85435. };
  85436. PhysicsUpdraftEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85437. if (impostor.mass === 0) {
  85438. return null;
  85439. }
  85440. if (!this._intersectsWithCylinder(impostor)) {
  85441. return null;
  85442. }
  85443. var impostorObjectCenter = impostor.getObjectCenter();
  85444. if (this._updraftMode === PhysicsUpdraftMode.Perpendicular) {
  85445. var direction = this._originDirection;
  85446. }
  85447. else {
  85448. var direction = impostorObjectCenter.subtract(this._originTop);
  85449. }
  85450. var multiplier = this._strength * -1;
  85451. var force = direction.multiplyByFloats(multiplier, multiplier, multiplier);
  85452. return { force: force, contactPoint: impostorObjectCenter };
  85453. };
  85454. PhysicsUpdraftEvent.prototype._tick = function () {
  85455. var _this = this;
  85456. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85457. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85458. if (!impostorForceAndContactPoint) {
  85459. return;
  85460. }
  85461. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85462. });
  85463. };
  85464. /*** Helpers ***/
  85465. PhysicsUpdraftEvent.prototype._prepareCylinder = function () {
  85466. if (!this._cylinder) {
  85467. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("updraftEventCylinder", {
  85468. height: this._height,
  85469. diameter: this._radius * 2,
  85470. }, this._scene);
  85471. this._cylinder.isVisible = false;
  85472. }
  85473. };
  85474. PhysicsUpdraftEvent.prototype._intersectsWithCylinder = function (impostor) {
  85475. var impostorObject = impostor.object;
  85476. this._prepareCylinder();
  85477. this._cylinder.position = this._cylinderPosition;
  85478. return this._cylinder.intersectsMesh(impostorObject, true);
  85479. };
  85480. return PhysicsUpdraftEvent;
  85481. }());
  85482. BABYLON.PhysicsUpdraftEvent = PhysicsUpdraftEvent;
  85483. /***** Vortex *****/
  85484. var PhysicsVortexEvent = /** @class */ (function () {
  85485. function PhysicsVortexEvent(_scene, _origin, _radius, _strength, _height) {
  85486. this._scene = _scene;
  85487. this._origin = _origin;
  85488. this._radius = _radius;
  85489. this._strength = _strength;
  85490. this._height = _height;
  85491. this._originTop = BABYLON.Vector3.Zero(); // the most upper part of the cylinder
  85492. this._centripetalForceThreshold = 0.7; // at which distance, relative to the radius the centripetal forces should kick in
  85493. this._updraftMultiplier = 0.02;
  85494. this._cylinderPosition = BABYLON.Vector3.Zero(); // to keep the cylinders position, because normally the origin is in the center and not on the bottom
  85495. this._dataFetched = false; // check if the has been fetched the data. If not, do cleanup
  85496. this._physicsEngine = this._scene.getPhysicsEngine();
  85497. this._origin.addToRef(new BABYLON.Vector3(0, this._height / 2, 0), this._cylinderPosition);
  85498. this._origin.addToRef(new BABYLON.Vector3(0, this._height, 0), this._originTop);
  85499. this._tickCallback = this._tick.bind(this);
  85500. }
  85501. /**
  85502. * Returns the data related to the vortex event (cylinder).
  85503. * @returns {PhysicsVortexEventData}
  85504. */
  85505. PhysicsVortexEvent.prototype.getData = function () {
  85506. this._dataFetched = true;
  85507. return {
  85508. cylinder: this._cylinder,
  85509. };
  85510. };
  85511. /**
  85512. * Enables the vortex.
  85513. */
  85514. PhysicsVortexEvent.prototype.enable = function () {
  85515. this._tickCallback.call(this);
  85516. this._scene.registerBeforeRender(this._tickCallback);
  85517. };
  85518. /**
  85519. * Disables the cortex.
  85520. */
  85521. PhysicsVortexEvent.prototype.disable = function () {
  85522. this._scene.unregisterBeforeRender(this._tickCallback);
  85523. };
  85524. /**
  85525. * Disposes the sphere.
  85526. * @param {bolean} force
  85527. */
  85528. PhysicsVortexEvent.prototype.dispose = function (force) {
  85529. var _this = this;
  85530. if (force === void 0) { force = true; }
  85531. if (force) {
  85532. this._cylinder.dispose();
  85533. }
  85534. else {
  85535. setTimeout(function () {
  85536. if (!_this._dataFetched) {
  85537. _this._cylinder.dispose();
  85538. }
  85539. }, 0);
  85540. }
  85541. };
  85542. PhysicsVortexEvent.prototype.getImpostorForceAndContactPoint = function (impostor) {
  85543. if (impostor.mass === 0) {
  85544. return null;
  85545. }
  85546. if (!this._intersectsWithCylinder(impostor)) {
  85547. return null;
  85548. }
  85549. if (impostor.object.getClassName() !== 'Mesh' && impostor.object.getClassName() !== 'InstancedMesh') {
  85550. return null;
  85551. }
  85552. var impostorObjectCenter = impostor.getObjectCenter();
  85553. 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)
  85554. var originToImpostorDirection = impostorObjectCenter.subtract(originOnPlane);
  85555. var ray = new BABYLON.Ray(originOnPlane, originToImpostorDirection, this._radius);
  85556. var hit = ray.intersectsMesh(impostor.object);
  85557. var contactPoint = hit.pickedPoint;
  85558. if (!contactPoint) {
  85559. return null;
  85560. }
  85561. var absoluteDistanceFromOrigin = hit.distance / this._radius;
  85562. var perpendicularDirection = BABYLON.Vector3.Cross(originOnPlane, impostorObjectCenter).normalize();
  85563. var directionToOrigin = contactPoint.normalize();
  85564. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85565. directionToOrigin = directionToOrigin.negate();
  85566. }
  85567. // TODO: find a more physically based solution
  85568. if (absoluteDistanceFromOrigin > this._centripetalForceThreshold) {
  85569. var forceX = directionToOrigin.x * this._strength / 8;
  85570. var forceY = directionToOrigin.y * this._updraftMultiplier;
  85571. var forceZ = directionToOrigin.z * this._strength / 8;
  85572. }
  85573. else {
  85574. var forceX = (perpendicularDirection.x + directionToOrigin.x) / 2;
  85575. var forceY = this._originTop.y * this._updraftMultiplier;
  85576. var forceZ = (perpendicularDirection.z + directionToOrigin.z) / 2;
  85577. }
  85578. var force = new BABYLON.Vector3(forceX, forceY, forceZ);
  85579. force = force.multiplyByFloats(this._strength, this._strength, this._strength);
  85580. return { force: force, contactPoint: impostorObjectCenter };
  85581. };
  85582. PhysicsVortexEvent.prototype._tick = function () {
  85583. var _this = this;
  85584. this._physicsEngine.getImpostors().forEach(function (impostor) {
  85585. var impostorForceAndContactPoint = _this.getImpostorForceAndContactPoint(impostor);
  85586. if (!impostorForceAndContactPoint) {
  85587. return;
  85588. }
  85589. impostor.applyForce(impostorForceAndContactPoint.force, impostorForceAndContactPoint.contactPoint);
  85590. });
  85591. };
  85592. /*** Helpers ***/
  85593. PhysicsVortexEvent.prototype._prepareCylinder = function () {
  85594. if (!this._cylinder) {
  85595. this._cylinder = BABYLON.MeshBuilder.CreateCylinder("vortexEventCylinder", {
  85596. height: this._height,
  85597. diameter: this._radius * 2,
  85598. }, this._scene);
  85599. this._cylinder.isVisible = false;
  85600. }
  85601. };
  85602. PhysicsVortexEvent.prototype._intersectsWithCylinder = function (impostor) {
  85603. var impostorObject = impostor.object;
  85604. this._prepareCylinder();
  85605. this._cylinder.position = this._cylinderPosition;
  85606. return this._cylinder.intersectsMesh(impostorObject, true);
  85607. };
  85608. return PhysicsVortexEvent;
  85609. }());
  85610. BABYLON.PhysicsVortexEvent = PhysicsVortexEvent;
  85611. /***** Enums *****/
  85612. /**
  85613. * The strenght of the force in correspondence to the distance of the affected object
  85614. */
  85615. var PhysicsRadialImpulseFalloff;
  85616. (function (PhysicsRadialImpulseFalloff) {
  85617. /** Defines that impulse is constant in strength across it's whole radius */
  85618. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Constant"] = 0] = "Constant";
  85619. /** DEfines that impulse gets weaker if it's further from the origin */
  85620. PhysicsRadialImpulseFalloff[PhysicsRadialImpulseFalloff["Linear"] = 1] = "Linear";
  85621. })(PhysicsRadialImpulseFalloff = BABYLON.PhysicsRadialImpulseFalloff || (BABYLON.PhysicsRadialImpulseFalloff = {}));
  85622. /**
  85623. * The strenght of the force in correspondence to the distance of the affected object
  85624. */
  85625. var PhysicsUpdraftMode;
  85626. (function (PhysicsUpdraftMode) {
  85627. /** Defines that the upstream forces will pull towards the top center of the cylinder */
  85628. PhysicsUpdraftMode[PhysicsUpdraftMode["Center"] = 0] = "Center";
  85629. /** Defines that once a impostor is inside the cylinder, it will shoot out perpendicular from the ground of the cylinder */
  85630. PhysicsUpdraftMode[PhysicsUpdraftMode["Perpendicular"] = 1] = "Perpendicular";
  85631. })(PhysicsUpdraftMode = BABYLON.PhysicsUpdraftMode || (BABYLON.PhysicsUpdraftMode = {}));
  85632. })(BABYLON || (BABYLON = {}));
  85633. //# sourceMappingURL=babylon.physicsHelper.js.map
  85634. var BABYLON;
  85635. (function (BABYLON) {
  85636. var CannonJSPlugin = /** @class */ (function () {
  85637. function CannonJSPlugin(_useDeltaForWorldStep, iterations) {
  85638. if (_useDeltaForWorldStep === void 0) { _useDeltaForWorldStep = true; }
  85639. if (iterations === void 0) { iterations = 10; }
  85640. this._useDeltaForWorldStep = _useDeltaForWorldStep;
  85641. this.name = "CannonJSPlugin";
  85642. this._physicsMaterials = new Array();
  85643. this._fixedTimeStep = 1 / 60;
  85644. //See https://github.com/schteppe/CANNON.js/blob/gh-pages/demos/collisionFilter.html
  85645. this.BJSCANNON = CANNON;
  85646. this._minus90X = new BABYLON.Quaternion(-0.7071067811865475, 0, 0, 0.7071067811865475);
  85647. this._plus90X = new BABYLON.Quaternion(0.7071067811865475, 0, 0, 0.7071067811865475);
  85648. this._tmpPosition = BABYLON.Vector3.Zero();
  85649. this._tmpDeltaPosition = BABYLON.Vector3.Zero();
  85650. this._tmpUnityRotation = new BABYLON.Quaternion();
  85651. if (!this.isSupported()) {
  85652. BABYLON.Tools.Error("CannonJS is not available. Please make sure you included the js file.");
  85653. return;
  85654. }
  85655. this._extendNamespace();
  85656. this.world = new this.BJSCANNON.World();
  85657. this.world.broadphase = new this.BJSCANNON.NaiveBroadphase();
  85658. this.world.solver.iterations = iterations;
  85659. }
  85660. CannonJSPlugin.prototype.setGravity = function (gravity) {
  85661. this.world.gravity.copy(gravity);
  85662. };
  85663. CannonJSPlugin.prototype.setTimeStep = function (timeStep) {
  85664. this._fixedTimeStep = timeStep;
  85665. };
  85666. CannonJSPlugin.prototype.getTimeStep = function () {
  85667. return this._fixedTimeStep;
  85668. };
  85669. CannonJSPlugin.prototype.executeStep = function (delta, impostors) {
  85670. this.world.step(this._fixedTimeStep, this._useDeltaForWorldStep ? delta : 0, 3);
  85671. };
  85672. CannonJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  85673. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85674. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85675. impostor.physicsBody.applyImpulse(impulse, worldPoint);
  85676. };
  85677. CannonJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  85678. var worldPoint = new this.BJSCANNON.Vec3(contactPoint.x, contactPoint.y, contactPoint.z);
  85679. var impulse = new this.BJSCANNON.Vec3(force.x, force.y, force.z);
  85680. impostor.physicsBody.applyForce(impulse, worldPoint);
  85681. };
  85682. CannonJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  85683. //parent-child relationship. Does this impostor has a parent impostor?
  85684. if (impostor.parent) {
  85685. if (impostor.physicsBody) {
  85686. this.removePhysicsBody(impostor);
  85687. //TODO is that needed?
  85688. impostor.forceUpdate();
  85689. }
  85690. return;
  85691. }
  85692. //should a new body be created for this impostor?
  85693. if (impostor.isBodyInitRequired()) {
  85694. var shape = this._createShape(impostor);
  85695. //unregister events, if body is being changed
  85696. var oldBody = impostor.physicsBody;
  85697. if (oldBody) {
  85698. this.removePhysicsBody(impostor);
  85699. }
  85700. //create the body and material
  85701. var material = this._addMaterial("mat-" + impostor.uniqueId, impostor.getParam("friction"), impostor.getParam("restitution"));
  85702. var bodyCreationObject = {
  85703. mass: impostor.getParam("mass"),
  85704. material: material
  85705. };
  85706. // A simple extend, in case native options were used.
  85707. var nativeOptions = impostor.getParam("nativeOptions");
  85708. for (var key in nativeOptions) {
  85709. if (nativeOptions.hasOwnProperty(key)) {
  85710. bodyCreationObject[key] = nativeOptions[key];
  85711. }
  85712. }
  85713. impostor.physicsBody = new this.BJSCANNON.Body(bodyCreationObject);
  85714. impostor.physicsBody.addEventListener("collide", impostor.onCollide);
  85715. this.world.addEventListener("preStep", impostor.beforeStep);
  85716. this.world.addEventListener("postStep", impostor.afterStep);
  85717. impostor.physicsBody.addShape(shape);
  85718. this.world.add(impostor.physicsBody);
  85719. //try to keep the body moving in the right direction by taking old properties.
  85720. //Should be tested!
  85721. if (oldBody) {
  85722. ['force', 'torque', 'velocity', 'angularVelocity'].forEach(function (param) {
  85723. impostor.physicsBody[param].copy(oldBody[param]);
  85724. });
  85725. }
  85726. this._processChildMeshes(impostor);
  85727. }
  85728. //now update the body's transformation
  85729. this._updatePhysicsBodyTransformation(impostor);
  85730. };
  85731. CannonJSPlugin.prototype._processChildMeshes = function (mainImpostor) {
  85732. var _this = this;
  85733. var meshChildren = mainImpostor.object.getChildMeshes ? mainImpostor.object.getChildMeshes(true) : [];
  85734. var currentRotation = mainImpostor.object.rotationQuaternion;
  85735. if (meshChildren.length) {
  85736. var processMesh = function (localPosition, mesh) {
  85737. if (!currentRotation || !mesh.rotationQuaternion) {
  85738. return;
  85739. }
  85740. var childImpostor = mesh.getPhysicsImpostor();
  85741. if (childImpostor) {
  85742. var parent = childImpostor.parent;
  85743. if (parent !== mainImpostor) {
  85744. var pPosition = mesh.getAbsolutePosition().subtract(mainImpostor.object.getAbsolutePosition());
  85745. var localRotation = mesh.rotationQuaternion.multiply(BABYLON.Quaternion.Inverse(currentRotation));
  85746. if (childImpostor.physicsBody) {
  85747. _this.removePhysicsBody(childImpostor);
  85748. childImpostor.physicsBody = null;
  85749. }
  85750. childImpostor.parent = mainImpostor;
  85751. childImpostor.resetUpdateFlags();
  85752. 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));
  85753. //Add the mass of the children.
  85754. mainImpostor.physicsBody.mass += childImpostor.getParam("mass");
  85755. }
  85756. }
  85757. currentRotation.multiplyInPlace(mesh.rotationQuaternion);
  85758. mesh.getChildMeshes(true).filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(_this, mesh.getAbsolutePosition()));
  85759. };
  85760. meshChildren.filter(function (m) { return !!m.physicsImpostor; }).forEach(processMesh.bind(this, mainImpostor.object.getAbsolutePosition()));
  85761. }
  85762. };
  85763. CannonJSPlugin.prototype.removePhysicsBody = function (impostor) {
  85764. impostor.physicsBody.removeEventListener("collide", impostor.onCollide);
  85765. this.world.removeEventListener("preStep", impostor.beforeStep);
  85766. this.world.removeEventListener("postStep", impostor.afterStep);
  85767. this.world.remove(impostor.physicsBody);
  85768. };
  85769. CannonJSPlugin.prototype.generateJoint = function (impostorJoint) {
  85770. var mainBody = impostorJoint.mainImpostor.physicsBody;
  85771. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  85772. if (!mainBody || !connectedBody) {
  85773. return;
  85774. }
  85775. var constraint;
  85776. var jointData = impostorJoint.joint.jointData;
  85777. //TODO - https://github.com/schteppe/this.BJSCANNON.js/blob/gh-pages/demos/collisionFilter.html
  85778. var constraintData = {
  85779. pivotA: jointData.mainPivot ? new this.BJSCANNON.Vec3().copy(jointData.mainPivot) : null,
  85780. pivotB: jointData.connectedPivot ? new this.BJSCANNON.Vec3().copy(jointData.connectedPivot) : null,
  85781. axisA: jointData.mainAxis ? new this.BJSCANNON.Vec3().copy(jointData.mainAxis) : null,
  85782. axisB: jointData.connectedAxis ? new this.BJSCANNON.Vec3().copy(jointData.connectedAxis) : null,
  85783. maxForce: jointData.nativeParams.maxForce,
  85784. collideConnected: !!jointData.collision
  85785. };
  85786. switch (impostorJoint.joint.type) {
  85787. case BABYLON.PhysicsJoint.HingeJoint:
  85788. case BABYLON.PhysicsJoint.Hinge2Joint:
  85789. constraint = new this.BJSCANNON.HingeConstraint(mainBody, connectedBody, constraintData);
  85790. break;
  85791. case BABYLON.PhysicsJoint.DistanceJoint:
  85792. constraint = new this.BJSCANNON.DistanceConstraint(mainBody, connectedBody, jointData.maxDistance || 2);
  85793. break;
  85794. case BABYLON.PhysicsJoint.SpringJoint:
  85795. var springData = jointData;
  85796. constraint = new this.BJSCANNON.Spring(mainBody, connectedBody, {
  85797. restLength: springData.length,
  85798. stiffness: springData.stiffness,
  85799. damping: springData.damping,
  85800. localAnchorA: constraintData.pivotA,
  85801. localAnchorB: constraintData.pivotB
  85802. });
  85803. break;
  85804. case BABYLON.PhysicsJoint.LockJoint:
  85805. constraint = new this.BJSCANNON.LockConstraint(mainBody, connectedBody, constraintData);
  85806. break;
  85807. case BABYLON.PhysicsJoint.PointToPointJoint:
  85808. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  85809. default:
  85810. constraint = new this.BJSCANNON.PointToPointConstraint(mainBody, constraintData.pivotA, connectedBody, constraintData.pivotA, constraintData.maxForce);
  85811. break;
  85812. }
  85813. //set the collideConnected flag after the creation, since DistanceJoint ignores it.
  85814. constraint.collideConnected = !!jointData.collision;
  85815. impostorJoint.joint.physicsJoint = constraint;
  85816. //don't add spring as constraint, as it is not one.
  85817. if (impostorJoint.joint.type !== BABYLON.PhysicsJoint.SpringJoint) {
  85818. this.world.addConstraint(constraint);
  85819. }
  85820. else {
  85821. impostorJoint.mainImpostor.registerAfterPhysicsStep(function () {
  85822. constraint.applyForce();
  85823. });
  85824. }
  85825. };
  85826. CannonJSPlugin.prototype.removeJoint = function (impostorJoint) {
  85827. this.world.removeConstraint(impostorJoint.joint.physicsJoint);
  85828. };
  85829. CannonJSPlugin.prototype._addMaterial = function (name, friction, restitution) {
  85830. var index;
  85831. var mat;
  85832. for (index = 0; index < this._physicsMaterials.length; index++) {
  85833. mat = this._physicsMaterials[index];
  85834. if (mat.friction === friction && mat.restitution === restitution) {
  85835. return mat;
  85836. }
  85837. }
  85838. var currentMat = new this.BJSCANNON.Material(name);
  85839. currentMat.friction = friction;
  85840. currentMat.restitution = restitution;
  85841. this._physicsMaterials.push(currentMat);
  85842. return currentMat;
  85843. };
  85844. CannonJSPlugin.prototype._checkWithEpsilon = function (value) {
  85845. return value < BABYLON.PhysicsEngine.Epsilon ? BABYLON.PhysicsEngine.Epsilon : value;
  85846. };
  85847. CannonJSPlugin.prototype._createShape = function (impostor) {
  85848. var object = impostor.object;
  85849. var returnValue;
  85850. var extendSize = impostor.getObjectExtendSize();
  85851. switch (impostor.type) {
  85852. case BABYLON.PhysicsImpostor.SphereImpostor:
  85853. var radiusX = extendSize.x;
  85854. var radiusY = extendSize.y;
  85855. var radiusZ = extendSize.z;
  85856. returnValue = new this.BJSCANNON.Sphere(Math.max(this._checkWithEpsilon(radiusX), this._checkWithEpsilon(radiusY), this._checkWithEpsilon(radiusZ)) / 2);
  85857. break;
  85858. //TMP also for cylinder - TODO Cannon supports cylinder natively.
  85859. case BABYLON.PhysicsImpostor.CylinderImpostor:
  85860. returnValue = new this.BJSCANNON.Cylinder(this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.x) / 2, this._checkWithEpsilon(extendSize.y), 16);
  85861. break;
  85862. case BABYLON.PhysicsImpostor.BoxImpostor:
  85863. var box = extendSize.scale(0.5);
  85864. returnValue = new this.BJSCANNON.Box(new this.BJSCANNON.Vec3(this._checkWithEpsilon(box.x), this._checkWithEpsilon(box.y), this._checkWithEpsilon(box.z)));
  85865. break;
  85866. case BABYLON.PhysicsImpostor.PlaneImpostor:
  85867. BABYLON.Tools.Warn("Attention, PlaneImposter might not behave as you expect. Consider using BoxImposter instead");
  85868. returnValue = new this.BJSCANNON.Plane();
  85869. break;
  85870. case BABYLON.PhysicsImpostor.MeshImpostor:
  85871. // should transform the vertex data to world coordinates!!
  85872. var rawVerts = object.getVerticesData ? object.getVerticesData(BABYLON.VertexBuffer.PositionKind) : [];
  85873. var rawFaces = object.getIndices ? object.getIndices() : [];
  85874. if (!rawVerts)
  85875. return;
  85876. // get only scale! so the object could transform correctly.
  85877. var oldPosition = object.position.clone();
  85878. var oldRotation = object.rotation && object.rotation.clone();
  85879. var oldQuaternion = object.rotationQuaternion && object.rotationQuaternion.clone();
  85880. object.position.copyFromFloats(0, 0, 0);
  85881. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85882. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85883. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85884. var transform = object.computeWorldMatrix(true);
  85885. // convert rawVerts to object space
  85886. var temp = new Array();
  85887. var index;
  85888. for (index = 0; index < rawVerts.length; index += 3) {
  85889. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(rawVerts, index), transform).toArray(temp, index);
  85890. }
  85891. BABYLON.Tools.Warn("MeshImpostor only collides against spheres.");
  85892. returnValue = new this.BJSCANNON.Trimesh(temp, rawFaces);
  85893. //now set back the transformation!
  85894. object.position.copyFrom(oldPosition);
  85895. oldRotation && object.rotation && object.rotation.copyFrom(oldRotation);
  85896. oldQuaternion && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion);
  85897. break;
  85898. case BABYLON.PhysicsImpostor.HeightmapImpostor:
  85899. var oldPosition2 = object.position.clone();
  85900. var oldRotation2 = object.rotation && object.rotation.clone();
  85901. var oldQuaternion2 = object.rotationQuaternion && object.rotationQuaternion.clone();
  85902. object.position.copyFromFloats(0, 0, 0);
  85903. object.rotation && object.rotation.copyFromFloats(0, 0, 0);
  85904. object.rotationQuaternion && object.rotationQuaternion.copyFrom(impostor.getParentsRotation());
  85905. object.rotationQuaternion && object.parent && object.rotationQuaternion.conjugateInPlace();
  85906. object.rotationQuaternion && object.rotationQuaternion.multiplyInPlace(this._minus90X);
  85907. returnValue = this._createHeightmap(object);
  85908. object.position.copyFrom(oldPosition2);
  85909. oldRotation2 && object.rotation && object.rotation.copyFrom(oldRotation2);
  85910. oldQuaternion2 && object.rotationQuaternion && object.rotationQuaternion.copyFrom(oldQuaternion2);
  85911. object.computeWorldMatrix(true);
  85912. break;
  85913. case BABYLON.PhysicsImpostor.ParticleImpostor:
  85914. returnValue = new this.BJSCANNON.Particle();
  85915. break;
  85916. }
  85917. return returnValue;
  85918. };
  85919. CannonJSPlugin.prototype._createHeightmap = function (object, pointDepth) {
  85920. var pos = (object.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  85921. var transform = object.computeWorldMatrix(true);
  85922. // convert rawVerts to object space
  85923. var temp = new Array();
  85924. var index;
  85925. for (index = 0; index < pos.length; index += 3) {
  85926. BABYLON.Vector3.TransformCoordinates(BABYLON.Vector3.FromArray(pos, index), transform).toArray(temp, index);
  85927. }
  85928. pos = temp;
  85929. var matrix = new Array();
  85930. //For now pointDepth will not be used and will be automatically calculated.
  85931. //Future reference - try and find the best place to add a reference to the pointDepth variable.
  85932. var arraySize = pointDepth || ~~(Math.sqrt(pos.length / 3) - 1);
  85933. var boundingInfo = object.getBoundingInfo();
  85934. var dim = Math.min(boundingInfo.boundingBox.extendSizeWorld.x, boundingInfo.boundingBox.extendSizeWorld.y);
  85935. var minY = boundingInfo.boundingBox.extendSizeWorld.z;
  85936. var elementSize = dim * 2 / arraySize;
  85937. for (var i = 0; i < pos.length; i = i + 3) {
  85938. var x = Math.round((pos[i + 0]) / elementSize + arraySize / 2);
  85939. var z = Math.round(((pos[i + 1]) / elementSize - arraySize / 2) * -1);
  85940. var y = -pos[i + 2] + minY;
  85941. if (!matrix[x]) {
  85942. matrix[x] = [];
  85943. }
  85944. if (!matrix[x][z]) {
  85945. matrix[x][z] = y;
  85946. }
  85947. matrix[x][z] = Math.max(y, matrix[x][z]);
  85948. }
  85949. for (var x = 0; x <= arraySize; ++x) {
  85950. if (!matrix[x]) {
  85951. var loc = 1;
  85952. while (!matrix[(x + loc) % arraySize]) {
  85953. loc++;
  85954. }
  85955. matrix[x] = matrix[(x + loc) % arraySize].slice();
  85956. //console.log("missing x", x);
  85957. }
  85958. for (var z = 0; z <= arraySize; ++z) {
  85959. if (!matrix[x][z]) {
  85960. var loc = 1;
  85961. var newValue;
  85962. while (newValue === undefined) {
  85963. newValue = matrix[x][(z + loc++) % arraySize];
  85964. }
  85965. matrix[x][z] = newValue;
  85966. }
  85967. }
  85968. }
  85969. var shape = new this.BJSCANNON.Heightfield(matrix, {
  85970. elementSize: elementSize
  85971. });
  85972. //For future reference, needed for body transformation
  85973. shape.minY = minY;
  85974. return shape;
  85975. };
  85976. CannonJSPlugin.prototype._updatePhysicsBodyTransformation = function (impostor) {
  85977. var object = impostor.object;
  85978. //make sure it is updated...
  85979. object.computeWorldMatrix && object.computeWorldMatrix(true);
  85980. // The delta between the mesh position and the mesh bounding box center
  85981. var bInfo = object.getBoundingInfo();
  85982. if (!bInfo)
  85983. return;
  85984. var center = impostor.getObjectCenter();
  85985. //m.getAbsolutePosition().subtract(m.getBoundingInfo().boundingBox.centerWorld)
  85986. this._tmpDeltaPosition.copyFrom(object.getAbsolutePivotPoint().subtract(center));
  85987. this._tmpDeltaPosition.divideInPlace(impostor.object.scaling);
  85988. this._tmpPosition.copyFrom(center);
  85989. var quaternion = object.rotationQuaternion;
  85990. if (!quaternion) {
  85991. return;
  85992. }
  85993. //is shape is a plane or a heightmap, it must be rotated 90 degs in the X axis.
  85994. if (impostor.type === BABYLON.PhysicsImpostor.PlaneImpostor || impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor || impostor.type === BABYLON.PhysicsImpostor.CylinderImpostor) {
  85995. //-90 DEG in X, precalculated
  85996. quaternion = quaternion.multiply(this._minus90X);
  85997. //Invert! (Precalculated, 90 deg in X)
  85998. //No need to clone. this will never change.
  85999. impostor.setDeltaRotation(this._plus90X);
  86000. }
  86001. //If it is a heightfield, if should be centered.
  86002. if (impostor.type === BABYLON.PhysicsImpostor.HeightmapImpostor) {
  86003. var mesh = object;
  86004. var boundingInfo = mesh.getBoundingInfo();
  86005. //calculate the correct body position:
  86006. var rotationQuaternion = mesh.rotationQuaternion;
  86007. mesh.rotationQuaternion = this._tmpUnityRotation;
  86008. mesh.computeWorldMatrix(true);
  86009. //get original center with no rotation
  86010. var c = center.clone();
  86011. var oldPivot = mesh.getPivotMatrix() || BABYLON.Matrix.Translation(0, 0, 0);
  86012. //calculate the new center using a pivot (since this.BJSCANNON.js doesn't center height maps)
  86013. var p = BABYLON.Matrix.Translation(boundingInfo.boundingBox.extendSizeWorld.x, 0, -boundingInfo.boundingBox.extendSizeWorld.z);
  86014. mesh.setPreTransformMatrix(p);
  86015. mesh.computeWorldMatrix(true);
  86016. //calculate the translation
  86017. var translation = boundingInfo.boundingBox.centerWorld.subtract(center).subtract(mesh.position).negate();
  86018. this._tmpPosition.copyFromFloats(translation.x, translation.y - boundingInfo.boundingBox.extendSizeWorld.y, translation.z);
  86019. //add it inverted to the delta
  86020. this._tmpDeltaPosition.copyFrom(boundingInfo.boundingBox.centerWorld.subtract(c));
  86021. this._tmpDeltaPosition.y += boundingInfo.boundingBox.extendSizeWorld.y;
  86022. //rotation is back
  86023. mesh.rotationQuaternion = rotationQuaternion;
  86024. mesh.setPreTransformMatrix(oldPivot);
  86025. mesh.computeWorldMatrix(true);
  86026. }
  86027. else if (impostor.type === BABYLON.PhysicsImpostor.MeshImpostor) {
  86028. this._tmpDeltaPosition.copyFromFloats(0, 0, 0);
  86029. //this._tmpPosition.copyFrom(object.position);
  86030. }
  86031. impostor.setDeltaPosition(this._tmpDeltaPosition);
  86032. //Now update the impostor object
  86033. impostor.physicsBody.position.copy(this._tmpPosition);
  86034. impostor.physicsBody.quaternion.copy(quaternion);
  86035. };
  86036. CannonJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86037. impostor.object.position.copyFrom(impostor.physicsBody.position);
  86038. if (impostor.object.rotationQuaternion) {
  86039. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.quaternion);
  86040. }
  86041. };
  86042. CannonJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86043. impostor.physicsBody.position.copy(newPosition);
  86044. impostor.physicsBody.quaternion.copy(newRotation);
  86045. };
  86046. CannonJSPlugin.prototype.isSupported = function () {
  86047. return this.BJSCANNON !== undefined;
  86048. };
  86049. CannonJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86050. impostor.physicsBody.velocity.copy(velocity);
  86051. };
  86052. CannonJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86053. impostor.physicsBody.angularVelocity.copy(velocity);
  86054. };
  86055. CannonJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86056. var v = impostor.physicsBody.velocity;
  86057. if (!v) {
  86058. return null;
  86059. }
  86060. return new BABYLON.Vector3(v.x, v.y, v.z);
  86061. };
  86062. CannonJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86063. var v = impostor.physicsBody.angularVelocity;
  86064. if (!v) {
  86065. return null;
  86066. }
  86067. return new BABYLON.Vector3(v.x, v.y, v.z);
  86068. };
  86069. CannonJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86070. impostor.physicsBody.mass = mass;
  86071. impostor.physicsBody.updateMassProperties();
  86072. };
  86073. CannonJSPlugin.prototype.getBodyMass = function (impostor) {
  86074. return impostor.physicsBody.mass;
  86075. };
  86076. CannonJSPlugin.prototype.getBodyFriction = function (impostor) {
  86077. return impostor.physicsBody.material.friction;
  86078. };
  86079. CannonJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86080. impostor.physicsBody.material.friction = friction;
  86081. };
  86082. CannonJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86083. return impostor.physicsBody.material.restitution;
  86084. };
  86085. CannonJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86086. impostor.physicsBody.material.restitution = restitution;
  86087. };
  86088. CannonJSPlugin.prototype.sleepBody = function (impostor) {
  86089. impostor.physicsBody.sleep();
  86090. };
  86091. CannonJSPlugin.prototype.wakeUpBody = function (impostor) {
  86092. impostor.physicsBody.wakeUp();
  86093. };
  86094. CannonJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86095. joint.physicsJoint.distance = maxDistance;
  86096. };
  86097. // private enableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86098. // if (!motorIndex) {
  86099. // joint.physicsJoint.enableMotor();
  86100. // }
  86101. // }
  86102. // private disableMotor(joint: IMotorEnabledJoint, motorIndex?: number) {
  86103. // if (!motorIndex) {
  86104. // joint.physicsJoint.disableMotor();
  86105. // }
  86106. // }
  86107. CannonJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86108. if (!motorIndex) {
  86109. joint.physicsJoint.enableMotor();
  86110. joint.physicsJoint.setMotorSpeed(speed);
  86111. if (maxForce) {
  86112. this.setLimit(joint, maxForce);
  86113. }
  86114. }
  86115. };
  86116. CannonJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit) {
  86117. joint.physicsJoint.motorEquation.maxForce = upperLimit;
  86118. joint.physicsJoint.motorEquation.minForce = lowerLimit === void 0 ? -upperLimit : lowerLimit;
  86119. };
  86120. CannonJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86121. var body = impostor.physicsBody;
  86122. mesh.position.x = body.position.x;
  86123. mesh.position.y = body.position.y;
  86124. mesh.position.z = body.position.z;
  86125. if (mesh.rotationQuaternion) {
  86126. mesh.rotationQuaternion.x = body.quaternion.x;
  86127. mesh.rotationQuaternion.y = body.quaternion.y;
  86128. mesh.rotationQuaternion.z = body.quaternion.z;
  86129. mesh.rotationQuaternion.w = body.quaternion.w;
  86130. }
  86131. };
  86132. CannonJSPlugin.prototype.getRadius = function (impostor) {
  86133. var shape = impostor.physicsBody.shapes[0];
  86134. return shape.boundingSphereRadius;
  86135. };
  86136. CannonJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86137. var shape = impostor.physicsBody.shapes[0];
  86138. result.x = shape.halfExtents.x * 2;
  86139. result.y = shape.halfExtents.y * 2;
  86140. result.z = shape.halfExtents.z * 2;
  86141. };
  86142. CannonJSPlugin.prototype.dispose = function () {
  86143. };
  86144. CannonJSPlugin.prototype._extendNamespace = function () {
  86145. //this will force cannon to execute at least one step when using interpolation
  86146. var step_tmp1 = new this.BJSCANNON.Vec3();
  86147. var Engine = this.BJSCANNON;
  86148. this.BJSCANNON.World.prototype.step = function (dt, timeSinceLastCalled, maxSubSteps) {
  86149. maxSubSteps = maxSubSteps || 10;
  86150. timeSinceLastCalled = timeSinceLastCalled || 0;
  86151. if (timeSinceLastCalled === 0) {
  86152. this.internalStep(dt);
  86153. this.time += dt;
  86154. }
  86155. else {
  86156. var internalSteps = Math.floor((this.time + timeSinceLastCalled) / dt) - Math.floor(this.time / dt);
  86157. internalSteps = Math.min(internalSteps, maxSubSteps) || 1;
  86158. var t0 = performance.now();
  86159. for (var i = 0; i !== internalSteps; i++) {
  86160. this.internalStep(dt);
  86161. if (performance.now() - t0 > dt * 1000) {
  86162. break;
  86163. }
  86164. }
  86165. this.time += timeSinceLastCalled;
  86166. var h = this.time % dt;
  86167. var h_div_dt = h / dt;
  86168. var interpvelo = step_tmp1;
  86169. var bodies = this.bodies;
  86170. for (var j = 0; j !== bodies.length; j++) {
  86171. var b = bodies[j];
  86172. if (b.type !== Engine.Body.STATIC && b.sleepState !== Engine.Body.SLEEPING) {
  86173. b.position.vsub(b.previousPosition, interpvelo);
  86174. interpvelo.scale(h_div_dt, interpvelo);
  86175. b.position.vadd(interpvelo, b.interpolatedPosition);
  86176. }
  86177. else {
  86178. b.interpolatedPosition.copy(b.position);
  86179. b.interpolatedQuaternion.copy(b.quaternion);
  86180. }
  86181. }
  86182. }
  86183. };
  86184. };
  86185. return CannonJSPlugin;
  86186. }());
  86187. BABYLON.CannonJSPlugin = CannonJSPlugin;
  86188. })(BABYLON || (BABYLON = {}));
  86189. //# sourceMappingURL=babylon.cannonJSPlugin.js.map
  86190. var BABYLON;
  86191. (function (BABYLON) {
  86192. var OimoJSPlugin = /** @class */ (function () {
  86193. function OimoJSPlugin(iterations) {
  86194. this.name = "OimoJSPlugin";
  86195. this._tmpImpostorsArray = [];
  86196. this._tmpPositionVector = BABYLON.Vector3.Zero();
  86197. this.BJSOIMO = OIMO;
  86198. this.world = new this.BJSOIMO.World({
  86199. iterations: iterations
  86200. });
  86201. this.world.clear();
  86202. }
  86203. OimoJSPlugin.prototype.setGravity = function (gravity) {
  86204. this.world.gravity.copy(gravity);
  86205. };
  86206. OimoJSPlugin.prototype.setTimeStep = function (timeStep) {
  86207. this.world.timeStep = timeStep;
  86208. };
  86209. OimoJSPlugin.prototype.getTimeStep = function () {
  86210. return this.world.timeStep;
  86211. };
  86212. OimoJSPlugin.prototype.executeStep = function (delta, impostors) {
  86213. var _this = this;
  86214. impostors.forEach(function (impostor) {
  86215. impostor.beforeStep();
  86216. });
  86217. this.world.step();
  86218. impostors.forEach(function (impostor) {
  86219. impostor.afterStep();
  86220. //update the ordered impostors array
  86221. _this._tmpImpostorsArray[impostor.uniqueId] = impostor;
  86222. });
  86223. //check for collisions
  86224. var contact = this.world.contacts;
  86225. while (contact !== null) {
  86226. if (contact.touching && !contact.body1.sleeping && !contact.body2.sleeping) {
  86227. contact = contact.next;
  86228. continue;
  86229. }
  86230. //is this body colliding with any other? get the impostor
  86231. var mainImpostor = this._tmpImpostorsArray[+contact.body1.name];
  86232. var collidingImpostor = this._tmpImpostorsArray[+contact.body2.name];
  86233. if (!mainImpostor || !collidingImpostor) {
  86234. contact = contact.next;
  86235. continue;
  86236. }
  86237. mainImpostor.onCollide({ body: collidingImpostor.physicsBody });
  86238. collidingImpostor.onCollide({ body: mainImpostor.physicsBody });
  86239. contact = contact.next;
  86240. }
  86241. };
  86242. OimoJSPlugin.prototype.applyImpulse = function (impostor, force, contactPoint) {
  86243. var mass = impostor.physicsBody.mass;
  86244. impostor.physicsBody.applyImpulse(contactPoint.scale(this.world.invScale), force.scale(this.world.invScale * mass));
  86245. };
  86246. OimoJSPlugin.prototype.applyForce = function (impostor, force, contactPoint) {
  86247. BABYLON.Tools.Warn("Oimo doesn't support applying force. Using impule instead.");
  86248. this.applyImpulse(impostor, force, contactPoint);
  86249. };
  86250. OimoJSPlugin.prototype.generatePhysicsBody = function (impostor) {
  86251. var _this = this;
  86252. //parent-child relationship. Does this impostor has a parent impostor?
  86253. if (impostor.parent) {
  86254. if (impostor.physicsBody) {
  86255. this.removePhysicsBody(impostor);
  86256. //TODO is that needed?
  86257. impostor.forceUpdate();
  86258. }
  86259. return;
  86260. }
  86261. if (impostor.isBodyInitRequired()) {
  86262. var bodyConfig = {
  86263. name: impostor.uniqueId,
  86264. //Oimo must have mass, also for static objects.
  86265. config: [impostor.getParam("mass") || 1, impostor.getParam("friction"), impostor.getParam("restitution")],
  86266. size: [],
  86267. type: [],
  86268. pos: [],
  86269. posShape: [],
  86270. rot: [],
  86271. rotShape: [],
  86272. move: impostor.getParam("mass") !== 0,
  86273. density: impostor.getParam("mass"),
  86274. friction: impostor.getParam("friction"),
  86275. restitution: impostor.getParam("restitution"),
  86276. //Supporting older versions of Oimo
  86277. world: this.world
  86278. };
  86279. var impostors = [impostor];
  86280. var addToArray = function (parent) {
  86281. if (!parent.getChildMeshes)
  86282. return;
  86283. parent.getChildMeshes().forEach(function (m) {
  86284. if (m.physicsImpostor) {
  86285. impostors.push(m.physicsImpostor);
  86286. //m.physicsImpostor._init();
  86287. }
  86288. });
  86289. };
  86290. addToArray(impostor.object);
  86291. var checkWithEpsilon_1 = function (value) {
  86292. return Math.max(value, BABYLON.PhysicsEngine.Epsilon);
  86293. };
  86294. impostors.forEach(function (i) {
  86295. if (!i.object.rotationQuaternion) {
  86296. return;
  86297. }
  86298. //get the correct bounding box
  86299. var oldQuaternion = i.object.rotationQuaternion;
  86300. var rot = oldQuaternion.toEulerAngles();
  86301. var extendSize = i.getObjectExtendSize();
  86302. var radToDeg = 57.295779513082320876;
  86303. if (i === impostor) {
  86304. var center = impostor.getObjectCenter();
  86305. impostor.object.getAbsolutePivotPoint().subtractToRef(center, _this._tmpPositionVector);
  86306. _this._tmpPositionVector.divideInPlace(impostor.object.scaling);
  86307. //Can also use Array.prototype.push.apply
  86308. bodyConfig.pos.push(center.x);
  86309. bodyConfig.pos.push(center.y);
  86310. bodyConfig.pos.push(center.z);
  86311. bodyConfig.posShape.push(0, 0, 0);
  86312. //tmp solution
  86313. bodyConfig.rot.push(rot.x * radToDeg);
  86314. bodyConfig.rot.push(rot.y * radToDeg);
  86315. bodyConfig.rot.push(rot.z * radToDeg);
  86316. bodyConfig.rotShape.push(0, 0, 0);
  86317. }
  86318. else {
  86319. var localPosition = i.object.getAbsolutePosition().subtract(impostor.object.getAbsolutePosition());
  86320. bodyConfig.posShape.push(localPosition.x);
  86321. bodyConfig.posShape.push(localPosition.y);
  86322. bodyConfig.posShape.push(localPosition.z);
  86323. bodyConfig.pos.push(0, 0, 0);
  86324. //tmp solution until https://github.com/lo-th/OIMO.js/pull/37 is merged
  86325. bodyConfig.rot.push(0);
  86326. bodyConfig.rot.push(0);
  86327. bodyConfig.rot.push(0);
  86328. bodyConfig.rotShape.push(rot.x * radToDeg);
  86329. bodyConfig.rotShape.push(rot.y * radToDeg);
  86330. bodyConfig.rotShape.push(rot.z * radToDeg);
  86331. }
  86332. // register mesh
  86333. switch (i.type) {
  86334. case BABYLON.PhysicsImpostor.ParticleImpostor:
  86335. BABYLON.Tools.Warn("No Particle support in OIMO.js. using SphereImpostor instead");
  86336. case BABYLON.PhysicsImpostor.SphereImpostor:
  86337. var radiusX = extendSize.x;
  86338. var radiusY = extendSize.y;
  86339. var radiusZ = extendSize.z;
  86340. var size = Math.max(checkWithEpsilon_1(radiusX), checkWithEpsilon_1(radiusY), checkWithEpsilon_1(radiusZ)) / 2;
  86341. bodyConfig.type.push('sphere');
  86342. //due to the way oimo works with compounds, add 3 times
  86343. bodyConfig.size.push(size);
  86344. bodyConfig.size.push(size);
  86345. bodyConfig.size.push(size);
  86346. break;
  86347. case BABYLON.PhysicsImpostor.CylinderImpostor:
  86348. var sizeX = checkWithEpsilon_1(extendSize.x) / 2;
  86349. var sizeY = checkWithEpsilon_1(extendSize.y);
  86350. bodyConfig.type.push('cylinder');
  86351. bodyConfig.size.push(sizeX);
  86352. bodyConfig.size.push(sizeY);
  86353. //due to the way oimo works with compounds, add one more value.
  86354. bodyConfig.size.push(sizeY);
  86355. break;
  86356. case BABYLON.PhysicsImpostor.PlaneImpostor:
  86357. case BABYLON.PhysicsImpostor.BoxImpostor:
  86358. default:
  86359. var sizeX = checkWithEpsilon_1(extendSize.x);
  86360. var sizeY = checkWithEpsilon_1(extendSize.y);
  86361. var sizeZ = checkWithEpsilon_1(extendSize.z);
  86362. bodyConfig.type.push('box');
  86363. //if (i === impostor) {
  86364. bodyConfig.size.push(sizeX);
  86365. bodyConfig.size.push(sizeY);
  86366. bodyConfig.size.push(sizeZ);
  86367. //} else {
  86368. // bodyConfig.size.push(0,0,0);
  86369. //}
  86370. break;
  86371. }
  86372. //actually not needed, but hey...
  86373. i.object.rotationQuaternion = oldQuaternion;
  86374. });
  86375. impostor.physicsBody = this.world.add(bodyConfig);
  86376. }
  86377. else {
  86378. this._tmpPositionVector.copyFromFloats(0, 0, 0);
  86379. }
  86380. impostor.setDeltaPosition(this._tmpPositionVector);
  86381. //this._tmpPositionVector.addInPlace(impostor.mesh.getBoundingInfo().boundingBox.center);
  86382. //this.setPhysicsBodyTransformation(impostor, this._tmpPositionVector, impostor.mesh.rotationQuaternion);
  86383. };
  86384. OimoJSPlugin.prototype.removePhysicsBody = function (impostor) {
  86385. //impostor.physicsBody.dispose();
  86386. //Same as : (older oimo versions)
  86387. this.world.removeRigidBody(impostor.physicsBody);
  86388. };
  86389. OimoJSPlugin.prototype.generateJoint = function (impostorJoint) {
  86390. var mainBody = impostorJoint.mainImpostor.physicsBody;
  86391. var connectedBody = impostorJoint.connectedImpostor.physicsBody;
  86392. if (!mainBody || !connectedBody) {
  86393. return;
  86394. }
  86395. var jointData = impostorJoint.joint.jointData;
  86396. var options = jointData.nativeParams || {};
  86397. var type;
  86398. var nativeJointData = {
  86399. body1: mainBody,
  86400. body2: connectedBody,
  86401. axe1: options.axe1 || (jointData.mainAxis ? jointData.mainAxis.asArray() : null),
  86402. axe2: options.axe2 || (jointData.connectedAxis ? jointData.connectedAxis.asArray() : null),
  86403. pos1: options.pos1 || (jointData.mainPivot ? jointData.mainPivot.asArray() : null),
  86404. pos2: options.pos2 || (jointData.connectedPivot ? jointData.connectedPivot.asArray() : null),
  86405. min: options.min,
  86406. max: options.max,
  86407. collision: options.collision || jointData.collision,
  86408. spring: options.spring,
  86409. //supporting older version of Oimo
  86410. world: this.world
  86411. };
  86412. switch (impostorJoint.joint.type) {
  86413. case BABYLON.PhysicsJoint.BallAndSocketJoint:
  86414. type = "jointBall";
  86415. break;
  86416. case BABYLON.PhysicsJoint.SpringJoint:
  86417. BABYLON.Tools.Warn("OIMO.js doesn't support Spring Constraint. Simulating using DistanceJoint instead");
  86418. var springData = jointData;
  86419. nativeJointData.min = springData.length || nativeJointData.min;
  86420. //Max should also be set, just make sure it is at least min
  86421. nativeJointData.max = Math.max(nativeJointData.min, nativeJointData.max);
  86422. case BABYLON.PhysicsJoint.DistanceJoint:
  86423. type = "jointDistance";
  86424. nativeJointData.max = jointData.maxDistance;
  86425. break;
  86426. case BABYLON.PhysicsJoint.PrismaticJoint:
  86427. type = "jointPrisme";
  86428. break;
  86429. case BABYLON.PhysicsJoint.SliderJoint:
  86430. type = "jointSlide";
  86431. break;
  86432. case BABYLON.PhysicsJoint.WheelJoint:
  86433. type = "jointWheel";
  86434. break;
  86435. case BABYLON.PhysicsJoint.HingeJoint:
  86436. default:
  86437. type = "jointHinge";
  86438. break;
  86439. }
  86440. nativeJointData.type = type;
  86441. impostorJoint.joint.physicsJoint = this.world.add(nativeJointData);
  86442. };
  86443. OimoJSPlugin.prototype.removeJoint = function (impostorJoint) {
  86444. //Bug in Oimo prevents us from disposing a joint in the playground
  86445. //joint.joint.physicsJoint.dispose();
  86446. //So we will bruteforce it!
  86447. try {
  86448. this.world.removeJoint(impostorJoint.joint.physicsJoint);
  86449. }
  86450. catch (e) {
  86451. BABYLON.Tools.Warn(e);
  86452. }
  86453. };
  86454. OimoJSPlugin.prototype.isSupported = function () {
  86455. return this.BJSOIMO !== undefined;
  86456. };
  86457. OimoJSPlugin.prototype.setTransformationFromPhysicsBody = function (impostor) {
  86458. if (!impostor.physicsBody.sleeping) {
  86459. //TODO check that
  86460. /*if (impostor.physicsBody.shapes.next) {
  86461. var parentShape = this._getLastShape(impostor.physicsBody);
  86462. impostor.object.position.copyFrom(parentShape.position);
  86463. console.log(parentShape.position);
  86464. } else {*/
  86465. impostor.object.position.copyFrom(impostor.physicsBody.getPosition());
  86466. //}
  86467. if (impostor.object.rotationQuaternion) {
  86468. impostor.object.rotationQuaternion.copyFrom(impostor.physicsBody.getQuaternion());
  86469. }
  86470. }
  86471. };
  86472. OimoJSPlugin.prototype.setPhysicsBodyTransformation = function (impostor, newPosition, newRotation) {
  86473. var body = impostor.physicsBody;
  86474. body.position.copy(newPosition);
  86475. body.orientation.copy(newRotation);
  86476. body.syncShapes();
  86477. body.awake();
  86478. };
  86479. /*private _getLastShape(body: any): any {
  86480. var lastShape = body.shapes;
  86481. while (lastShape.next) {
  86482. lastShape = lastShape.next;
  86483. }
  86484. return lastShape;
  86485. }*/
  86486. OimoJSPlugin.prototype.setLinearVelocity = function (impostor, velocity) {
  86487. impostor.physicsBody.linearVelocity.copy(velocity);
  86488. };
  86489. OimoJSPlugin.prototype.setAngularVelocity = function (impostor, velocity) {
  86490. impostor.physicsBody.angularVelocity.copy(velocity);
  86491. };
  86492. OimoJSPlugin.prototype.getLinearVelocity = function (impostor) {
  86493. var v = impostor.physicsBody.linearVelocity;
  86494. if (!v) {
  86495. return null;
  86496. }
  86497. return new BABYLON.Vector3(v.x, v.y, v.z);
  86498. };
  86499. OimoJSPlugin.prototype.getAngularVelocity = function (impostor) {
  86500. var v = impostor.physicsBody.angularVelocity;
  86501. if (!v) {
  86502. return null;
  86503. }
  86504. return new BABYLON.Vector3(v.x, v.y, v.z);
  86505. };
  86506. OimoJSPlugin.prototype.setBodyMass = function (impostor, mass) {
  86507. var staticBody = mass === 0;
  86508. //this will actually set the body's density and not its mass.
  86509. //But this is how oimo treats the mass variable.
  86510. impostor.physicsBody.shapes.density = staticBody ? 1 : mass;
  86511. impostor.physicsBody.setupMass(staticBody ? 0x2 : 0x1);
  86512. };
  86513. OimoJSPlugin.prototype.getBodyMass = function (impostor) {
  86514. return impostor.physicsBody.shapes.density;
  86515. };
  86516. OimoJSPlugin.prototype.getBodyFriction = function (impostor) {
  86517. return impostor.physicsBody.shapes.friction;
  86518. };
  86519. OimoJSPlugin.prototype.setBodyFriction = function (impostor, friction) {
  86520. impostor.physicsBody.shapes.friction = friction;
  86521. };
  86522. OimoJSPlugin.prototype.getBodyRestitution = function (impostor) {
  86523. return impostor.physicsBody.shapes.restitution;
  86524. };
  86525. OimoJSPlugin.prototype.setBodyRestitution = function (impostor, restitution) {
  86526. impostor.physicsBody.shapes.restitution = restitution;
  86527. };
  86528. OimoJSPlugin.prototype.sleepBody = function (impostor) {
  86529. impostor.physicsBody.sleep();
  86530. };
  86531. OimoJSPlugin.prototype.wakeUpBody = function (impostor) {
  86532. impostor.physicsBody.awake();
  86533. };
  86534. OimoJSPlugin.prototype.updateDistanceJoint = function (joint, maxDistance, minDistance) {
  86535. joint.physicsJoint.limitMotor.upperLimit = maxDistance;
  86536. if (minDistance !== void 0) {
  86537. joint.physicsJoint.limitMotor.lowerLimit = minDistance;
  86538. }
  86539. };
  86540. OimoJSPlugin.prototype.setMotor = function (joint, speed, maxForce, motorIndex) {
  86541. //TODO separate rotational and transational motors.
  86542. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86543. if (motor) {
  86544. motor.setMotor(speed, maxForce);
  86545. }
  86546. };
  86547. OimoJSPlugin.prototype.setLimit = function (joint, upperLimit, lowerLimit, motorIndex) {
  86548. //TODO separate rotational and transational motors.
  86549. var motor = motorIndex ? joint.physicsJoint.rotationalLimitMotor2 : joint.physicsJoint.rotationalLimitMotor1 || joint.physicsJoint.rotationalLimitMotor || joint.physicsJoint.limitMotor;
  86550. if (motor) {
  86551. motor.setLimit(upperLimit, lowerLimit === void 0 ? -upperLimit : lowerLimit);
  86552. }
  86553. };
  86554. OimoJSPlugin.prototype.syncMeshWithImpostor = function (mesh, impostor) {
  86555. var body = impostor.physicsBody;
  86556. mesh.position.x = body.position.x;
  86557. mesh.position.y = body.position.y;
  86558. mesh.position.z = body.position.z;
  86559. if (mesh.rotationQuaternion) {
  86560. mesh.rotationQuaternion.x = body.orientation.x;
  86561. mesh.rotationQuaternion.y = body.orientation.y;
  86562. mesh.rotationQuaternion.z = body.orientation.z;
  86563. mesh.rotationQuaternion.w = body.orientation.s;
  86564. }
  86565. };
  86566. OimoJSPlugin.prototype.getRadius = function (impostor) {
  86567. return impostor.physicsBody.shapes.radius;
  86568. };
  86569. OimoJSPlugin.prototype.getBoxSizeToRef = function (impostor, result) {
  86570. var shape = impostor.physicsBody.shapes;
  86571. result.x = shape.halfWidth * 2;
  86572. result.y = shape.halfHeight * 2;
  86573. result.z = shape.halfDepth * 2;
  86574. };
  86575. OimoJSPlugin.prototype.dispose = function () {
  86576. this.world.clear();
  86577. };
  86578. return OimoJSPlugin;
  86579. }());
  86580. BABYLON.OimoJSPlugin = OimoJSPlugin;
  86581. })(BABYLON || (BABYLON = {}));
  86582. //# sourceMappingURL=babylon.oimoJSPlugin.js.map
  86583. var BABYLON;
  86584. (function (BABYLON) {
  86585. /*
  86586. * Based on jsTGALoader - Javascript loader for TGA file
  86587. * By Vincent Thibault
  86588. * @blog http://blog.robrowser.com/javascript-tga-loader.html
  86589. */
  86590. var TGATools = /** @class */ (function () {
  86591. function TGATools() {
  86592. }
  86593. TGATools.GetTGAHeader = function (data) {
  86594. var offset = 0;
  86595. var header = {
  86596. id_length: data[offset++],
  86597. colormap_type: data[offset++],
  86598. image_type: data[offset++],
  86599. colormap_index: data[offset++] | data[offset++] << 8,
  86600. colormap_length: data[offset++] | data[offset++] << 8,
  86601. colormap_size: data[offset++],
  86602. origin: [
  86603. data[offset++] | data[offset++] << 8,
  86604. data[offset++] | data[offset++] << 8
  86605. ],
  86606. width: data[offset++] | data[offset++] << 8,
  86607. height: data[offset++] | data[offset++] << 8,
  86608. pixel_size: data[offset++],
  86609. flags: data[offset++]
  86610. };
  86611. return header;
  86612. };
  86613. TGATools.UploadContent = function (gl, data) {
  86614. // Not enough data to contain header ?
  86615. if (data.length < 19) {
  86616. BABYLON.Tools.Error("Unable to load TGA file - Not enough data to contain header");
  86617. return;
  86618. }
  86619. // Read Header
  86620. var offset = 18;
  86621. var header = TGATools.GetTGAHeader(data);
  86622. // Assume it's a valid Targa file.
  86623. if (header.id_length + offset > data.length) {
  86624. BABYLON.Tools.Error("Unable to load TGA file - Not enough data");
  86625. return;
  86626. }
  86627. // Skip not needed data
  86628. offset += header.id_length;
  86629. var use_rle = false;
  86630. var use_pal = false;
  86631. var use_grey = false;
  86632. // Get some informations.
  86633. switch (header.image_type) {
  86634. case TGATools._TYPE_RLE_INDEXED:
  86635. use_rle = true;
  86636. case TGATools._TYPE_INDEXED:
  86637. use_pal = true;
  86638. break;
  86639. case TGATools._TYPE_RLE_RGB:
  86640. use_rle = true;
  86641. case TGATools._TYPE_RGB:
  86642. // use_rgb = true;
  86643. break;
  86644. case TGATools._TYPE_RLE_GREY:
  86645. use_rle = true;
  86646. case TGATools._TYPE_GREY:
  86647. use_grey = true;
  86648. break;
  86649. }
  86650. var pixel_data;
  86651. // var numAlphaBits = header.flags & 0xf;
  86652. var pixel_size = header.pixel_size >> 3;
  86653. var pixel_total = header.width * header.height * pixel_size;
  86654. // Read palettes
  86655. var palettes;
  86656. if (use_pal) {
  86657. palettes = data.subarray(offset, offset += header.colormap_length * (header.colormap_size >> 3));
  86658. }
  86659. // Read LRE
  86660. if (use_rle) {
  86661. pixel_data = new Uint8Array(pixel_total);
  86662. var c, count, i;
  86663. var localOffset = 0;
  86664. var pixels = new Uint8Array(pixel_size);
  86665. while (offset < pixel_total && localOffset < pixel_total) {
  86666. c = data[offset++];
  86667. count = (c & 0x7f) + 1;
  86668. // RLE pixels
  86669. if (c & 0x80) {
  86670. // Bind pixel tmp array
  86671. for (i = 0; i < pixel_size; ++i) {
  86672. pixels[i] = data[offset++];
  86673. }
  86674. // Copy pixel array
  86675. for (i = 0; i < count; ++i) {
  86676. pixel_data.set(pixels, localOffset + i * pixel_size);
  86677. }
  86678. localOffset += pixel_size * count;
  86679. }
  86680. // Raw pixels
  86681. else {
  86682. count *= pixel_size;
  86683. for (i = 0; i < count; ++i) {
  86684. pixel_data[localOffset + i] = data[offset++];
  86685. }
  86686. localOffset += count;
  86687. }
  86688. }
  86689. }
  86690. // RAW Pixels
  86691. else {
  86692. pixel_data = data.subarray(offset, offset += (use_pal ? header.width * header.height : pixel_total));
  86693. }
  86694. // Load to texture
  86695. var x_start, y_start, x_step, y_step, y_end, x_end;
  86696. switch ((header.flags & TGATools._ORIGIN_MASK) >> TGATools._ORIGIN_SHIFT) {
  86697. default:
  86698. case TGATools._ORIGIN_UL:
  86699. x_start = 0;
  86700. x_step = 1;
  86701. x_end = header.width;
  86702. y_start = 0;
  86703. y_step = 1;
  86704. y_end = header.height;
  86705. break;
  86706. case TGATools._ORIGIN_BL:
  86707. x_start = 0;
  86708. x_step = 1;
  86709. x_end = header.width;
  86710. y_start = header.height - 1;
  86711. y_step = -1;
  86712. y_end = -1;
  86713. break;
  86714. case TGATools._ORIGIN_UR:
  86715. x_start = header.width - 1;
  86716. x_step = -1;
  86717. x_end = -1;
  86718. y_start = 0;
  86719. y_step = 1;
  86720. y_end = header.height;
  86721. break;
  86722. case TGATools._ORIGIN_BR:
  86723. x_start = header.width - 1;
  86724. x_step = -1;
  86725. x_end = -1;
  86726. y_start = header.height - 1;
  86727. y_step = -1;
  86728. y_end = -1;
  86729. break;
  86730. }
  86731. // Load the specify method
  86732. var func = '_getImageData' + (use_grey ? 'Grey' : '') + (header.pixel_size) + 'bits';
  86733. var imageData = TGATools[func](header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end);
  86734. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, header.width, header.height, 0, gl.RGBA, gl.UNSIGNED_BYTE, imageData);
  86735. };
  86736. TGATools._getImageData8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86737. var image = pixel_data, colormap = palettes;
  86738. var width = header.width, height = header.height;
  86739. var color, i = 0, x, y;
  86740. var imageData = new Uint8Array(width * height * 4);
  86741. for (y = y_start; y !== y_end; y += y_step) {
  86742. for (x = x_start; x !== x_end; x += x_step, i++) {
  86743. color = image[i];
  86744. imageData[(x + width * y) * 4 + 3] = 255;
  86745. imageData[(x + width * y) * 4 + 2] = colormap[(color * 3) + 0];
  86746. imageData[(x + width * y) * 4 + 1] = colormap[(color * 3) + 1];
  86747. imageData[(x + width * y) * 4 + 0] = colormap[(color * 3) + 2];
  86748. }
  86749. }
  86750. return imageData;
  86751. };
  86752. TGATools._getImageData16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86753. var image = pixel_data;
  86754. var width = header.width, height = header.height;
  86755. var color, i = 0, x, y;
  86756. var imageData = new Uint8Array(width * height * 4);
  86757. for (y = y_start; y !== y_end; y += y_step) {
  86758. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86759. color = image[i + 0] + (image[i + 1] << 8); // Inversed ?
  86760. var r = (((color & 0x7C00) >> 10) * 255) / 0x1F | 0;
  86761. var g = (((color & 0x03E0) >> 5) * 255) / 0x1F | 0;
  86762. var b = ((color & 0x001F) * 255) / 0x1F | 0;
  86763. imageData[(x + width * y) * 4 + 0] = r;
  86764. imageData[(x + width * y) * 4 + 1] = g;
  86765. imageData[(x + width * y) * 4 + 2] = b;
  86766. imageData[(x + width * y) * 4 + 3] = (color & 0x8000) ? 0 : 255;
  86767. }
  86768. }
  86769. return imageData;
  86770. };
  86771. TGATools._getImageData24bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86772. var image = pixel_data;
  86773. var width = header.width, height = header.height;
  86774. var i = 0, x, y;
  86775. var imageData = new Uint8Array(width * height * 4);
  86776. for (y = y_start; y !== y_end; y += y_step) {
  86777. for (x = x_start; x !== x_end; x += x_step, i += 3) {
  86778. imageData[(x + width * y) * 4 + 3] = 255;
  86779. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86780. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86781. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86782. }
  86783. }
  86784. return imageData;
  86785. };
  86786. TGATools._getImageData32bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86787. var image = pixel_data;
  86788. var width = header.width, height = header.height;
  86789. var i = 0, x, y;
  86790. var imageData = new Uint8Array(width * height * 4);
  86791. for (y = y_start; y !== y_end; y += y_step) {
  86792. for (x = x_start; x !== x_end; x += x_step, i += 4) {
  86793. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86794. imageData[(x + width * y) * 4 + 1] = image[i + 1];
  86795. imageData[(x + width * y) * 4 + 0] = image[i + 2];
  86796. imageData[(x + width * y) * 4 + 3] = image[i + 3];
  86797. }
  86798. }
  86799. return imageData;
  86800. };
  86801. TGATools._getImageDataGrey8bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86802. var image = pixel_data;
  86803. var width = header.width, height = header.height;
  86804. var color, i = 0, x, y;
  86805. var imageData = new Uint8Array(width * height * 4);
  86806. for (y = y_start; y !== y_end; y += y_step) {
  86807. for (x = x_start; x !== x_end; x += x_step, i++) {
  86808. color = image[i];
  86809. imageData[(x + width * y) * 4 + 0] = color;
  86810. imageData[(x + width * y) * 4 + 1] = color;
  86811. imageData[(x + width * y) * 4 + 2] = color;
  86812. imageData[(x + width * y) * 4 + 3] = 255;
  86813. }
  86814. }
  86815. return imageData;
  86816. };
  86817. TGATools._getImageDataGrey16bits = function (header, palettes, pixel_data, y_start, y_step, y_end, x_start, x_step, x_end) {
  86818. var image = pixel_data;
  86819. var width = header.width, height = header.height;
  86820. var i = 0, x, y;
  86821. var imageData = new Uint8Array(width * height * 4);
  86822. for (y = y_start; y !== y_end; y += y_step) {
  86823. for (x = x_start; x !== x_end; x += x_step, i += 2) {
  86824. imageData[(x + width * y) * 4 + 0] = image[i + 0];
  86825. imageData[(x + width * y) * 4 + 1] = image[i + 0];
  86826. imageData[(x + width * y) * 4 + 2] = image[i + 0];
  86827. imageData[(x + width * y) * 4 + 3] = image[i + 1];
  86828. }
  86829. }
  86830. return imageData;
  86831. };
  86832. //private static _TYPE_NO_DATA = 0;
  86833. TGATools._TYPE_INDEXED = 1;
  86834. TGATools._TYPE_RGB = 2;
  86835. TGATools._TYPE_GREY = 3;
  86836. TGATools._TYPE_RLE_INDEXED = 9;
  86837. TGATools._TYPE_RLE_RGB = 10;
  86838. TGATools._TYPE_RLE_GREY = 11;
  86839. TGATools._ORIGIN_MASK = 0x30;
  86840. TGATools._ORIGIN_SHIFT = 0x04;
  86841. TGATools._ORIGIN_BL = 0x00;
  86842. TGATools._ORIGIN_BR = 0x01;
  86843. TGATools._ORIGIN_UL = 0x02;
  86844. TGATools._ORIGIN_UR = 0x03;
  86845. return TGATools;
  86846. }());
  86847. BABYLON.TGATools = TGATools;
  86848. })(BABYLON || (BABYLON = {}));
  86849. //# sourceMappingURL=babylon.tga.js.map
  86850. var BABYLON;
  86851. (function (BABYLON) {
  86852. // Based on demo done by Brandon Jones - http://media.tojicode.com/webgl-samples/dds.html
  86853. // All values and structures referenced from:
  86854. // http://msdn.microsoft.com/en-us/library/bb943991.aspx/
  86855. var DDS_MAGIC = 0x20534444;
  86856. var
  86857. //DDSD_CAPS = 0x1,
  86858. //DDSD_HEIGHT = 0x2,
  86859. //DDSD_WIDTH = 0x4,
  86860. //DDSD_PITCH = 0x8,
  86861. //DDSD_PIXELFORMAT = 0x1000,
  86862. DDSD_MIPMAPCOUNT = 0x20000;
  86863. //DDSD_LINEARSIZE = 0x80000,
  86864. //DDSD_DEPTH = 0x800000;
  86865. // var DDSCAPS_COMPLEX = 0x8,
  86866. // DDSCAPS_MIPMAP = 0x400000,
  86867. // DDSCAPS_TEXTURE = 0x1000;
  86868. var DDSCAPS2_CUBEMAP = 0x200;
  86869. // DDSCAPS2_CUBEMAP_POSITIVEX = 0x400,
  86870. // DDSCAPS2_CUBEMAP_NEGATIVEX = 0x800,
  86871. // DDSCAPS2_CUBEMAP_POSITIVEY = 0x1000,
  86872. // DDSCAPS2_CUBEMAP_NEGATIVEY = 0x2000,
  86873. // DDSCAPS2_CUBEMAP_POSITIVEZ = 0x4000,
  86874. // DDSCAPS2_CUBEMAP_NEGATIVEZ = 0x8000,
  86875. // DDSCAPS2_VOLUME = 0x200000;
  86876. var
  86877. //DDPF_ALPHAPIXELS = 0x1,
  86878. //DDPF_ALPHA = 0x2,
  86879. DDPF_FOURCC = 0x4, DDPF_RGB = 0x40,
  86880. //DDPF_YUV = 0x200,
  86881. DDPF_LUMINANCE = 0x20000;
  86882. function FourCCToInt32(value) {
  86883. return value.charCodeAt(0) +
  86884. (value.charCodeAt(1) << 8) +
  86885. (value.charCodeAt(2) << 16) +
  86886. (value.charCodeAt(3) << 24);
  86887. }
  86888. function Int32ToFourCC(value) {
  86889. return String.fromCharCode(value & 0xff, (value >> 8) & 0xff, (value >> 16) & 0xff, (value >> 24) & 0xff);
  86890. }
  86891. var FOURCC_DXT1 = FourCCToInt32("DXT1");
  86892. var FOURCC_DXT3 = FourCCToInt32("DXT3");
  86893. var FOURCC_DXT5 = FourCCToInt32("DXT5");
  86894. var FOURCC_DX10 = FourCCToInt32("DX10");
  86895. var FOURCC_D3DFMT_R16G16B16A16F = 113;
  86896. var FOURCC_D3DFMT_R32G32B32A32F = 116;
  86897. var DXGI_FORMAT_R16G16B16A16_FLOAT = 10;
  86898. var DXGI_FORMAT_B8G8R8X8_UNORM = 88;
  86899. var headerLengthInt = 31; // The header length in 32 bit ints
  86900. // Offsets into the header array
  86901. var off_magic = 0;
  86902. var off_size = 1;
  86903. var off_flags = 2;
  86904. var off_height = 3;
  86905. var off_width = 4;
  86906. var off_mipmapCount = 7;
  86907. var off_pfFlags = 20;
  86908. var off_pfFourCC = 21;
  86909. var off_RGBbpp = 22;
  86910. var off_RMask = 23;
  86911. var off_GMask = 24;
  86912. var off_BMask = 25;
  86913. var off_AMask = 26;
  86914. // var off_caps1 = 27;
  86915. var off_caps2 = 28;
  86916. // var off_caps3 = 29;
  86917. // var off_caps4 = 30;
  86918. var off_dxgiFormat = 32;
  86919. ;
  86920. var DDSTools = /** @class */ (function () {
  86921. function DDSTools() {
  86922. }
  86923. DDSTools.GetDDSInfo = function (arrayBuffer) {
  86924. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  86925. var extendedHeader = new Int32Array(arrayBuffer, 0, headerLengthInt + 4);
  86926. var mipmapCount = 1;
  86927. if (header[off_flags] & DDSD_MIPMAPCOUNT) {
  86928. mipmapCount = Math.max(1, header[off_mipmapCount]);
  86929. }
  86930. var fourCC = header[off_pfFourCC];
  86931. var dxgiFormat = (fourCC === FOURCC_DX10) ? extendedHeader[off_dxgiFormat] : 0;
  86932. var textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  86933. switch (fourCC) {
  86934. case FOURCC_D3DFMT_R16G16B16A16F:
  86935. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86936. break;
  86937. case FOURCC_D3DFMT_R32G32B32A32F:
  86938. textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  86939. break;
  86940. case FOURCC_DX10:
  86941. if (dxgiFormat === DXGI_FORMAT_R16G16B16A16_FLOAT) {
  86942. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  86943. break;
  86944. }
  86945. }
  86946. return {
  86947. width: header[off_width],
  86948. height: header[off_height],
  86949. mipmapCount: mipmapCount,
  86950. isFourCC: (header[off_pfFlags] & DDPF_FOURCC) === DDPF_FOURCC,
  86951. isRGB: (header[off_pfFlags] & DDPF_RGB) === DDPF_RGB,
  86952. isLuminance: (header[off_pfFlags] & DDPF_LUMINANCE) === DDPF_LUMINANCE,
  86953. isCube: (header[off_caps2] & DDSCAPS2_CUBEMAP) === DDSCAPS2_CUBEMAP,
  86954. isCompressed: (fourCC === FOURCC_DXT1 || fourCC === FOURCC_DXT3 || fourCC === FOURCC_DXT5),
  86955. dxgiFormat: dxgiFormat,
  86956. textureType: textureType
  86957. };
  86958. };
  86959. DDSTools._ToHalfFloat = function (value) {
  86960. if (!DDSTools._FloatView) {
  86961. DDSTools._FloatView = new Float32Array(1);
  86962. DDSTools._Int32View = new Int32Array(DDSTools._FloatView.buffer);
  86963. }
  86964. DDSTools._FloatView[0] = value;
  86965. var x = DDSTools._Int32View[0];
  86966. var bits = (x >> 16) & 0x8000; /* Get the sign */
  86967. var m = (x >> 12) & 0x07ff; /* Keep one extra bit for rounding */
  86968. var e = (x >> 23) & 0xff; /* Using int is faster here */
  86969. /* If zero, or denormal, or exponent underflows too much for a denormal
  86970. * half, return signed zero. */
  86971. if (e < 103) {
  86972. return bits;
  86973. }
  86974. /* If NaN, return NaN. If Inf or exponent overflow, return Inf. */
  86975. if (e > 142) {
  86976. bits |= 0x7c00;
  86977. /* If exponent was 0xff and one mantissa bit was set, it means NaN,
  86978. * not Inf, so make sure we set one mantissa bit too. */
  86979. bits |= ((e == 255) ? 0 : 1) && (x & 0x007fffff);
  86980. return bits;
  86981. }
  86982. /* If exponent underflows but not too much, return a denormal */
  86983. if (e < 113) {
  86984. m |= 0x0800;
  86985. /* Extra rounding may overflow and set mantissa to 0 and exponent
  86986. * to 1, which is OK. */
  86987. bits |= (m >> (114 - e)) + ((m >> (113 - e)) & 1);
  86988. return bits;
  86989. }
  86990. bits |= ((e - 112) << 10) | (m >> 1);
  86991. bits += m & 1;
  86992. return bits;
  86993. };
  86994. DDSTools._FromHalfFloat = function (value) {
  86995. var s = (value & 0x8000) >> 15;
  86996. var e = (value & 0x7C00) >> 10;
  86997. var f = value & 0x03FF;
  86998. if (e === 0) {
  86999. return (s ? -1 : 1) * Math.pow(2, -14) * (f / Math.pow(2, 10));
  87000. }
  87001. else if (e == 0x1F) {
  87002. return f ? NaN : ((s ? -1 : 1) * Infinity);
  87003. }
  87004. return (s ? -1 : 1) * Math.pow(2, e - 15) * (1 + (f / Math.pow(2, 10)));
  87005. };
  87006. DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87007. var destArray = new Float32Array(dataLength);
  87008. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87009. var index = 0;
  87010. for (var y = 0; y < height; y++) {
  87011. for (var x = 0; x < width; x++) {
  87012. var srcPos = (x + y * width) * 4;
  87013. destArray[index] = DDSTools._FromHalfFloat(srcData[srcPos]);
  87014. destArray[index + 1] = DDSTools._FromHalfFloat(srcData[srcPos + 1]);
  87015. destArray[index + 2] = DDSTools._FromHalfFloat(srcData[srcPos + 2]);
  87016. if (DDSTools.StoreLODInAlphaChannel) {
  87017. destArray[index + 3] = lod;
  87018. }
  87019. else {
  87020. destArray[index + 3] = DDSTools._FromHalfFloat(srcData[srcPos + 3]);
  87021. }
  87022. index += 4;
  87023. }
  87024. }
  87025. return destArray;
  87026. };
  87027. DDSTools._GetHalfFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87028. if (DDSTools.StoreLODInAlphaChannel) {
  87029. var destArray = new Uint16Array(dataLength);
  87030. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87031. var index = 0;
  87032. for (var y = 0; y < height; y++) {
  87033. for (var x = 0; x < width; x++) {
  87034. var srcPos = (x + y * width) * 4;
  87035. destArray[index] = srcData[srcPos];
  87036. destArray[index + 1] = srcData[srcPos + 1];
  87037. destArray[index + 2] = srcData[srcPos + 2];
  87038. destArray[index + 3] = DDSTools._ToHalfFloat(lod);
  87039. index += 4;
  87040. }
  87041. }
  87042. return destArray;
  87043. }
  87044. return new Uint16Array(arrayBuffer, dataOffset, dataLength);
  87045. };
  87046. DDSTools._GetFloatRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87047. if (DDSTools.StoreLODInAlphaChannel) {
  87048. var destArray = new Float32Array(dataLength);
  87049. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87050. var index = 0;
  87051. for (var y = 0; y < height; y++) {
  87052. for (var x = 0; x < width; x++) {
  87053. var srcPos = (x + y * width) * 4;
  87054. destArray[index] = srcData[srcPos];
  87055. destArray[index + 1] = srcData[srcPos + 1];
  87056. destArray[index + 2] = srcData[srcPos + 2];
  87057. destArray[index + 3] = lod;
  87058. index += 4;
  87059. }
  87060. }
  87061. return destArray;
  87062. }
  87063. return new Float32Array(arrayBuffer, dataOffset, dataLength);
  87064. };
  87065. DDSTools._GetFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87066. var destArray = new Uint8Array(dataLength);
  87067. var srcData = new Float32Array(arrayBuffer, dataOffset);
  87068. var index = 0;
  87069. for (var y = 0; y < height; y++) {
  87070. for (var x = 0; x < width; x++) {
  87071. var srcPos = (x + y * width) * 4;
  87072. destArray[index] = BABYLON.Scalar.Clamp(srcData[srcPos]) * 255;
  87073. destArray[index + 1] = BABYLON.Scalar.Clamp(srcData[srcPos + 1]) * 255;
  87074. destArray[index + 2] = BABYLON.Scalar.Clamp(srcData[srcPos + 2]) * 255;
  87075. if (DDSTools.StoreLODInAlphaChannel) {
  87076. destArray[index + 3] = lod;
  87077. }
  87078. else {
  87079. destArray[index + 3] = BABYLON.Scalar.Clamp(srcData[srcPos + 3]) * 255;
  87080. }
  87081. index += 4;
  87082. }
  87083. }
  87084. return destArray;
  87085. };
  87086. DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, lod) {
  87087. var destArray = new Uint8Array(dataLength);
  87088. var srcData = new Uint16Array(arrayBuffer, dataOffset);
  87089. var index = 0;
  87090. for (var y = 0; y < height; y++) {
  87091. for (var x = 0; x < width; x++) {
  87092. var srcPos = (x + y * width) * 4;
  87093. destArray[index] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos])) * 255;
  87094. destArray[index + 1] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 1])) * 255;
  87095. destArray[index + 2] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 2])) * 255;
  87096. if (DDSTools.StoreLODInAlphaChannel) {
  87097. destArray[index + 3] = lod;
  87098. }
  87099. else {
  87100. destArray[index + 3] = BABYLON.Scalar.Clamp(DDSTools._FromHalfFloat(srcData[srcPos + 3])) * 255;
  87101. }
  87102. index += 4;
  87103. }
  87104. }
  87105. return destArray;
  87106. };
  87107. DDSTools._GetRGBAArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset) {
  87108. var byteArray = new Uint8Array(dataLength);
  87109. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87110. var index = 0;
  87111. for (var y = 0; y < height; y++) {
  87112. for (var x = 0; x < width; x++) {
  87113. var srcPos = (x + y * width) * 4;
  87114. byteArray[index] = srcData[srcPos + rOffset];
  87115. byteArray[index + 1] = srcData[srcPos + gOffset];
  87116. byteArray[index + 2] = srcData[srcPos + bOffset];
  87117. byteArray[index + 3] = srcData[srcPos + aOffset];
  87118. index += 4;
  87119. }
  87120. }
  87121. return byteArray;
  87122. };
  87123. DDSTools._ExtractLongWordOrder = function (value) {
  87124. if (value === 0 || value === 255 || value === -16777216) {
  87125. return 0;
  87126. }
  87127. return 1 + DDSTools._ExtractLongWordOrder(value >> 8);
  87128. };
  87129. DDSTools._GetRGBArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset) {
  87130. var byteArray = new Uint8Array(dataLength);
  87131. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87132. var index = 0;
  87133. for (var y = 0; y < height; y++) {
  87134. for (var x = 0; x < width; x++) {
  87135. var srcPos = (x + y * width) * 3;
  87136. byteArray[index] = srcData[srcPos + rOffset];
  87137. byteArray[index + 1] = srcData[srcPos + gOffset];
  87138. byteArray[index + 2] = srcData[srcPos + bOffset];
  87139. index += 3;
  87140. }
  87141. }
  87142. return byteArray;
  87143. };
  87144. DDSTools._GetLuminanceArrayBuffer = function (width, height, dataOffset, dataLength, arrayBuffer) {
  87145. var byteArray = new Uint8Array(dataLength);
  87146. var srcData = new Uint8Array(arrayBuffer, dataOffset);
  87147. var index = 0;
  87148. for (var y = 0; y < height; y++) {
  87149. for (var x = 0; x < width; x++) {
  87150. var srcPos = (x + y * width);
  87151. byteArray[index] = srcData[srcPos];
  87152. index++;
  87153. }
  87154. }
  87155. return byteArray;
  87156. };
  87157. DDSTools.UploadDDSLevels = function (engine, gl, arrayBuffer, info, loadMipmaps, faces, lodIndex, currentFace) {
  87158. if (lodIndex === void 0) { lodIndex = -1; }
  87159. var sphericalPolynomialFaces = null;
  87160. if (info.sphericalPolynomial) {
  87161. sphericalPolynomialFaces = new Array();
  87162. }
  87163. var ext = engine.getCaps().s3tc;
  87164. var header = new Int32Array(arrayBuffer, 0, headerLengthInt);
  87165. var fourCC, width, height, dataLength = 0, dataOffset;
  87166. var byteArray, mipmapCount, mip;
  87167. var internalFormat = 0;
  87168. var format = 0;
  87169. var blockBytes = 1;
  87170. if (header[off_magic] !== DDS_MAGIC) {
  87171. BABYLON.Tools.Error("Invalid magic number in DDS header");
  87172. return;
  87173. }
  87174. if (!info.isFourCC && !info.isRGB && !info.isLuminance) {
  87175. BABYLON.Tools.Error("Unsupported format, must contain a FourCC, RGB or LUMINANCE code");
  87176. return;
  87177. }
  87178. if (info.isCompressed && !ext) {
  87179. BABYLON.Tools.Error("Compressed textures are not supported on this platform.");
  87180. return;
  87181. }
  87182. var bpp = header[off_RGBbpp];
  87183. dataOffset = header[off_size] + 4;
  87184. var computeFormats = false;
  87185. if (info.isFourCC) {
  87186. fourCC = header[off_pfFourCC];
  87187. switch (fourCC) {
  87188. case FOURCC_DXT1:
  87189. blockBytes = 8;
  87190. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT1_EXT;
  87191. break;
  87192. case FOURCC_DXT3:
  87193. blockBytes = 16;
  87194. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT3_EXT;
  87195. break;
  87196. case FOURCC_DXT5:
  87197. blockBytes = 16;
  87198. internalFormat = ext.COMPRESSED_RGBA_S3TC_DXT5_EXT;
  87199. break;
  87200. case FOURCC_D3DFMT_R16G16B16A16F:
  87201. computeFormats = true;
  87202. break;
  87203. case FOURCC_D3DFMT_R32G32B32A32F:
  87204. computeFormats = true;
  87205. break;
  87206. case FOURCC_DX10:
  87207. // There is an additionnal header so dataOffset need to be changed
  87208. dataOffset += 5 * 4; // 5 uints
  87209. var supported = false;
  87210. switch (info.dxgiFormat) {
  87211. case DXGI_FORMAT_R16G16B16A16_FLOAT:
  87212. computeFormats = true;
  87213. supported = true;
  87214. break;
  87215. case DXGI_FORMAT_B8G8R8X8_UNORM:
  87216. info.isRGB = true;
  87217. info.isFourCC = false;
  87218. bpp = 32;
  87219. supported = true;
  87220. break;
  87221. }
  87222. if (supported) {
  87223. break;
  87224. }
  87225. default:
  87226. console.error("Unsupported FourCC code:", Int32ToFourCC(fourCC));
  87227. return;
  87228. }
  87229. }
  87230. var rOffset = DDSTools._ExtractLongWordOrder(header[off_RMask]);
  87231. var gOffset = DDSTools._ExtractLongWordOrder(header[off_GMask]);
  87232. var bOffset = DDSTools._ExtractLongWordOrder(header[off_BMask]);
  87233. var aOffset = DDSTools._ExtractLongWordOrder(header[off_AMask]);
  87234. if (computeFormats) {
  87235. format = engine._getWebGLTextureType(info.textureType);
  87236. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87237. }
  87238. mipmapCount = 1;
  87239. if (header[off_flags] & DDSD_MIPMAPCOUNT && loadMipmaps !== false) {
  87240. mipmapCount = Math.max(1, header[off_mipmapCount]);
  87241. }
  87242. for (var face = 0; face < faces; face++) {
  87243. var sampler = faces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face + (currentFace ? currentFace : 0));
  87244. width = header[off_width];
  87245. height = header[off_height];
  87246. for (mip = 0; mip < mipmapCount; ++mip) {
  87247. if (lodIndex === -1 || lodIndex === mip) {
  87248. // In case of fixed LOD, if the lod has just been uploaded, early exit.
  87249. var i = (lodIndex === -1) ? mip : 0;
  87250. if (!info.isCompressed && info.isFourCC) {
  87251. dataLength = width * height * 4;
  87252. var floatArray = null;
  87253. if (engine._badOS || engine._badDesktopOS || (!engine.getCaps().textureHalfFloat && !engine.getCaps().textureFloat)) { // Required because iOS has many issues with float and half float generation
  87254. if (bpp === 128) {
  87255. floatArray = DDSTools._GetFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87256. if (sphericalPolynomialFaces && i == 0) {
  87257. sphericalPolynomialFaces.push(DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87258. }
  87259. }
  87260. else if (bpp === 64) {
  87261. floatArray = DDSTools._GetHalfFloatAsUIntRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87262. if (sphericalPolynomialFaces && i == 0) {
  87263. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87264. }
  87265. }
  87266. info.textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  87267. format = engine._getWebGLTextureType(info.textureType);
  87268. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87269. }
  87270. else {
  87271. if (bpp === 128) {
  87272. floatArray = DDSTools._GetFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87273. if (sphericalPolynomialFaces && i == 0) {
  87274. sphericalPolynomialFaces.push(floatArray);
  87275. }
  87276. }
  87277. else if (bpp === 64 && !engine.getCaps().textureHalfFloat) {
  87278. floatArray = DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87279. if (sphericalPolynomialFaces && i == 0) {
  87280. sphericalPolynomialFaces.push(floatArray);
  87281. }
  87282. info.textureType = BABYLON.Engine.TEXTURETYPE_FLOAT;
  87283. format = engine._getWebGLTextureType(info.textureType);
  87284. internalFormat = engine._getRGBABufferInternalSizedFormat(info.textureType);
  87285. }
  87286. else { // 64
  87287. floatArray = DDSTools._GetHalfFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i);
  87288. if (sphericalPolynomialFaces && i == 0) {
  87289. sphericalPolynomialFaces.push(DDSTools._GetHalfFloatAsFloatRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, i));
  87290. }
  87291. }
  87292. }
  87293. if (floatArray) {
  87294. engine._uploadDataToTexture(sampler, i, internalFormat, width, height, gl.RGBA, format, floatArray);
  87295. }
  87296. }
  87297. else if (info.isRGB) {
  87298. if (bpp === 24) {
  87299. dataLength = width * height * 3;
  87300. byteArray = DDSTools._GetRGBArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset);
  87301. engine._uploadDataToTexture(sampler, i, gl.RGB, width, height, gl.RGB, gl.UNSIGNED_BYTE, byteArray);
  87302. }
  87303. else { // 32
  87304. dataLength = width * height * 4;
  87305. byteArray = DDSTools._GetRGBAArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer, rOffset, gOffset, bOffset, aOffset);
  87306. engine._uploadDataToTexture(sampler, i, gl.RGBA, width, height, gl.RGBA, gl.UNSIGNED_BYTE, byteArray);
  87307. }
  87308. }
  87309. else if (info.isLuminance) {
  87310. var unpackAlignment = gl.getParameter(gl.UNPACK_ALIGNMENT);
  87311. var unpaddedRowSize = width;
  87312. var paddedRowSize = Math.floor((width + unpackAlignment - 1) / unpackAlignment) * unpackAlignment;
  87313. dataLength = paddedRowSize * (height - 1) + unpaddedRowSize;
  87314. byteArray = DDSTools._GetLuminanceArrayBuffer(width, height, dataOffset, dataLength, arrayBuffer);
  87315. engine._uploadDataToTexture(sampler, i, gl.LUMINANCE, width, height, gl.LUMINANCE, gl.UNSIGNED_BYTE, byteArray);
  87316. }
  87317. else {
  87318. dataLength = Math.max(4, width) / 4 * Math.max(4, height) / 4 * blockBytes;
  87319. byteArray = new Uint8Array(arrayBuffer, dataOffset, dataLength);
  87320. engine._uploadCompressedDataToTexture(sampler, i, internalFormat, width, height, byteArray);
  87321. }
  87322. }
  87323. dataOffset += bpp ? (width * height * (bpp / 8)) : dataLength;
  87324. width *= 0.5;
  87325. height *= 0.5;
  87326. width = Math.max(1.0, width);
  87327. height = Math.max(1.0, height);
  87328. }
  87329. if (currentFace !== undefined) {
  87330. // Loading a single face
  87331. break;
  87332. }
  87333. }
  87334. if (sphericalPolynomialFaces && sphericalPolynomialFaces.length > 0) {
  87335. info.sphericalPolynomial = BABYLON.CubeMapToSphericalPolynomialTools.ConvertCubeMapToSphericalPolynomial({
  87336. size: header[off_width],
  87337. right: sphericalPolynomialFaces[0],
  87338. left: sphericalPolynomialFaces[1],
  87339. up: sphericalPolynomialFaces[2],
  87340. down: sphericalPolynomialFaces[3],
  87341. front: sphericalPolynomialFaces[4],
  87342. back: sphericalPolynomialFaces[5],
  87343. format: BABYLON.Engine.TEXTUREFORMAT_RGBA,
  87344. type: BABYLON.Engine.TEXTURETYPE_FLOAT,
  87345. gammaSpace: false,
  87346. });
  87347. }
  87348. else {
  87349. info.sphericalPolynomial = undefined;
  87350. }
  87351. };
  87352. DDSTools.StoreLODInAlphaChannel = false;
  87353. return DDSTools;
  87354. }());
  87355. BABYLON.DDSTools = DDSTools;
  87356. })(BABYLON || (BABYLON = {}));
  87357. //# sourceMappingURL=babylon.dds.js.map
  87358. var BABYLON;
  87359. (function (BABYLON) {
  87360. /**
  87361. * for description see https://www.khronos.org/opengles/sdk/tools/KTX/
  87362. * for file layout see https://www.khronos.org/opengles/sdk/tools/KTX/file_format_spec/
  87363. */
  87364. var KhronosTextureContainer = /** @class */ (function () {
  87365. /**
  87366. * @param {ArrayBuffer} arrayBuffer- contents of the KTX container file
  87367. * @param {number} facesExpected- should be either 1 or 6, based whether a cube texture or or
  87368. * @param {boolean} threeDExpected- provision for indicating that data should be a 3D texture, not implemented
  87369. * @param {boolean} textureArrayExpected- provision for indicating that data should be a texture array, not implemented
  87370. */
  87371. function KhronosTextureContainer(arrayBuffer, facesExpected, threeDExpected, textureArrayExpected) {
  87372. this.arrayBuffer = arrayBuffer;
  87373. // Test that it is a ktx formatted file, based on the first 12 bytes, character representation is:
  87374. // '�', 'K', 'T', 'X', ' ', '1', '1', '�', '\r', '\n', '\x1A', '\n'
  87375. // 0xAB, 0x4B, 0x54, 0x58, 0x20, 0x31, 0x31, 0xBB, 0x0D, 0x0A, 0x1A, 0x0A
  87376. var identifier = new Uint8Array(this.arrayBuffer, 0, 12);
  87377. if (identifier[0] !== 0xAB || identifier[1] !== 0x4B || identifier[2] !== 0x54 || identifier[3] !== 0x58 || identifier[4] !== 0x20 || identifier[5] !== 0x31 ||
  87378. identifier[6] !== 0x31 || identifier[7] !== 0xBB || identifier[8] !== 0x0D || identifier[9] !== 0x0A || identifier[10] !== 0x1A || identifier[11] !== 0x0A) {
  87379. BABYLON.Tools.Error("texture missing KTX identifier");
  87380. return;
  87381. }
  87382. // load the reset of the header in native 32 bit int
  87383. var header = new Int32Array(this.arrayBuffer, 12, 13);
  87384. // determine of the remaining header values are recorded in the opposite endianness & require conversion
  87385. var oppositeEndianess = header[0] === 0x01020304;
  87386. // read all the header elements in order they exist in the file, without modification (sans endainness)
  87387. this.glType = oppositeEndianess ? this.switchEndainness(header[1]) : header[1]; // must be 0 for compressed textures
  87388. this.glTypeSize = oppositeEndianess ? this.switchEndainness(header[2]) : header[2]; // must be 1 for compressed textures
  87389. this.glFormat = oppositeEndianess ? this.switchEndainness(header[3]) : header[3]; // must be 0 for compressed textures
  87390. this.glInternalFormat = oppositeEndianess ? this.switchEndainness(header[4]) : header[4]; // the value of arg passed to gl.compressedTexImage2D(,,x,,,,)
  87391. this.glBaseInternalFormat = oppositeEndianess ? this.switchEndainness(header[5]) : header[5]; // specify GL_RGB, GL_RGBA, GL_ALPHA, etc (un-compressed only)
  87392. this.pixelWidth = oppositeEndianess ? this.switchEndainness(header[6]) : header[6]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,x,,,)
  87393. this.pixelHeight = oppositeEndianess ? this.switchEndainness(header[7]) : header[7]; // level 0 value of arg passed to gl.compressedTexImage2D(,,,,x,,)
  87394. this.pixelDepth = oppositeEndianess ? this.switchEndainness(header[8]) : header[8]; // level 0 value of arg passed to gl.compressedTexImage3D(,,,,,x,,)
  87395. this.numberOfArrayElements = oppositeEndianess ? this.switchEndainness(header[9]) : header[9]; // used for texture arrays
  87396. this.numberOfFaces = oppositeEndianess ? this.switchEndainness(header[10]) : header[10]; // used for cubemap textures, should either be 1 or 6
  87397. this.numberOfMipmapLevels = oppositeEndianess ? this.switchEndainness(header[11]) : header[11]; // number of levels; disregard possibility of 0 for compressed textures
  87398. this.bytesOfKeyValueData = oppositeEndianess ? this.switchEndainness(header[12]) : header[12]; // the amount of space after the header for meta-data
  87399. // Make sure we have a compressed type. Not only reduces work, but probably better to let dev know they are not compressing.
  87400. if (this.glType !== 0) {
  87401. BABYLON.Tools.Error("only compressed formats currently supported");
  87402. return;
  87403. }
  87404. else {
  87405. // value of zero is an indication to generate mipmaps @ runtime. Not usually allowed for compressed, so disregard.
  87406. this.numberOfMipmapLevels = Math.max(1, this.numberOfMipmapLevels);
  87407. }
  87408. if (this.pixelHeight === 0 || this.pixelDepth !== 0) {
  87409. BABYLON.Tools.Error("only 2D textures currently supported");
  87410. return;
  87411. }
  87412. if (this.numberOfArrayElements !== 0) {
  87413. BABYLON.Tools.Error("texture arrays not currently supported");
  87414. return;
  87415. }
  87416. if (this.numberOfFaces !== facesExpected) {
  87417. BABYLON.Tools.Error("number of faces expected" + facesExpected + ", but found " + this.numberOfFaces);
  87418. return;
  87419. }
  87420. // we now have a completely validated file, so could use existence of loadType as success
  87421. // would need to make this more elaborate & adjust checks above to support more than one load type
  87422. this.loadType = KhronosTextureContainer.COMPRESSED_2D;
  87423. }
  87424. // not as fast hardware based, but will probably never need to use
  87425. KhronosTextureContainer.prototype.switchEndainness = function (val) {
  87426. return ((val & 0xFF) << 24)
  87427. | ((val & 0xFF00) << 8)
  87428. | ((val >> 8) & 0xFF00)
  87429. | ((val >> 24) & 0xFF);
  87430. };
  87431. /**
  87432. * It is assumed that the texture has already been created & is currently bound
  87433. */
  87434. KhronosTextureContainer.prototype.uploadLevels = function (gl, loadMipmaps) {
  87435. switch (this.loadType) {
  87436. case KhronosTextureContainer.COMPRESSED_2D:
  87437. this._upload2DCompressedLevels(gl, loadMipmaps);
  87438. break;
  87439. case KhronosTextureContainer.TEX_2D:
  87440. case KhronosTextureContainer.COMPRESSED_3D:
  87441. case KhronosTextureContainer.TEX_3D:
  87442. }
  87443. };
  87444. KhronosTextureContainer.prototype._upload2DCompressedLevels = function (gl, loadMipmaps) {
  87445. // initialize width & height for level 1
  87446. var dataOffset = KhronosTextureContainer.HEADER_LEN + this.bytesOfKeyValueData;
  87447. var width = this.pixelWidth;
  87448. var height = this.pixelHeight;
  87449. var mipmapCount = loadMipmaps ? this.numberOfMipmapLevels : 1;
  87450. for (var level = 0; level < mipmapCount; level++) {
  87451. var imageSize = new Int32Array(this.arrayBuffer, dataOffset, 1)[0]; // size per face, since not supporting array cubemaps
  87452. dataOffset += 4; //image data starts from next multiple of 4 offset. Each face refers to same imagesize field above.
  87453. for (var face = 0; face < this.numberOfFaces; face++) {
  87454. var sampler = this.numberOfFaces === 1 ? gl.TEXTURE_2D : (gl.TEXTURE_CUBE_MAP_POSITIVE_X + face);
  87455. var byteArray = new Uint8Array(this.arrayBuffer, dataOffset, imageSize);
  87456. gl.compressedTexImage2D(sampler, level, this.glInternalFormat, width, height, 0, byteArray);
  87457. dataOffset += imageSize; // add size of the image for the next face/mipmap
  87458. dataOffset += 3 - ((imageSize + 3) % 4); // add padding for odd sized image
  87459. }
  87460. width = Math.max(1.0, width * 0.5);
  87461. height = Math.max(1.0, height * 0.5);
  87462. }
  87463. };
  87464. KhronosTextureContainer.HEADER_LEN = 12 + (13 * 4); // identifier + header elements (not including key value meta-data pairs)
  87465. // load types
  87466. KhronosTextureContainer.COMPRESSED_2D = 0; // uses a gl.compressedTexImage2D()
  87467. KhronosTextureContainer.COMPRESSED_3D = 1; // uses a gl.compressedTexImage3D()
  87468. KhronosTextureContainer.TEX_2D = 2; // uses a gl.texImage2D()
  87469. KhronosTextureContainer.TEX_3D = 3; // uses a gl.texImage3D()
  87470. return KhronosTextureContainer;
  87471. }());
  87472. BABYLON.KhronosTextureContainer = KhronosTextureContainer;
  87473. })(BABYLON || (BABYLON = {}));
  87474. //# sourceMappingURL=babylon.khronosTextureContainer.js.map
  87475. var BABYLON;
  87476. (function (BABYLON) {
  87477. var Debug;
  87478. (function (Debug) {
  87479. /**
  87480. * Class used to render a debug view of a given skeleton
  87481. * @see http://www.babylonjs-playground.com/#1BZJVJ#8
  87482. */
  87483. var SkeletonViewer = /** @class */ (function () {
  87484. /**
  87485. * Creates a new SkeletonViewer
  87486. * @param skeleton defines the skeleton to render
  87487. * @param mesh defines the mesh attached to the skeleton
  87488. * @param scene defines the hosting scene
  87489. * @param autoUpdateBonesMatrices defines a boolean indicating if bones matrices must be forced to update before rendering (true by default)
  87490. * @param renderingGroupId defines the rendering group id to use with the viewer
  87491. */
  87492. function SkeletonViewer(
  87493. /** defines the skeleton to render */
  87494. skeleton,
  87495. /** defines the mesh attached to the skeleton */
  87496. mesh, scene,
  87497. /** defines a boolean indicating if bones matrices must be forced to update before rendering (true by default) */
  87498. autoUpdateBonesMatrices,
  87499. /** defines the rendering group id to use with the viewer */
  87500. renderingGroupId) {
  87501. if (autoUpdateBonesMatrices === void 0) { autoUpdateBonesMatrices = true; }
  87502. if (renderingGroupId === void 0) { renderingGroupId = 1; }
  87503. this.skeleton = skeleton;
  87504. this.mesh = mesh;
  87505. this.autoUpdateBonesMatrices = autoUpdateBonesMatrices;
  87506. this.renderingGroupId = renderingGroupId;
  87507. /** Gets or sets the color used to render the skeleton */
  87508. this.color = BABYLON.Color3.White();
  87509. this._debugLines = new Array();
  87510. this._isEnabled = false;
  87511. this._scene = scene;
  87512. this.update();
  87513. this._renderFunction = this.update.bind(this);
  87514. }
  87515. Object.defineProperty(SkeletonViewer.prototype, "isEnabled", {
  87516. get: function () {
  87517. return this._isEnabled;
  87518. },
  87519. /** Gets or sets a boolean indicating if the viewer is enabled */
  87520. set: function (value) {
  87521. if (this._isEnabled === value) {
  87522. return;
  87523. }
  87524. this._isEnabled = value;
  87525. if (value) {
  87526. this._scene.registerBeforeRender(this._renderFunction);
  87527. }
  87528. else {
  87529. this._scene.unregisterBeforeRender(this._renderFunction);
  87530. }
  87531. },
  87532. enumerable: true,
  87533. configurable: true
  87534. });
  87535. SkeletonViewer.prototype._getBonePosition = function (position, bone, meshMat, x, y, z) {
  87536. if (x === void 0) { x = 0; }
  87537. if (y === void 0) { y = 0; }
  87538. if (z === void 0) { z = 0; }
  87539. var tmat = BABYLON.Tmp.Matrix[0];
  87540. var parentBone = bone.getParent();
  87541. tmat.copyFrom(bone.getLocalMatrix());
  87542. if (x !== 0 || y !== 0 || z !== 0) {
  87543. var tmat2 = BABYLON.Tmp.Matrix[1];
  87544. BABYLON.Matrix.IdentityToRef(tmat2);
  87545. tmat2.m[12] = x;
  87546. tmat2.m[13] = y;
  87547. tmat2.m[14] = z;
  87548. tmat2.multiplyToRef(tmat, tmat);
  87549. }
  87550. if (parentBone) {
  87551. tmat.multiplyToRef(parentBone.getAbsoluteTransform(), tmat);
  87552. }
  87553. tmat.multiplyToRef(meshMat, tmat);
  87554. position.x = tmat.m[12];
  87555. position.y = tmat.m[13];
  87556. position.z = tmat.m[14];
  87557. };
  87558. SkeletonViewer.prototype._getLinesForBonesWithLength = function (bones, meshMat) {
  87559. var len = bones.length;
  87560. var meshPos = this.mesh.position;
  87561. for (var i = 0; i < len; i++) {
  87562. var bone = bones[i];
  87563. var points = this._debugLines[i];
  87564. if (!points) {
  87565. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87566. this._debugLines[i] = points;
  87567. }
  87568. this._getBonePosition(points[0], bone, meshMat);
  87569. this._getBonePosition(points[1], bone, meshMat, 0, bone.length, 0);
  87570. points[0].subtractInPlace(meshPos);
  87571. points[1].subtractInPlace(meshPos);
  87572. }
  87573. };
  87574. SkeletonViewer.prototype._getLinesForBonesNoLength = function (bones, meshMat) {
  87575. var len = bones.length;
  87576. var boneNum = 0;
  87577. var meshPos = this.mesh.position;
  87578. for (var i = len - 1; i >= 0; i--) {
  87579. var childBone = bones[i];
  87580. var parentBone = childBone.getParent();
  87581. if (!parentBone) {
  87582. continue;
  87583. }
  87584. var points = this._debugLines[boneNum];
  87585. if (!points) {
  87586. points = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87587. this._debugLines[boneNum] = points;
  87588. }
  87589. childBone.getAbsolutePositionToRef(this.mesh, points[0]);
  87590. parentBone.getAbsolutePositionToRef(this.mesh, points[1]);
  87591. points[0].subtractInPlace(meshPos);
  87592. points[1].subtractInPlace(meshPos);
  87593. boneNum++;
  87594. }
  87595. };
  87596. /** Update the viewer to sync with current skeleton state */
  87597. SkeletonViewer.prototype.update = function () {
  87598. if (this.autoUpdateBonesMatrices) {
  87599. this.skeleton.computeAbsoluteTransforms();
  87600. }
  87601. if (this.skeleton.bones[0].length === undefined) {
  87602. this._getLinesForBonesNoLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87603. }
  87604. else {
  87605. this._getLinesForBonesWithLength(this.skeleton.bones, this.mesh.getWorldMatrix());
  87606. }
  87607. if (!this._debugMesh) {
  87608. this._debugMesh = BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: null }, this._scene);
  87609. this._debugMesh.renderingGroupId = this.renderingGroupId;
  87610. }
  87611. else {
  87612. BABYLON.MeshBuilder.CreateLineSystem("", { lines: this._debugLines, updatable: true, instance: this._debugMesh }, this._scene);
  87613. }
  87614. this._debugMesh.position.copyFrom(this.mesh.position);
  87615. this._debugMesh.color = this.color;
  87616. };
  87617. /** Release associated resources */
  87618. SkeletonViewer.prototype.dispose = function () {
  87619. if (this._debugMesh) {
  87620. this.isEnabled = false;
  87621. this._debugMesh.dispose();
  87622. this._debugMesh = null;
  87623. }
  87624. };
  87625. return SkeletonViewer;
  87626. }());
  87627. Debug.SkeletonViewer = SkeletonViewer;
  87628. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87629. })(BABYLON || (BABYLON = {}));
  87630. //# sourceMappingURL=babylon.skeletonViewer.js.map
  87631. /**
  87632. * Module Debug contains the (visual) components to debug a scene correctly
  87633. */
  87634. var BABYLON;
  87635. (function (BABYLON) {
  87636. var Debug;
  87637. (function (Debug) {
  87638. /**
  87639. * The Axes viewer will show 3 axes in a specific point in space
  87640. */
  87641. var AxesViewer = /** @class */ (function () {
  87642. /**
  87643. * Creates a new AxesViewer
  87644. * @param scene defines the hosting scene
  87645. * @param scaleLines defines a number used to scale line length (1 by default)
  87646. */
  87647. function AxesViewer(scene, scaleLines) {
  87648. if (scaleLines === void 0) { scaleLines = 1; }
  87649. this._xline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87650. this._yline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87651. this._zline = [BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero()];
  87652. /**
  87653. * Gets or sets a number used to scale line length
  87654. */
  87655. this.scaleLines = 1;
  87656. this.scaleLines = scaleLines;
  87657. this._xmesh = BABYLON.Mesh.CreateLines("xline", this._xline, scene, true);
  87658. this._ymesh = BABYLON.Mesh.CreateLines("yline", this._yline, scene, true);
  87659. this._zmesh = BABYLON.Mesh.CreateLines("zline", this._zline, scene, true);
  87660. this._xmesh.renderingGroupId = 2;
  87661. this._ymesh.renderingGroupId = 2;
  87662. this._zmesh.renderingGroupId = 2;
  87663. this._xmesh.material.checkReadyOnlyOnce = true;
  87664. this._xmesh.color = new BABYLON.Color3(1, 0, 0);
  87665. this._ymesh.material.checkReadyOnlyOnce = true;
  87666. this._ymesh.color = new BABYLON.Color3(0, 1, 0);
  87667. this._zmesh.material.checkReadyOnlyOnce = true;
  87668. this._zmesh.color = new BABYLON.Color3(0, 0, 1);
  87669. this.scene = scene;
  87670. }
  87671. /**
  87672. * Force the viewer to update
  87673. * @param position defines the position of the viewer
  87674. * @param xaxis defines the x axis of the viewer
  87675. * @param yaxis defines the y axis of the viewer
  87676. * @param zaxis defines the z axis of the viewer
  87677. */
  87678. AxesViewer.prototype.update = function (position, xaxis, yaxis, zaxis) {
  87679. var scaleLines = this.scaleLines;
  87680. if (this._xmesh) {
  87681. this._xmesh.position.copyFrom(position);
  87682. }
  87683. if (this._ymesh) {
  87684. this._ymesh.position.copyFrom(position);
  87685. }
  87686. if (this._zmesh) {
  87687. this._zmesh.position.copyFrom(position);
  87688. }
  87689. var point2 = this._xline[1];
  87690. point2.x = xaxis.x * scaleLines;
  87691. point2.y = xaxis.y * scaleLines;
  87692. point2.z = xaxis.z * scaleLines;
  87693. BABYLON.Mesh.CreateLines("", this._xline, null, false, this._xmesh);
  87694. point2 = this._yline[1];
  87695. point2.x = yaxis.x * scaleLines;
  87696. point2.y = yaxis.y * scaleLines;
  87697. point2.z = yaxis.z * scaleLines;
  87698. BABYLON.Mesh.CreateLines("", this._yline, null, false, this._ymesh);
  87699. point2 = this._zline[1];
  87700. point2.x = zaxis.x * scaleLines;
  87701. point2.y = zaxis.y * scaleLines;
  87702. point2.z = zaxis.z * scaleLines;
  87703. BABYLON.Mesh.CreateLines("", this._zline, null, false, this._zmesh);
  87704. };
  87705. /** Releases resources */
  87706. AxesViewer.prototype.dispose = function () {
  87707. if (this._xmesh) {
  87708. this._xmesh.dispose();
  87709. }
  87710. if (this._ymesh) {
  87711. this._ymesh.dispose();
  87712. }
  87713. if (this._zmesh) {
  87714. this._zmesh.dispose();
  87715. }
  87716. this._xmesh = null;
  87717. this._ymesh = null;
  87718. this._zmesh = null;
  87719. this.scene = null;
  87720. };
  87721. return AxesViewer;
  87722. }());
  87723. Debug.AxesViewer = AxesViewer;
  87724. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87725. })(BABYLON || (BABYLON = {}));
  87726. //# sourceMappingURL=babylon.axesViewer.js.map
  87727. var BABYLON;
  87728. (function (BABYLON) {
  87729. var Debug;
  87730. (function (Debug) {
  87731. /**
  87732. * The BoneAxesViewer will attach 3 axes to a specific bone of a specific mesh
  87733. * @see demo here: https://www.babylonjs-playground.com/#0DE8F4#8
  87734. */
  87735. var BoneAxesViewer = /** @class */ (function (_super) {
  87736. __extends(BoneAxesViewer, _super);
  87737. /**
  87738. * Creates a new BoneAxesViewer
  87739. * @param scene defines the hosting scene
  87740. * @param bone defines the target bone
  87741. * @param mesh defines the target mesh
  87742. * @param scaleLines defines a scaling factor for line length (1 by default)
  87743. */
  87744. function BoneAxesViewer(scene, bone, mesh, scaleLines) {
  87745. if (scaleLines === void 0) { scaleLines = 1; }
  87746. var _this = _super.call(this, scene, scaleLines) || this;
  87747. /** Gets current position */
  87748. _this.pos = BABYLON.Vector3.Zero();
  87749. /** Gets direction of X axis */
  87750. _this.xaxis = BABYLON.Vector3.Zero();
  87751. /** Gets direction of Y axis */
  87752. _this.yaxis = BABYLON.Vector3.Zero();
  87753. /** Gets direction of Z axis */
  87754. _this.zaxis = BABYLON.Vector3.Zero();
  87755. _this.mesh = mesh;
  87756. _this.bone = bone;
  87757. return _this;
  87758. }
  87759. /**
  87760. * Force the viewer to update
  87761. */
  87762. BoneAxesViewer.prototype.update = function () {
  87763. if (!this.mesh || !this.bone) {
  87764. return;
  87765. }
  87766. var bone = this.bone;
  87767. bone.getAbsolutePositionToRef(this.mesh, this.pos);
  87768. bone.getDirectionToRef(BABYLON.Axis.X, this.mesh, this.xaxis);
  87769. bone.getDirectionToRef(BABYLON.Axis.Y, this.mesh, this.yaxis);
  87770. bone.getDirectionToRef(BABYLON.Axis.Z, this.mesh, this.zaxis);
  87771. _super.prototype.update.call(this, this.pos, this.xaxis, this.yaxis, this.zaxis);
  87772. };
  87773. /** Releases resources */
  87774. BoneAxesViewer.prototype.dispose = function () {
  87775. if (this.mesh) {
  87776. this.mesh = null;
  87777. this.bone = null;
  87778. _super.prototype.dispose.call(this);
  87779. }
  87780. };
  87781. return BoneAxesViewer;
  87782. }(Debug.AxesViewer));
  87783. Debug.BoneAxesViewer = BoneAxesViewer;
  87784. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  87785. })(BABYLON || (BABYLON = {}));
  87786. //# sourceMappingURL=babylon.boneAxesViewer.js.map
  87787. var BABYLON;
  87788. (function (BABYLON) {
  87789. var RayHelper = /** @class */ (function () {
  87790. function RayHelper(ray) {
  87791. this.ray = ray;
  87792. }
  87793. RayHelper.CreateAndShow = function (ray, scene, color) {
  87794. var helper = new RayHelper(ray);
  87795. helper.show(scene, color);
  87796. return helper;
  87797. };
  87798. RayHelper.prototype.show = function (scene, color) {
  87799. if (!this._renderFunction && this.ray) {
  87800. var ray = this.ray;
  87801. this._renderFunction = this._render.bind(this);
  87802. this._scene = scene;
  87803. this._renderPoints = [ray.origin, ray.origin.add(ray.direction.scale(ray.length))];
  87804. this._renderLine = BABYLON.Mesh.CreateLines("ray", this._renderPoints, scene, true);
  87805. if (this._renderFunction) {
  87806. this._scene.registerBeforeRender(this._renderFunction);
  87807. }
  87808. }
  87809. if (color && this._renderLine) {
  87810. this._renderLine.color.copyFrom(color);
  87811. }
  87812. };
  87813. RayHelper.prototype.hide = function () {
  87814. if (this._renderFunction && this._scene) {
  87815. this._scene.unregisterBeforeRender(this._renderFunction);
  87816. this._scene = null;
  87817. this._renderFunction = null;
  87818. if (this._renderLine) {
  87819. this._renderLine.dispose();
  87820. this._renderLine = null;
  87821. }
  87822. this._renderPoints = [];
  87823. }
  87824. };
  87825. RayHelper.prototype._render = function () {
  87826. var ray = this.ray;
  87827. if (!ray) {
  87828. return;
  87829. }
  87830. var point = this._renderPoints[1];
  87831. var len = Math.min(ray.length, 1000000);
  87832. point.copyFrom(ray.direction);
  87833. point.scaleInPlace(len);
  87834. point.addInPlace(ray.origin);
  87835. BABYLON.Mesh.CreateLines("ray", this._renderPoints, this._scene, true, this._renderLine);
  87836. };
  87837. RayHelper.prototype.attachToMesh = function (mesh, meshSpaceDirection, meshSpaceOrigin, length) {
  87838. this._attachedToMesh = mesh;
  87839. var ray = this.ray;
  87840. if (!ray) {
  87841. return;
  87842. }
  87843. if (!ray.direction) {
  87844. ray.direction = BABYLON.Vector3.Zero();
  87845. }
  87846. if (!ray.origin) {
  87847. ray.origin = BABYLON.Vector3.Zero();
  87848. }
  87849. if (length) {
  87850. ray.length = length;
  87851. }
  87852. if (!meshSpaceOrigin) {
  87853. meshSpaceOrigin = BABYLON.Vector3.Zero();
  87854. }
  87855. if (!meshSpaceDirection) {
  87856. // -1 so that this will work with Mesh.lookAt
  87857. meshSpaceDirection = new BABYLON.Vector3(0, 0, -1);
  87858. }
  87859. if (!this._meshSpaceDirection) {
  87860. this._meshSpaceDirection = meshSpaceDirection.clone();
  87861. this._meshSpaceOrigin = meshSpaceOrigin.clone();
  87862. }
  87863. else {
  87864. this._meshSpaceDirection.copyFrom(meshSpaceDirection);
  87865. this._meshSpaceOrigin.copyFrom(meshSpaceOrigin);
  87866. }
  87867. if (!this._updateToMeshFunction) {
  87868. this._updateToMeshFunction = this._updateToMesh.bind(this);
  87869. this._attachedToMesh.getScene().registerBeforeRender(this._updateToMeshFunction);
  87870. }
  87871. this._updateToMesh();
  87872. };
  87873. RayHelper.prototype.detachFromMesh = function () {
  87874. if (this._attachedToMesh) {
  87875. if (this._updateToMeshFunction) {
  87876. this._attachedToMesh.getScene().unregisterBeforeRender(this._updateToMeshFunction);
  87877. }
  87878. this._attachedToMesh = null;
  87879. this._updateToMeshFunction = null;
  87880. }
  87881. };
  87882. RayHelper.prototype._updateToMesh = function () {
  87883. var ray = this.ray;
  87884. if (!this._attachedToMesh || !ray) {
  87885. return;
  87886. }
  87887. if (this._attachedToMesh._isDisposed) {
  87888. this.detachFromMesh();
  87889. return;
  87890. }
  87891. this._attachedToMesh.getDirectionToRef(this._meshSpaceDirection, ray.direction);
  87892. BABYLON.Vector3.TransformCoordinatesToRef(this._meshSpaceOrigin, this._attachedToMesh.getWorldMatrix(), ray.origin);
  87893. };
  87894. RayHelper.prototype.dispose = function () {
  87895. this.hide();
  87896. this.detachFromMesh();
  87897. this.ray = null;
  87898. };
  87899. return RayHelper;
  87900. }());
  87901. BABYLON.RayHelper = RayHelper;
  87902. })(BABYLON || (BABYLON = {}));
  87903. //# sourceMappingURL=babylon.rayHelper.js.map
  87904. var BABYLON;
  87905. (function (BABYLON) {
  87906. // load the inspector using require, if not present in the global namespace.
  87907. var DebugLayer = /** @class */ (function () {
  87908. function DebugLayer(scene) {
  87909. this.BJSINSPECTOR = typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87910. this._scene = scene;
  87911. // load inspector using require, if it doesn't exist on the global namespace.
  87912. }
  87913. /** Creates the inspector window. */
  87914. DebugLayer.prototype._createInspector = function (config) {
  87915. if (config === void 0) { config = {}; }
  87916. var popup = config.popup || false;
  87917. var initialTab = config.initialTab || 0;
  87918. var parentElement = config.parentElement || null;
  87919. if (!this._inspector) {
  87920. this.BJSINSPECTOR = this.BJSINSPECTOR || typeof INSPECTOR !== 'undefined' ? INSPECTOR : undefined;
  87921. this._inspector = new this.BJSINSPECTOR.Inspector(this._scene, popup, initialTab, parentElement, config.newColors);
  87922. } // else nothing to do,; instance is already existing
  87923. };
  87924. DebugLayer.prototype.isVisible = function () {
  87925. if (!this._inspector) {
  87926. return false;
  87927. }
  87928. return true;
  87929. };
  87930. DebugLayer.prototype.hide = function () {
  87931. if (this._inspector) {
  87932. try {
  87933. this._inspector.dispose();
  87934. }
  87935. catch (e) {
  87936. // If the inspector has been removed directly from the inspector tool
  87937. }
  87938. this.onPropertyChangedObservable.clear();
  87939. this._inspector = null;
  87940. }
  87941. };
  87942. /**
  87943. *
  87944. * Launch the debugLayer.
  87945. *
  87946. * initialTab:
  87947. * | Value | Tab Name |
  87948. * | --- | --- |
  87949. * | 0 | Scene |
  87950. * | 1 | Console |
  87951. * | 2 | Stats |
  87952. * | 3 | Textures |
  87953. * | 4 | Mesh |
  87954. * | 5 | Light |
  87955. * | 6 | Material |
  87956. * | 7 | GLTF |
  87957. * | 8 | GUI |
  87958. * | 9 | Physics |
  87959. * | 10 | Camera |
  87960. * | 11 | Audio |
  87961. *
  87962. */
  87963. DebugLayer.prototype.show = function (config) {
  87964. if (config === void 0) { config = {}; }
  87965. if (typeof this.BJSINSPECTOR == 'undefined') {
  87966. // Load inspector and add it to the DOM
  87967. BABYLON.Tools.LoadScript(DebugLayer.InspectorURL, this._createInspector.bind(this, config));
  87968. }
  87969. else {
  87970. // Otherwise creates the inspector
  87971. this._createInspector(config);
  87972. this.onPropertyChangedObservable = new BABYLON.Observable();
  87973. }
  87974. };
  87975. /**
  87976. * Gets the active tab
  87977. * @return the index of the active tab or -1 if the inspector is hidden
  87978. */
  87979. DebugLayer.prototype.getActiveTab = function () {
  87980. return this._inspector ? this._inspector.getActiveTabIndex() : -1;
  87981. };
  87982. DebugLayer.InspectorURL = 'https://preview.babylonjs.com/inspector/babylon.inspector.bundle.js';
  87983. return DebugLayer;
  87984. }());
  87985. BABYLON.DebugLayer = DebugLayer;
  87986. })(BABYLON || (BABYLON = {}));
  87987. //# sourceMappingURL=babylon.debugLayer.js.map
  87988. var BABYLON;
  87989. (function (BABYLON) {
  87990. var Debug;
  87991. (function (Debug) {
  87992. /**
  87993. * Used to show the physics impostor around the specific mesh
  87994. */
  87995. var PhysicsViewer = /** @class */ (function () {
  87996. /**
  87997. * Creates a new PhysicsViewer
  87998. * @param scene defines the hosting scene
  87999. */
  88000. function PhysicsViewer(scene) {
  88001. /** @hidden */
  88002. this._impostors = [];
  88003. /** @hidden */
  88004. this._meshes = [];
  88005. /** @hidden */
  88006. this._numMeshes = 0;
  88007. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  88008. var physicEngine = this._scene.getPhysicsEngine();
  88009. if (physicEngine) {
  88010. this._physicsEnginePlugin = physicEngine.getPhysicsPlugin();
  88011. }
  88012. }
  88013. /** @hidden */
  88014. PhysicsViewer.prototype._updateDebugMeshes = function () {
  88015. var plugin = this._physicsEnginePlugin;
  88016. for (var i = 0; i < this._numMeshes; i++) {
  88017. var impostor = this._impostors[i];
  88018. if (!impostor) {
  88019. continue;
  88020. }
  88021. if (impostor.isDisposed) {
  88022. this.hideImpostor(this._impostors[i--]);
  88023. }
  88024. else {
  88025. var mesh = this._meshes[i];
  88026. if (mesh && plugin) {
  88027. plugin.syncMeshWithImpostor(mesh, impostor);
  88028. }
  88029. }
  88030. }
  88031. };
  88032. /**
  88033. * Renders a specified physic impostor
  88034. * @param impostor defines the impostor to render
  88035. */
  88036. PhysicsViewer.prototype.showImpostor = function (impostor) {
  88037. if (!this._scene) {
  88038. return;
  88039. }
  88040. for (var i = 0; i < this._numMeshes; i++) {
  88041. if (this._impostors[i] == impostor) {
  88042. return;
  88043. }
  88044. }
  88045. var debugMesh = this._getDebugMesh(impostor, this._scene);
  88046. if (debugMesh) {
  88047. this._impostors[this._numMeshes] = impostor;
  88048. this._meshes[this._numMeshes] = debugMesh;
  88049. if (this._numMeshes === 0) {
  88050. this._renderFunction = this._updateDebugMeshes.bind(this);
  88051. this._scene.registerBeforeRender(this._renderFunction);
  88052. }
  88053. this._numMeshes++;
  88054. }
  88055. };
  88056. /**
  88057. * Hides a specified physic impostor
  88058. * @param impostor defines the impostor to hide
  88059. */
  88060. PhysicsViewer.prototype.hideImpostor = function (impostor) {
  88061. if (!impostor || !this._scene) {
  88062. return;
  88063. }
  88064. var removed = false;
  88065. for (var i = 0; i < this._numMeshes; i++) {
  88066. if (this._impostors[i] == impostor) {
  88067. var mesh = this._meshes[i];
  88068. if (!mesh) {
  88069. continue;
  88070. }
  88071. this._scene.removeMesh(mesh);
  88072. mesh.dispose();
  88073. this._numMeshes--;
  88074. if (this._numMeshes > 0) {
  88075. this._meshes[i] = this._meshes[this._numMeshes];
  88076. this._impostors[i] = this._impostors[this._numMeshes];
  88077. this._meshes[this._numMeshes] = null;
  88078. this._impostors[this._numMeshes] = null;
  88079. }
  88080. else {
  88081. this._meshes[0] = null;
  88082. this._impostors[0] = null;
  88083. }
  88084. removed = true;
  88085. break;
  88086. }
  88087. }
  88088. if (removed && this._numMeshes === 0) {
  88089. this._scene.unregisterBeforeRender(this._renderFunction);
  88090. }
  88091. };
  88092. PhysicsViewer.prototype._getDebugMaterial = function (scene) {
  88093. if (!this._debugMaterial) {
  88094. this._debugMaterial = new BABYLON.StandardMaterial('', scene);
  88095. this._debugMaterial.wireframe = true;
  88096. }
  88097. return this._debugMaterial;
  88098. };
  88099. PhysicsViewer.prototype._getDebugBoxMesh = function (scene) {
  88100. if (!this._debugBoxMesh) {
  88101. this._debugBoxMesh = BABYLON.MeshBuilder.CreateBox('physicsBodyBoxViewMesh', { size: 1 }, scene);
  88102. this._debugBoxMesh.renderingGroupId = 1;
  88103. this._debugBoxMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88104. this._debugBoxMesh.material = this._getDebugMaterial(scene);
  88105. scene.removeMesh(this._debugBoxMesh);
  88106. }
  88107. return this._debugBoxMesh.createInstance('physicsBodyBoxViewInstance');
  88108. };
  88109. PhysicsViewer.prototype._getDebugSphereMesh = function (scene) {
  88110. if (!this._debugSphereMesh) {
  88111. this._debugSphereMesh = BABYLON.MeshBuilder.CreateSphere('physicsBodySphereViewMesh', { diameter: 1 }, scene);
  88112. this._debugSphereMesh.renderingGroupId = 1;
  88113. this._debugSphereMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  88114. this._debugSphereMesh.material = this._getDebugMaterial(scene);
  88115. scene.removeMesh(this._debugSphereMesh);
  88116. }
  88117. return this._debugSphereMesh.createInstance('physicsBodyBoxViewInstance');
  88118. };
  88119. PhysicsViewer.prototype._getDebugMesh = function (impostor, scene) {
  88120. var mesh = null;
  88121. if (impostor.type == BABYLON.PhysicsImpostor.BoxImpostor) {
  88122. mesh = this._getDebugBoxMesh(scene);
  88123. impostor.getBoxSizeToRef(mesh.scaling);
  88124. }
  88125. else if (impostor.type == BABYLON.PhysicsImpostor.SphereImpostor) {
  88126. mesh = this._getDebugSphereMesh(scene);
  88127. var radius = impostor.getRadius();
  88128. mesh.scaling.x = radius * 2;
  88129. mesh.scaling.y = radius * 2;
  88130. mesh.scaling.z = radius * 2;
  88131. }
  88132. return mesh;
  88133. };
  88134. /** Releases all resources */
  88135. PhysicsViewer.prototype.dispose = function () {
  88136. for (var i = 0; i < this._numMeshes; i++) {
  88137. this.hideImpostor(this._impostors[i]);
  88138. }
  88139. if (this._debugBoxMesh) {
  88140. this._debugBoxMesh.dispose();
  88141. }
  88142. if (this._debugSphereMesh) {
  88143. this._debugSphereMesh.dispose();
  88144. }
  88145. if (this._debugMaterial) {
  88146. this._debugMaterial.dispose();
  88147. }
  88148. this._impostors.length = 0;
  88149. this._scene = null;
  88150. this._physicsEnginePlugin = null;
  88151. };
  88152. return PhysicsViewer;
  88153. }());
  88154. Debug.PhysicsViewer = PhysicsViewer;
  88155. })(Debug = BABYLON.Debug || (BABYLON.Debug = {}));
  88156. })(BABYLON || (BABYLON = {}));
  88157. //# sourceMappingURL=babylon.physicsViewer.js.map
  88158. var BABYLON;
  88159. (function (BABYLON) {
  88160. var BoundingBoxRenderer = /** @class */ (function () {
  88161. function BoundingBoxRenderer(scene) {
  88162. this.frontColor = new BABYLON.Color3(1, 1, 1);
  88163. this.backColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  88164. this.showBackLines = true;
  88165. this.renderList = new BABYLON.SmartArray(32);
  88166. this._vertexBuffers = {};
  88167. this._scene = scene;
  88168. }
  88169. BoundingBoxRenderer.prototype._prepareRessources = function () {
  88170. if (this._colorShader) {
  88171. return;
  88172. }
  88173. this._colorShader = new BABYLON.ShaderMaterial("colorShader", this._scene, "color", {
  88174. attributes: [BABYLON.VertexBuffer.PositionKind],
  88175. uniforms: ["world", "viewProjection", "color"]
  88176. });
  88177. var engine = this._scene.getEngine();
  88178. var boxdata = BABYLON.VertexData.CreateBox({ size: 1.0 });
  88179. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, boxdata.positions, BABYLON.VertexBuffer.PositionKind, false);
  88180. this._createIndexBuffer();
  88181. };
  88182. BoundingBoxRenderer.prototype._createIndexBuffer = function () {
  88183. var engine = this._scene.getEngine();
  88184. 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]);
  88185. };
  88186. BoundingBoxRenderer.prototype._rebuild = function () {
  88187. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88188. if (vb) {
  88189. vb._rebuild();
  88190. }
  88191. this._createIndexBuffer();
  88192. };
  88193. BoundingBoxRenderer.prototype.reset = function () {
  88194. this.renderList.reset();
  88195. };
  88196. BoundingBoxRenderer.prototype.render = function () {
  88197. if (this.renderList.length === 0) {
  88198. return;
  88199. }
  88200. this._prepareRessources();
  88201. if (!this._colorShader.isReady()) {
  88202. return;
  88203. }
  88204. var engine = this._scene.getEngine();
  88205. engine.setDepthWrite(false);
  88206. this._colorShader._preBind();
  88207. for (var boundingBoxIndex = 0; boundingBoxIndex < this.renderList.length; boundingBoxIndex++) {
  88208. var boundingBox = this.renderList.data[boundingBoxIndex];
  88209. var min = boundingBox.minimum;
  88210. var max = boundingBox.maximum;
  88211. var diff = max.subtract(min);
  88212. var median = min.add(diff.scale(0.5));
  88213. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88214. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88215. .multiply(boundingBox.getWorldMatrix());
  88216. // VBOs
  88217. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88218. if (this.showBackLines) {
  88219. // Back
  88220. engine.setDepthFunctionToGreaterOrEqual();
  88221. this._scene.resetCachedMaterial();
  88222. this._colorShader.setColor4("color", this.backColor.toColor4());
  88223. this._colorShader.bind(worldMatrix);
  88224. // Draw order
  88225. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88226. }
  88227. // Front
  88228. engine.setDepthFunctionToLess();
  88229. this._scene.resetCachedMaterial();
  88230. this._colorShader.setColor4("color", this.frontColor.toColor4());
  88231. this._colorShader.bind(worldMatrix);
  88232. // Draw order
  88233. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88234. }
  88235. this._colorShader.unbind();
  88236. engine.setDepthFunctionToLessOrEqual();
  88237. engine.setDepthWrite(true);
  88238. };
  88239. BoundingBoxRenderer.prototype.renderOcclusionBoundingBox = function (mesh) {
  88240. this._prepareRessources();
  88241. if (!this._colorShader.isReady() || !mesh._boundingInfo) {
  88242. return;
  88243. }
  88244. var engine = this._scene.getEngine();
  88245. engine.setDepthWrite(false);
  88246. engine.setColorWrite(false);
  88247. this._colorShader._preBind();
  88248. var boundingBox = mesh._boundingInfo.boundingBox;
  88249. var min = boundingBox.minimum;
  88250. var max = boundingBox.maximum;
  88251. var diff = max.subtract(min);
  88252. var median = min.add(diff.scale(0.5));
  88253. var worldMatrix = BABYLON.Matrix.Scaling(diff.x, diff.y, diff.z)
  88254. .multiply(BABYLON.Matrix.Translation(median.x, median.y, median.z))
  88255. .multiply(boundingBox.getWorldMatrix());
  88256. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, this._colorShader.getEffect());
  88257. engine.setDepthFunctionToLess();
  88258. this._scene.resetCachedMaterial();
  88259. this._colorShader.bind(worldMatrix);
  88260. engine.drawElementsType(BABYLON.Material.LineListDrawMode, 0, 24);
  88261. this._colorShader.unbind();
  88262. engine.setDepthFunctionToLessOrEqual();
  88263. engine.setDepthWrite(true);
  88264. engine.setColorWrite(true);
  88265. };
  88266. BoundingBoxRenderer.prototype.dispose = function () {
  88267. if (!this._colorShader) {
  88268. return;
  88269. }
  88270. this.renderList.dispose();
  88271. this._colorShader.dispose();
  88272. var buffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  88273. if (buffer) {
  88274. buffer.dispose();
  88275. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  88276. }
  88277. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  88278. };
  88279. return BoundingBoxRenderer;
  88280. }());
  88281. BABYLON.BoundingBoxRenderer = BoundingBoxRenderer;
  88282. })(BABYLON || (BABYLON = {}));
  88283. //# sourceMappingURL=babylon.boundingBoxRenderer.js.map
  88284. var BABYLON;
  88285. (function (BABYLON) {
  88286. /**
  88287. * Renders a layer on top of an existing scene
  88288. */
  88289. var UtilityLayerRenderer = /** @class */ (function () {
  88290. /**
  88291. * Instantiates a UtilityLayerRenderer
  88292. * @param originalScene the original scene that will be rendered on top of
  88293. */
  88294. function UtilityLayerRenderer(/** the original scene that will be rendered on top of */ originalScene) {
  88295. var _this = this;
  88296. this.originalScene = originalScene;
  88297. this._pointerCaptures = {};
  88298. this._lastPointerEvents = {};
  88299. /**
  88300. * If the utility layer should automatically be rendered on top of existing scene
  88301. */
  88302. this.shouldRender = true;
  88303. /**
  88304. * If set to true, only pointer down onPointerObservable events will be blocked when picking is occluded by original scene
  88305. */
  88306. this.onlyCheckPointerDownEvents = true;
  88307. /**
  88308. * If set to false, only pointerUp, pointerDown and pointerMove will be sent to the utilityLayerScene (false by default)
  88309. */
  88310. this.processAllEvents = false;
  88311. /**
  88312. * Observable raised when the pointer move from the utility layer scene to the main scene
  88313. */
  88314. this.onPointerOutObservable = new BABYLON.Observable();
  88315. // Create scene which will be rendered in the foreground and remove it from being referenced by engine to avoid interfering with existing app
  88316. this.utilityLayerScene = new BABYLON.Scene(originalScene.getEngine());
  88317. originalScene.getEngine().scenes.pop();
  88318. // Detach controls on utility scene, events will be fired by logic below to handle picking priority
  88319. this.utilityLayerScene.detachControl();
  88320. this._originalPointerObserver = originalScene.onPrePointerObservable.add(function (prePointerInfo, eventState) {
  88321. if (!_this.processAllEvents) {
  88322. if (prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERMOVE
  88323. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERUP
  88324. && prePointerInfo.type !== BABYLON.PointerEventTypes.POINTERDOWN) {
  88325. return;
  88326. }
  88327. }
  88328. var pointerEvent = (prePointerInfo.event);
  88329. if (originalScene.isPointerCaptured(pointerEvent.pointerId)) {
  88330. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88331. return;
  88332. }
  88333. var utilityScenePick = prePointerInfo.ray ? _this.utilityLayerScene.pickWithRay(prePointerInfo.ray) : _this.utilityLayerScene.pick(originalScene.pointerX, originalScene.pointerY);
  88334. if (!prePointerInfo.ray && utilityScenePick) {
  88335. prePointerInfo.ray = utilityScenePick.ray;
  88336. }
  88337. // always fire the prepointer oversvable
  88338. _this.utilityLayerScene.onPrePointerObservable.notifyObservers(prePointerInfo);
  88339. // allow every non pointer down event to flow to the utility layer
  88340. if (_this.onlyCheckPointerDownEvents && prePointerInfo.type != BABYLON.PointerEventTypes.POINTERDOWN) {
  88341. if (!prePointerInfo.skipOnPointerObservable) {
  88342. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88343. }
  88344. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent.pointerId]) {
  88345. _this._pointerCaptures[pointerEvent.pointerId] = false;
  88346. }
  88347. return;
  88348. }
  88349. if (_this.utilityLayerScene.autoClearDepthAndStencil) {
  88350. // If this layer is an overlay, check if this layer was hit and if so, skip pointer events for the main scene
  88351. if (utilityScenePick && utilityScenePick.hit) {
  88352. if (!prePointerInfo.skipOnPointerObservable) {
  88353. _this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, utilityScenePick));
  88354. }
  88355. prePointerInfo.skipOnPointerObservable = true;
  88356. }
  88357. }
  88358. else {
  88359. var originalScenePick = prePointerInfo.ray ? originalScene.pickWithRay(prePointerInfo.ray) : originalScene.pick(originalScene.pointerX, originalScene.pointerY);
  88360. var pointerEvent_1 = (prePointerInfo.event);
  88361. // If the layer can be occluded by the original scene, only fire pointer events to the first layer that hit they ray
  88362. if (originalScenePick && utilityScenePick) {
  88363. // No pick in utility scene
  88364. if (utilityScenePick.distance === 0 && originalScenePick.pickedMesh) {
  88365. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88366. // We touched an utility mesh present in the main scene
  88367. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88368. prePointerInfo.skipOnPointerObservable = true;
  88369. }
  88370. else if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  88371. _this._pointerCaptures[pointerEvent_1.pointerId] = true;
  88372. }
  88373. }
  88374. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance < originalScenePick.distance || originalScenePick.distance === 0)) {
  88375. // We pick something in utility scene or the pick in utility is closer than the one in main scene
  88376. _this._notifyObservers(prePointerInfo, utilityScenePick, pointerEvent_1);
  88377. prePointerInfo.skipOnPointerObservable = utilityScenePick.distance > 0;
  88378. }
  88379. else if (!_this._pointerCaptures[pointerEvent_1.pointerId] && (utilityScenePick.distance > originalScenePick.distance)) {
  88380. // We have a pick in both scenes but main is closer than utility
  88381. // We touched an utility mesh present in the main scene
  88382. if (_this.mainSceneTrackerPredicate && _this.mainSceneTrackerPredicate(originalScenePick.pickedMesh)) {
  88383. _this._notifyObservers(prePointerInfo, originalScenePick, pointerEvent_1);
  88384. prePointerInfo.skipOnPointerObservable = true;
  88385. }
  88386. else if (_this._lastPointerEvents[pointerEvent_1.pointerId]) {
  88387. // We need to send a last pointerup to the utilityLayerScene to make sure animations can complete
  88388. _this.onPointerOutObservable.notifyObservers(pointerEvent_1.pointerId);
  88389. delete _this._lastPointerEvents[pointerEvent_1.pointerId];
  88390. }
  88391. }
  88392. if (prePointerInfo.type === BABYLON.PointerEventTypes.POINTERUP && _this._pointerCaptures[pointerEvent_1.pointerId]) {
  88393. _this._pointerCaptures[pointerEvent_1.pointerId] = false;
  88394. }
  88395. }
  88396. }
  88397. });
  88398. // Render directly on top of existing scene without clearing
  88399. this.utilityLayerScene.autoClear = false;
  88400. this._afterRenderObserver = this.originalScene.onAfterRenderObservable.add(function () {
  88401. if (_this.shouldRender) {
  88402. _this.render();
  88403. }
  88404. });
  88405. this._sceneDisposeObserver = this.originalScene.onDisposeObservable.add(function () {
  88406. _this.dispose();
  88407. });
  88408. this._updateCamera();
  88409. }
  88410. Object.defineProperty(UtilityLayerRenderer, "DefaultUtilityLayer", {
  88411. get: function () {
  88412. if (UtilityLayerRenderer._DefaultUtilityLayer == null) {
  88413. UtilityLayerRenderer._DefaultUtilityLayer = new UtilityLayerRenderer(BABYLON.Engine.LastCreatedScene);
  88414. UtilityLayerRenderer._DefaultUtilityLayer.originalScene.onDisposeObservable.add(function () {
  88415. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88416. });
  88417. }
  88418. return UtilityLayerRenderer._DefaultUtilityLayer;
  88419. },
  88420. enumerable: true,
  88421. configurable: true
  88422. });
  88423. UtilityLayerRenderer.prototype._notifyObservers = function (prePointerInfo, pickInfo, pointerEvent) {
  88424. if (!prePointerInfo.skipOnPointerObservable) {
  88425. this.utilityLayerScene.onPointerObservable.notifyObservers(new BABYLON.PointerInfo(prePointerInfo.type, prePointerInfo.event, pickInfo));
  88426. this._lastPointerEvents[pointerEvent.pointerId] = pointerEvent.pointerType;
  88427. }
  88428. };
  88429. /**
  88430. * Renders the utility layers scene on top of the original scene
  88431. */
  88432. UtilityLayerRenderer.prototype.render = function () {
  88433. this._updateCamera();
  88434. this.utilityLayerScene.render(false);
  88435. };
  88436. /**
  88437. * Disposes of the renderer
  88438. */
  88439. UtilityLayerRenderer.prototype.dispose = function () {
  88440. this.onPointerOutObservable.clear();
  88441. if (this._afterRenderObserver) {
  88442. this.originalScene.onAfterRenderObservable.remove(this._afterRenderObserver);
  88443. }
  88444. if (this._sceneDisposeObserver) {
  88445. this.originalScene.onDisposeObservable.remove(this._sceneDisposeObserver);
  88446. }
  88447. if (this._originalPointerObserver) {
  88448. this.originalScene.onPrePointerObservable.remove(this._originalPointerObserver);
  88449. }
  88450. this.utilityLayerScene.dispose();
  88451. };
  88452. UtilityLayerRenderer.prototype._updateCamera = function () {
  88453. this.utilityLayerScene.activeCamera = this.originalScene.activeCamera;
  88454. };
  88455. UtilityLayerRenderer._DefaultUtilityLayer = null;
  88456. return UtilityLayerRenderer;
  88457. }());
  88458. BABYLON.UtilityLayerRenderer = UtilityLayerRenderer;
  88459. })(BABYLON || (BABYLON = {}));
  88460. //# sourceMappingURL=babylon.utilityLayerRenderer.js.map
  88461. //# sourceMappingURL=babylon.behavior.js.map
  88462. var BABYLON;
  88463. (function (BABYLON) {
  88464. /**
  88465. * A behavior that when attached to a mesh will allow the mesh to be dragged around the screen based on pointer events
  88466. */
  88467. var PointerDragBehavior = /** @class */ (function () {
  88468. /**
  88469. * Creates a pointer drag behavior that can be attached to a mesh
  88470. * @param options The drag axis or normal of the plane that will be dragged across. If no options are specified the drag plane will always face the ray's origin (eg. camera)
  88471. */
  88472. function PointerDragBehavior(options) {
  88473. this.options = options;
  88474. /**
  88475. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88476. */
  88477. this.currentDraggingPointerID = -1;
  88478. /**
  88479. * If the behavior is currently in a dragging state
  88480. */
  88481. this.dragging = false;
  88482. /**
  88483. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88484. */
  88485. this.dragDeltaRatio = 0.2;
  88486. /**
  88487. * If the drag plane orientation should be updated during the dragging (Default: true)
  88488. */
  88489. this.updateDragPlane = true;
  88490. // Debug mode will display drag planes to help visualize behavior
  88491. this._debugMode = false;
  88492. this._moving = false;
  88493. /**
  88494. * Fires each time the attached mesh is dragged with the pointer
  88495. * * delta between last drag position and current drag position in world space
  88496. * * dragDistance along the drag axis
  88497. * * dragPlaneNormal normal of the current drag plane used during the drag
  88498. * * dragPlanePoint in world space where the drag intersects the drag plane
  88499. */
  88500. this.onDragObservable = new BABYLON.Observable();
  88501. /**
  88502. * Fires each time a drag begins (eg. mouse down on mesh)
  88503. */
  88504. this.onDragStartObservable = new BABYLON.Observable();
  88505. /**
  88506. * Fires each time a drag ends (eg. mouse release after drag)
  88507. */
  88508. this.onDragEndObservable = new BABYLON.Observable();
  88509. /**
  88510. * If the attached mesh should be moved when dragged
  88511. */
  88512. this.moveAttached = true;
  88513. /**
  88514. * If the drag behavior will react to drag events (Default: true)
  88515. */
  88516. this.enabled = true;
  88517. /**
  88518. * If set, the drag plane/axis will be rotated based on the attached mesh's world rotation (Default: true)
  88519. */
  88520. this.useObjectOrienationForDragging = true;
  88521. this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  88522. this._worldDragAxis = new BABYLON.Vector3(0, 0, 0);
  88523. // Variables to avoid instantiation in the below method
  88524. this._pointA = new BABYLON.Vector3(0, 0, 0);
  88525. this._pointB = new BABYLON.Vector3(0, 0, 0);
  88526. this._pointC = new BABYLON.Vector3(0, 0, 0);
  88527. this._lineA = new BABYLON.Vector3(0, 0, 0);
  88528. this._lineB = new BABYLON.Vector3(0, 0, 0);
  88529. this._localAxis = new BABYLON.Vector3(0, 0, 0);
  88530. this._lookAt = new BABYLON.Vector3(0, 0, 0);
  88531. var optionCount = 0;
  88532. if (options === undefined) {
  88533. options = {};
  88534. }
  88535. if (options.dragAxis) {
  88536. optionCount++;
  88537. }
  88538. if (options.dragPlaneNormal) {
  88539. optionCount++;
  88540. }
  88541. if (optionCount > 1) {
  88542. throw "Multiple drag modes specified in dragBehavior options. Only one expected";
  88543. }
  88544. }
  88545. Object.defineProperty(PointerDragBehavior.prototype, "name", {
  88546. /**
  88547. * The name of the behavior
  88548. */
  88549. get: function () {
  88550. return "PointerDrag";
  88551. },
  88552. enumerable: true,
  88553. configurable: true
  88554. });
  88555. /**
  88556. * Initializes the behavior
  88557. */
  88558. PointerDragBehavior.prototype.init = function () { };
  88559. /**
  88560. * Attaches the drag behavior the passed in mesh
  88561. * @param ownerNode The mesh that will be dragged around once attached
  88562. */
  88563. PointerDragBehavior.prototype.attach = function (ownerNode) {
  88564. var _this = this;
  88565. this._scene = ownerNode.getScene();
  88566. this._attachedNode = ownerNode;
  88567. // Initialize drag plane to not interfere with existing scene
  88568. if (!PointerDragBehavior._planeScene) {
  88569. if (this._debugMode) {
  88570. PointerDragBehavior._planeScene = this._scene;
  88571. }
  88572. else {
  88573. PointerDragBehavior._planeScene = new BABYLON.Scene(this._scene.getEngine());
  88574. this._scene.getEngine().scenes.pop();
  88575. }
  88576. }
  88577. this._dragPlane = BABYLON.Mesh.CreatePlane("pointerDragPlane", this._debugMode ? 1 : 10000, PointerDragBehavior._planeScene, false, BABYLON.Mesh.DOUBLESIDE);
  88578. // State of the drag
  88579. this.lastDragPosition = new BABYLON.Vector3(0, 0, 0);
  88580. var delta = new BABYLON.Vector3(0, 0, 0);
  88581. var dragLength = 0;
  88582. var targetPosition = new BABYLON.Vector3(0, 0, 0);
  88583. var pickPredicate = function (m) {
  88584. return _this._attachedNode == m || m.isDescendantOf(_this._attachedNode);
  88585. };
  88586. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88587. if (!_this.enabled) {
  88588. return;
  88589. }
  88590. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88591. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.pickedPoint && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88592. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pointerInfo.pickInfo.pickedPoint);
  88593. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88594. if (pickedPoint) {
  88595. _this.dragging = true;
  88596. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88597. _this.lastDragPosition.copyFrom(pickedPoint);
  88598. _this.onDragStartObservable.notifyObservers({ dragPlanePoint: pickedPoint, pointerId: _this.currentDraggingPointerID });
  88599. targetPosition.copyFrom(_this._attachedNode.absolutePosition);
  88600. }
  88601. }
  88602. }
  88603. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88604. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88605. _this.releaseDrag();
  88606. }
  88607. }
  88608. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88609. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  88610. _this._moving = true;
  88611. var pickedPoint = _this._pickWithRayOnDragPlane(pointerInfo.pickInfo.ray);
  88612. if (pickedPoint) {
  88613. if (_this.updateDragPlane) {
  88614. _this._updateDragPlanePosition(pointerInfo.pickInfo.ray, pickedPoint);
  88615. }
  88616. // depending on the drag mode option drag accordingly
  88617. if (_this.options.dragAxis) {
  88618. // Convert local drag axis to world
  88619. BABYLON.Vector3.TransformCoordinatesToRef(_this.options.dragAxis, _this._attachedNode.getWorldMatrix().getRotationMatrix(), _this._worldDragAxis);
  88620. // Project delta drag from the drag plane onto the drag axis
  88621. pickedPoint.subtractToRef(_this.lastDragPosition, _this._tmpVector);
  88622. dragLength = BABYLON.Vector3.Dot(_this._tmpVector, _this._worldDragAxis);
  88623. _this._worldDragAxis.scaleToRef(dragLength, delta);
  88624. }
  88625. else {
  88626. dragLength = delta.length();
  88627. pickedPoint.subtractToRef(_this.lastDragPosition, delta);
  88628. }
  88629. targetPosition.addInPlace(delta);
  88630. _this.onDragObservable.notifyObservers({ dragDistance: dragLength, delta: delta, dragPlanePoint: pickedPoint, dragPlaneNormal: _this._dragPlane.forward, pointerId: _this.currentDraggingPointerID });
  88631. _this.lastDragPosition.copyFrom(pickedPoint);
  88632. }
  88633. }
  88634. }
  88635. });
  88636. this._scene.onBeforeRenderObservable.add(function () {
  88637. if (_this._moving && _this.moveAttached) {
  88638. // Slowly move mesh to avoid jitter
  88639. targetPosition.subtractToRef(_this._attachedNode.absolutePosition, _this._tmpVector);
  88640. _this._tmpVector.scaleInPlace(0.2);
  88641. _this._attachedNode.getAbsolutePosition().addToRef(_this._tmpVector, _this._tmpVector);
  88642. _this._attachedNode.setAbsolutePosition(_this._tmpVector);
  88643. }
  88644. });
  88645. };
  88646. PointerDragBehavior.prototype.releaseDrag = function () {
  88647. this.dragging = false;
  88648. this.onDragEndObservable.notifyObservers({ dragPlanePoint: this.lastDragPosition, pointerId: this.currentDraggingPointerID });
  88649. this.currentDraggingPointerID = -1;
  88650. this._moving = false;
  88651. };
  88652. PointerDragBehavior.prototype._pickWithRayOnDragPlane = function (ray) {
  88653. var _this = this;
  88654. if (!ray) {
  88655. return null;
  88656. }
  88657. var pickResult = PointerDragBehavior._planeScene.pickWithRay(ray, function (m) { return m == _this._dragPlane; });
  88658. if (pickResult && pickResult.hit && pickResult.pickedMesh && pickResult.pickedPoint) {
  88659. return pickResult.pickedPoint;
  88660. }
  88661. else {
  88662. return null;
  88663. }
  88664. };
  88665. // Position the drag plane based on the attached mesh position, for single axis rotate the plane along the axis to face the camera
  88666. PointerDragBehavior.prototype._updateDragPlanePosition = function (ray, dragPlanePosition) {
  88667. this._pointA.copyFrom(dragPlanePosition);
  88668. if (this.options.dragAxis) {
  88669. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragAxis, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragAxis);
  88670. // Calculate plane normal in direction of camera but perpendicular to drag axis
  88671. this._pointA.addToRef(this._localAxis, this._pointB); // towards drag axis
  88672. ray.origin.subtractToRef(this._pointA, this._pointC);
  88673. this._pointA.addToRef(this._pointC.normalize(), this._pointC); // towards camera
  88674. // Get perpendicular line from direction to camera and drag axis
  88675. this._pointB.subtractToRef(this._pointA, this._lineA);
  88676. this._pointC.subtractToRef(this._pointA, this._lineB);
  88677. BABYLON.Vector3.CrossToRef(this._lineA, this._lineB, this._lookAt);
  88678. // Get perpendicular line from previous result and drag axis to adjust lineB to be perpendiculat to camera
  88679. BABYLON.Vector3.CrossToRef(this._lineA, this._lookAt, this._lookAt);
  88680. this._lookAt.normalize();
  88681. this._dragPlane.position.copyFrom(this._pointA);
  88682. this._pointA.subtractToRef(this._lookAt, this._lookAt);
  88683. this._dragPlane.lookAt(this._lookAt);
  88684. }
  88685. else if (this.options.dragPlaneNormal) {
  88686. this.useObjectOrienationForDragging ? BABYLON.Vector3.TransformCoordinatesToRef(this.options.dragPlaneNormal, this._attachedNode.getWorldMatrix().getRotationMatrix(), this._localAxis) : this._localAxis.copyFrom(this.options.dragPlaneNormal);
  88687. this._dragPlane.position.copyFrom(this._pointA);
  88688. this._pointA.subtractToRef(this._localAxis, this._lookAt);
  88689. this._dragPlane.lookAt(this._lookAt);
  88690. }
  88691. else {
  88692. this._dragPlane.position.copyFrom(this._pointA);
  88693. this._dragPlane.lookAt(ray.origin);
  88694. }
  88695. this._dragPlane.computeWorldMatrix(true);
  88696. };
  88697. /**
  88698. * Detaches the behavior from the mesh
  88699. */
  88700. PointerDragBehavior.prototype.detach = function () {
  88701. if (this._pointerObserver) {
  88702. this._scene.onPointerObservable.remove(this._pointerObserver);
  88703. }
  88704. };
  88705. return PointerDragBehavior;
  88706. }());
  88707. BABYLON.PointerDragBehavior = PointerDragBehavior;
  88708. })(BABYLON || (BABYLON = {}));
  88709. //# sourceMappingURL=babylon.pointerDragBehavior.js.map
  88710. var BABYLON;
  88711. (function (BABYLON) {
  88712. /**
  88713. * A behavior that when attached to a mesh will allow the mesh to be scaled
  88714. */
  88715. var MultiPointerScaleBehavior = /** @class */ (function () {
  88716. function MultiPointerScaleBehavior() {
  88717. this._startDistance = 0;
  88718. this._initialScale = new BABYLON.Vector3(0, 0, 0);
  88719. this._targetScale = new BABYLON.Vector3(0, 0, 0);
  88720. this._sceneRenderObserver = null;
  88721. this._dragBehaviorA = new BABYLON.PointerDragBehavior({});
  88722. this._dragBehaviorA.moveAttached = false;
  88723. this._dragBehaviorB = new BABYLON.PointerDragBehavior({});
  88724. this._dragBehaviorB.moveAttached = false;
  88725. }
  88726. Object.defineProperty(MultiPointerScaleBehavior.prototype, "name", {
  88727. /**
  88728. * The name of the behavior
  88729. */
  88730. get: function () {
  88731. return "MultiPointerScale";
  88732. },
  88733. enumerable: true,
  88734. configurable: true
  88735. });
  88736. /**
  88737. * Initializes the behavior
  88738. */
  88739. MultiPointerScaleBehavior.prototype.init = function () { };
  88740. MultiPointerScaleBehavior.prototype._getCurrentDistance = function () {
  88741. return this._dragBehaviorA.lastDragPosition.subtract(this._dragBehaviorB.lastDragPosition).length();
  88742. };
  88743. /**
  88744. * Attaches the scale behavior the passed in mesh
  88745. * @param ownerNode The mesh that will be scaled around once attached
  88746. */
  88747. MultiPointerScaleBehavior.prototype.attach = function (ownerNode) {
  88748. var _this = this;
  88749. this._ownerNode = ownerNode;
  88750. // Create 2 drag behaviors such that each will only be triggered by a separate pointer
  88751. this._dragBehaviorA.onDragStartObservable.add(function (e) {
  88752. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88753. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88754. _this._dragBehaviorA.releaseDrag();
  88755. }
  88756. else {
  88757. _this._initialScale.copyFrom(ownerNode.scaling);
  88758. _this._startDistance = _this._getCurrentDistance();
  88759. }
  88760. }
  88761. });
  88762. this._dragBehaviorB.onDragStartObservable.add(function (e) {
  88763. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88764. if (_this._dragBehaviorA.currentDraggingPointerID == _this._dragBehaviorB.currentDraggingPointerID) {
  88765. _this._dragBehaviorB.releaseDrag();
  88766. }
  88767. else {
  88768. _this._initialScale.copyFrom(ownerNode.scaling);
  88769. _this._startDistance = _this._getCurrentDistance();
  88770. }
  88771. }
  88772. });
  88773. // Once both drag behaviors are active scale based on the distance between the two pointers
  88774. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88775. behavior.onDragObservable.add(function () {
  88776. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88777. var ratio = _this._getCurrentDistance() / _this._startDistance;
  88778. _this._initialScale.scaleToRef(ratio, _this._targetScale);
  88779. }
  88780. });
  88781. });
  88782. ownerNode.addBehavior(this._dragBehaviorA);
  88783. ownerNode.addBehavior(this._dragBehaviorB);
  88784. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88785. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88786. if (_this._dragBehaviorA.dragging && _this._dragBehaviorB.dragging) {
  88787. var change = _this._targetScale.subtract(ownerNode.scaling).scaleInPlace(0.1);
  88788. if (change.length() > 0.01) {
  88789. ownerNode.scaling.addInPlace(change);
  88790. }
  88791. }
  88792. });
  88793. };
  88794. /**
  88795. * Detaches the behavior from the mesh
  88796. */
  88797. MultiPointerScaleBehavior.prototype.detach = function () {
  88798. var _this = this;
  88799. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88800. [this._dragBehaviorA, this._dragBehaviorB].forEach(function (behavior) {
  88801. behavior.onDragStartObservable.clear();
  88802. behavior.onDragObservable.clear();
  88803. _this._ownerNode.removeBehavior(behavior);
  88804. });
  88805. };
  88806. return MultiPointerScaleBehavior;
  88807. }());
  88808. BABYLON.MultiPointerScaleBehavior = MultiPointerScaleBehavior;
  88809. })(BABYLON || (BABYLON = {}));
  88810. //# sourceMappingURL=babylon.multiPointerScaleBehavior.js.map
  88811. var BABYLON;
  88812. (function (BABYLON) {
  88813. /**
  88814. * A behavior that when attached to a mesh will allow the mesh to be dragged around based on directions and origin of the pointer's ray
  88815. */
  88816. var SixDofDragBehavior = /** @class */ (function () {
  88817. function SixDofDragBehavior() {
  88818. this._sceneRenderObserver = null;
  88819. this._targetPosition = new BABYLON.Vector3(0, 0, 0);
  88820. this._moving = false;
  88821. this._startingOrientation = new BABYLON.Quaternion();
  88822. /**
  88823. * How much faster the object should move when the controller is moving towards it. This is useful to bring objects that are far away from the user to them faster. Set this to 0 to avoid any speed increase. (Default: 5)
  88824. */
  88825. this.zDragFactor = 5;
  88826. /**
  88827. * If the behavior is currently in a dragging state
  88828. */
  88829. this.dragging = false;
  88830. /**
  88831. * The distance towards the target drag position to move each frame. This can be useful to avoid jitter. Set this to 1 for no delay. (Default: 0.2)
  88832. */
  88833. this.dragDeltaRatio = 0.2;
  88834. /**
  88835. * The id of the pointer that is currently interacting with the behavior (-1 when no pointer is active)
  88836. */
  88837. this.currentDraggingPointerID = -1;
  88838. }
  88839. Object.defineProperty(SixDofDragBehavior.prototype, "name", {
  88840. /**
  88841. * The name of the behavior
  88842. */
  88843. get: function () {
  88844. return "SixDofDrag";
  88845. },
  88846. enumerable: true,
  88847. configurable: true
  88848. });
  88849. /**
  88850. * Initializes the behavior
  88851. */
  88852. SixDofDragBehavior.prototype.init = function () { };
  88853. /**
  88854. * Attaches the scale behavior the passed in mesh
  88855. * @param ownerNode The mesh that will be scaled around once attached
  88856. */
  88857. SixDofDragBehavior.prototype.attach = function (ownerNode) {
  88858. var _this = this;
  88859. this._ownerNode = ownerNode;
  88860. this._scene = this._ownerNode.getScene();
  88861. if (!SixDofDragBehavior._virtualScene) {
  88862. SixDofDragBehavior._virtualScene = new BABYLON.Scene(this._scene.getEngine());
  88863. this._scene.getEngine().scenes.pop();
  88864. }
  88865. var pickedMesh = null;
  88866. var lastSixDofOriginPosition = new BABYLON.Vector3(0, 0, 0);
  88867. // Setup virtual meshes to be used for dragging without dirtying the existing scene
  88868. this._virtualOriginMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88869. this._virtualOriginMesh.rotationQuaternion = new BABYLON.Quaternion();
  88870. this._virtualDragMesh = new BABYLON.AbstractMesh("", SixDofDragBehavior._virtualScene);
  88871. this._virtualDragMesh.rotationQuaternion = new BABYLON.Quaternion();
  88872. var pickPredicate = function (m) {
  88873. return _this._ownerNode == m || m.isDescendantOf(_this._ownerNode);
  88874. };
  88875. this._pointerObserver = this._scene.onPointerObservable.add(function (pointerInfo, eventState) {
  88876. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  88877. if (!_this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.hit && pointerInfo.pickInfo.pickedMesh && pointerInfo.pickInfo.ray && pickPredicate(pointerInfo.pickInfo.pickedMesh)) {
  88878. pickedMesh = pointerInfo.pickInfo.pickedMesh;
  88879. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88880. // Set position and orientation of the controller
  88881. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88882. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88883. // Attach the virtual drag mesh to the virtual origin mesh so it can be dragged
  88884. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88885. _this._virtualDragMesh.position.copyFrom(pickedMesh.absolutePosition);
  88886. if (!pickedMesh.rotationQuaternion) {
  88887. pickedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(pickedMesh.rotation.y, pickedMesh.rotation.x, pickedMesh.rotation.z);
  88888. }
  88889. var oldParent = pickedMesh.parent;
  88890. pickedMesh.setParent(null);
  88891. _this._virtualDragMesh.rotationQuaternion.copyFrom(pickedMesh.rotationQuaternion);
  88892. pickedMesh.setParent(oldParent);
  88893. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88894. // Update state
  88895. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88896. _this.dragging = true;
  88897. _this.currentDraggingPointerID = pointerInfo.event.pointerId;
  88898. }
  88899. }
  88900. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERUP) {
  88901. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId) {
  88902. _this.dragging = false;
  88903. _this._moving = false;
  88904. _this.currentDraggingPointerID = -1;
  88905. pickedMesh = null;
  88906. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88907. }
  88908. }
  88909. else if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERMOVE) {
  88910. if (_this.currentDraggingPointerID == pointerInfo.event.pointerId && _this.dragging && pointerInfo.pickInfo && pointerInfo.pickInfo.ray && pickedMesh) {
  88911. // Calculate controller drag distance in controller space
  88912. var originDragDifference = pointerInfo.pickInfo.ray.origin.subtract(lastSixDofOriginPosition);
  88913. lastSixDofOriginPosition.copyFrom(pointerInfo.pickInfo.ray.origin);
  88914. var localOriginDragDifference = BABYLON.Vector3.TransformCoordinates(originDragDifference, BABYLON.Matrix.Invert(_this._virtualOriginMesh.getWorldMatrix().getRotationMatrix()));
  88915. _this._virtualOriginMesh.addChild(_this._virtualDragMesh);
  88916. // Determine how much the controller moved to/away towards the dragged object and use this to move the object further when its further away
  88917. var zDragDistance = BABYLON.Vector3.Dot(localOriginDragDifference, _this._virtualOriginMesh.position.normalizeToNew());
  88918. _this._virtualDragMesh.position.z -= _this._virtualDragMesh.position.z < 1 ? zDragDistance * _this.zDragFactor : zDragDistance * _this.zDragFactor * _this._virtualDragMesh.position.z;
  88919. if (_this._virtualDragMesh.position.z < 0) {
  88920. _this._virtualDragMesh.position.z = 0;
  88921. }
  88922. // Update the controller position
  88923. _this._virtualOriginMesh.position.copyFrom(pointerInfo.pickInfo.ray.origin);
  88924. _this._virtualOriginMesh.lookAt(pointerInfo.pickInfo.ray.origin.subtract(pointerInfo.pickInfo.ray.direction));
  88925. _this._virtualOriginMesh.removeChild(_this._virtualDragMesh);
  88926. // Move the virtualObjectsPosition into the picked mesh's space if needed
  88927. _this._targetPosition.copyFrom(_this._virtualDragMesh.absolutePosition);
  88928. if (pickedMesh.parent) {
  88929. BABYLON.Vector3.TransformCoordinatesToRef(_this._targetPosition, BABYLON.Matrix.Invert(pickedMesh.parent.getWorldMatrix()), _this._targetPosition);
  88930. }
  88931. if (!_this._moving) {
  88932. _this._startingOrientation.copyFrom(_this._virtualDragMesh.rotationQuaternion);
  88933. }
  88934. _this._moving = true;
  88935. }
  88936. }
  88937. });
  88938. var tmpQuaternion = new BABYLON.Quaternion();
  88939. // On every frame move towards target scaling to avoid jitter caused by vr controllers
  88940. this._sceneRenderObserver = ownerNode.getScene().onBeforeRenderObservable.add(function () {
  88941. if (_this.dragging && _this._moving && pickedMesh) {
  88942. // Slowly move mesh to avoid jitter
  88943. pickedMesh.position.addInPlace(_this._targetPosition.subtract(pickedMesh.position).scale(_this.dragDeltaRatio));
  88944. // Get change in rotation
  88945. tmpQuaternion.copyFrom(_this._startingOrientation);
  88946. tmpQuaternion.x = -tmpQuaternion.x;
  88947. tmpQuaternion.y = -tmpQuaternion.y;
  88948. tmpQuaternion.z = -tmpQuaternion.z;
  88949. _this._virtualDragMesh.rotationQuaternion.multiplyToRef(tmpQuaternion, tmpQuaternion);
  88950. // Convert change in rotation to only y axis rotation
  88951. BABYLON.Quaternion.RotationYawPitchRollToRef(tmpQuaternion.toEulerAngles("xyz").y, 0, 0, tmpQuaternion);
  88952. tmpQuaternion.multiplyToRef(_this._startingOrientation, tmpQuaternion);
  88953. // Slowly move mesh to avoid jitter
  88954. var oldParent = pickedMesh.parent;
  88955. pickedMesh.setParent(null);
  88956. BABYLON.Quaternion.SlerpToRef(pickedMesh.rotationQuaternion, tmpQuaternion, _this.dragDeltaRatio, pickedMesh.rotationQuaternion);
  88957. pickedMesh.setParent(oldParent);
  88958. }
  88959. });
  88960. };
  88961. /**
  88962. * Detaches the behavior from the mesh
  88963. */
  88964. SixDofDragBehavior.prototype.detach = function () {
  88965. this._scene.onPointerObservable.remove(this._pointerObserver);
  88966. this._ownerNode.getScene().onBeforeRenderObservable.remove(this._sceneRenderObserver);
  88967. this._virtualOriginMesh.dispose();
  88968. this._virtualDragMesh.dispose();
  88969. };
  88970. return SixDofDragBehavior;
  88971. }());
  88972. BABYLON.SixDofDragBehavior = SixDofDragBehavior;
  88973. })(BABYLON || (BABYLON = {}));
  88974. //# sourceMappingURL=babylon.sixDofDragBehavior.js.map
  88975. var BABYLON;
  88976. (function (BABYLON) {
  88977. /**
  88978. * Renders gizmos on top of an existing scene which provide controls for position, rotation, etc.
  88979. */
  88980. var Gizmo = /** @class */ (function () {
  88981. /**
  88982. * Creates a gizmo
  88983. * @param gizmoLayer The utility layer the gizmo will be added to
  88984. */
  88985. function Gizmo(/** The utility layer the gizmo will be added to */ gizmoLayer) {
  88986. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  88987. var _this = this;
  88988. this.gizmoLayer = gizmoLayer;
  88989. /**
  88990. * If set the gizmo's rotation will be updated to match the attached mesh each frame (Default: true)
  88991. */
  88992. this.updateGizmoRotationToMatchAttachedMesh = true;
  88993. /**
  88994. * If set the gizmo's position will be updated to match the attached mesh each frame (Default: true)
  88995. */
  88996. this.updateGizmoPositionToMatchAttachedMesh = true;
  88997. /**
  88998. * When set, the gizmo will always appear the same size no matter where the camera is (default: false)
  88999. */
  89000. this._updateScale = true;
  89001. this._interactionsEnabled = true;
  89002. this._rootMesh = new BABYLON.Mesh("gizmoRootNode", gizmoLayer.utilityLayerScene);
  89003. this._beforeRenderObserver = this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.add(function () {
  89004. if (_this._updateScale && _this.gizmoLayer.utilityLayerScene.activeCamera && _this.attachedMesh) {
  89005. var dist = _this.attachedMesh.position.subtract(_this.gizmoLayer.utilityLayerScene.activeCamera.position).length() / 3;
  89006. _this._rootMesh.scaling.set(dist, dist, dist);
  89007. }
  89008. if (_this.attachedMesh) {
  89009. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89010. if (!_this._rootMesh.rotationQuaternion) {
  89011. _this._rootMesh.rotationQuaternion = new BABYLON.Quaternion();
  89012. }
  89013. BABYLON.Quaternion.FromRotationMatrixToRef(_this.attachedMesh.getWorldMatrix().getRotationMatrix(), _this._rootMesh.rotationQuaternion);
  89014. }
  89015. if (_this.updateGizmoPositionToMatchAttachedMesh) {
  89016. _this._rootMesh.position.copyFrom(_this.attachedMesh.absolutePosition);
  89017. }
  89018. }
  89019. });
  89020. this.attachedMesh = null;
  89021. }
  89022. Object.defineProperty(Gizmo.prototype, "attachedMesh", {
  89023. /**
  89024. * Mesh that the gizmo will be attached to. (eg. on a drag gizmo the mesh that will be dragged)
  89025. * * When set, interactions will be enabled
  89026. */
  89027. get: function () {
  89028. return this._attachedMesh;
  89029. },
  89030. set: function (value) {
  89031. this._attachedMesh = value;
  89032. this._rootMesh.setEnabled(value ? true : false);
  89033. this._attachedMeshChanged(value);
  89034. },
  89035. enumerable: true,
  89036. configurable: true
  89037. });
  89038. Gizmo.prototype._attachedMeshChanged = function (value) {
  89039. };
  89040. /**
  89041. * Disposes of the gizmo
  89042. */
  89043. Gizmo.prototype.dispose = function () {
  89044. this._rootMesh.dispose();
  89045. if (this._beforeRenderObserver) {
  89046. this.gizmoLayer.utilityLayerScene.onBeforeRenderObservable.remove(this._beforeRenderObserver);
  89047. }
  89048. };
  89049. return Gizmo;
  89050. }());
  89051. BABYLON.Gizmo = Gizmo;
  89052. })(BABYLON || (BABYLON = {}));
  89053. //# sourceMappingURL=babylon.gizmo.js.map
  89054. var BABYLON;
  89055. (function (BABYLON) {
  89056. /**
  89057. * Single axis drag gizmo
  89058. */
  89059. var AxisDragGizmo = /** @class */ (function (_super) {
  89060. __extends(AxisDragGizmo, _super);
  89061. /**
  89062. * Creates an AxisDragGizmo
  89063. * @param gizmoLayer The utility layer the gizmo will be added to
  89064. * @param dragAxis The axis which the gizmo will be able to drag on
  89065. * @param color The color of the gizmo
  89066. */
  89067. function AxisDragGizmo(dragAxis, color, gizmoLayer) {
  89068. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89069. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89070. var _this = _super.call(this, gizmoLayer) || this;
  89071. _this._pointerObserver = null;
  89072. /**
  89073. * Drag distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89074. */
  89075. _this.snapDistance = 0;
  89076. /**
  89077. * Event that fires each time the gizmo snaps to a new location.
  89078. * * snapDistance is the the change in distance
  89079. */
  89080. _this.onSnapObservable = new BABYLON.Observable();
  89081. // Create Material
  89082. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89083. coloredMaterial.disableLighting = true;
  89084. coloredMaterial.emissiveColor = color;
  89085. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89086. hoverMaterial.disableLighting = true;
  89087. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89088. // Build mesh on root node
  89089. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89090. var arrowMesh = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameterTop: 0, height: 2, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89091. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89092. arrow.addChild(arrowMesh);
  89093. arrow.addChild(arrowTail);
  89094. // Position arrow pointing in its drag axis
  89095. arrowMesh.scaling.scaleInPlace(0.05);
  89096. arrowMesh.material = coloredMaterial;
  89097. arrowMesh.rotation.x = Math.PI / 2;
  89098. arrowMesh.position.z += 0.3;
  89099. arrowTail.rotation.x = Math.PI / 2;
  89100. arrowTail.material = coloredMaterial;
  89101. arrowTail.position.z += 0.15;
  89102. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89103. _this._rootMesh.addChild(arrow);
  89104. var currentSnapDragDistance = 0;
  89105. var tmpVector = new BABYLON.Vector3();
  89106. var tmpSnapEvent = { snapDistance: 0 };
  89107. // Add drag behavior to handle events when the gizmo is dragged
  89108. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89109. _this._dragBehavior.moveAttached = false;
  89110. _this._rootMesh.addBehavior(_this._dragBehavior);
  89111. _this._dragBehavior.onDragObservable.add(function (event) {
  89112. if (_this.attachedMesh) {
  89113. // Snapping logic
  89114. if (_this.snapDistance == 0) {
  89115. _this.attachedMesh.position.addInPlace(event.delta);
  89116. }
  89117. else {
  89118. currentSnapDragDistance += event.dragDistance;
  89119. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89120. var dragSteps = Math.floor(Math.abs(currentSnapDragDistance) / _this.snapDistance);
  89121. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89122. event.delta.normalizeToRef(tmpVector);
  89123. tmpVector.scaleInPlace(_this.snapDistance * dragSteps);
  89124. _this.attachedMesh.position.addInPlace(tmpVector);
  89125. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89126. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89127. }
  89128. }
  89129. }
  89130. });
  89131. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89132. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89133. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89134. m.material = hoverMaterial;
  89135. });
  89136. }
  89137. else {
  89138. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89139. m.material = coloredMaterial;
  89140. });
  89141. }
  89142. });
  89143. return _this;
  89144. }
  89145. AxisDragGizmo.prototype._attachedMeshChanged = function (value) {
  89146. if (this._dragBehavior) {
  89147. this._dragBehavior.enabled = value ? true : false;
  89148. }
  89149. };
  89150. /**
  89151. * Disposes of the gizmo
  89152. */
  89153. AxisDragGizmo.prototype.dispose = function () {
  89154. this.onSnapObservable.clear();
  89155. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89156. this._dragBehavior.detach();
  89157. _super.prototype.dispose.call(this);
  89158. };
  89159. return AxisDragGizmo;
  89160. }(BABYLON.Gizmo));
  89161. BABYLON.AxisDragGizmo = AxisDragGizmo;
  89162. })(BABYLON || (BABYLON = {}));
  89163. //# sourceMappingURL=babylon.axisDragGizmo.js.map
  89164. var BABYLON;
  89165. (function (BABYLON) {
  89166. /**
  89167. * Single axis scale gizmo
  89168. */
  89169. var AxisScaleGizmo = /** @class */ (function (_super) {
  89170. __extends(AxisScaleGizmo, _super);
  89171. /**
  89172. * Creates an AxisScaleGizmo
  89173. * @param gizmoLayer The utility layer the gizmo will be added to
  89174. * @param dragAxis The axis which the gizmo will be able to scale on
  89175. * @param color The color of the gizmo
  89176. */
  89177. function AxisScaleGizmo(dragAxis, color, gizmoLayer) {
  89178. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89179. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89180. var _this = _super.call(this, gizmoLayer) || this;
  89181. _this._pointerObserver = null;
  89182. /**
  89183. * Scale distance in babylon units that the gizmo will snap to when dragged (Default: 0)
  89184. */
  89185. _this.snapDistance = 0;
  89186. /**
  89187. * Event that fires each time the gizmo snaps to a new location.
  89188. * * snapDistance is the the change in distance
  89189. */
  89190. _this.onSnapObservable = new BABYLON.Observable();
  89191. // Create Material
  89192. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89193. coloredMaterial.disableLighting = true;
  89194. coloredMaterial.emissiveColor = color;
  89195. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89196. hoverMaterial.disableLighting = true;
  89197. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89198. // Build mesh on root node
  89199. var arrow = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89200. var arrowMesh = BABYLON.MeshBuilder.CreateBox("yPosMesh", { size: 0.5 }, gizmoLayer.utilityLayerScene);
  89201. var arrowTail = BABYLON.MeshBuilder.CreateCylinder("yPosMesh", { diameter: 0.015, height: 0.3, tessellation: 96 }, gizmoLayer.utilityLayerScene);
  89202. arrow.addChild(arrowMesh);
  89203. arrow.addChild(arrowTail);
  89204. // Position arrow pointing in its drag axis
  89205. arrowMesh.scaling.scaleInPlace(0.1);
  89206. arrowMesh.material = coloredMaterial;
  89207. arrowMesh.rotation.x = Math.PI / 2;
  89208. arrowMesh.position.z += 0.3;
  89209. arrowTail.rotation.x = Math.PI / 2;
  89210. arrowTail.material = coloredMaterial;
  89211. arrowTail.position.z += 0.15;
  89212. arrow.lookAt(_this._rootMesh.position.subtract(dragAxis));
  89213. _this._rootMesh.addChild(arrow);
  89214. // Add drag behavior to handle events when the gizmo is dragged
  89215. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89216. _this._dragBehavior.moveAttached = false;
  89217. _this._rootMesh.addBehavior(_this._dragBehavior);
  89218. var currentSnapDragDistance = 0;
  89219. var tmpVector = new BABYLON.Vector3();
  89220. var tmpSnapEvent = { snapDistance: 0 };
  89221. _this._dragBehavior.onDragObservable.add(function (event) {
  89222. if (_this.attachedMesh) {
  89223. // Snapping logic
  89224. var snapped = false;
  89225. var dragSteps = 0;
  89226. if (_this.snapDistance == 0) {
  89227. dragAxis.scaleToRef(event.dragDistance, tmpVector);
  89228. }
  89229. else {
  89230. currentSnapDragDistance += event.dragDistance;
  89231. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89232. dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89233. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89234. dragAxis.scaleToRef(_this.snapDistance * dragSteps, tmpVector);
  89235. snapped = true;
  89236. }
  89237. else {
  89238. tmpVector.scaleInPlace(0);
  89239. }
  89240. }
  89241. var invertCount = 0;
  89242. if (_this.attachedMesh.scaling["x"] < 0) {
  89243. invertCount++;
  89244. }
  89245. if (_this.attachedMesh.scaling["y"] < 0) {
  89246. invertCount++;
  89247. }
  89248. if (_this.attachedMesh.scaling["z"] < 0) {
  89249. invertCount++;
  89250. }
  89251. if (invertCount % 2 == 0) {
  89252. _this.attachedMesh.scaling.addInPlace(tmpVector);
  89253. }
  89254. else {
  89255. _this.attachedMesh.scaling.subtractInPlace(tmpVector);
  89256. }
  89257. if (snapped) {
  89258. tmpSnapEvent.snapDistance = _this.snapDistance * dragSteps;
  89259. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89260. }
  89261. }
  89262. });
  89263. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89264. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89265. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89266. m.material = hoverMaterial;
  89267. });
  89268. }
  89269. else {
  89270. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89271. m.material = coloredMaterial;
  89272. });
  89273. }
  89274. });
  89275. return _this;
  89276. }
  89277. AxisScaleGizmo.prototype._attachedMeshChanged = function (value) {
  89278. if (this._dragBehavior) {
  89279. this._dragBehavior.enabled = value ? true : false;
  89280. }
  89281. };
  89282. /**
  89283. * Disposes of the gizmo
  89284. */
  89285. AxisScaleGizmo.prototype.dispose = function () {
  89286. this.onSnapObservable.clear();
  89287. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89288. this._dragBehavior.detach();
  89289. _super.prototype.dispose.call(this);
  89290. };
  89291. return AxisScaleGizmo;
  89292. }(BABYLON.Gizmo));
  89293. BABYLON.AxisScaleGizmo = AxisScaleGizmo;
  89294. })(BABYLON || (BABYLON = {}));
  89295. //# sourceMappingURL=babylon.axisScaleGizmo.js.map
  89296. var BABYLON;
  89297. (function (BABYLON) {
  89298. /**
  89299. * Single plane rotation gizmo
  89300. */
  89301. var PlaneRotationGizmo = /** @class */ (function (_super) {
  89302. __extends(PlaneRotationGizmo, _super);
  89303. /**
  89304. * Creates a PlaneRotationGizmo
  89305. * @param gizmoLayer The utility layer the gizmo will be added to
  89306. * @param planeNormal The normal of the plane which the gizmo will be able to rotate on
  89307. * @param color The color of the gizmo
  89308. */
  89309. function PlaneRotationGizmo(planeNormal, color, gizmoLayer) {
  89310. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89311. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89312. var _this = _super.call(this, gizmoLayer) || this;
  89313. _this._pointerObserver = null;
  89314. /**
  89315. * Rotation distance in radians that the gizmo will snap to (Default: 0)
  89316. */
  89317. _this.snapDistance = 0;
  89318. /**
  89319. * Event that fires each time the gizmo snaps to a new location.
  89320. * * snapDistance is the the change in distance
  89321. */
  89322. _this.onSnapObservable = new BABYLON.Observable();
  89323. // Create Material
  89324. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89325. coloredMaterial.disableLighting = true;
  89326. coloredMaterial.emissiveColor = color;
  89327. var hoverMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89328. hoverMaterial.disableLighting = true;
  89329. hoverMaterial.emissiveColor = color.add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89330. // Build mesh on root node
  89331. var parentMesh = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89332. var rotationMesh = BABYLON.Mesh.CreateTorus("torus", 3, 0.15, 20, gizmoLayer.utilityLayerScene, false);
  89333. // Position arrow pointing in its drag axis
  89334. rotationMesh.scaling.scaleInPlace(0.1);
  89335. rotationMesh.material = coloredMaterial;
  89336. rotationMesh.rotation.x = Math.PI / 2;
  89337. parentMesh.addChild(rotationMesh);
  89338. parentMesh.lookAt(_this._rootMesh.position.subtract(planeNormal));
  89339. _this._rootMesh.addChild(parentMesh);
  89340. // Add drag behavior to handle events when the gizmo is dragged
  89341. _this._dragBehavior = new BABYLON.PointerDragBehavior({ dragPlaneNormal: planeNormal });
  89342. _this._dragBehavior.moveAttached = false;
  89343. _this._rootMesh.addBehavior(_this._dragBehavior);
  89344. var lastDragPosition = null;
  89345. _this._dragBehavior.onDragStartObservable.add(function (e) {
  89346. if (_this.attachedMesh) {
  89347. lastDragPosition = e.dragPlanePoint;
  89348. }
  89349. });
  89350. var rotationMatrix = new BABYLON.Matrix();
  89351. var planeNormalTowardsCamera = new BABYLON.Vector3();
  89352. var localPlaneNormalTowardsCamera = new BABYLON.Vector3();
  89353. var tmpSnapEvent = { snapDistance: 0 };
  89354. var currentSnapDragDistance = 0;
  89355. _this._dragBehavior.onDragObservable.add(function (event) {
  89356. if (_this.attachedMesh && lastDragPosition) {
  89357. if (!_this.attachedMesh.rotationQuaternion) {
  89358. _this.attachedMesh.rotationQuaternion = new BABYLON.Quaternion();
  89359. }
  89360. // Calc angle over full 360 degree (https://stackoverflow.com/questions/43493711/the-angle-between-two-3d-vectors-with-a-result-range-0-360)
  89361. var newVector = event.dragPlanePoint.subtract(_this.attachedMesh.position).normalize();
  89362. var originalVector = lastDragPosition.subtract(_this.attachedMesh.position).normalize();
  89363. var cross = BABYLON.Vector3.Cross(newVector, originalVector);
  89364. var dot = BABYLON.Vector3.Dot(newVector, originalVector);
  89365. var angle = Math.atan2(cross.length(), dot);
  89366. planeNormalTowardsCamera.copyFrom(planeNormal);
  89367. localPlaneNormalTowardsCamera.copyFrom(planeNormal);
  89368. if (_this.updateGizmoRotationToMatchAttachedMesh) {
  89369. _this.attachedMesh.rotationQuaternion.toRotationMatrix(rotationMatrix);
  89370. localPlaneNormalTowardsCamera = BABYLON.Vector3.TransformCoordinates(planeNormalTowardsCamera, rotationMatrix);
  89371. }
  89372. // Flip up vector depending on which side the camera is on
  89373. if (gizmoLayer.utilityLayerScene.activeCamera) {
  89374. var camVec = gizmoLayer.utilityLayerScene.activeCamera.position.subtract(_this.attachedMesh.position);
  89375. if (BABYLON.Vector3.Dot(camVec, localPlaneNormalTowardsCamera) > 0) {
  89376. planeNormalTowardsCamera.scaleInPlace(-1);
  89377. localPlaneNormalTowardsCamera.scaleInPlace(-1);
  89378. }
  89379. }
  89380. var halfCircleSide = BABYLON.Vector3.Dot(localPlaneNormalTowardsCamera, cross) > 0.0;
  89381. if (halfCircleSide)
  89382. angle = -angle;
  89383. // Snapping logic
  89384. var snapped = false;
  89385. if (_this.snapDistance != 0) {
  89386. currentSnapDragDistance += angle;
  89387. if (Math.abs(currentSnapDragDistance) > _this.snapDistance) {
  89388. var dragSteps = Math.floor(currentSnapDragDistance / _this.snapDistance);
  89389. currentSnapDragDistance = currentSnapDragDistance % _this.snapDistance;
  89390. angle = _this.snapDistance * dragSteps;
  89391. snapped = true;
  89392. }
  89393. else {
  89394. angle = 0;
  89395. }
  89396. }
  89397. // Convert angle and axis to quaternion (http://www.euclideanspace.com/maths/geometry/rotations/conversions/angleToQuaternion/index.htm)
  89398. var quaternionCoefficient = Math.sin(angle / 2);
  89399. var amountToRotate = new BABYLON.Quaternion(planeNormalTowardsCamera.x * quaternionCoefficient, planeNormalTowardsCamera.y * quaternionCoefficient, planeNormalTowardsCamera.z * quaternionCoefficient, Math.cos(angle / 2));
  89400. // Rotate selected mesh quaternion over fixed axis
  89401. _this.attachedMesh.rotationQuaternion.multiplyToRef(amountToRotate, _this.attachedMesh.rotationQuaternion);
  89402. lastDragPosition = event.dragPlanePoint;
  89403. if (snapped) {
  89404. tmpSnapEvent.snapDistance = angle;
  89405. _this.onSnapObservable.notifyObservers(tmpSnapEvent);
  89406. }
  89407. }
  89408. });
  89409. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89410. if (pointerInfo.pickInfo && (_this._rootMesh.getChildMeshes().indexOf(pointerInfo.pickInfo.pickedMesh) != -1)) {
  89411. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89412. m.material = hoverMaterial;
  89413. });
  89414. }
  89415. else {
  89416. _this._rootMesh.getChildMeshes().forEach(function (m) {
  89417. m.material = coloredMaterial;
  89418. });
  89419. }
  89420. });
  89421. return _this;
  89422. }
  89423. PlaneRotationGizmo.prototype._attachedMeshChanged = function (value) {
  89424. if (this._dragBehavior) {
  89425. this._dragBehavior.enabled = value ? true : false;
  89426. }
  89427. };
  89428. /**
  89429. * Disposes of the gizmo
  89430. */
  89431. PlaneRotationGizmo.prototype.dispose = function () {
  89432. this.onSnapObservable.clear();
  89433. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89434. this._dragBehavior.detach();
  89435. _super.prototype.dispose.call(this);
  89436. };
  89437. return PlaneRotationGizmo;
  89438. }(BABYLON.Gizmo));
  89439. BABYLON.PlaneRotationGizmo = PlaneRotationGizmo;
  89440. })(BABYLON || (BABYLON = {}));
  89441. //# sourceMappingURL=babylon.planeRotationGizmo.js.map
  89442. var BABYLON;
  89443. (function (BABYLON) {
  89444. /**
  89445. * Gizmo that enables dragging a mesh along 3 axis
  89446. */
  89447. var PositionGizmo = /** @class */ (function (_super) {
  89448. __extends(PositionGizmo, _super);
  89449. /**
  89450. * Creates a PositionGizmo
  89451. * @param gizmoLayer The utility layer the gizmo will be added to
  89452. */
  89453. function PositionGizmo(gizmoLayer) {
  89454. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89455. var _this = _super.call(this, gizmoLayer) || this;
  89456. _this._xDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89457. _this._yDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89458. _this._zDrag = new BABYLON.AxisDragGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89459. _this.attachedMesh = null;
  89460. return _this;
  89461. }
  89462. Object.defineProperty(PositionGizmo.prototype, "attachedMesh", {
  89463. set: function (mesh) {
  89464. if (this._xDrag) {
  89465. this._xDrag.attachedMesh = mesh;
  89466. this._yDrag.attachedMesh = mesh;
  89467. this._zDrag.attachedMesh = mesh;
  89468. }
  89469. },
  89470. enumerable: true,
  89471. configurable: true
  89472. });
  89473. Object.defineProperty(PositionGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89474. get: function () {
  89475. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89476. },
  89477. set: function (value) {
  89478. if (this._xDrag) {
  89479. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89480. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89481. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89482. }
  89483. },
  89484. enumerable: true,
  89485. configurable: true
  89486. });
  89487. /**
  89488. * Disposes of the gizmo
  89489. */
  89490. PositionGizmo.prototype.dispose = function () {
  89491. this._xDrag.dispose();
  89492. this._yDrag.dispose();
  89493. this._zDrag.dispose();
  89494. };
  89495. return PositionGizmo;
  89496. }(BABYLON.Gizmo));
  89497. BABYLON.PositionGizmo = PositionGizmo;
  89498. })(BABYLON || (BABYLON = {}));
  89499. //# sourceMappingURL=babylon.positionGizmo.js.map
  89500. var BABYLON;
  89501. (function (BABYLON) {
  89502. /**
  89503. * Gizmo that enables rotating a mesh along 3 axis
  89504. */
  89505. var RotationGizmo = /** @class */ (function (_super) {
  89506. __extends(RotationGizmo, _super);
  89507. /**
  89508. * Creates a RotationGizmo
  89509. * @param gizmoLayer The utility layer the gizmo will be added to
  89510. */
  89511. function RotationGizmo(gizmoLayer) {
  89512. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89513. var _this = _super.call(this, gizmoLayer) || this;
  89514. _this._xDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89515. _this._yDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89516. _this._zDrag = new BABYLON.PlaneRotationGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89517. _this.attachedMesh = null;
  89518. return _this;
  89519. }
  89520. Object.defineProperty(RotationGizmo.prototype, "attachedMesh", {
  89521. set: function (mesh) {
  89522. if (this._xDrag) {
  89523. this._xDrag.attachedMesh = mesh;
  89524. this._yDrag.attachedMesh = mesh;
  89525. this._zDrag.attachedMesh = mesh;
  89526. }
  89527. },
  89528. enumerable: true,
  89529. configurable: true
  89530. });
  89531. Object.defineProperty(RotationGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89532. get: function () {
  89533. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89534. },
  89535. set: function (value) {
  89536. if (this._xDrag) {
  89537. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89538. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89539. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89540. }
  89541. },
  89542. enumerable: true,
  89543. configurable: true
  89544. });
  89545. /**
  89546. * Disposes of the gizmo
  89547. */
  89548. RotationGizmo.prototype.dispose = function () {
  89549. this._xDrag.dispose();
  89550. this._yDrag.dispose();
  89551. this._zDrag.dispose();
  89552. };
  89553. return RotationGizmo;
  89554. }(BABYLON.Gizmo));
  89555. BABYLON.RotationGizmo = RotationGizmo;
  89556. })(BABYLON || (BABYLON = {}));
  89557. //# sourceMappingURL=babylon.rotationGizmo.js.map
  89558. var BABYLON;
  89559. (function (BABYLON) {
  89560. /**
  89561. * Gizmo that enables scaling a mesh along 3 axis
  89562. */
  89563. var ScaleGizmo = /** @class */ (function (_super) {
  89564. __extends(ScaleGizmo, _super);
  89565. /**
  89566. * Creates a ScaleGizmo
  89567. * @param gizmoLayer The utility layer the gizmo will be added to
  89568. */
  89569. function ScaleGizmo(gizmoLayer) {
  89570. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89571. var _this = _super.call(this, gizmoLayer) || this;
  89572. _this._xDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(1, 0, 0), BABYLON.Color3.Green().scale(0.5), gizmoLayer);
  89573. _this._yDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 1, 0), BABYLON.Color3.Red().scale(0.5), gizmoLayer);
  89574. _this._zDrag = new BABYLON.AxisScaleGizmo(new BABYLON.Vector3(0, 0, 1), BABYLON.Color3.Blue().scale(0.5), gizmoLayer);
  89575. _this.attachedMesh = null;
  89576. return _this;
  89577. }
  89578. Object.defineProperty(ScaleGizmo.prototype, "attachedMesh", {
  89579. set: function (mesh) {
  89580. if (this._xDrag) {
  89581. this._xDrag.attachedMesh = mesh;
  89582. this._yDrag.attachedMesh = mesh;
  89583. this._zDrag.attachedMesh = mesh;
  89584. }
  89585. },
  89586. enumerable: true,
  89587. configurable: true
  89588. });
  89589. Object.defineProperty(ScaleGizmo.prototype, "updateGizmoRotationToMatchAttachedMesh", {
  89590. get: function () {
  89591. return this._xDrag.updateGizmoRotationToMatchAttachedMesh;
  89592. },
  89593. set: function (value) {
  89594. if (this._xDrag) {
  89595. this._xDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89596. this._yDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89597. this._zDrag.updateGizmoRotationToMatchAttachedMesh = value;
  89598. }
  89599. },
  89600. enumerable: true,
  89601. configurable: true
  89602. });
  89603. /**
  89604. * Disposes of the gizmo
  89605. */
  89606. ScaleGizmo.prototype.dispose = function () {
  89607. this._xDrag.dispose();
  89608. this._yDrag.dispose();
  89609. this._zDrag.dispose();
  89610. };
  89611. return ScaleGizmo;
  89612. }(BABYLON.Gizmo));
  89613. BABYLON.ScaleGizmo = ScaleGizmo;
  89614. })(BABYLON || (BABYLON = {}));
  89615. //# sourceMappingURL=babylon.scaleGizmo.js.map
  89616. var BABYLON;
  89617. (function (BABYLON) {
  89618. /**
  89619. * Bounding box gizmo
  89620. */
  89621. var BoundingBoxGizmo = /** @class */ (function (_super) {
  89622. __extends(BoundingBoxGizmo, _super);
  89623. /**
  89624. * Creates an BoundingBoxGizmo
  89625. * @param gizmoLayer The utility layer the gizmo will be added to
  89626. * @param color The color of the gizmo
  89627. */
  89628. function BoundingBoxGizmo(color, gizmoLayer) {
  89629. if (color === void 0) { color = BABYLON.Color3.Gray(); }
  89630. if (gizmoLayer === void 0) { gizmoLayer = BABYLON.UtilityLayerRenderer.DefaultUtilityLayer; }
  89631. var _this = _super.call(this, gizmoLayer) || this;
  89632. _this._boundingDimensions = new BABYLON.Vector3(1, 1, 1);
  89633. _this._renderObserver = null;
  89634. _this._pointerObserver = null;
  89635. _this._scaleDragSpeed = 0.2;
  89636. _this._tmpQuaternion = new BABYLON.Quaternion();
  89637. _this._tmpVector = new BABYLON.Vector3(0, 0, 0);
  89638. /**
  89639. * The size of the rotation spheres attached to the bounding box (Default: 0.1)
  89640. */
  89641. _this.rotationSphereSize = 0.1;
  89642. /**
  89643. * The size of the scale boxes attached to the bounding box (Default: 0.1)
  89644. */
  89645. _this.scaleBoxSize = 0.1;
  89646. /**
  89647. * If set, the rotation spheres and scale boxes will increase in size based on the distance away from the camera to have a consistent screen size (Default: false)
  89648. */
  89649. _this.fixedDragMeshScreenSize = false;
  89650. /**
  89651. * The distance away from the object which the draggable meshes should appear world sized when fixedDragMeshScreenSize is set to true (default: 10)
  89652. */
  89653. _this.fixedDragMeshScreenSizeDistanceFactor = 10;
  89654. /**
  89655. * Fired when a rotation sphere or scale box is dragged
  89656. */
  89657. _this.onDragStartObservable = new BABYLON.Observable();
  89658. /**
  89659. * Fired when a rotation sphere or scale box drag is started
  89660. */
  89661. _this.onDragObservable = new BABYLON.Observable();
  89662. /**
  89663. * Fired when a rotation sphere or scale box drag is needed
  89664. */
  89665. _this.onDragEndObservable = new BABYLON.Observable();
  89666. // Do not update the gizmo's scale so it has a fixed size to the object its attached to
  89667. _this._updateScale = false;
  89668. // Create Materials
  89669. var coloredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89670. coloredMaterial.disableLighting = true;
  89671. coloredMaterial.emissiveColor = color;
  89672. var hoverColoredMaterial = new BABYLON.StandardMaterial("", gizmoLayer.utilityLayerScene);
  89673. hoverColoredMaterial.disableLighting = true;
  89674. hoverColoredMaterial.emissiveColor = color.clone().add(new BABYLON.Color3(0.2, 0.2, 0.2));
  89675. // Build bounding box out of lines
  89676. _this._lineBoundingBox = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89677. _this._lineBoundingBox.rotationQuaternion = new BABYLON.Quaternion();
  89678. var lines = [];
  89679. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0)] }, gizmoLayer.utilityLayerScene));
  89680. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89681. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, 0), new BABYLON.Vector3(0, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89682. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89683. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, 0, 0), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89684. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89685. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, _this._boundingDimensions.y, 0), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89686. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89687. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(0, 0, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89688. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(0, _this._boundingDimensions.y, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89689. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, 0, _this._boundingDimensions.z)] }, gizmoLayer.utilityLayerScene));
  89690. lines.push(BABYLON.MeshBuilder.CreateLines("lines", { points: [new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, _this._boundingDimensions.z), new BABYLON.Vector3(_this._boundingDimensions.x, _this._boundingDimensions.y, 0)] }, gizmoLayer.utilityLayerScene));
  89691. lines.forEach(function (l) {
  89692. l.color = color;
  89693. l.position.addInPlace(new BABYLON.Vector3(-_this._boundingDimensions.x / 2, -_this._boundingDimensions.y / 2, -_this._boundingDimensions.z / 2));
  89694. l.isPickable = false;
  89695. _this._lineBoundingBox.addChild(l);
  89696. });
  89697. _this._rootMesh.addChild(_this._lineBoundingBox);
  89698. // Create rotation spheres
  89699. _this._rotateSpheresParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89700. _this._rotateSpheresParent.rotationQuaternion = new BABYLON.Quaternion();
  89701. var _loop_1 = function (i_1) {
  89702. var sphere = BABYLON.MeshBuilder.CreateSphere("", { diameter: 1 }, gizmoLayer.utilityLayerScene);
  89703. sphere.rotationQuaternion = new BABYLON.Quaternion();
  89704. sphere.material = coloredMaterial;
  89705. // Drag behavior
  89706. _dragBehavior = new BABYLON.PointerDragBehavior({});
  89707. _dragBehavior.moveAttached = false;
  89708. _dragBehavior.updateDragPlane = false;
  89709. sphere.addBehavior(_dragBehavior);
  89710. var startingTurnDirection = new BABYLON.Vector3(1, 0, 0);
  89711. var totalTurnAmountOfDrag = 0;
  89712. _dragBehavior.onDragStartObservable.add(function (event) {
  89713. startingTurnDirection.copyFrom(sphere.forward);
  89714. totalTurnAmountOfDrag = 0;
  89715. });
  89716. _dragBehavior.onDragObservable.add(function (event) {
  89717. _this.onDragObservable.notifyObservers({});
  89718. if (_this.attachedMesh) {
  89719. var worldDragDirection = startingTurnDirection;
  89720. // Project the world right on to the drag plane
  89721. var toSub = event.dragPlaneNormal.scale(BABYLON.Vector3.Dot(event.dragPlaneNormal, worldDragDirection));
  89722. var dragAxis = worldDragDirection.subtract(toSub).normalizeToNew();
  89723. // project drag delta on to the resulting drag axis and rotate based on that
  89724. var projectDist = -BABYLON.Vector3.Dot(dragAxis, event.delta);
  89725. // Rotate based on axis
  89726. if (!_this.attachedMesh.rotationQuaternion) {
  89727. _this.attachedMesh.rotationQuaternion = BABYLON.Quaternion.RotationYawPitchRoll(_this.attachedMesh.rotation.y, _this.attachedMesh.rotation.x, _this.attachedMesh.rotation.z);
  89728. }
  89729. // Do not allow the object to turn more than a full circle
  89730. totalTurnAmountOfDrag += projectDist;
  89731. if (Math.abs(totalTurnAmountOfDrag) <= 2 * Math.PI) {
  89732. if (i_1 >= 8) {
  89733. BABYLON.Quaternion.RotationYawPitchRollToRef(0, 0, projectDist, _this._tmpQuaternion);
  89734. }
  89735. else if (i_1 >= 4) {
  89736. BABYLON.Quaternion.RotationYawPitchRollToRef(projectDist, 0, 0, _this._tmpQuaternion);
  89737. }
  89738. else {
  89739. BABYLON.Quaternion.RotationYawPitchRollToRef(0, projectDist, 0, _this._tmpQuaternion);
  89740. }
  89741. _this.attachedMesh.rotationQuaternion.multiplyInPlace(_this._tmpQuaternion);
  89742. }
  89743. }
  89744. });
  89745. // Selection/deselection
  89746. _dragBehavior.onDragStartObservable.add(function () {
  89747. _this.onDragStartObservable.notifyObservers({});
  89748. _this._selectNode(sphere);
  89749. });
  89750. _dragBehavior.onDragEndObservable.add(function () {
  89751. _this.onDragEndObservable.notifyObservers({});
  89752. _this._selectNode(null);
  89753. });
  89754. this_1._rotateSpheresParent.addChild(sphere);
  89755. };
  89756. var this_1 = this, _dragBehavior;
  89757. for (var i_1 = 0; i_1 < 12; i_1++) {
  89758. _loop_1(i_1);
  89759. }
  89760. _this._rootMesh.addChild(_this._rotateSpheresParent);
  89761. // Create scale cubes
  89762. _this._scaleBoxesParent = new BABYLON.AbstractMesh("", gizmoLayer.utilityLayerScene);
  89763. _this._scaleBoxesParent.rotationQuaternion = new BABYLON.Quaternion();
  89764. for (var i = 0; i < 2; i++) {
  89765. for (var j = 0; j < 2; j++) {
  89766. var _loop_2 = function () {
  89767. var box = BABYLON.MeshBuilder.CreateBox("", { size: 1 }, gizmoLayer.utilityLayerScene);
  89768. box.material = coloredMaterial;
  89769. // Dragging logic
  89770. var dragAxis = new BABYLON.Vector3(i == 0 ? -1 : 1, j == 0 ? -1 : 1, k == 0 ? -1 : 1);
  89771. _dragBehavior = new BABYLON.PointerDragBehavior({ dragAxis: dragAxis });
  89772. _dragBehavior.moveAttached = false;
  89773. box.addBehavior(_dragBehavior);
  89774. _dragBehavior.onDragObservable.add(function (event) {
  89775. _this.onDragObservable.notifyObservers({});
  89776. if (_this.attachedMesh) {
  89777. // Current boudning box dimensions
  89778. var boundingInfo = _this.attachedMesh.getBoundingInfo().boundingBox;
  89779. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(_this.attachedMesh.scaling);
  89780. // Get the change in bounding box size/2 and add this to the mesh's position to offset from scaling with center pivot point
  89781. var deltaScale = new BABYLON.Vector3(event.dragDistance, event.dragDistance, event.dragDistance);
  89782. deltaScale.scaleInPlace(_this._scaleDragSpeed);
  89783. var scaleRatio = deltaScale.divide(_this.attachedMesh.scaling).scaleInPlace(0.5);
  89784. var moveDirection = boundBoxDimensions.multiply(scaleRatio).multiplyInPlace(dragAxis);
  89785. var worldMoveDirection = BABYLON.Vector3.TransformCoordinates(moveDirection, _this.attachedMesh.getWorldMatrix().getRotationMatrix());
  89786. // Update scale and position
  89787. _this.attachedMesh.scaling.addInPlace(deltaScale);
  89788. _this.attachedMesh.getAbsolutePosition().addToRef(worldMoveDirection, _this._tmpVector);
  89789. _this.attachedMesh.setAbsolutePosition(_this._tmpVector);
  89790. }
  89791. });
  89792. // Selection/deselection
  89793. _dragBehavior.onDragStartObservable.add(function () {
  89794. _this.onDragStartObservable.notifyObservers({});
  89795. _this._selectNode(box);
  89796. });
  89797. _dragBehavior.onDragEndObservable.add(function () {
  89798. _this.onDragEndObservable.notifyObservers({});
  89799. _this._selectNode(null);
  89800. });
  89801. this_2._scaleBoxesParent.addChild(box);
  89802. };
  89803. var this_2 = this, _dragBehavior;
  89804. for (var k = 0; k < 2; k++) {
  89805. _loop_2();
  89806. }
  89807. }
  89808. }
  89809. _this._rootMesh.addChild(_this._scaleBoxesParent);
  89810. // Hover color change
  89811. var pointerIds = new Array();
  89812. _this._pointerObserver = gizmoLayer.utilityLayerScene.onPointerObservable.add(function (pointerInfo, eventState) {
  89813. if (!pointerIds[pointerInfo.event.pointerId]) {
  89814. _this._rotateSpheresParent.getChildMeshes().concat(_this._scaleBoxesParent.getChildMeshes()).forEach(function (mesh) {
  89815. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh == mesh) {
  89816. pointerIds[pointerInfo.event.pointerId] = mesh;
  89817. mesh.material = hoverColoredMaterial;
  89818. }
  89819. });
  89820. }
  89821. else {
  89822. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh != pointerIds[pointerInfo.event.pointerId]) {
  89823. pointerIds[pointerInfo.event.pointerId].material = coloredMaterial;
  89824. delete pointerIds[pointerInfo.event.pointerId];
  89825. }
  89826. }
  89827. });
  89828. // Update bounding box positions
  89829. _this._renderObserver = _this.gizmoLayer.originalScene.onBeforeRenderObservable.add(function () {
  89830. _this._updateBoundingBox();
  89831. });
  89832. _this._updateBoundingBox();
  89833. return _this;
  89834. }
  89835. BoundingBoxGizmo.prototype._selectNode = function (selectedMesh) {
  89836. this._rotateSpheresParent.getChildMeshes()
  89837. .concat(this._scaleBoxesParent.getChildMeshes()).forEach(function (m, i) {
  89838. m.isVisible = (!selectedMesh || m == selectedMesh);
  89839. });
  89840. };
  89841. BoundingBoxGizmo.prototype._updateBoundingBox = function () {
  89842. if (this.attachedMesh) {
  89843. // Update bounding dimensions/positions
  89844. var boundingInfo = this.attachedMesh.getBoundingInfo().boundingBox;
  89845. var boundBoxDimensions = boundingInfo.maximum.subtract(boundingInfo.minimum).multiplyInPlace(this.attachedMesh.scaling);
  89846. this._boundingDimensions.copyFrom(boundBoxDimensions);
  89847. this._lineBoundingBox.scaling.copyFrom(this._boundingDimensions);
  89848. }
  89849. // Update rotation sphere locations
  89850. var rotateSpheres = this._rotateSpheresParent.getChildMeshes();
  89851. for (var i = 0; i < 3; i++) {
  89852. for (var j = 0; j < 2; j++) {
  89853. for (var k = 0; k < 2; k++) {
  89854. var index = ((i * 4) + (j * 2)) + k;
  89855. if (i == 0) {
  89856. rotateSpheres[index].position.set(this._boundingDimensions.x / 2, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89857. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89858. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Right(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89859. }
  89860. if (i == 1) {
  89861. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y / 2, this._boundingDimensions.z * k);
  89862. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89863. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Up(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89864. }
  89865. if (i == 2) {
  89866. rotateSpheres[index].position.set(this._boundingDimensions.x * j, this._boundingDimensions.y * k, this._boundingDimensions.z / 2);
  89867. rotateSpheres[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89868. rotateSpheres[index].lookAt(BABYLON.Vector3.Cross(BABYLON.Vector3.Forward(), rotateSpheres[index].position.normalizeToNew()).normalizeToNew().add(rotateSpheres[index].position));
  89869. }
  89870. if (this.fixedDragMeshScreenSize) {
  89871. rotateSpheres[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89872. var distanceFromCamera = this.rotationSphereSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89873. rotateSpheres[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89874. }
  89875. else {
  89876. rotateSpheres[index].scaling.set(this.rotationSphereSize, this.rotationSphereSize, this.rotationSphereSize);
  89877. }
  89878. }
  89879. }
  89880. }
  89881. // Update scale box locations
  89882. var scaleBoxes = this._scaleBoxesParent.getChildMeshes();
  89883. for (var i = 0; i < 2; i++) {
  89884. for (var j = 0; j < 2; j++) {
  89885. for (var k = 0; k < 2; k++) {
  89886. var index = ((i * 4) + (j * 2)) + k;
  89887. if (scaleBoxes[index]) {
  89888. scaleBoxes[index].position.set(this._boundingDimensions.x * i, this._boundingDimensions.y * j, this._boundingDimensions.z * k);
  89889. scaleBoxes[index].position.addInPlace(new BABYLON.Vector3(-this._boundingDimensions.x / 2, -this._boundingDimensions.y / 2, -this._boundingDimensions.z / 2));
  89890. if (this.fixedDragMeshScreenSize) {
  89891. scaleBoxes[index].absolutePosition.subtractToRef(this.gizmoLayer.utilityLayerScene.activeCamera.position, this._tmpVector);
  89892. var distanceFromCamera = this.scaleBoxSize * this._tmpVector.length() / this.fixedDragMeshScreenSizeDistanceFactor;
  89893. scaleBoxes[index].scaling.set(distanceFromCamera, distanceFromCamera, distanceFromCamera);
  89894. }
  89895. else {
  89896. scaleBoxes[index].scaling.set(this.scaleBoxSize, this.scaleBoxSize, this.scaleBoxSize);
  89897. }
  89898. }
  89899. }
  89900. }
  89901. }
  89902. };
  89903. /**
  89904. * Enables rotation on the specified axis and disables rotation on the others
  89905. * @param axis The list of axis that should be enabled (eg. "xy" or "xyz")
  89906. */
  89907. BoundingBoxGizmo.prototype.setEnabledRotationAxis = function (axis) {
  89908. this._rotateSpheresParent.getChildMeshes().forEach(function (m, i) {
  89909. if (i < 4) {
  89910. m.setEnabled(axis.indexOf("x") != -1);
  89911. }
  89912. else if (i < 8) {
  89913. m.setEnabled(axis.indexOf("y") != -1);
  89914. }
  89915. else {
  89916. m.setEnabled(axis.indexOf("z") != -1);
  89917. }
  89918. });
  89919. };
  89920. /**
  89921. * Disposes of the gizmo
  89922. */
  89923. BoundingBoxGizmo.prototype.dispose = function () {
  89924. this.gizmoLayer.utilityLayerScene.onPointerObservable.remove(this._pointerObserver);
  89925. this.gizmoLayer.originalScene.onBeforeRenderObservable.remove(this._renderObserver);
  89926. this._lineBoundingBox.dispose();
  89927. this._rotateSpheresParent.dispose();
  89928. this._scaleBoxesParent.dispose();
  89929. _super.prototype.dispose.call(this);
  89930. };
  89931. return BoundingBoxGizmo;
  89932. }(BABYLON.Gizmo));
  89933. BABYLON.BoundingBoxGizmo = BoundingBoxGizmo;
  89934. })(BABYLON || (BABYLON = {}));
  89935. //# sourceMappingURL=babylon.boundingBoxGizmo.js.map
  89936. var BABYLON;
  89937. (function (BABYLON) {
  89938. /**
  89939. * Helps setup gizmo's in the scene to rotate/scale/position meshes
  89940. */
  89941. var GizmoManager = /** @class */ (function () {
  89942. /**
  89943. * Instatiates a gizmo manager
  89944. * @param scene the scene to overlay the gizmos on top of
  89945. * @param options If only a single gizmo should exist at one time
  89946. */
  89947. function GizmoManager(scene, options) {
  89948. var _this = this;
  89949. this.scene = scene;
  89950. // Set of gizmos that are currently in the scene for each mesh
  89951. this._gizmoSet = {};
  89952. this._pointerObserver = null;
  89953. this._gizmoLayer = new BABYLON.UtilityLayerRenderer(scene);
  89954. // Options parsing
  89955. if (!options) {
  89956. options = {};
  89957. }
  89958. if (options.singleGizmo === undefined) {
  89959. options.singleGizmo = true;
  89960. }
  89961. // Instatiate/dispose gizmos based on pointer actions
  89962. this._pointerObserver = scene.onPointerObservable.add(function (pointerInfo, state) {
  89963. if (pointerInfo.type == BABYLON.PointerEventTypes.POINTERDOWN) {
  89964. if (pointerInfo.pickInfo && pointerInfo.pickInfo.pickedMesh) {
  89965. if (!_this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId]) {
  89966. if (options.singleGizmo) {
  89967. _this._clearGizmos();
  89968. }
  89969. // Enable gizmo when mesh is selected
  89970. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId] = { positionGizmo: new BABYLON.PositionGizmo(_this._gizmoLayer), rotationGizmo: new BABYLON.RotationGizmo(_this._gizmoLayer) };
  89971. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89972. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.attachedMesh = pointerInfo.pickInfo.pickedMesh;
  89973. }
  89974. else {
  89975. if (!options.singleGizmo) {
  89976. // Disable gizmo when clicked again
  89977. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].positionGizmo.dispose();
  89978. _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId].rotationGizmo.dispose();
  89979. delete _this._gizmoSet[pointerInfo.pickInfo.pickedMesh.uniqueId];
  89980. }
  89981. }
  89982. }
  89983. else {
  89984. if (options.singleGizmo) {
  89985. // Disable gizmo when clicked away
  89986. if (pointerInfo.pickInfo && pointerInfo.pickInfo.ray) {
  89987. var gizmoPick = _this._gizmoLayer.utilityLayerScene.pickWithRay(pointerInfo.pickInfo.ray);
  89988. if (gizmoPick && !gizmoPick.hit) {
  89989. _this._clearGizmos();
  89990. }
  89991. }
  89992. }
  89993. }
  89994. }
  89995. });
  89996. }
  89997. /**
  89998. * Disposes of the gizmo manager
  89999. */
  90000. GizmoManager.prototype.dispose = function () {
  90001. this.scene.onPointerObservable.remove(this._pointerObserver);
  90002. this._clearGizmos();
  90003. this._gizmoLayer.dispose();
  90004. };
  90005. GizmoManager.prototype._clearGizmos = function () {
  90006. for (var key in this._gizmoSet) {
  90007. if (this._gizmoSet.hasOwnProperty(key)) {
  90008. this._gizmoSet[key].positionGizmo.dispose();
  90009. this._gizmoSet[key].rotationGizmo.dispose();
  90010. delete this._gizmoSet[key];
  90011. }
  90012. }
  90013. };
  90014. return GizmoManager;
  90015. }());
  90016. BABYLON.GizmoManager = GizmoManager;
  90017. })(BABYLON || (BABYLON = {}));
  90018. //# sourceMappingURL=babylon.gizmoManager.js.map
  90019. var BABYLON;
  90020. (function (BABYLON) {
  90021. /**
  90022. * Defines a target to use with MorphTargetManager
  90023. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90024. */
  90025. var MorphTarget = /** @class */ (function () {
  90026. /**
  90027. * Creates a new MorphTarget
  90028. * @param name defines the name of the target
  90029. * @param influence defines the influence to use
  90030. */
  90031. function MorphTarget(
  90032. /** defines the name of the target */
  90033. name, influence, scene) {
  90034. if (influence === void 0) { influence = 0; }
  90035. if (scene === void 0) { scene = null; }
  90036. this.name = name;
  90037. /**
  90038. * Gets or sets the list of animations
  90039. */
  90040. this.animations = new Array();
  90041. this._positions = null;
  90042. this._normals = null;
  90043. this._tangents = null;
  90044. /**
  90045. * Observable raised when the influence changes
  90046. */
  90047. this.onInfluenceChanged = new BABYLON.Observable();
  90048. this._animationPropertiesOverride = null;
  90049. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  90050. this.influence = influence;
  90051. }
  90052. Object.defineProperty(MorphTarget.prototype, "influence", {
  90053. /**
  90054. * Gets or sets the influence of this target (ie. its weight in the overall morphing)
  90055. */
  90056. get: function () {
  90057. return this._influence;
  90058. },
  90059. set: function (influence) {
  90060. if (this._influence === influence) {
  90061. return;
  90062. }
  90063. var previous = this._influence;
  90064. this._influence = influence;
  90065. if (this.onInfluenceChanged.hasObservers) {
  90066. this.onInfluenceChanged.notifyObservers(previous === 0 || influence === 0);
  90067. }
  90068. },
  90069. enumerable: true,
  90070. configurable: true
  90071. });
  90072. Object.defineProperty(MorphTarget.prototype, "animationPropertiesOverride", {
  90073. /**
  90074. * Gets or sets the animation properties override
  90075. */
  90076. get: function () {
  90077. if (!this._animationPropertiesOverride && this._scene) {
  90078. return this._scene.animationPropertiesOverride;
  90079. }
  90080. return this._animationPropertiesOverride;
  90081. },
  90082. set: function (value) {
  90083. this._animationPropertiesOverride = value;
  90084. },
  90085. enumerable: true,
  90086. configurable: true
  90087. });
  90088. Object.defineProperty(MorphTarget.prototype, "hasPositions", {
  90089. /**
  90090. * Gets a boolean defining if the target contains position data
  90091. */
  90092. get: function () {
  90093. return !!this._positions;
  90094. },
  90095. enumerable: true,
  90096. configurable: true
  90097. });
  90098. Object.defineProperty(MorphTarget.prototype, "hasNormals", {
  90099. /**
  90100. * Gets a boolean defining if the target contains normal data
  90101. */
  90102. get: function () {
  90103. return !!this._normals;
  90104. },
  90105. enumerable: true,
  90106. configurable: true
  90107. });
  90108. Object.defineProperty(MorphTarget.prototype, "hasTangents", {
  90109. /**
  90110. * Gets a boolean defining if the target contains tangent data
  90111. */
  90112. get: function () {
  90113. return !!this._tangents;
  90114. },
  90115. enumerable: true,
  90116. configurable: true
  90117. });
  90118. /**
  90119. * Affects position data to this target
  90120. * @param data defines the position data to use
  90121. */
  90122. MorphTarget.prototype.setPositions = function (data) {
  90123. this._positions = data;
  90124. };
  90125. /**
  90126. * Gets the position data stored in this target
  90127. * @returns a FloatArray containing the position data (or null if not present)
  90128. */
  90129. MorphTarget.prototype.getPositions = function () {
  90130. return this._positions;
  90131. };
  90132. /**
  90133. * Affects normal data to this target
  90134. * @param data defines the normal data to use
  90135. */
  90136. MorphTarget.prototype.setNormals = function (data) {
  90137. this._normals = data;
  90138. };
  90139. /**
  90140. * Gets the normal data stored in this target
  90141. * @returns a FloatArray containing the normal data (or null if not present)
  90142. */
  90143. MorphTarget.prototype.getNormals = function () {
  90144. return this._normals;
  90145. };
  90146. /**
  90147. * Affects tangent data to this target
  90148. * @param data defines the tangent data to use
  90149. */
  90150. MorphTarget.prototype.setTangents = function (data) {
  90151. this._tangents = data;
  90152. };
  90153. /**
  90154. * Gets the tangent data stored in this target
  90155. * @returns a FloatArray containing the tangent data (or null if not present)
  90156. */
  90157. MorphTarget.prototype.getTangents = function () {
  90158. return this._tangents;
  90159. };
  90160. /**
  90161. * Serializes the current target into a Serialization object
  90162. * @returns the serialized object
  90163. */
  90164. MorphTarget.prototype.serialize = function () {
  90165. var serializationObject = {};
  90166. serializationObject.name = this.name;
  90167. serializationObject.influence = this.influence;
  90168. serializationObject.positions = Array.prototype.slice.call(this.getPositions());
  90169. if (this.hasNormals) {
  90170. serializationObject.normals = Array.prototype.slice.call(this.getNormals());
  90171. }
  90172. if (this.hasTangents) {
  90173. serializationObject.tangents = Array.prototype.slice.call(this.getTangents());
  90174. }
  90175. // Animations
  90176. BABYLON.Animation.AppendSerializedAnimations(this, serializationObject);
  90177. return serializationObject;
  90178. };
  90179. // Statics
  90180. /**
  90181. * Creates a new target from serialized data
  90182. * @param serializationObject defines the serialized data to use
  90183. * @returns a new MorphTarget
  90184. */
  90185. MorphTarget.Parse = function (serializationObject) {
  90186. var result = new MorphTarget(serializationObject.name, serializationObject.influence);
  90187. result.setPositions(serializationObject.positions);
  90188. if (serializationObject.normals) {
  90189. result.setNormals(serializationObject.normals);
  90190. }
  90191. if (serializationObject.tangents) {
  90192. result.setTangents(serializationObject.tangents);
  90193. }
  90194. // Animations
  90195. if (serializationObject.animations) {
  90196. for (var animationIndex = 0; animationIndex < serializationObject.animations.length; animationIndex++) {
  90197. var parsedAnimation = serializationObject.animations[animationIndex];
  90198. result.animations.push(BABYLON.Animation.Parse(parsedAnimation));
  90199. }
  90200. }
  90201. return result;
  90202. };
  90203. /**
  90204. * Creates a MorphTarget from mesh data
  90205. * @param mesh defines the source mesh
  90206. * @param name defines the name to use for the new target
  90207. * @param influence defines the influence to attach to the target
  90208. * @returns a new MorphTarget
  90209. */
  90210. MorphTarget.FromMesh = function (mesh, name, influence) {
  90211. if (!name) {
  90212. name = mesh.name;
  90213. }
  90214. var result = new MorphTarget(name, influence, mesh.getScene());
  90215. result.setPositions(mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind));
  90216. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  90217. result.setNormals(mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind));
  90218. }
  90219. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.TangentKind)) {
  90220. result.setTangents(mesh.getVerticesData(BABYLON.VertexBuffer.TangentKind));
  90221. }
  90222. return result;
  90223. };
  90224. return MorphTarget;
  90225. }());
  90226. BABYLON.MorphTarget = MorphTarget;
  90227. })(BABYLON || (BABYLON = {}));
  90228. //# sourceMappingURL=babylon.morphTarget.js.map
  90229. var BABYLON;
  90230. (function (BABYLON) {
  90231. /**
  90232. * This class is used to deform meshes using morphing between different targets
  90233. * @see http://doc.babylonjs.com/how_to/how_to_use_morphtargets
  90234. */
  90235. var MorphTargetManager = /** @class */ (function () {
  90236. /**
  90237. * Creates a new MorphTargetManager
  90238. * @param scene defines the current scene
  90239. */
  90240. function MorphTargetManager(scene) {
  90241. if (scene === void 0) { scene = null; }
  90242. this._targets = new Array();
  90243. this._targetObservable = new Array();
  90244. this._activeTargets = new BABYLON.SmartArray(16);
  90245. this._supportsNormals = false;
  90246. this._supportsTangents = false;
  90247. this._vertexCount = 0;
  90248. this._uniqueId = 0;
  90249. this._tempInfluences = new Array();
  90250. if (!scene) {
  90251. scene = BABYLON.Engine.LastCreatedScene;
  90252. }
  90253. this._scene = scene;
  90254. if (this._scene) {
  90255. this._scene.morphTargetManagers.push(this);
  90256. this._uniqueId = this._scene.getUniqueId();
  90257. }
  90258. }
  90259. Object.defineProperty(MorphTargetManager.prototype, "uniqueId", {
  90260. /**
  90261. * Gets the unique ID of this manager
  90262. */
  90263. get: function () {
  90264. return this._uniqueId;
  90265. },
  90266. enumerable: true,
  90267. configurable: true
  90268. });
  90269. Object.defineProperty(MorphTargetManager.prototype, "vertexCount", {
  90270. /**
  90271. * Gets the number of vertices handled by this manager
  90272. */
  90273. get: function () {
  90274. return this._vertexCount;
  90275. },
  90276. enumerable: true,
  90277. configurable: true
  90278. });
  90279. Object.defineProperty(MorphTargetManager.prototype, "supportsNormals", {
  90280. /**
  90281. * Gets a boolean indicating if this manager supports morphing of normals
  90282. */
  90283. get: function () {
  90284. return this._supportsNormals;
  90285. },
  90286. enumerable: true,
  90287. configurable: true
  90288. });
  90289. Object.defineProperty(MorphTargetManager.prototype, "supportsTangents", {
  90290. /**
  90291. * Gets a boolean indicating if this manager supports morphing of tangents
  90292. */
  90293. get: function () {
  90294. return this._supportsTangents;
  90295. },
  90296. enumerable: true,
  90297. configurable: true
  90298. });
  90299. Object.defineProperty(MorphTargetManager.prototype, "numTargets", {
  90300. /**
  90301. * Gets the number of targets stored in this manager
  90302. */
  90303. get: function () {
  90304. return this._targets.length;
  90305. },
  90306. enumerable: true,
  90307. configurable: true
  90308. });
  90309. Object.defineProperty(MorphTargetManager.prototype, "numInfluencers", {
  90310. /**
  90311. * Gets the number of influencers (ie. the number of targets with influences > 0)
  90312. */
  90313. get: function () {
  90314. return this._activeTargets.length;
  90315. },
  90316. enumerable: true,
  90317. configurable: true
  90318. });
  90319. Object.defineProperty(MorphTargetManager.prototype, "influences", {
  90320. /**
  90321. * Gets the list of influences (one per target)
  90322. */
  90323. get: function () {
  90324. return this._influences;
  90325. },
  90326. enumerable: true,
  90327. configurable: true
  90328. });
  90329. /**
  90330. * Gets the active target at specified index. An active target is a target with an influence > 0
  90331. * @param index defines the index to check
  90332. * @returns the requested target
  90333. */
  90334. MorphTargetManager.prototype.getActiveTarget = function (index) {
  90335. return this._activeTargets.data[index];
  90336. };
  90337. /**
  90338. * Gets the target at specified index
  90339. * @param index defines the index to check
  90340. * @returns the requested target
  90341. */
  90342. MorphTargetManager.prototype.getTarget = function (index) {
  90343. return this._targets[index];
  90344. };
  90345. /**
  90346. * Add a new target to this manager
  90347. * @param target defines the target to add
  90348. */
  90349. MorphTargetManager.prototype.addTarget = function (target) {
  90350. var _this = this;
  90351. this._targets.push(target);
  90352. this._targetObservable.push(target.onInfluenceChanged.add(function (needUpdate) {
  90353. _this._syncActiveTargets(needUpdate);
  90354. }));
  90355. this._syncActiveTargets(true);
  90356. };
  90357. /**
  90358. * Removes a target from the manager
  90359. * @param target defines the target to remove
  90360. */
  90361. MorphTargetManager.prototype.removeTarget = function (target) {
  90362. var index = this._targets.indexOf(target);
  90363. if (index >= 0) {
  90364. this._targets.splice(index, 1);
  90365. target.onInfluenceChanged.remove(this._targetObservable.splice(index, 1)[0]);
  90366. this._syncActiveTargets(true);
  90367. }
  90368. };
  90369. /**
  90370. * Serializes the current manager into a Serialization object
  90371. * @returns the serialized object
  90372. */
  90373. MorphTargetManager.prototype.serialize = function () {
  90374. var serializationObject = {};
  90375. serializationObject.id = this.uniqueId;
  90376. serializationObject.targets = [];
  90377. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90378. var target = _a[_i];
  90379. serializationObject.targets.push(target.serialize());
  90380. }
  90381. return serializationObject;
  90382. };
  90383. MorphTargetManager.prototype._syncActiveTargets = function (needUpdate) {
  90384. var influenceCount = 0;
  90385. this._activeTargets.reset();
  90386. this._supportsNormals = true;
  90387. this._supportsTangents = true;
  90388. this._vertexCount = 0;
  90389. for (var _i = 0, _a = this._targets; _i < _a.length; _i++) {
  90390. var target = _a[_i];
  90391. this._activeTargets.push(target);
  90392. this._tempInfluences[influenceCount++] = target.influence;
  90393. var positions = target.getPositions();
  90394. if (positions) {
  90395. this._supportsNormals = this._supportsNormals && target.hasNormals;
  90396. this._supportsTangents = this._supportsTangents && target.hasTangents;
  90397. var vertexCount = positions.length / 3;
  90398. if (this._vertexCount === 0) {
  90399. this._vertexCount = vertexCount;
  90400. }
  90401. else if (this._vertexCount !== vertexCount) {
  90402. BABYLON.Tools.Error("Incompatible target. Targets must all have the same vertices count.");
  90403. return;
  90404. }
  90405. }
  90406. }
  90407. if (!this._influences || this._influences.length !== influenceCount) {
  90408. this._influences = new Float32Array(influenceCount);
  90409. }
  90410. for (var index = 0; index < influenceCount; index++) {
  90411. this._influences[index] = this._tempInfluences[index];
  90412. }
  90413. if (needUpdate) {
  90414. this.synchronize();
  90415. }
  90416. };
  90417. /**
  90418. * Syncrhonize the targets with all the meshes using this morph target manager
  90419. */
  90420. MorphTargetManager.prototype.synchronize = function () {
  90421. if (!this._scene) {
  90422. return;
  90423. }
  90424. // Flag meshes as dirty to resync with the active targets
  90425. for (var _i = 0, _a = this._scene.meshes; _i < _a.length; _i++) {
  90426. var mesh = _a[_i];
  90427. if (mesh.morphTargetManager === this) {
  90428. mesh._syncGeometryWithMorphTargetManager();
  90429. }
  90430. }
  90431. };
  90432. // Statics
  90433. /**
  90434. * Creates a new MorphTargetManager from serialized data
  90435. * @param serializationObject defines the serialized data
  90436. * @param scene defines the hosting scene
  90437. * @returns the new MorphTargetManager
  90438. */
  90439. MorphTargetManager.Parse = function (serializationObject, scene) {
  90440. var result = new MorphTargetManager(scene);
  90441. result._uniqueId = serializationObject.id;
  90442. for (var _i = 0, _a = serializationObject.targets; _i < _a.length; _i++) {
  90443. var targetData = _a[_i];
  90444. result.addTarget(BABYLON.MorphTarget.Parse(targetData));
  90445. }
  90446. return result;
  90447. };
  90448. return MorphTargetManager;
  90449. }());
  90450. BABYLON.MorphTargetManager = MorphTargetManager;
  90451. })(BABYLON || (BABYLON = {}));
  90452. //# sourceMappingURL=babylon.morphTargetManager.js.map
  90453. var BABYLON;
  90454. (function (BABYLON) {
  90455. var Octree = /** @class */ (function () {
  90456. function Octree(creationFunc, maxBlockCapacity, maxDepth) {
  90457. if (maxDepth === void 0) { maxDepth = 2; }
  90458. this.maxDepth = maxDepth;
  90459. this.dynamicContent = new Array();
  90460. this._maxBlockCapacity = maxBlockCapacity || 64;
  90461. this._selectionContent = new BABYLON.SmartArrayNoDuplicate(1024);
  90462. this._creationFunc = creationFunc;
  90463. }
  90464. // Methods
  90465. Octree.prototype.update = function (worldMin, worldMax, entries) {
  90466. Octree._CreateBlocks(worldMin, worldMax, entries, this._maxBlockCapacity, 0, this.maxDepth, this, this._creationFunc);
  90467. };
  90468. Octree.prototype.addMesh = function (entry) {
  90469. for (var index = 0; index < this.blocks.length; index++) {
  90470. var block = this.blocks[index];
  90471. block.addEntry(entry);
  90472. }
  90473. };
  90474. Octree.prototype.select = function (frustumPlanes, allowDuplicate) {
  90475. this._selectionContent.reset();
  90476. for (var index = 0; index < this.blocks.length; index++) {
  90477. var block = this.blocks[index];
  90478. block.select(frustumPlanes, this._selectionContent, allowDuplicate);
  90479. }
  90480. if (allowDuplicate) {
  90481. this._selectionContent.concat(this.dynamicContent);
  90482. }
  90483. else {
  90484. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90485. }
  90486. return this._selectionContent;
  90487. };
  90488. Octree.prototype.intersects = function (sphereCenter, sphereRadius, allowDuplicate) {
  90489. this._selectionContent.reset();
  90490. for (var index = 0; index < this.blocks.length; index++) {
  90491. var block = this.blocks[index];
  90492. block.intersects(sphereCenter, sphereRadius, this._selectionContent, allowDuplicate);
  90493. }
  90494. if (allowDuplicate) {
  90495. this._selectionContent.concat(this.dynamicContent);
  90496. }
  90497. else {
  90498. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90499. }
  90500. return this._selectionContent;
  90501. };
  90502. Octree.prototype.intersectsRay = function (ray) {
  90503. this._selectionContent.reset();
  90504. for (var index = 0; index < this.blocks.length; index++) {
  90505. var block = this.blocks[index];
  90506. block.intersectsRay(ray, this._selectionContent);
  90507. }
  90508. this._selectionContent.concatWithNoDuplicate(this.dynamicContent);
  90509. return this._selectionContent;
  90510. };
  90511. Octree._CreateBlocks = function (worldMin, worldMax, entries, maxBlockCapacity, currentDepth, maxDepth, target, creationFunc) {
  90512. target.blocks = new Array();
  90513. var blockSize = new BABYLON.Vector3((worldMax.x - worldMin.x) / 2, (worldMax.y - worldMin.y) / 2, (worldMax.z - worldMin.z) / 2);
  90514. // Segmenting space
  90515. for (var x = 0; x < 2; x++) {
  90516. for (var y = 0; y < 2; y++) {
  90517. for (var z = 0; z < 2; z++) {
  90518. var localMin = worldMin.add(blockSize.multiplyByFloats(x, y, z));
  90519. var localMax = worldMin.add(blockSize.multiplyByFloats(x + 1, y + 1, z + 1));
  90520. var block = new BABYLON.OctreeBlock(localMin, localMax, maxBlockCapacity, currentDepth + 1, maxDepth, creationFunc);
  90521. block.addEntries(entries);
  90522. target.blocks.push(block);
  90523. }
  90524. }
  90525. }
  90526. };
  90527. Octree.CreationFuncForMeshes = function (entry, block) {
  90528. var boundingInfo = entry.getBoundingInfo();
  90529. if (!entry.isBlocked && boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90530. block.entries.push(entry);
  90531. }
  90532. };
  90533. Octree.CreationFuncForSubMeshes = function (entry, block) {
  90534. var boundingInfo = entry.getBoundingInfo();
  90535. if (boundingInfo.boundingBox.intersectsMinMax(block.minPoint, block.maxPoint)) {
  90536. block.entries.push(entry);
  90537. }
  90538. };
  90539. return Octree;
  90540. }());
  90541. BABYLON.Octree = Octree;
  90542. })(BABYLON || (BABYLON = {}));
  90543. //# sourceMappingURL=babylon.octree.js.map
  90544. var BABYLON;
  90545. (function (BABYLON) {
  90546. var OctreeBlock = /** @class */ (function () {
  90547. function OctreeBlock(minPoint, maxPoint, capacity, depth, maxDepth, creationFunc) {
  90548. this.entries = new Array();
  90549. this._boundingVectors = new Array();
  90550. this._capacity = capacity;
  90551. this._depth = depth;
  90552. this._maxDepth = maxDepth;
  90553. this._creationFunc = creationFunc;
  90554. this._minPoint = minPoint;
  90555. this._maxPoint = maxPoint;
  90556. this._boundingVectors.push(minPoint.clone());
  90557. this._boundingVectors.push(maxPoint.clone());
  90558. this._boundingVectors.push(minPoint.clone());
  90559. this._boundingVectors[2].x = maxPoint.x;
  90560. this._boundingVectors.push(minPoint.clone());
  90561. this._boundingVectors[3].y = maxPoint.y;
  90562. this._boundingVectors.push(minPoint.clone());
  90563. this._boundingVectors[4].z = maxPoint.z;
  90564. this._boundingVectors.push(maxPoint.clone());
  90565. this._boundingVectors[5].z = minPoint.z;
  90566. this._boundingVectors.push(maxPoint.clone());
  90567. this._boundingVectors[6].x = minPoint.x;
  90568. this._boundingVectors.push(maxPoint.clone());
  90569. this._boundingVectors[7].y = minPoint.y;
  90570. }
  90571. Object.defineProperty(OctreeBlock.prototype, "capacity", {
  90572. // Property
  90573. get: function () {
  90574. return this._capacity;
  90575. },
  90576. enumerable: true,
  90577. configurable: true
  90578. });
  90579. Object.defineProperty(OctreeBlock.prototype, "minPoint", {
  90580. get: function () {
  90581. return this._minPoint;
  90582. },
  90583. enumerable: true,
  90584. configurable: true
  90585. });
  90586. Object.defineProperty(OctreeBlock.prototype, "maxPoint", {
  90587. get: function () {
  90588. return this._maxPoint;
  90589. },
  90590. enumerable: true,
  90591. configurable: true
  90592. });
  90593. // Methods
  90594. OctreeBlock.prototype.addEntry = function (entry) {
  90595. if (this.blocks) {
  90596. for (var index = 0; index < this.blocks.length; index++) {
  90597. var block = this.blocks[index];
  90598. block.addEntry(entry);
  90599. }
  90600. return;
  90601. }
  90602. this._creationFunc(entry, this);
  90603. if (this.entries.length > this.capacity && this._depth < this._maxDepth) {
  90604. this.createInnerBlocks();
  90605. }
  90606. };
  90607. OctreeBlock.prototype.addEntries = function (entries) {
  90608. for (var index = 0; index < entries.length; index++) {
  90609. var mesh = entries[index];
  90610. this.addEntry(mesh);
  90611. }
  90612. };
  90613. OctreeBlock.prototype.select = function (frustumPlanes, selection, allowDuplicate) {
  90614. if (BABYLON.BoundingBox.IsInFrustum(this._boundingVectors, frustumPlanes)) {
  90615. if (this.blocks) {
  90616. for (var index = 0; index < this.blocks.length; index++) {
  90617. var block = this.blocks[index];
  90618. block.select(frustumPlanes, selection, allowDuplicate);
  90619. }
  90620. return;
  90621. }
  90622. if (allowDuplicate) {
  90623. selection.concat(this.entries);
  90624. }
  90625. else {
  90626. selection.concatWithNoDuplicate(this.entries);
  90627. }
  90628. }
  90629. };
  90630. OctreeBlock.prototype.intersects = function (sphereCenter, sphereRadius, selection, allowDuplicate) {
  90631. if (BABYLON.BoundingBox.IntersectsSphere(this._minPoint, this._maxPoint, sphereCenter, sphereRadius)) {
  90632. if (this.blocks) {
  90633. for (var index = 0; index < this.blocks.length; index++) {
  90634. var block = this.blocks[index];
  90635. block.intersects(sphereCenter, sphereRadius, selection, allowDuplicate);
  90636. }
  90637. return;
  90638. }
  90639. if (allowDuplicate) {
  90640. selection.concat(this.entries);
  90641. }
  90642. else {
  90643. selection.concatWithNoDuplicate(this.entries);
  90644. }
  90645. }
  90646. };
  90647. OctreeBlock.prototype.intersectsRay = function (ray, selection) {
  90648. if (ray.intersectsBoxMinMax(this._minPoint, this._maxPoint)) {
  90649. if (this.blocks) {
  90650. for (var index = 0; index < this.blocks.length; index++) {
  90651. var block = this.blocks[index];
  90652. block.intersectsRay(ray, selection);
  90653. }
  90654. return;
  90655. }
  90656. selection.concatWithNoDuplicate(this.entries);
  90657. }
  90658. };
  90659. OctreeBlock.prototype.createInnerBlocks = function () {
  90660. BABYLON.Octree._CreateBlocks(this._minPoint, this._maxPoint, this.entries, this._capacity, this._depth, this._maxDepth, this, this._creationFunc);
  90661. };
  90662. return OctreeBlock;
  90663. }());
  90664. BABYLON.OctreeBlock = OctreeBlock;
  90665. })(BABYLON || (BABYLON = {}));
  90666. //# sourceMappingURL=babylon.octreeBlock.js.map
  90667. var BABYLON;
  90668. (function (BABYLON) {
  90669. var VRDistortionCorrectionPostProcess = /** @class */ (function (_super) {
  90670. __extends(VRDistortionCorrectionPostProcess, _super);
  90671. function VRDistortionCorrectionPostProcess(name, camera, isRightEye, vrMetrics) {
  90672. var _this = _super.call(this, name, "vrDistortionCorrection", [
  90673. 'LensCenter',
  90674. 'Scale',
  90675. 'ScaleIn',
  90676. 'HmdWarpParam'
  90677. ], null, vrMetrics.postProcessScaleFactor, camera, BABYLON.Texture.BILINEAR_SAMPLINGMODE) || this;
  90678. _this._isRightEye = isRightEye;
  90679. _this._distortionFactors = vrMetrics.distortionK;
  90680. _this._postProcessScaleFactor = vrMetrics.postProcessScaleFactor;
  90681. _this._lensCenterOffset = vrMetrics.lensCenterOffset;
  90682. _this.adaptScaleToCurrentViewport = true;
  90683. _this.onSizeChangedObservable.add(function () {
  90684. _this._scaleIn = new BABYLON.Vector2(2, 2 / _this.aspectRatio);
  90685. _this._scaleFactor = new BABYLON.Vector2(.5 * (1 / _this._postProcessScaleFactor), .5 * (1 / _this._postProcessScaleFactor) * _this.aspectRatio);
  90686. _this._lensCenter = new BABYLON.Vector2(_this._isRightEye ? 0.5 - _this._lensCenterOffset * 0.5 : 0.5 + _this._lensCenterOffset * 0.5, 0.5);
  90687. });
  90688. _this.onApplyObservable.add(function (effect) {
  90689. effect.setFloat2("LensCenter", _this._lensCenter.x, _this._lensCenter.y);
  90690. effect.setFloat2("Scale", _this._scaleFactor.x, _this._scaleFactor.y);
  90691. effect.setFloat2("ScaleIn", _this._scaleIn.x, _this._scaleIn.y);
  90692. effect.setFloat4("HmdWarpParam", _this._distortionFactors[0], _this._distortionFactors[1], _this._distortionFactors[2], _this._distortionFactors[3]);
  90693. });
  90694. return _this;
  90695. }
  90696. return VRDistortionCorrectionPostProcess;
  90697. }(BABYLON.PostProcess));
  90698. BABYLON.VRDistortionCorrectionPostProcess = VRDistortionCorrectionPostProcess;
  90699. })(BABYLON || (BABYLON = {}));
  90700. //# sourceMappingURL=babylon.vrDistortionCorrectionPostProcess.js.map
  90701. var BABYLON;
  90702. (function (BABYLON) {
  90703. /**
  90704. * Postprocess used to generate anaglyphic rendering
  90705. */
  90706. var AnaglyphPostProcess = /** @class */ (function (_super) {
  90707. __extends(AnaglyphPostProcess, _super);
  90708. /**
  90709. * Creates a new AnaglyphPostProcess
  90710. * @param name defines postprocess name
  90711. * @param options defines creation options or target ratio scale
  90712. * @param rigCameras defines cameras using this postprocess
  90713. * @param samplingMode defines required sampling mode (BABYLON.Texture.NEAREST_SAMPLINGMODE by default)
  90714. * @param engine defines hosting engine
  90715. * @param reusable defines if the postprocess will be reused multiple times per frame
  90716. */
  90717. function AnaglyphPostProcess(name, options, rigCameras, samplingMode, engine, reusable) {
  90718. var _this = _super.call(this, name, "anaglyph", null, ["leftSampler"], options, rigCameras[1], samplingMode, engine, reusable) || this;
  90719. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90720. _this.onApplyObservable.add(function (effect) {
  90721. effect.setTextureFromPostProcess("leftSampler", _this._passedProcess);
  90722. });
  90723. return _this;
  90724. }
  90725. return AnaglyphPostProcess;
  90726. }(BABYLON.PostProcess));
  90727. BABYLON.AnaglyphPostProcess = AnaglyphPostProcess;
  90728. })(BABYLON || (BABYLON = {}));
  90729. //# sourceMappingURL=babylon.anaglyphPostProcess.js.map
  90730. var BABYLON;
  90731. (function (BABYLON) {
  90732. var StereoscopicInterlacePostProcess = /** @class */ (function (_super) {
  90733. __extends(StereoscopicInterlacePostProcess, _super);
  90734. function StereoscopicInterlacePostProcess(name, rigCameras, isStereoscopicHoriz, samplingMode, engine, reusable) {
  90735. var _this = _super.call(this, name, "stereoscopicInterlace", ['stepSize'], ['camASampler'], 1, rigCameras[1], samplingMode, engine, reusable, isStereoscopicHoriz ? "#define IS_STEREOSCOPIC_HORIZ 1" : undefined) || this;
  90736. _this._passedProcess = rigCameras[0]._rigPostProcess;
  90737. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90738. _this.onSizeChangedObservable.add(function () {
  90739. _this._stepSize = new BABYLON.Vector2(1 / _this.width, 1 / _this.height);
  90740. });
  90741. _this.onApplyObservable.add(function (effect) {
  90742. effect.setTextureFromPostProcess("camASampler", _this._passedProcess);
  90743. effect.setFloat2("stepSize", _this._stepSize.x, _this._stepSize.y);
  90744. });
  90745. return _this;
  90746. }
  90747. return StereoscopicInterlacePostProcess;
  90748. }(BABYLON.PostProcess));
  90749. BABYLON.StereoscopicInterlacePostProcess = StereoscopicInterlacePostProcess;
  90750. })(BABYLON || (BABYLON = {}));
  90751. //# sourceMappingURL=babylon.stereoscopicInterlacePostProcess.js.map
  90752. var BABYLON;
  90753. (function (BABYLON) {
  90754. /**
  90755. * Takes information about the orientation of the device as reported by the deviceorientation event to orient the camera.
  90756. * Screen rotation is taken into account.
  90757. */
  90758. var FreeCameraDeviceOrientationInput = /** @class */ (function () {
  90759. function FreeCameraDeviceOrientationInput() {
  90760. var _this = this;
  90761. this._screenOrientationAngle = 0;
  90762. this._screenQuaternion = new BABYLON.Quaternion();
  90763. this._alpha = 0;
  90764. this._beta = 0;
  90765. this._gamma = 0;
  90766. this._orientationChanged = function () {
  90767. _this._screenOrientationAngle = (window.orientation !== undefined ? +window.orientation : (window.screen.orientation && window.screen.orientation['angle'] ? window.screen.orientation.angle : 0));
  90768. _this._screenOrientationAngle = -BABYLON.Tools.ToRadians(_this._screenOrientationAngle / 2);
  90769. _this._screenQuaternion.copyFromFloats(0, Math.sin(_this._screenOrientationAngle), 0, Math.cos(_this._screenOrientationAngle));
  90770. };
  90771. this._deviceOrientation = function (evt) {
  90772. _this._alpha = evt.alpha !== null ? evt.alpha : 0;
  90773. _this._beta = evt.beta !== null ? evt.beta : 0;
  90774. _this._gamma = evt.gamma !== null ? evt.gamma : 0;
  90775. };
  90776. this._constantTranform = new BABYLON.Quaternion(-Math.sqrt(0.5), 0, 0, Math.sqrt(0.5));
  90777. this._orientationChanged();
  90778. }
  90779. Object.defineProperty(FreeCameraDeviceOrientationInput.prototype, "camera", {
  90780. get: function () {
  90781. return this._camera;
  90782. },
  90783. set: function (camera) {
  90784. this._camera = camera;
  90785. if (this._camera != null && !this._camera.rotationQuaternion) {
  90786. this._camera.rotationQuaternion = new BABYLON.Quaternion();
  90787. }
  90788. },
  90789. enumerable: true,
  90790. configurable: true
  90791. });
  90792. FreeCameraDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90793. window.addEventListener("orientationchange", this._orientationChanged);
  90794. window.addEventListener("deviceorientation", this._deviceOrientation);
  90795. //In certain cases, the attach control is called AFTER orientation was changed,
  90796. //So this is needed.
  90797. this._orientationChanged();
  90798. };
  90799. FreeCameraDeviceOrientationInput.prototype.detachControl = function (element) {
  90800. window.removeEventListener("orientationchange", this._orientationChanged);
  90801. window.removeEventListener("deviceorientation", this._deviceOrientation);
  90802. };
  90803. FreeCameraDeviceOrientationInput.prototype.checkInputs = function () {
  90804. //if no device orientation provided, don't update the rotation.
  90805. //Only testing against alpha under the assumption thatnorientation will never be so exact when set.
  90806. if (!this._alpha)
  90807. return;
  90808. BABYLON.Quaternion.RotationYawPitchRollToRef(BABYLON.Tools.ToRadians(this._alpha), BABYLON.Tools.ToRadians(this._beta), -BABYLON.Tools.ToRadians(this._gamma), this.camera.rotationQuaternion);
  90809. this._camera.rotationQuaternion.multiplyInPlace(this._screenQuaternion);
  90810. this._camera.rotationQuaternion.multiplyInPlace(this._constantTranform);
  90811. //Mirror on XY Plane
  90812. this._camera.rotationQuaternion.z *= -1;
  90813. this._camera.rotationQuaternion.w *= -1;
  90814. };
  90815. FreeCameraDeviceOrientationInput.prototype.getClassName = function () {
  90816. return "FreeCameraDeviceOrientationInput";
  90817. };
  90818. FreeCameraDeviceOrientationInput.prototype.getSimpleName = function () {
  90819. return "deviceOrientation";
  90820. };
  90821. return FreeCameraDeviceOrientationInput;
  90822. }());
  90823. BABYLON.FreeCameraDeviceOrientationInput = FreeCameraDeviceOrientationInput;
  90824. BABYLON.CameraInputTypes["FreeCameraDeviceOrientationInput"] = FreeCameraDeviceOrientationInput;
  90825. })(BABYLON || (BABYLON = {}));
  90826. //# sourceMappingURL=babylon.freeCameraDeviceOrientationInput.js.map
  90827. var BABYLON;
  90828. (function (BABYLON) {
  90829. var ArcRotateCameraVRDeviceOrientationInput = /** @class */ (function () {
  90830. function ArcRotateCameraVRDeviceOrientationInput() {
  90831. this.alphaCorrection = 1;
  90832. this.betaCorrection = 1;
  90833. this.gammaCorrection = 1;
  90834. this._alpha = 0;
  90835. this._gamma = 0;
  90836. this._dirty = false;
  90837. this._deviceOrientationHandler = this._onOrientationEvent.bind(this);
  90838. }
  90839. ArcRotateCameraVRDeviceOrientationInput.prototype.attachControl = function (element, noPreventDefault) {
  90840. this.camera.attachControl(element, noPreventDefault);
  90841. window.addEventListener("deviceorientation", this._deviceOrientationHandler);
  90842. };
  90843. ArcRotateCameraVRDeviceOrientationInput.prototype._onOrientationEvent = function (evt) {
  90844. if (evt.alpha !== null) {
  90845. this._alpha = +evt.alpha | 0;
  90846. }
  90847. if (evt.gamma !== null) {
  90848. this._gamma = +evt.gamma | 0;
  90849. }
  90850. this._dirty = true;
  90851. };
  90852. ArcRotateCameraVRDeviceOrientationInput.prototype.checkInputs = function () {
  90853. if (this._dirty) {
  90854. this._dirty = false;
  90855. if (this._gamma < 0) {
  90856. this._gamma = 180 + this._gamma;
  90857. }
  90858. this.camera.alpha = (-this._alpha / 180.0 * Math.PI) % Math.PI * 2;
  90859. this.camera.beta = (this._gamma / 180.0 * Math.PI);
  90860. }
  90861. };
  90862. ArcRotateCameraVRDeviceOrientationInput.prototype.detachControl = function (element) {
  90863. window.removeEventListener("deviceorientation", this._deviceOrientationHandler);
  90864. };
  90865. ArcRotateCameraVRDeviceOrientationInput.prototype.getClassName = function () {
  90866. return "ArcRotateCameraVRDeviceOrientationInput";
  90867. };
  90868. ArcRotateCameraVRDeviceOrientationInput.prototype.getSimpleName = function () {
  90869. return "VRDeviceOrientation";
  90870. };
  90871. return ArcRotateCameraVRDeviceOrientationInput;
  90872. }());
  90873. BABYLON.ArcRotateCameraVRDeviceOrientationInput = ArcRotateCameraVRDeviceOrientationInput;
  90874. BABYLON.CameraInputTypes["ArcRotateCameraVRDeviceOrientationInput"] = ArcRotateCameraVRDeviceOrientationInput;
  90875. })(BABYLON || (BABYLON = {}));
  90876. //# sourceMappingURL=babylon.arcRotateCameraVRDeviceOrientationInput.js.map
  90877. var BABYLON;
  90878. (function (BABYLON) {
  90879. var VRCameraMetrics = /** @class */ (function () {
  90880. function VRCameraMetrics() {
  90881. this.compensateDistortion = true;
  90882. }
  90883. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatio", {
  90884. get: function () {
  90885. return this.hResolution / (2 * this.vResolution);
  90886. },
  90887. enumerable: true,
  90888. configurable: true
  90889. });
  90890. Object.defineProperty(VRCameraMetrics.prototype, "aspectRatioFov", {
  90891. get: function () {
  90892. return (2 * Math.atan((this.postProcessScaleFactor * this.vScreenSize) / (2 * this.eyeToScreenDistance)));
  90893. },
  90894. enumerable: true,
  90895. configurable: true
  90896. });
  90897. Object.defineProperty(VRCameraMetrics.prototype, "leftHMatrix", {
  90898. get: function () {
  90899. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90900. var h = (4 * meters) / this.hScreenSize;
  90901. return BABYLON.Matrix.Translation(h, 0, 0);
  90902. },
  90903. enumerable: true,
  90904. configurable: true
  90905. });
  90906. Object.defineProperty(VRCameraMetrics.prototype, "rightHMatrix", {
  90907. get: function () {
  90908. var meters = (this.hScreenSize / 4) - (this.lensSeparationDistance / 2);
  90909. var h = (4 * meters) / this.hScreenSize;
  90910. return BABYLON.Matrix.Translation(-h, 0, 0);
  90911. },
  90912. enumerable: true,
  90913. configurable: true
  90914. });
  90915. Object.defineProperty(VRCameraMetrics.prototype, "leftPreViewMatrix", {
  90916. get: function () {
  90917. return BABYLON.Matrix.Translation(0.5 * this.interpupillaryDistance, 0, 0);
  90918. },
  90919. enumerable: true,
  90920. configurable: true
  90921. });
  90922. Object.defineProperty(VRCameraMetrics.prototype, "rightPreViewMatrix", {
  90923. get: function () {
  90924. return BABYLON.Matrix.Translation(-0.5 * this.interpupillaryDistance, 0, 0);
  90925. },
  90926. enumerable: true,
  90927. configurable: true
  90928. });
  90929. VRCameraMetrics.GetDefault = function () {
  90930. var result = new VRCameraMetrics();
  90931. result.hResolution = 1280;
  90932. result.vResolution = 800;
  90933. result.hScreenSize = 0.149759993;
  90934. result.vScreenSize = 0.0935999975;
  90935. result.vScreenCenter = 0.0467999987;
  90936. result.eyeToScreenDistance = 0.0410000011;
  90937. result.lensSeparationDistance = 0.0635000020;
  90938. result.interpupillaryDistance = 0.0640000030;
  90939. result.distortionK = [1.0, 0.219999999, 0.239999995, 0.0];
  90940. result.chromaAbCorrection = [0.995999992, -0.00400000019, 1.01400006, 0.0];
  90941. result.postProcessScaleFactor = 1.714605507808412;
  90942. result.lensCenterOffset = 0.151976421;
  90943. return result;
  90944. };
  90945. return VRCameraMetrics;
  90946. }());
  90947. BABYLON.VRCameraMetrics = VRCameraMetrics;
  90948. })(BABYLON || (BABYLON = {}));
  90949. //# sourceMappingURL=babylon.vrCameraMetrics.js.map
  90950. var BABYLON;
  90951. (function (BABYLON) {
  90952. /**
  90953. * This represents a WebVR camera.
  90954. * The WebVR camera is Babylon's simple interface to interaction with Windows Mixed Reality, HTC Vive and Oculus Rift.
  90955. * @example http://doc.babylonjs.com/how_to/webvr_camera
  90956. */
  90957. var WebVRFreeCamera = /** @class */ (function (_super) {
  90958. __extends(WebVRFreeCamera, _super);
  90959. /**
  90960. * Instantiates a WebVRFreeCamera.
  90961. * @param name The name of the WebVRFreeCamera
  90962. * @param position The starting anchor position for the camera
  90963. * @param scene The scene the camera belongs to
  90964. * @param webVROptions a set of customizable options for the webVRCamera
  90965. */
  90966. function WebVRFreeCamera(name, position, scene, webVROptions) {
  90967. if (webVROptions === void 0) { webVROptions = {}; }
  90968. var _this = _super.call(this, name, position, scene) || this;
  90969. _this.webVROptions = webVROptions;
  90970. /**
  90971. * The vrDisplay tied to the camera. See https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay
  90972. */
  90973. _this._vrDevice = null;
  90974. /**
  90975. * The rawPose of the vrDevice.
  90976. */
  90977. _this.rawPose = null;
  90978. _this._specsVersion = "1.1";
  90979. _this._attached = false;
  90980. _this._descendants = [];
  90981. // Represents device position and rotation in room space. Should only be used to help calculate babylon space values
  90982. _this._deviceRoomPosition = BABYLON.Vector3.Zero();
  90983. _this._deviceRoomRotationQuaternion = BABYLON.Quaternion.Identity();
  90984. _this._standingMatrix = null;
  90985. /**
  90986. * Represents device position in babylon space.
  90987. */
  90988. _this.devicePosition = BABYLON.Vector3.Zero();
  90989. /**
  90990. * Represents device rotation in babylon space.
  90991. */
  90992. _this.deviceRotationQuaternion = BABYLON.Quaternion.Identity();
  90993. /**
  90994. * The scale of the device to be used when translating from device space to babylon space.
  90995. */
  90996. _this.deviceScaleFactor = 1;
  90997. _this._deviceToWorld = BABYLON.Matrix.Identity();
  90998. _this._worldToDevice = BABYLON.Matrix.Identity();
  90999. /**
  91000. * References to the webVR controllers for the vrDevice.
  91001. */
  91002. _this.controllers = [];
  91003. /**
  91004. * Emits an event when a controller is attached.
  91005. */
  91006. _this.onControllersAttachedObservable = new BABYLON.Observable();
  91007. /**
  91008. * Emits an event when a controller's mesh has been loaded;
  91009. */
  91010. _this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  91011. /**
  91012. * If the rig cameras be used as parent instead of this camera.
  91013. */
  91014. _this.rigParenting = true;
  91015. _this._defaultHeight = undefined;
  91016. _this._workingVector = BABYLON.Vector3.Zero();
  91017. _this._oneVector = BABYLON.Vector3.One();
  91018. _this._workingMatrix = BABYLON.Matrix.Identity();
  91019. _this._cache.position = BABYLON.Vector3.Zero();
  91020. if (webVROptions.defaultHeight) {
  91021. _this._defaultHeight = webVROptions.defaultHeight;
  91022. _this.position.y = _this._defaultHeight;
  91023. }
  91024. _this.minZ = 0.1;
  91025. //legacy support - the compensation boolean was removed.
  91026. if (arguments.length === 5) {
  91027. _this.webVROptions = arguments[4];
  91028. }
  91029. // default webVR options
  91030. if (_this.webVROptions.trackPosition == undefined) {
  91031. _this.webVROptions.trackPosition = true;
  91032. }
  91033. if (_this.webVROptions.controllerMeshes == undefined) {
  91034. _this.webVROptions.controllerMeshes = true;
  91035. }
  91036. if (_this.webVROptions.defaultLightingOnControllers == undefined) {
  91037. _this.webVROptions.defaultLightingOnControllers = true;
  91038. }
  91039. _this.rotationQuaternion = new BABYLON.Quaternion();
  91040. if (_this.webVROptions && _this.webVROptions.positionScale) {
  91041. _this.deviceScaleFactor = _this.webVROptions.positionScale;
  91042. }
  91043. //enable VR
  91044. var engine = _this.getEngine();
  91045. _this._onVREnabled = function (success) { if (success) {
  91046. _this.initControllers();
  91047. } };
  91048. engine.onVRRequestPresentComplete.add(_this._onVREnabled);
  91049. engine.initWebVR().add(function (event) {
  91050. if (!event.vrDisplay || _this._vrDevice === event.vrDisplay) {
  91051. return;
  91052. }
  91053. _this._vrDevice = event.vrDisplay;
  91054. //reset the rig parameters.
  91055. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_WEBVR, { parentCamera: _this, vrDisplay: _this._vrDevice, frameData: _this._frameData, specs: _this._specsVersion });
  91056. if (_this._attached) {
  91057. _this.getEngine().enableVR();
  91058. }
  91059. });
  91060. if (typeof (VRFrameData) !== "undefined")
  91061. _this._frameData = new VRFrameData();
  91062. /**
  91063. * The idea behind the following lines:
  91064. * objects that have the camera as parent should actually have the rig cameras as a parent.
  91065. * BUT, each of those cameras has a different view matrix, which means that if we set the parent to the first rig camera,
  91066. * the second will not show it correctly.
  91067. *
  91068. * To solve this - each object that has the camera as parent will be added to a protected array.
  91069. * When the rig camera renders, it will take this array and set all of those to be its children.
  91070. * This way, the right camera will be used as a parent, and the mesh will be rendered correctly.
  91071. * Amazing!
  91072. */
  91073. scene.onBeforeCameraRenderObservable.add(function (camera) {
  91074. if (camera.parent === _this && _this.rigParenting) {
  91075. _this._descendants = _this.getDescendants(true, function (n) {
  91076. // don't take the cameras or the controllers!
  91077. var isController = _this.controllers.some(function (controller) { return controller._mesh === n; });
  91078. var isRigCamera = _this._rigCameras.indexOf(n) !== -1;
  91079. return !isController && !isRigCamera;
  91080. });
  91081. _this._descendants.forEach(function (node) {
  91082. node.parent = camera;
  91083. });
  91084. }
  91085. });
  91086. scene.onAfterCameraRenderObservable.add(function (camera) {
  91087. if (camera.parent === _this && _this.rigParenting) {
  91088. _this._descendants.forEach(function (node) {
  91089. node.parent = _this;
  91090. });
  91091. }
  91092. });
  91093. return _this;
  91094. }
  91095. /**
  91096. * Gets the device distance from the ground in meters.
  91097. * @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.
  91098. */
  91099. WebVRFreeCamera.prototype.deviceDistanceToRoomGround = function () {
  91100. if (this._standingMatrix) {
  91101. // Add standing matrix offset to get real offset from ground in room
  91102. this._standingMatrix.getTranslationToRef(this._workingVector);
  91103. return this._deviceRoomPosition.y + this._workingVector.y;
  91104. }
  91105. //If VRDisplay does not inform stage parameters and no default height is set we fallback to zero.
  91106. return this._defaultHeight || 0;
  91107. };
  91108. /**
  91109. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91110. * @param callback will be called when the standing matrix is set. Callback parameter is if the standing matrix is supported.
  91111. */
  91112. WebVRFreeCamera.prototype.useStandingMatrix = function (callback) {
  91113. var _this = this;
  91114. if (callback === void 0) { callback = function (bool) { }; }
  91115. // Use standing matrix if available
  91116. this.getEngine().initWebVRAsync().then(function (result) {
  91117. if (!result.vrDisplay || !result.vrDisplay.stageParameters || !result.vrDisplay.stageParameters.sittingToStandingTransform) {
  91118. callback(false);
  91119. }
  91120. else {
  91121. _this._standingMatrix = new BABYLON.Matrix();
  91122. BABYLON.Matrix.FromFloat32ArrayToRefScaled(result.vrDisplay.stageParameters.sittingToStandingTransform, 0, 1, _this._standingMatrix);
  91123. if (!_this.getScene().useRightHandedSystem) {
  91124. [2, 6, 8, 9, 14].forEach(function (num) {
  91125. if (_this._standingMatrix) {
  91126. _this._standingMatrix.m[num] *= -1;
  91127. }
  91128. });
  91129. }
  91130. callback(true);
  91131. }
  91132. });
  91133. };
  91134. /**
  91135. * Enables the standing matrix when supported. This can be used to position the user's view the correct height from the ground.
  91136. * @returns A promise with a boolean set to if the standing matrix is supported.
  91137. */
  91138. WebVRFreeCamera.prototype.useStandingMatrixAsync = function () {
  91139. var _this = this;
  91140. return new Promise(function (res, rej) {
  91141. _this.useStandingMatrix(function (supported) {
  91142. res(supported);
  91143. });
  91144. });
  91145. };
  91146. /**
  91147. * Disposes the camera
  91148. */
  91149. WebVRFreeCamera.prototype.dispose = function () {
  91150. this.getEngine().onVRRequestPresentComplete.removeCallback(this._onVREnabled);
  91151. _super.prototype.dispose.call(this);
  91152. };
  91153. /**
  91154. * Gets a vrController by name.
  91155. * @param name The name of the controller to retreive
  91156. * @returns the controller matching the name specified or null if not found
  91157. */
  91158. WebVRFreeCamera.prototype.getControllerByName = function (name) {
  91159. for (var _i = 0, _a = this.controllers; _i < _a.length; _i++) {
  91160. var gp = _a[_i];
  91161. if (gp.hand === name) {
  91162. return gp;
  91163. }
  91164. }
  91165. return null;
  91166. };
  91167. Object.defineProperty(WebVRFreeCamera.prototype, "leftController", {
  91168. /**
  91169. * The controller corrisponding to the users left hand.
  91170. */
  91171. get: function () {
  91172. if (!this._leftController) {
  91173. this._leftController = this.getControllerByName("left");
  91174. }
  91175. return this._leftController;
  91176. },
  91177. enumerable: true,
  91178. configurable: true
  91179. });
  91180. ;
  91181. Object.defineProperty(WebVRFreeCamera.prototype, "rightController", {
  91182. /**
  91183. * The controller corrisponding to the users right hand.
  91184. */
  91185. get: function () {
  91186. if (!this._rightController) {
  91187. this._rightController = this.getControllerByName("right");
  91188. }
  91189. return this._rightController;
  91190. },
  91191. enumerable: true,
  91192. configurable: true
  91193. });
  91194. ;
  91195. /**
  91196. * Casts a ray forward from the vrCamera's gaze.
  91197. * @param length Length of the ray (default: 100)
  91198. * @returns the ray corrisponding to the gaze
  91199. */
  91200. WebVRFreeCamera.prototype.getForwardRay = function (length) {
  91201. if (length === void 0) { length = 100; }
  91202. if (this.leftCamera) {
  91203. // Use left eye to avoid computation to compute center on every call
  91204. return _super.prototype.getForwardRay.call(this, length, this.leftCamera.getWorldMatrix(), this.leftCamera.globalPosition); // Need the actual rendered camera
  91205. }
  91206. else {
  91207. return _super.prototype.getForwardRay.call(this, length);
  91208. }
  91209. };
  91210. /**
  91211. * Updates the camera based on device's frame data
  91212. */
  91213. WebVRFreeCamera.prototype._checkInputs = function () {
  91214. if (this._vrDevice && this._vrDevice.isPresenting) {
  91215. this._vrDevice.getFrameData(this._frameData);
  91216. this.updateFromDevice(this._frameData.pose);
  91217. }
  91218. _super.prototype._checkInputs.call(this);
  91219. };
  91220. /**
  91221. * Updates the poseControlled values based on the input device pose.
  91222. * @param poseData Pose coming from the device
  91223. */
  91224. WebVRFreeCamera.prototype.updateFromDevice = function (poseData) {
  91225. if (poseData && poseData.orientation) {
  91226. this.rawPose = poseData;
  91227. this._deviceRoomRotationQuaternion.copyFromFloats(poseData.orientation[0], poseData.orientation[1], -poseData.orientation[2], -poseData.orientation[3]);
  91228. if (this.getScene().useRightHandedSystem) {
  91229. this._deviceRoomRotationQuaternion.z *= -1;
  91230. this._deviceRoomRotationQuaternion.w *= -1;
  91231. }
  91232. if (this.webVROptions.trackPosition && this.rawPose.position) {
  91233. this._deviceRoomPosition.copyFromFloats(this.rawPose.position[0], this.rawPose.position[1], -this.rawPose.position[2]);
  91234. if (this.getScene().useRightHandedSystem) {
  91235. this._deviceRoomPosition.z *= -1;
  91236. }
  91237. }
  91238. }
  91239. };
  91240. /**
  91241. * WebVR's attach control will start broadcasting frames to the device.
  91242. * Note that in certain browsers (chrome for example) this function must be called
  91243. * within a user-interaction callback. Example:
  91244. * <pre> scene.onPointerDown = function() { camera.attachControl(canvas); }</pre>
  91245. *
  91246. * @param element html element to attach the vrDevice to
  91247. * @param noPreventDefault prevent the default html element operation when attaching the vrDevice
  91248. */
  91249. WebVRFreeCamera.prototype.attachControl = function (element, noPreventDefault) {
  91250. _super.prototype.attachControl.call(this, element, noPreventDefault);
  91251. this._attached = true;
  91252. noPreventDefault = BABYLON.Camera.ForceAttachControlToAlwaysPreventDefault ? false : noPreventDefault;
  91253. if (this._vrDevice) {
  91254. this.getEngine().enableVR();
  91255. }
  91256. };
  91257. /**
  91258. * Detaches the camera from the html element and disables VR
  91259. *
  91260. * @param element html element to detach from
  91261. */
  91262. WebVRFreeCamera.prototype.detachControl = function (element) {
  91263. this.getScene().gamepadManager.onGamepadConnectedObservable.remove(this._onGamepadConnectedObserver);
  91264. this.getScene().gamepadManager.onGamepadDisconnectedObservable.remove(this._onGamepadDisconnectedObserver);
  91265. _super.prototype.detachControl.call(this, element);
  91266. this._attached = false;
  91267. this.getEngine().disableVR();
  91268. };
  91269. /**
  91270. * @returns the name of this class
  91271. */
  91272. WebVRFreeCamera.prototype.getClassName = function () {
  91273. return "WebVRFreeCamera";
  91274. };
  91275. /**
  91276. * Calls resetPose on the vrDisplay
  91277. * See: https://developer.mozilla.org/en-US/docs/Web/API/VRDisplay/resetPose
  91278. */
  91279. WebVRFreeCamera.prototype.resetToCurrentRotation = function () {
  91280. //uses the vrDisplay's "resetPose()".
  91281. //pitch and roll won't be affected.
  91282. this._vrDevice.resetPose();
  91283. };
  91284. /**
  91285. * Updates the rig cameras (left and right eye)
  91286. */
  91287. WebVRFreeCamera.prototype._updateRigCameras = function () {
  91288. var camLeft = this._rigCameras[0];
  91289. var camRight = this._rigCameras[1];
  91290. camLeft.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91291. camRight.rotationQuaternion.copyFrom(this._deviceRoomRotationQuaternion);
  91292. camLeft.position.copyFrom(this._deviceRoomPosition);
  91293. camRight.position.copyFrom(this._deviceRoomPosition);
  91294. };
  91295. /**
  91296. * Updates the cached values of the camera
  91297. * @param ignoreParentClass ignores updating the parent class's cache (default: false)
  91298. */
  91299. WebVRFreeCamera.prototype._updateCache = function (ignoreParentClass) {
  91300. var _this = this;
  91301. if (!this.rotationQuaternion.equals(this._cache.rotationQuaternion) || !this.position.equals(this._cache.position)) {
  91302. // Update to ensure devicePosition is up to date with most recent _deviceRoomPosition
  91303. if (!this.updateCacheCalled) {
  91304. // make sure it is only called once per loop. this.update() might cause an infinite loop.
  91305. this.updateCacheCalled = true;
  91306. this.update();
  91307. }
  91308. // Set working vector to the device position in room space rotated by the new rotation
  91309. this.rotationQuaternion.toRotationMatrix(this._workingMatrix);
  91310. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._workingMatrix, this._workingVector);
  91311. // Subtract this vector from the current device position in world to get the translation for the device world matrix
  91312. this.devicePosition.subtractToRef(this._workingVector, this._workingVector);
  91313. BABYLON.Matrix.ComposeToRef(this._oneVector, this.rotationQuaternion, this._workingVector, this._deviceToWorld);
  91314. // Add translation from anchor position
  91315. this._deviceToWorld.getTranslationToRef(this._workingVector);
  91316. this._workingVector.addInPlace(this.position);
  91317. this._workingVector.subtractInPlace(this._cache.position);
  91318. this._deviceToWorld.setTranslation(this._workingVector);
  91319. // Set an inverted matrix to be used when updating the camera
  91320. this._deviceToWorld.invertToRef(this._worldToDevice);
  91321. // Update the gamepad to ensure the mesh is updated on the same frame as camera
  91322. this.controllers.forEach(function (controller) {
  91323. controller._deviceToWorld.copyFrom(_this._deviceToWorld);
  91324. controller.update();
  91325. });
  91326. }
  91327. if (!ignoreParentClass) {
  91328. _super.prototype._updateCache.call(this);
  91329. }
  91330. this.updateCacheCalled = false;
  91331. };
  91332. /**
  91333. * Updates the current device position and rotation in the babylon world
  91334. */
  91335. WebVRFreeCamera.prototype.update = function () {
  91336. // Get current device position in babylon world
  91337. BABYLON.Vector3.TransformCoordinatesToRef(this._deviceRoomPosition, this._deviceToWorld, this.devicePosition);
  91338. // Get current device rotation in babylon world
  91339. BABYLON.Matrix.FromQuaternionToRef(this._deviceRoomRotationQuaternion, this._workingMatrix);
  91340. this._workingMatrix.multiplyToRef(this._deviceToWorld, this._workingMatrix);
  91341. BABYLON.Quaternion.FromRotationMatrixToRef(this._workingMatrix, this.deviceRotationQuaternion);
  91342. _super.prototype.update.call(this);
  91343. };
  91344. /**
  91345. * Gets the view matrix of this camera (Always set to identity as left and right eye cameras contain the actual view matrix)
  91346. * @returns an identity matrix
  91347. */
  91348. WebVRFreeCamera.prototype._getViewMatrix = function () {
  91349. return BABYLON.Matrix.Identity();
  91350. };
  91351. /**
  91352. * This function is called by the two RIG cameras.
  91353. * 'this' is the left or right camera (and NOT (!!!) the WebVRFreeCamera instance)
  91354. */
  91355. WebVRFreeCamera.prototype._getWebVRViewMatrix = function () {
  91356. var _this = this;
  91357. // Update the parent camera prior to using a child camera to avoid desynchronization
  91358. var parentCamera = this._cameraRigParams["parentCamera"];
  91359. parentCamera._updateCache();
  91360. //WebVR 1.1
  91361. var viewArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftViewMatrix : this._cameraRigParams["frameData"].rightViewMatrix;
  91362. BABYLON.Matrix.FromArrayToRef(viewArray, 0, this._webvrViewMatrix);
  91363. if (!this.getScene().useRightHandedSystem) {
  91364. [2, 6, 8, 9, 14].forEach(function (num) {
  91365. _this._webvrViewMatrix.m[num] *= -1;
  91366. });
  91367. }
  91368. // update the camera rotation matrix
  91369. this._webvrViewMatrix.getRotationMatrixToRef(this._cameraRotationMatrix);
  91370. BABYLON.Vector3.TransformCoordinatesToRef(this._referencePoint, this._cameraRotationMatrix, this._transformedReferencePoint);
  91371. // Computing target and final matrix
  91372. this.position.addToRef(this._transformedReferencePoint, this._currentTarget);
  91373. // should the view matrix be updated with scale and position offset?
  91374. if (parentCamera.deviceScaleFactor !== 1) {
  91375. this._webvrViewMatrix.invert();
  91376. // scale the position, if set
  91377. if (parentCamera.deviceScaleFactor) {
  91378. this._webvrViewMatrix.m[12] *= parentCamera.deviceScaleFactor;
  91379. this._webvrViewMatrix.m[13] *= parentCamera.deviceScaleFactor;
  91380. this._webvrViewMatrix.m[14] *= parentCamera.deviceScaleFactor;
  91381. }
  91382. this._webvrViewMatrix.invert();
  91383. }
  91384. parentCamera._worldToDevice.multiplyToRef(this._webvrViewMatrix, this._webvrViewMatrix);
  91385. // Compute global position
  91386. this._workingMatrix = this._workingMatrix || BABYLON.Matrix.Identity();
  91387. this._webvrViewMatrix.invertToRef(this._workingMatrix);
  91388. this._workingMatrix.multiplyToRef(parentCamera.getWorldMatrix(), this._workingMatrix);
  91389. this._workingMatrix.getTranslationToRef(this._globalPosition);
  91390. this._markSyncedWithParent();
  91391. return this._webvrViewMatrix;
  91392. };
  91393. WebVRFreeCamera.prototype._getWebVRProjectionMatrix = function () {
  91394. var _this = this;
  91395. var parentCamera = this.parent;
  91396. parentCamera._vrDevice.depthNear = parentCamera.minZ;
  91397. parentCamera._vrDevice.depthFar = parentCamera.maxZ;
  91398. var projectionArray = this._cameraRigParams["left"] ? this._cameraRigParams["frameData"].leftProjectionMatrix : this._cameraRigParams["frameData"].rightProjectionMatrix;
  91399. BABYLON.Matrix.FromArrayToRef(projectionArray, 0, this._projectionMatrix);
  91400. //babylon compatible matrix
  91401. if (!this.getScene().useRightHandedSystem) {
  91402. [8, 9, 10, 11].forEach(function (num) {
  91403. _this._projectionMatrix.m[num] *= -1;
  91404. });
  91405. }
  91406. return this._projectionMatrix;
  91407. };
  91408. /**
  91409. * Initializes the controllers and their meshes
  91410. */
  91411. WebVRFreeCamera.prototype.initControllers = function () {
  91412. var _this = this;
  91413. this.controllers = [];
  91414. var manager = this.getScene().gamepadManager;
  91415. this._onGamepadDisconnectedObserver = manager.onGamepadDisconnectedObservable.add(function (gamepad) {
  91416. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91417. var webVrController = gamepad;
  91418. if (webVrController.defaultModel) {
  91419. webVrController.defaultModel.setEnabled(false);
  91420. }
  91421. if (webVrController.hand === "right") {
  91422. _this._rightController = null;
  91423. }
  91424. if (webVrController.hand === "left") {
  91425. _this._leftController = null;
  91426. }
  91427. var controllerIndex = _this.controllers.indexOf(webVrController);
  91428. if (controllerIndex !== -1) {
  91429. _this.controllers.splice(controllerIndex, 1);
  91430. }
  91431. }
  91432. });
  91433. this._onGamepadConnectedObserver = manager.onGamepadConnectedObservable.add(function (gamepad) {
  91434. if (gamepad.type === BABYLON.Gamepad.POSE_ENABLED) {
  91435. var webVrController_1 = gamepad;
  91436. webVrController_1.deviceScaleFactor = _this.deviceScaleFactor;
  91437. webVrController_1._deviceToWorld.copyFrom(_this._deviceToWorld);
  91438. if (_this.webVROptions.controllerMeshes) {
  91439. if (webVrController_1.defaultModel) {
  91440. webVrController_1.defaultModel.setEnabled(true);
  91441. }
  91442. else {
  91443. // Load the meshes
  91444. webVrController_1.initControllerMesh(_this.getScene(), function (loadedMesh) {
  91445. loadedMesh.scaling.scaleInPlace(_this.deviceScaleFactor);
  91446. _this.onControllerMeshLoadedObservable.notifyObservers(webVrController_1);
  91447. if (_this.webVROptions.defaultLightingOnControllers) {
  91448. if (!_this._lightOnControllers) {
  91449. _this._lightOnControllers = new BABYLON.HemisphericLight("vrControllersLight", new BABYLON.Vector3(0, 1, 0), _this.getScene());
  91450. }
  91451. var activateLightOnSubMeshes_1 = function (mesh, light) {
  91452. var children = mesh.getChildren();
  91453. if (children.length !== 0) {
  91454. children.forEach(function (mesh) {
  91455. light.includedOnlyMeshes.push(mesh);
  91456. activateLightOnSubMeshes_1(mesh, light);
  91457. });
  91458. }
  91459. };
  91460. _this._lightOnControllers.includedOnlyMeshes.push(loadedMesh);
  91461. activateLightOnSubMeshes_1(loadedMesh, _this._lightOnControllers);
  91462. }
  91463. });
  91464. }
  91465. }
  91466. webVrController_1.attachToPoseControlledCamera(_this);
  91467. // since this is async - sanity check. Is the controller already stored?
  91468. if (_this.controllers.indexOf(webVrController_1) === -1) {
  91469. //add to the controllers array
  91470. _this.controllers.push(webVrController_1);
  91471. // Forced to add some control code for Vive as it doesn't always fill properly the "hand" property
  91472. // Sometimes, both controllers are set correctly (left and right), sometimes none, sometimes only one of them...
  91473. // So we're overriding setting left & right manually to be sure
  91474. var firstViveWandDetected = false;
  91475. for (var i = 0; i < _this.controllers.length; i++) {
  91476. if (_this.controllers[i].controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  91477. if (!firstViveWandDetected) {
  91478. firstViveWandDetected = true;
  91479. _this.controllers[i].hand = "left";
  91480. }
  91481. else {
  91482. _this.controllers[i].hand = "right";
  91483. }
  91484. }
  91485. }
  91486. //did we find enough controllers? Great! let the developer know.
  91487. if (_this.controllers.length >= 2) {
  91488. _this.onControllersAttachedObservable.notifyObservers(_this.controllers);
  91489. }
  91490. }
  91491. }
  91492. });
  91493. };
  91494. return WebVRFreeCamera;
  91495. }(BABYLON.FreeCamera));
  91496. BABYLON.WebVRFreeCamera = WebVRFreeCamera;
  91497. })(BABYLON || (BABYLON = {}));
  91498. //# sourceMappingURL=babylon.webVRCamera.js.map
  91499. var BABYLON;
  91500. (function (BABYLON) {
  91501. // We're mainly based on the logic defined into the FreeCamera code
  91502. /**
  91503. * This is a camera specifically designed to react to device orientation events such as a modern mobile device
  91504. * being tilted forward or back and left or right.
  91505. */
  91506. var DeviceOrientationCamera = /** @class */ (function (_super) {
  91507. __extends(DeviceOrientationCamera, _super);
  91508. /**
  91509. * Creates a new device orientation camera
  91510. * @param name The name of the camera
  91511. * @param position The start position camera
  91512. * @param scene The scene the camera belongs to
  91513. */
  91514. function DeviceOrientationCamera(name, position, scene) {
  91515. var _this = _super.call(this, name, position, scene) || this;
  91516. _this._quaternionCache = new BABYLON.Quaternion();
  91517. _this.inputs.addDeviceOrientation();
  91518. return _this;
  91519. }
  91520. /**
  91521. * Gets the current instance class name ("DeviceOrientationCamera").
  91522. * This helps avoiding instanceof at run time.
  91523. * @returns the class name
  91524. */
  91525. DeviceOrientationCamera.prototype.getClassName = function () {
  91526. return "DeviceOrientationCamera";
  91527. };
  91528. /**
  91529. * Checks and applies the current values of the inputs to the camera. (Internal use only)
  91530. */
  91531. DeviceOrientationCamera.prototype._checkInputs = function () {
  91532. _super.prototype._checkInputs.call(this);
  91533. this._quaternionCache.copyFrom(this.rotationQuaternion);
  91534. if (this._initialQuaternion) {
  91535. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91536. }
  91537. };
  91538. /**
  91539. * Reset the camera to its default orientation on the specified axis only.
  91540. * @param axis The axis to reset
  91541. */
  91542. DeviceOrientationCamera.prototype.resetToCurrentRotation = function (axis) {
  91543. var _this = this;
  91544. if (axis === void 0) { axis = BABYLON.Axis.Y; }
  91545. //can only work if this camera has a rotation quaternion already.
  91546. if (!this.rotationQuaternion)
  91547. return;
  91548. if (!this._initialQuaternion) {
  91549. this._initialQuaternion = new BABYLON.Quaternion();
  91550. }
  91551. this._initialQuaternion.copyFrom(this._quaternionCache || this.rotationQuaternion);
  91552. ['x', 'y', 'z'].forEach(function (axisName) {
  91553. if (!axis[axisName]) {
  91554. _this._initialQuaternion[axisName] = 0;
  91555. }
  91556. else {
  91557. _this._initialQuaternion[axisName] *= -1;
  91558. }
  91559. });
  91560. this._initialQuaternion.normalize();
  91561. //force rotation update
  91562. this._initialQuaternion.multiplyToRef(this.rotationQuaternion, this.rotationQuaternion);
  91563. };
  91564. return DeviceOrientationCamera;
  91565. }(BABYLON.FreeCamera));
  91566. BABYLON.DeviceOrientationCamera = DeviceOrientationCamera;
  91567. })(BABYLON || (BABYLON = {}));
  91568. //# sourceMappingURL=babylon.deviceOrientationCamera.js.map
  91569. var BABYLON;
  91570. (function (BABYLON) {
  91571. var VRDeviceOrientationFreeCamera = /** @class */ (function (_super) {
  91572. __extends(VRDeviceOrientationFreeCamera, _super);
  91573. function VRDeviceOrientationFreeCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91574. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91575. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91576. var _this = _super.call(this, name, position, scene) || this;
  91577. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91578. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91579. return _this;
  91580. }
  91581. VRDeviceOrientationFreeCamera.prototype.getClassName = function () {
  91582. return "VRDeviceOrientationFreeCamera";
  91583. };
  91584. return VRDeviceOrientationFreeCamera;
  91585. }(BABYLON.DeviceOrientationCamera));
  91586. BABYLON.VRDeviceOrientationFreeCamera = VRDeviceOrientationFreeCamera;
  91587. var VRDeviceOrientationGamepadCamera = /** @class */ (function (_super) {
  91588. __extends(VRDeviceOrientationGamepadCamera, _super);
  91589. function VRDeviceOrientationGamepadCamera(name, position, scene, compensateDistortion, vrCameraMetrics) {
  91590. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91591. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91592. var _this = _super.call(this, name, position, scene, compensateDistortion, vrCameraMetrics) || this;
  91593. _this.inputs.addGamepad();
  91594. return _this;
  91595. }
  91596. VRDeviceOrientationGamepadCamera.prototype.getClassName = function () {
  91597. return "VRDeviceOrientationGamepadCamera";
  91598. };
  91599. return VRDeviceOrientationGamepadCamera;
  91600. }(VRDeviceOrientationFreeCamera));
  91601. BABYLON.VRDeviceOrientationGamepadCamera = VRDeviceOrientationGamepadCamera;
  91602. var VRDeviceOrientationArcRotateCamera = /** @class */ (function (_super) {
  91603. __extends(VRDeviceOrientationArcRotateCamera, _super);
  91604. function VRDeviceOrientationArcRotateCamera(name, alpha, beta, radius, target, scene, compensateDistortion, vrCameraMetrics) {
  91605. if (compensateDistortion === void 0) { compensateDistortion = true; }
  91606. if (vrCameraMetrics === void 0) { vrCameraMetrics = BABYLON.VRCameraMetrics.GetDefault(); }
  91607. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91608. vrCameraMetrics.compensateDistortion = compensateDistortion;
  91609. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_VR, { vrCameraMetrics: vrCameraMetrics });
  91610. _this.inputs.addVRDeviceOrientation();
  91611. return _this;
  91612. }
  91613. VRDeviceOrientationArcRotateCamera.prototype.getClassName = function () {
  91614. return "VRDeviceOrientationArcRotateCamera";
  91615. };
  91616. return VRDeviceOrientationArcRotateCamera;
  91617. }(BABYLON.ArcRotateCamera));
  91618. BABYLON.VRDeviceOrientationArcRotateCamera = VRDeviceOrientationArcRotateCamera;
  91619. })(BABYLON || (BABYLON = {}));
  91620. //# sourceMappingURL=babylon.vrDeviceOrientationCamera.js.map
  91621. var BABYLON;
  91622. (function (BABYLON) {
  91623. /**
  91624. * Camera used to simulate anaglyphic rendering (based on FreeCamera)
  91625. */
  91626. var AnaglyphFreeCamera = /** @class */ (function (_super) {
  91627. __extends(AnaglyphFreeCamera, _super);
  91628. /**
  91629. * Creates a new AnaglyphFreeCamera
  91630. * @param name defines camera name
  91631. * @param position defines initial position
  91632. * @param interaxialDistance defines distance between each color axis
  91633. * @param scene defines the hosting scene
  91634. */
  91635. function AnaglyphFreeCamera(name, position, interaxialDistance, scene) {
  91636. var _this = _super.call(this, name, position, scene) || this;
  91637. _this.interaxialDistance = interaxialDistance;
  91638. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91639. return _this;
  91640. }
  91641. /**
  91642. * Gets camera class name
  91643. * @returns AnaglyphFreeCamera
  91644. */
  91645. AnaglyphFreeCamera.prototype.getClassName = function () {
  91646. return "AnaglyphFreeCamera";
  91647. };
  91648. return AnaglyphFreeCamera;
  91649. }(BABYLON.FreeCamera));
  91650. BABYLON.AnaglyphFreeCamera = AnaglyphFreeCamera;
  91651. /**
  91652. * Camera used to simulate anaglyphic rendering (based on ArcRotateCamera)
  91653. */
  91654. var AnaglyphArcRotateCamera = /** @class */ (function (_super) {
  91655. __extends(AnaglyphArcRotateCamera, _super);
  91656. /**
  91657. * Creates a new AnaglyphArcRotateCamera
  91658. * @param name defines camera name
  91659. * @param alpha defines alpha angle (in radians)
  91660. * @param beta defines beta angle (in radians)
  91661. * @param radius defines radius
  91662. * @param target defines camera target
  91663. * @param interaxialDistance defines distance between each color axis
  91664. * @param scene defines the hosting scene
  91665. */
  91666. function AnaglyphArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, scene) {
  91667. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91668. _this.interaxialDistance = interaxialDistance;
  91669. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91670. return _this;
  91671. }
  91672. /**
  91673. * Gets camera class name
  91674. * @returns AnaglyphArcRotateCamera
  91675. */
  91676. AnaglyphArcRotateCamera.prototype.getClassName = function () {
  91677. return "AnaglyphArcRotateCamera";
  91678. };
  91679. return AnaglyphArcRotateCamera;
  91680. }(BABYLON.ArcRotateCamera));
  91681. BABYLON.AnaglyphArcRotateCamera = AnaglyphArcRotateCamera;
  91682. /**
  91683. * Camera used to simulate anaglyphic rendering (based on GamepadCamera)
  91684. */
  91685. var AnaglyphGamepadCamera = /** @class */ (function (_super) {
  91686. __extends(AnaglyphGamepadCamera, _super);
  91687. /**
  91688. * Creates a new AnaglyphGamepadCamera
  91689. * @param name defines camera name
  91690. * @param position defines initial position
  91691. * @param interaxialDistance defines distance between each color axis
  91692. * @param scene defines the hosting scene
  91693. */
  91694. function AnaglyphGamepadCamera(name, position, interaxialDistance, scene) {
  91695. var _this = _super.call(this, name, position, scene) || this;
  91696. _this.interaxialDistance = interaxialDistance;
  91697. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91698. return _this;
  91699. }
  91700. /**
  91701. * Gets camera class name
  91702. * @returns AnaglyphGamepadCamera
  91703. */
  91704. AnaglyphGamepadCamera.prototype.getClassName = function () {
  91705. return "AnaglyphGamepadCamera";
  91706. };
  91707. return AnaglyphGamepadCamera;
  91708. }(BABYLON.GamepadCamera));
  91709. BABYLON.AnaglyphGamepadCamera = AnaglyphGamepadCamera;
  91710. /**
  91711. * Camera used to simulate anaglyphic rendering (based on UniversalCamera)
  91712. */
  91713. var AnaglyphUniversalCamera = /** @class */ (function (_super) {
  91714. __extends(AnaglyphUniversalCamera, _super);
  91715. /**
  91716. * Creates a new AnaglyphUniversalCamera
  91717. * @param name defines camera name
  91718. * @param position defines initial position
  91719. * @param interaxialDistance defines distance between each color axis
  91720. * @param scene defines the hosting scene
  91721. */
  91722. function AnaglyphUniversalCamera(name, position, interaxialDistance, scene) {
  91723. var _this = _super.call(this, name, position, scene) || this;
  91724. _this.interaxialDistance = interaxialDistance;
  91725. _this.setCameraRigMode(BABYLON.Camera.RIG_MODE_STEREOSCOPIC_ANAGLYPH, { interaxialDistance: interaxialDistance });
  91726. return _this;
  91727. }
  91728. /**
  91729. * Gets camera class name
  91730. * @returns AnaglyphUniversalCamera
  91731. */
  91732. AnaglyphUniversalCamera.prototype.getClassName = function () {
  91733. return "AnaglyphUniversalCamera";
  91734. };
  91735. return AnaglyphUniversalCamera;
  91736. }(BABYLON.UniversalCamera));
  91737. BABYLON.AnaglyphUniversalCamera = AnaglyphUniversalCamera;
  91738. /**
  91739. * Camera used to simulate stereoscopic rendering (based on FreeCamera)
  91740. */
  91741. var StereoscopicFreeCamera = /** @class */ (function (_super) {
  91742. __extends(StereoscopicFreeCamera, _super);
  91743. /**
  91744. * Creates a new StereoscopicFreeCamera
  91745. * @param name defines camera name
  91746. * @param position defines initial position
  91747. * @param interaxialDistance defines distance between each color axis
  91748. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91749. * @param scene defines the hosting scene
  91750. */
  91751. function StereoscopicFreeCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91752. var _this = _super.call(this, name, position, scene) || this;
  91753. _this.interaxialDistance = interaxialDistance;
  91754. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91755. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91756. return _this;
  91757. }
  91758. /**
  91759. * Gets camera class name
  91760. * @returns StereoscopicFreeCamera
  91761. */
  91762. StereoscopicFreeCamera.prototype.getClassName = function () {
  91763. return "StereoscopicFreeCamera";
  91764. };
  91765. return StereoscopicFreeCamera;
  91766. }(BABYLON.FreeCamera));
  91767. BABYLON.StereoscopicFreeCamera = StereoscopicFreeCamera;
  91768. /**
  91769. * Camera used to simulate stereoscopic rendering (based on ArcRotateCamera)
  91770. */
  91771. var StereoscopicArcRotateCamera = /** @class */ (function (_super) {
  91772. __extends(StereoscopicArcRotateCamera, _super);
  91773. /**
  91774. * Creates a new StereoscopicArcRotateCamera
  91775. * @param name defines camera name
  91776. * @param alpha defines alpha angle (in radians)
  91777. * @param beta defines beta angle (in radians)
  91778. * @param radius defines radius
  91779. * @param target defines camera target
  91780. * @param interaxialDistance defines distance between each color axis
  91781. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91782. * @param scene defines the hosting scene
  91783. */
  91784. function StereoscopicArcRotateCamera(name, alpha, beta, radius, target, interaxialDistance, isStereoscopicSideBySide, scene) {
  91785. var _this = _super.call(this, name, alpha, beta, radius, target, scene) || this;
  91786. _this.interaxialDistance = interaxialDistance;
  91787. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91788. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91789. return _this;
  91790. }
  91791. /**
  91792. * Gets camera class name
  91793. * @returns StereoscopicArcRotateCamera
  91794. */
  91795. StereoscopicArcRotateCamera.prototype.getClassName = function () {
  91796. return "StereoscopicArcRotateCamera";
  91797. };
  91798. return StereoscopicArcRotateCamera;
  91799. }(BABYLON.ArcRotateCamera));
  91800. BABYLON.StereoscopicArcRotateCamera = StereoscopicArcRotateCamera;
  91801. /**
  91802. * Camera used to simulate stereoscopic rendering (based on GamepadCamera)
  91803. */
  91804. var StereoscopicGamepadCamera = /** @class */ (function (_super) {
  91805. __extends(StereoscopicGamepadCamera, _super);
  91806. /**
  91807. * Creates a new StereoscopicGamepadCamera
  91808. * @param name defines camera name
  91809. * @param position defines initial position
  91810. * @param interaxialDistance defines distance between each color axis
  91811. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91812. * @param scene defines the hosting scene
  91813. */
  91814. function StereoscopicGamepadCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91815. var _this = _super.call(this, name, position, scene) || this;
  91816. _this.interaxialDistance = interaxialDistance;
  91817. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91818. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91819. return _this;
  91820. }
  91821. /**
  91822. * Gets camera class name
  91823. * @returns StereoscopicGamepadCamera
  91824. */
  91825. StereoscopicGamepadCamera.prototype.getClassName = function () {
  91826. return "StereoscopicGamepadCamera";
  91827. };
  91828. return StereoscopicGamepadCamera;
  91829. }(BABYLON.GamepadCamera));
  91830. BABYLON.StereoscopicGamepadCamera = StereoscopicGamepadCamera;
  91831. /**
  91832. * Camera used to simulate stereoscopic rendering (based on UniversalCamera)
  91833. */
  91834. var StereoscopicUniversalCamera = /** @class */ (function (_super) {
  91835. __extends(StereoscopicUniversalCamera, _super);
  91836. /**
  91837. * Creates a new StereoscopicUniversalCamera
  91838. * @param name defines camera name
  91839. * @param position defines initial position
  91840. * @param interaxialDistance defines distance between each color axis
  91841. * @param isStereoscopicSideBySide defines is stereoscopic is done side by side or over under
  91842. * @param scene defines the hosting scene
  91843. */
  91844. function StereoscopicUniversalCamera(name, position, interaxialDistance, isStereoscopicSideBySide, scene) {
  91845. var _this = _super.call(this, name, position, scene) || this;
  91846. _this.interaxialDistance = interaxialDistance;
  91847. _this.isStereoscopicSideBySide = isStereoscopicSideBySide;
  91848. _this.setCameraRigMode(isStereoscopicSideBySide ? BABYLON.Camera.RIG_MODE_STEREOSCOPIC_SIDEBYSIDE_PARALLEL : BABYLON.Camera.RIG_MODE_STEREOSCOPIC_OVERUNDER, { interaxialDistance: interaxialDistance });
  91849. return _this;
  91850. }
  91851. /**
  91852. * Gets camera class name
  91853. * @returns StereoscopicUniversalCamera
  91854. */
  91855. StereoscopicUniversalCamera.prototype.getClassName = function () {
  91856. return "StereoscopicUniversalCamera";
  91857. };
  91858. return StereoscopicUniversalCamera;
  91859. }(BABYLON.UniversalCamera));
  91860. BABYLON.StereoscopicUniversalCamera = StereoscopicUniversalCamera;
  91861. })(BABYLON || (BABYLON = {}));
  91862. //# sourceMappingURL=babylon.stereoscopicCameras.js.map
  91863. var BABYLON;
  91864. (function (BABYLON) {
  91865. var VRExperienceHelperGazer = /** @class */ (function () {
  91866. function VRExperienceHelperGazer(scene, gazeTrackerToClone) {
  91867. if (gazeTrackerToClone === void 0) { gazeTrackerToClone = null; }
  91868. this.scene = scene;
  91869. this._pointerDownOnMeshAsked = false;
  91870. this._isActionableMesh = false;
  91871. this._teleportationRequestInitiated = false;
  91872. this._teleportationBackRequestInitiated = false;
  91873. this._rotationRightAsked = false;
  91874. this._rotationLeftAsked = false;
  91875. this._dpadPressed = true;
  91876. this._activePointer = false;
  91877. this._id = VRExperienceHelperGazer._idCounter++;
  91878. // Gaze tracker
  91879. if (!gazeTrackerToClone) {
  91880. this._gazeTracker = BABYLON.Mesh.CreateTorus("gazeTracker", 0.0035, 0.0025, 20, scene, false);
  91881. this._gazeTracker.bakeCurrentTransformIntoVertices();
  91882. this._gazeTracker.isPickable = false;
  91883. this._gazeTracker.isVisible = false;
  91884. var targetMat = new BABYLON.StandardMaterial("targetMat", scene);
  91885. targetMat.specularColor = BABYLON.Color3.Black();
  91886. targetMat.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91887. targetMat.backFaceCulling = false;
  91888. this._gazeTracker.material = targetMat;
  91889. }
  91890. else {
  91891. this._gazeTracker = gazeTrackerToClone.clone("gazeTracker");
  91892. }
  91893. }
  91894. VRExperienceHelperGazer.prototype._getForwardRay = function (length) {
  91895. return new BABYLON.Ray(BABYLON.Vector3.Zero(), new BABYLON.Vector3(0, 0, length));
  91896. };
  91897. VRExperienceHelperGazer.prototype._selectionPointerDown = function () {
  91898. this._pointerDownOnMeshAsked = true;
  91899. if (this._currentHit) {
  91900. this.scene.simulatePointerDown(this._currentHit, { pointerId: this._id });
  91901. }
  91902. };
  91903. VRExperienceHelperGazer.prototype._selectionPointerUp = function () {
  91904. if (this._currentHit) {
  91905. this.scene.simulatePointerUp(this._currentHit, { pointerId: this._id });
  91906. }
  91907. this._pointerDownOnMeshAsked = false;
  91908. };
  91909. VRExperienceHelperGazer.prototype._activatePointer = function () {
  91910. this._activePointer = true;
  91911. };
  91912. VRExperienceHelperGazer.prototype._deactivatePointer = function () {
  91913. this._activePointer = false;
  91914. };
  91915. VRExperienceHelperGazer.prototype._updatePointerDistance = function (distance) {
  91916. if (distance === void 0) { distance = 100; }
  91917. };
  91918. VRExperienceHelperGazer.prototype.dispose = function () {
  91919. this._interactionsEnabled = false;
  91920. this._teleportationEnabled = false;
  91921. if (this._gazeTracker) {
  91922. this._gazeTracker.dispose();
  91923. }
  91924. };
  91925. VRExperienceHelperGazer._idCounter = 0;
  91926. return VRExperienceHelperGazer;
  91927. }());
  91928. var VRExperienceHelperControllerGazer = /** @class */ (function (_super) {
  91929. __extends(VRExperienceHelperControllerGazer, _super);
  91930. function VRExperienceHelperControllerGazer(webVRController, scene, gazeTrackerToClone) {
  91931. var _this = _super.call(this, scene, gazeTrackerToClone) || this;
  91932. _this.webVRController = webVRController;
  91933. // Laser pointer
  91934. _this._laserPointer = BABYLON.Mesh.CreateCylinder("laserPointer", 1, 0.004, 0.0002, 20, 1, scene, false);
  91935. var laserPointerMaterial = new BABYLON.StandardMaterial("laserPointerMat", scene);
  91936. laserPointerMaterial.emissiveColor = new BABYLON.Color3(0.7, 0.7, 0.7);
  91937. laserPointerMaterial.alpha = 0.6;
  91938. _this._laserPointer.material = laserPointerMaterial;
  91939. _this._laserPointer.rotation.x = Math.PI / 2;
  91940. _this._laserPointer.position.z = -0.5;
  91941. _this._laserPointer.isVisible = false;
  91942. _this._laserPointer.isPickable = false;
  91943. if (!webVRController.mesh) {
  91944. // Create an empty mesh that is used prior to loading the high quality model
  91945. var preloadMesh = new BABYLON.Mesh("preloadControllerMesh", scene);
  91946. var preloadPointerPose = new BABYLON.Mesh(BABYLON.PoseEnabledController.POINTING_POSE, scene);
  91947. preloadPointerPose.rotation.x = -0.7;
  91948. preloadMesh.addChild(preloadPointerPose);
  91949. webVRController.attachToMesh(preloadMesh);
  91950. }
  91951. _this._setLaserPointerParent(webVRController.mesh);
  91952. _this._meshAttachedObserver = webVRController._meshAttachedObservable.add(function (mesh) {
  91953. _this._setLaserPointerParent(mesh);
  91954. });
  91955. return _this;
  91956. }
  91957. VRExperienceHelperControllerGazer.prototype._getForwardRay = function (length) {
  91958. return this.webVRController.getForwardRay(length);
  91959. };
  91960. VRExperienceHelperControllerGazer.prototype._activatePointer = function () {
  91961. _super.prototype._activatePointer.call(this);
  91962. this._laserPointer.isVisible = true;
  91963. };
  91964. VRExperienceHelperControllerGazer.prototype._deactivatePointer = function () {
  91965. _super.prototype._deactivatePointer.call(this);
  91966. this._laserPointer.isVisible = false;
  91967. };
  91968. VRExperienceHelperControllerGazer.prototype._setLaserPointerColor = function (color) {
  91969. this._laserPointer.material.emissiveColor = color;
  91970. };
  91971. VRExperienceHelperControllerGazer.prototype._setLaserPointerParent = function (mesh) {
  91972. var makeNotPick = function (root) {
  91973. root.name += " laserPointer";
  91974. root.isPickable = false;
  91975. root.getChildMeshes().forEach(function (c) {
  91976. makeNotPick(c);
  91977. });
  91978. };
  91979. makeNotPick(mesh);
  91980. var childMeshes = mesh.getChildMeshes();
  91981. this.webVRController._pointingPoseNode = null;
  91982. for (var i = 0; i < childMeshes.length; i++) {
  91983. if (childMeshes[i].name && childMeshes[i].name.indexOf(BABYLON.PoseEnabledController.POINTING_POSE) >= 0) {
  91984. mesh = childMeshes[i];
  91985. this.webVRController._pointingPoseNode = mesh;
  91986. break;
  91987. }
  91988. }
  91989. this._laserPointer.parent = mesh;
  91990. };
  91991. VRExperienceHelperControllerGazer.prototype._updatePointerDistance = function (distance) {
  91992. if (distance === void 0) { distance = 100; }
  91993. this._laserPointer.scaling.y = distance;
  91994. this._laserPointer.position.z = -distance / 2;
  91995. };
  91996. VRExperienceHelperControllerGazer.prototype.dispose = function () {
  91997. _super.prototype.dispose.call(this);
  91998. this._laserPointer.dispose();
  91999. if (this._meshAttachedObserver) {
  92000. this.webVRController._meshAttachedObservable.remove(this._meshAttachedObserver);
  92001. }
  92002. };
  92003. return VRExperienceHelperControllerGazer;
  92004. }(VRExperienceHelperGazer));
  92005. var VRExperienceHelperCameraGazer = /** @class */ (function (_super) {
  92006. __extends(VRExperienceHelperCameraGazer, _super);
  92007. function VRExperienceHelperCameraGazer(getCamera, scene) {
  92008. var _this = _super.call(this, scene) || this;
  92009. _this.getCamera = getCamera;
  92010. return _this;
  92011. }
  92012. VRExperienceHelperCameraGazer.prototype._getForwardRay = function (length) {
  92013. var camera = this.getCamera();
  92014. if (camera) {
  92015. return camera.getForwardRay(length);
  92016. }
  92017. else {
  92018. return new BABYLON.Ray(BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward());
  92019. }
  92020. };
  92021. return VRExperienceHelperCameraGazer;
  92022. }(VRExperienceHelperGazer));
  92023. /**
  92024. * Helps to quickly add VR support to an existing scene.
  92025. * See http://doc.babylonjs.com/how_to/webvr_helper
  92026. */
  92027. var VRExperienceHelper = /** @class */ (function () {
  92028. /**
  92029. * Instantiates a VRExperienceHelper.
  92030. * Helps to quickly add VR support to an existing scene.
  92031. * @param scene The scene the VRExperienceHelper belongs to.
  92032. * @param webVROptions Options to modify the vr experience helper's behavior.
  92033. */
  92034. function VRExperienceHelper(scene, /** Options to modify the vr experience helper's behavior. */ webVROptions) {
  92035. if (webVROptions === void 0) { webVROptions = {}; }
  92036. var _this = this;
  92037. this.webVROptions = webVROptions;
  92038. // Can the system support WebVR, even if a headset isn't plugged in?
  92039. this._webVRsupported = false;
  92040. // If WebVR is supported, is a headset plugged in and are we ready to present?
  92041. this._webVRready = false;
  92042. // Are we waiting for the requestPresent callback to complete?
  92043. this._webVRrequesting = false;
  92044. // Are we presenting to the headset right now?
  92045. this._webVRpresenting = false;
  92046. // Are we presenting in the fullscreen fallback?
  92047. this._fullscreenVRpresenting = false;
  92048. /**
  92049. * Observable raised when entering VR.
  92050. */
  92051. this.onEnteringVRObservable = new BABYLON.Observable();
  92052. /**
  92053. * Observable raised when exiting VR.
  92054. */
  92055. this.onExitingVRObservable = new BABYLON.Observable();
  92056. /**
  92057. * Observable raised when controller mesh is loaded.
  92058. */
  92059. this.onControllerMeshLoadedObservable = new BABYLON.Observable();
  92060. this._useCustomVRButton = false;
  92061. this._teleportationRequested = false;
  92062. this._teleportActive = false;
  92063. this._floorMeshesCollection = [];
  92064. this._rotationAllowed = true;
  92065. this._teleportBackwardsVector = new BABYLON.Vector3(0, -1, -1);
  92066. this._isDefaultTeleportationTarget = true;
  92067. this._teleportationFillColor = "#444444";
  92068. this._teleportationBorderColor = "#FFFFFF";
  92069. this._rotationAngle = 0;
  92070. this._haloCenter = new BABYLON.Vector3(0, 0, 0);
  92071. this._padSensibilityUp = 0.65;
  92072. this._padSensibilityDown = 0.35;
  92073. this.leftController = null;
  92074. this.rightController = null;
  92075. /**
  92076. * Observable raised when a new mesh is selected based on meshSelectionPredicate
  92077. */
  92078. this.onNewMeshSelected = new BABYLON.Observable();
  92079. /**
  92080. * Observable raised when a new mesh is picked based on meshSelectionPredicate
  92081. */
  92082. this.onNewMeshPicked = new BABYLON.Observable();
  92083. /**
  92084. * Observable raised before camera teleportation
  92085. */
  92086. this.onBeforeCameraTeleport = new BABYLON.Observable();
  92087. /**
  92088. * Observable raised after camera teleportation
  92089. */
  92090. this.onAfterCameraTeleport = new BABYLON.Observable();
  92091. /**
  92092. * Observable raised when current selected mesh gets unselected
  92093. */
  92094. this.onSelectedMeshUnselected = new BABYLON.Observable();
  92095. /**
  92096. * Set teleportation enabled. If set to false camera teleportation will be disabled but camera rotation will be kept.
  92097. */
  92098. this.teleportationEnabled = true;
  92099. this._teleportationInitialized = false;
  92100. this._interactionsEnabled = false;
  92101. this._interactionsRequested = false;
  92102. this._displayGaze = true;
  92103. this._displayLaserPointer = true;
  92104. this._onResize = function () {
  92105. _this.moveButtonToBottomRight();
  92106. if (_this._fullscreenVRpresenting && _this._webVRready) {
  92107. _this.exitVR();
  92108. }
  92109. };
  92110. this._onFullscreenChange = function () {
  92111. if (document.fullscreen !== undefined) {
  92112. _this._fullscreenVRpresenting = document.fullscreen;
  92113. }
  92114. else if (document.mozFullScreen !== undefined) {
  92115. _this._fullscreenVRpresenting = document.mozFullScreen;
  92116. }
  92117. else if (document.webkitIsFullScreen !== undefined) {
  92118. _this._fullscreenVRpresenting = document.webkitIsFullScreen;
  92119. }
  92120. else if (document.msIsFullScreen !== undefined) {
  92121. _this._fullscreenVRpresenting = document.msIsFullScreen;
  92122. }
  92123. else if (document.msFullscreenElement !== undefined) {
  92124. _this._fullscreenVRpresenting = document.msFullscreenElement;
  92125. }
  92126. if (!_this._fullscreenVRpresenting && _this._canvas) {
  92127. _this.exitVR();
  92128. if (!_this._useCustomVRButton) {
  92129. _this._btnVR.style.top = _this._canvas.offsetTop + _this._canvas.offsetHeight - 70 + "px";
  92130. _this._btnVR.style.left = _this._canvas.offsetLeft + _this._canvas.offsetWidth - 100 + "px";
  92131. }
  92132. }
  92133. };
  92134. this.beforeRender = function () {
  92135. if (_this.leftController && _this.leftController._activePointer) {
  92136. _this._castRayAndSelectObject(_this.leftController);
  92137. }
  92138. if (_this.rightController && _this.rightController._activePointer) {
  92139. _this._castRayAndSelectObject(_this.rightController);
  92140. }
  92141. if (_this._noControllerIsActive) {
  92142. _this._castRayAndSelectObject(_this._cameraGazer);
  92143. }
  92144. else {
  92145. _this._cameraGazer._gazeTracker.isVisible = false;
  92146. }
  92147. };
  92148. this._onNewGamepadConnected = function (gamepad) {
  92149. if (gamepad.type !== BABYLON.Gamepad.POSE_ENABLED) {
  92150. if (gamepad.leftStick) {
  92151. gamepad.onleftstickchanged(function (stickValues) {
  92152. if (_this._teleportationInitialized && _this.teleportationEnabled) {
  92153. // Listening to classic/xbox gamepad only if no VR controller is active
  92154. if ((!_this.leftController && !_this.rightController) ||
  92155. ((_this.leftController && !_this.leftController._activePointer) &&
  92156. (_this.rightController && !_this.rightController._activePointer))) {
  92157. _this._checkTeleportWithRay(stickValues, _this._cameraGazer);
  92158. _this._checkTeleportBackwards(stickValues, _this._cameraGazer);
  92159. }
  92160. }
  92161. });
  92162. }
  92163. if (gamepad.rightStick) {
  92164. gamepad.onrightstickchanged(function (stickValues) {
  92165. if (_this._teleportationInitialized) {
  92166. _this._checkRotate(stickValues, _this._cameraGazer);
  92167. }
  92168. });
  92169. }
  92170. if (gamepad.type === BABYLON.Gamepad.XBOX) {
  92171. gamepad.onbuttondown(function (buttonPressed) {
  92172. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92173. _this._cameraGazer._selectionPointerDown();
  92174. }
  92175. });
  92176. gamepad.onbuttonup(function (buttonPressed) {
  92177. if (_this._interactionsEnabled && buttonPressed === BABYLON.Xbox360Button.A) {
  92178. _this._cameraGazer._selectionPointerUp();
  92179. }
  92180. });
  92181. }
  92182. }
  92183. else {
  92184. var webVRController = gamepad;
  92185. var controller = new VRExperienceHelperControllerGazer(webVRController, _this._scene, _this._cameraGazer._gazeTracker);
  92186. if (webVRController.hand === "right" || (_this.leftController && _this.leftController.webVRController != webVRController)) {
  92187. _this.rightController = controller;
  92188. }
  92189. else {
  92190. _this.leftController = controller;
  92191. }
  92192. _this._tryEnableInteractionOnController(controller);
  92193. }
  92194. };
  92195. // 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
  92196. this._tryEnableInteractionOnController = function (controller) {
  92197. if (_this._interactionsRequested && !controller._interactionsEnabled) {
  92198. _this._enableInteractionOnController(controller);
  92199. }
  92200. if (_this._teleportationRequested && !controller._teleportationEnabled) {
  92201. _this._enableTeleportationOnController(controller);
  92202. }
  92203. };
  92204. this._onNewGamepadDisconnected = function (gamepad) {
  92205. if (gamepad instanceof BABYLON.WebVRController) {
  92206. if (gamepad.hand === "left" && _this.leftController != null) {
  92207. _this.leftController.dispose();
  92208. _this.leftController = null;
  92209. }
  92210. if (gamepad.hand === "right" && _this.rightController != null) {
  92211. _this.rightController.dispose();
  92212. _this.rightController = null;
  92213. }
  92214. }
  92215. };
  92216. this._workingVector = BABYLON.Vector3.Zero();
  92217. this._workingQuaternion = BABYLON.Quaternion.Identity();
  92218. this._workingMatrix = BABYLON.Matrix.Identity();
  92219. this._scene = scene;
  92220. this._canvas = scene.getEngine().getRenderingCanvas();
  92221. // Parse options
  92222. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera === undefined) {
  92223. webVROptions.createFallbackVRDeviceOrientationFreeCamera = true;
  92224. }
  92225. if (webVROptions.createDeviceOrientationCamera === undefined) {
  92226. webVROptions.createDeviceOrientationCamera = true;
  92227. }
  92228. if (webVROptions.laserToggle === undefined) {
  92229. webVROptions.laserToggle = true;
  92230. }
  92231. if (webVROptions.defaultHeight === undefined) {
  92232. webVROptions.defaultHeight = 1.7;
  92233. }
  92234. if (webVROptions.useCustomVRButton) {
  92235. this._useCustomVRButton = true;
  92236. if (webVROptions.customVRButton) {
  92237. this._btnVR = webVROptions.customVRButton;
  92238. }
  92239. }
  92240. if (webVROptions.rayLength) {
  92241. this._rayLength = webVROptions.rayLength;
  92242. }
  92243. this._defaultHeight = webVROptions.defaultHeight;
  92244. if (webVROptions.positionScale) {
  92245. this._rayLength *= webVROptions.positionScale;
  92246. this._defaultHeight *= webVROptions.positionScale;
  92247. }
  92248. // Set position
  92249. if (this._scene.activeCamera) {
  92250. this._position = this._scene.activeCamera.position.clone();
  92251. }
  92252. else {
  92253. this._position = new BABYLON.Vector3(0, this._defaultHeight, 0);
  92254. }
  92255. // Set non-vr camera
  92256. if (webVROptions.createDeviceOrientationCamera || !this._scene.activeCamera) {
  92257. this._deviceOrientationCamera = new BABYLON.DeviceOrientationCamera("deviceOrientationVRHelper", this._position.clone(), scene);
  92258. // Copy data from existing camera
  92259. if (this._scene.activeCamera) {
  92260. this._deviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92261. this._deviceOrientationCamera.maxZ = this._scene.activeCamera.maxZ;
  92262. // Set rotation from previous camera
  92263. if (this._scene.activeCamera instanceof BABYLON.TargetCamera && this._scene.activeCamera.rotation) {
  92264. var targetCamera = this._scene.activeCamera;
  92265. if (targetCamera.rotationQuaternion) {
  92266. this._deviceOrientationCamera.rotationQuaternion.copyFrom(targetCamera.rotationQuaternion);
  92267. }
  92268. else {
  92269. this._deviceOrientationCamera.rotationQuaternion.copyFrom(BABYLON.Quaternion.RotationYawPitchRoll(targetCamera.rotation.y, targetCamera.rotation.x, targetCamera.rotation.z));
  92270. }
  92271. this._deviceOrientationCamera.rotation = targetCamera.rotation.clone();
  92272. }
  92273. }
  92274. this._scene.activeCamera = this._deviceOrientationCamera;
  92275. if (this._canvas) {
  92276. this._scene.activeCamera.attachControl(this._canvas);
  92277. }
  92278. }
  92279. else {
  92280. this._existingCamera = this._scene.activeCamera;
  92281. }
  92282. // Create VR cameras
  92283. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92284. this._vrDeviceOrientationCamera = new BABYLON.VRDeviceOrientationFreeCamera("VRDeviceOrientationVRHelper", this._position, this._scene);
  92285. }
  92286. this._webVRCamera = new BABYLON.WebVRFreeCamera("WebVRHelper", this._position, this._scene, webVROptions);
  92287. this._webVRCamera.useStandingMatrix();
  92288. this._cameraGazer = new VRExperienceHelperCameraGazer(function () { return _this.currentVRCamera; }, scene);
  92289. // Create default button
  92290. if (!this._useCustomVRButton) {
  92291. this._btnVR = document.createElement("BUTTON");
  92292. this._btnVR.className = "babylonVRicon";
  92293. this._btnVR.id = "babylonVRiconbtn";
  92294. this._btnVR.title = "Click to switch to VR";
  92295. 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) }";
  92296. css += ".babylonVRicon.vrdisplaypresenting { display: none; }";
  92297. // TODO: Add user feedback so that they know what state the VRDisplay is in (disconnected, connected, entering-VR)
  92298. // css += ".babylonVRicon.vrdisplaysupported { }";
  92299. // css += ".babylonVRicon.vrdisplayready { }";
  92300. // css += ".babylonVRicon.vrdisplayrequesting { }";
  92301. var style = document.createElement('style');
  92302. style.appendChild(document.createTextNode(css));
  92303. document.getElementsByTagName('head')[0].appendChild(style);
  92304. this.moveButtonToBottomRight();
  92305. }
  92306. // VR button click event
  92307. if (this._btnVR) {
  92308. this._btnVR.addEventListener("click", function () {
  92309. if (!_this.isInVRMode) {
  92310. _this.enterVR();
  92311. }
  92312. else {
  92313. _this.exitVR();
  92314. }
  92315. });
  92316. }
  92317. // Window events
  92318. window.addEventListener("resize", this._onResize);
  92319. document.addEventListener("fullscreenchange", this._onFullscreenChange, false);
  92320. document.addEventListener("mozfullscreenchange", this._onFullscreenChange, false);
  92321. document.addEventListener("webkitfullscreenchange", this._onFullscreenChange, false);
  92322. document.addEventListener("msfullscreenchange", this._onFullscreenChange, false);
  92323. document.onmsfullscreenchange = this._onFullscreenChange;
  92324. // Display vr button when headset is connected
  92325. if (webVROptions.createFallbackVRDeviceOrientationFreeCamera) {
  92326. this.displayVRButton();
  92327. }
  92328. else {
  92329. this._scene.getEngine().onVRDisplayChangedObservable.add(function (e) {
  92330. if (e.vrDisplay) {
  92331. _this.displayVRButton();
  92332. }
  92333. });
  92334. }
  92335. // Exiting VR mode using 'ESC' key on desktop
  92336. this._onKeyDown = function (event) {
  92337. if (event.keyCode === 27 && _this.isInVRMode) {
  92338. _this.exitVR();
  92339. }
  92340. };
  92341. document.addEventListener("keydown", this._onKeyDown);
  92342. // Exiting VR mode double tapping the touch screen
  92343. this._scene.onPrePointerObservable.add(function (pointerInfo, eventState) {
  92344. if (_this.isInVRMode) {
  92345. _this.exitVR();
  92346. if (_this._fullscreenVRpresenting) {
  92347. _this._scene.getEngine().switchFullscreen(true);
  92348. }
  92349. }
  92350. }, BABYLON.PointerEventTypes.POINTERDOUBLETAP, false);
  92351. // Listen for WebVR display changes
  92352. this._onVRDisplayChanged = function (eventArgs) { return _this.onVRDisplayChanged(eventArgs); };
  92353. this._onVrDisplayPresentChange = function () { return _this.onVrDisplayPresentChange(); };
  92354. this._onVRRequestPresentStart = function () {
  92355. _this._webVRrequesting = true;
  92356. _this.updateButtonVisibility();
  92357. };
  92358. this._onVRRequestPresentComplete = function (success) {
  92359. _this._webVRrequesting = false;
  92360. _this.updateButtonVisibility();
  92361. };
  92362. scene.getEngine().onVRDisplayChangedObservable.add(this._onVRDisplayChanged);
  92363. scene.getEngine().onVRRequestPresentStart.add(this._onVRRequestPresentStart);
  92364. scene.getEngine().onVRRequestPresentComplete.add(this._onVRRequestPresentComplete);
  92365. window.addEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  92366. scene.onDisposeObservable.add(function () {
  92367. _this.dispose();
  92368. });
  92369. // Gamepad connection events
  92370. this._webVRCamera.onControllerMeshLoadedObservable.add(function (webVRController) { return _this._onDefaultMeshLoaded(webVRController); });
  92371. this._scene.gamepadManager.onGamepadConnectedObservable.add(this._onNewGamepadConnected);
  92372. this._scene.gamepadManager.onGamepadDisconnectedObservable.add(this._onNewGamepadDisconnected);
  92373. this.updateButtonVisibility();
  92374. //create easing functions
  92375. this._circleEase = new BABYLON.CircleEase();
  92376. this._circleEase.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  92377. if (this.webVROptions.floorMeshes) {
  92378. this.enableTeleportation({ floorMeshes: this.webVROptions.floorMeshes });
  92379. }
  92380. }
  92381. Object.defineProperty(VRExperienceHelper.prototype, "onEnteringVR", {
  92382. /** Return this.onEnteringVRObservable
  92383. * Note: This one is for backward compatibility. Please use onEnteringVRObservable directly
  92384. */
  92385. get: function () {
  92386. return this.onEnteringVRObservable;
  92387. },
  92388. enumerable: true,
  92389. configurable: true
  92390. });
  92391. Object.defineProperty(VRExperienceHelper.prototype, "onExitingVR", {
  92392. /** Return this.onExitingVRObservable
  92393. * Note: This one is for backward compatibility. Please use onExitingVRObservable directly
  92394. */
  92395. get: function () {
  92396. return this.onExitingVRObservable;
  92397. },
  92398. enumerable: true,
  92399. configurable: true
  92400. });
  92401. Object.defineProperty(VRExperienceHelper.prototype, "onControllerMeshLoaded", {
  92402. /** Return this.onControllerMeshLoadedObservable
  92403. * Note: This one is for backward compatibility. Please use onControllerMeshLoadedObservable directly
  92404. */
  92405. get: function () {
  92406. return this.onControllerMeshLoadedObservable;
  92407. },
  92408. enumerable: true,
  92409. configurable: true
  92410. });
  92411. Object.defineProperty(VRExperienceHelper.prototype, "teleportationTarget", {
  92412. /**
  92413. * The mesh used to display where the user is going to teleport.
  92414. */
  92415. get: function () {
  92416. return this._teleportationTarget;
  92417. },
  92418. /**
  92419. * Sets the mesh to be used to display where the user is going to teleport.
  92420. */
  92421. set: function (value) {
  92422. if (value) {
  92423. value.name = "teleportationTarget";
  92424. this._isDefaultTeleportationTarget = false;
  92425. this._teleportationTarget = value;
  92426. }
  92427. },
  92428. enumerable: true,
  92429. configurable: true
  92430. });
  92431. Object.defineProperty(VRExperienceHelper.prototype, "gazeTrackerMesh", {
  92432. /**
  92433. * The mesh used to display where the user is selecting,
  92434. * when set bakeCurrentTransformIntoVertices will be called on the mesh.
  92435. * See http://doc.babylonjs.com/resources/baking_transformations
  92436. */
  92437. get: function () {
  92438. return this._cameraGazer._gazeTracker;
  92439. },
  92440. set: function (value) {
  92441. if (value) {
  92442. this._cameraGazer._gazeTracker = value;
  92443. this._cameraGazer._gazeTracker.bakeCurrentTransformIntoVertices();
  92444. this._cameraGazer._gazeTracker.isPickable = false;
  92445. this._cameraGazer._gazeTracker.isVisible = false;
  92446. this._cameraGazer._gazeTracker.name = "gazeTracker";
  92447. if (this.leftController) {
  92448. this.leftController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92449. }
  92450. if (this.rightController) {
  92451. this.rightController._gazeTracker = this._cameraGazer._gazeTracker.clone("gazeTracker");
  92452. }
  92453. }
  92454. },
  92455. enumerable: true,
  92456. configurable: true
  92457. });
  92458. Object.defineProperty(VRExperienceHelper.prototype, "displayGaze", {
  92459. /**
  92460. * If the ray of the gaze should be displayed.
  92461. */
  92462. get: function () {
  92463. return this._displayGaze;
  92464. },
  92465. /**
  92466. * Sets if the ray of the gaze should be displayed.
  92467. */
  92468. set: function (value) {
  92469. this._displayGaze = value;
  92470. if (!value) {
  92471. this._cameraGazer._gazeTracker.isVisible = false;
  92472. if (this.leftController) {
  92473. this.leftController._gazeTracker.isVisible = false;
  92474. }
  92475. if (this.rightController) {
  92476. this.rightController._gazeTracker.isVisible = false;
  92477. }
  92478. }
  92479. },
  92480. enumerable: true,
  92481. configurable: true
  92482. });
  92483. Object.defineProperty(VRExperienceHelper.prototype, "displayLaserPointer", {
  92484. /**
  92485. * If the ray of the LaserPointer should be displayed.
  92486. */
  92487. get: function () {
  92488. return this._displayLaserPointer;
  92489. },
  92490. /**
  92491. * Sets if the ray of the LaserPointer should be displayed.
  92492. */
  92493. set: function (value) {
  92494. this._displayLaserPointer = value;
  92495. if (!value) {
  92496. if (this.rightController) {
  92497. this.rightController._deactivatePointer();
  92498. this.rightController._gazeTracker.isVisible = false;
  92499. }
  92500. if (this.leftController) {
  92501. this.leftController._deactivatePointer();
  92502. this.leftController._gazeTracker.isVisible = false;
  92503. }
  92504. }
  92505. else {
  92506. if (this.rightController) {
  92507. this.rightController._activatePointer();
  92508. }
  92509. if (this.leftController) {
  92510. this.leftController._activatePointer();
  92511. }
  92512. }
  92513. },
  92514. enumerable: true,
  92515. configurable: true
  92516. });
  92517. Object.defineProperty(VRExperienceHelper.prototype, "deviceOrientationCamera", {
  92518. /**
  92519. * The deviceOrientationCamera used as the camera when not in VR.
  92520. */
  92521. get: function () {
  92522. return this._deviceOrientationCamera;
  92523. },
  92524. enumerable: true,
  92525. configurable: true
  92526. });
  92527. Object.defineProperty(VRExperienceHelper.prototype, "currentVRCamera", {
  92528. /**
  92529. * Based on the current WebVR support, returns the current VR camera used.
  92530. */
  92531. get: function () {
  92532. if (this._webVRready) {
  92533. return this._webVRCamera;
  92534. }
  92535. else {
  92536. return this._scene.activeCamera;
  92537. }
  92538. },
  92539. enumerable: true,
  92540. configurable: true
  92541. });
  92542. Object.defineProperty(VRExperienceHelper.prototype, "webVRCamera", {
  92543. /**
  92544. * The webVRCamera which is used when in VR.
  92545. */
  92546. get: function () {
  92547. return this._webVRCamera;
  92548. },
  92549. enumerable: true,
  92550. configurable: true
  92551. });
  92552. Object.defineProperty(VRExperienceHelper.prototype, "vrDeviceOrientationCamera", {
  92553. /**
  92554. * The deviceOrientationCamera that is used as a fallback when vr device is not connected.
  92555. */
  92556. get: function () {
  92557. return this._vrDeviceOrientationCamera;
  92558. },
  92559. enumerable: true,
  92560. configurable: true
  92561. });
  92562. Object.defineProperty(VRExperienceHelper.prototype, "_teleportationRequestInitiated", {
  92563. get: function () {
  92564. var result = this._cameraGazer._teleportationRequestInitiated
  92565. || (this.leftController !== null && this.leftController._teleportationRequestInitiated)
  92566. || (this.rightController !== null && this.rightController._teleportationRequestInitiated);
  92567. return result;
  92568. },
  92569. enumerable: true,
  92570. configurable: true
  92571. });
  92572. // Raised when one of the controller has loaded successfully its associated default mesh
  92573. VRExperienceHelper.prototype._onDefaultMeshLoaded = function (webVRController) {
  92574. if (this.leftController && this.leftController.webVRController == webVRController) {
  92575. if (webVRController.mesh) {
  92576. this.leftController._setLaserPointerParent(webVRController.mesh);
  92577. }
  92578. }
  92579. if (this.rightController && this.rightController.webVRController == webVRController) {
  92580. if (webVRController.mesh) {
  92581. this.rightController._setLaserPointerParent(webVRController.mesh);
  92582. }
  92583. }
  92584. try {
  92585. this.onControllerMeshLoadedObservable.notifyObservers(webVRController);
  92586. }
  92587. catch (err) {
  92588. BABYLON.Tools.Warn("Error in your custom logic onControllerMeshLoaded: " + err);
  92589. }
  92590. };
  92591. Object.defineProperty(VRExperienceHelper.prototype, "isInVRMode", {
  92592. /**
  92593. * Gets a value indicating if we are currently in VR mode.
  92594. */
  92595. get: function () {
  92596. return this._webVRpresenting || this._fullscreenVRpresenting;
  92597. },
  92598. enumerable: true,
  92599. configurable: true
  92600. });
  92601. VRExperienceHelper.prototype.onVrDisplayPresentChange = function () {
  92602. var vrDisplay = this._scene.getEngine().getVRDevice();
  92603. if (vrDisplay) {
  92604. var wasPresenting = this._webVRpresenting;
  92605. // A VR display is connected
  92606. this._webVRpresenting = vrDisplay.isPresenting;
  92607. if (wasPresenting && !this._webVRpresenting)
  92608. this.exitVR();
  92609. }
  92610. else {
  92611. BABYLON.Tools.Warn('Detected VRDisplayPresentChange on an unknown VRDisplay. Did you can enterVR on the vrExperienceHelper?');
  92612. }
  92613. this.updateButtonVisibility();
  92614. };
  92615. VRExperienceHelper.prototype.onVRDisplayChanged = function (eventArgs) {
  92616. this._webVRsupported = eventArgs.vrSupported;
  92617. this._webVRready = !!eventArgs.vrDisplay;
  92618. this._webVRpresenting = eventArgs.vrDisplay && eventArgs.vrDisplay.isPresenting;
  92619. this.updateButtonVisibility();
  92620. };
  92621. VRExperienceHelper.prototype.moveButtonToBottomRight = function () {
  92622. if (this._canvas && !this._useCustomVRButton) {
  92623. this._btnVR.style.top = this._canvas.offsetTop + this._canvas.offsetHeight - 70 + "px";
  92624. this._btnVR.style.left = this._canvas.offsetLeft + this._canvas.offsetWidth - 100 + "px";
  92625. }
  92626. };
  92627. VRExperienceHelper.prototype.displayVRButton = function () {
  92628. if (!this._useCustomVRButton && !this._btnVRDisplayed) {
  92629. document.body.appendChild(this._btnVR);
  92630. this._btnVRDisplayed = true;
  92631. }
  92632. };
  92633. VRExperienceHelper.prototype.updateButtonVisibility = function () {
  92634. if (!this._btnVR || this._useCustomVRButton) {
  92635. return;
  92636. }
  92637. this._btnVR.className = "babylonVRicon";
  92638. if (this.isInVRMode) {
  92639. this._btnVR.className += " vrdisplaypresenting";
  92640. }
  92641. else {
  92642. if (this._webVRready)
  92643. this._btnVR.className += " vrdisplayready";
  92644. if (this._webVRsupported)
  92645. this._btnVR.className += " vrdisplaysupported";
  92646. if (this._webVRrequesting)
  92647. this._btnVR.className += " vrdisplayrequesting";
  92648. }
  92649. };
  92650. /**
  92651. * Attempt to enter VR. If a headset is connected and ready, will request present on that.
  92652. * Otherwise, will use the fullscreen API.
  92653. */
  92654. VRExperienceHelper.prototype.enterVR = function () {
  92655. if (this.onEnteringVRObservable) {
  92656. try {
  92657. this.onEnteringVRObservable.notifyObservers(this);
  92658. }
  92659. catch (err) {
  92660. BABYLON.Tools.Warn("Error in your custom logic onEnteringVR: " + err);
  92661. }
  92662. }
  92663. if (this._scene.activeCamera) {
  92664. this._position = this._scene.activeCamera.position.clone();
  92665. // make sure that we return to the last active camera
  92666. this._existingCamera = this._scene.activeCamera;
  92667. }
  92668. if (this._webVRrequesting)
  92669. return;
  92670. // If WebVR is supported and a headset is connected
  92671. if (this._webVRready) {
  92672. if (!this._webVRpresenting) {
  92673. this._webVRCamera.position = this._position;
  92674. this._scene.activeCamera = this._webVRCamera;
  92675. }
  92676. }
  92677. else if (this._vrDeviceOrientationCamera) {
  92678. this._vrDeviceOrientationCamera.position = this._position;
  92679. if (this._scene.activeCamera) {
  92680. this._vrDeviceOrientationCamera.minZ = this._scene.activeCamera.minZ;
  92681. }
  92682. this._scene.activeCamera = this._vrDeviceOrientationCamera;
  92683. this._scene.getEngine().switchFullscreen(true);
  92684. this.updateButtonVisibility();
  92685. }
  92686. if (this._scene.activeCamera && this._canvas) {
  92687. this._scene.activeCamera.attachControl(this._canvas);
  92688. }
  92689. if (this._interactionsEnabled) {
  92690. this._scene.registerBeforeRender(this.beforeRender);
  92691. }
  92692. };
  92693. /**
  92694. * Attempt to exit VR, or fullscreen.
  92695. */
  92696. VRExperienceHelper.prototype.exitVR = function () {
  92697. if (this.onExitingVRObservable) {
  92698. try {
  92699. this.onExitingVRObservable.notifyObservers(this);
  92700. }
  92701. catch (err) {
  92702. BABYLON.Tools.Warn("Error in your custom logic onExitingVR: " + err);
  92703. }
  92704. }
  92705. if (this._webVRpresenting) {
  92706. this._scene.getEngine().disableVR();
  92707. }
  92708. if (this._scene.activeCamera) {
  92709. this._position = this._scene.activeCamera.position.clone();
  92710. }
  92711. if (this._deviceOrientationCamera) {
  92712. this._deviceOrientationCamera.position = this._position;
  92713. this._scene.activeCamera = this._deviceOrientationCamera;
  92714. if (this._canvas) {
  92715. this._scene.activeCamera.attachControl(this._canvas);
  92716. }
  92717. }
  92718. else if (this._existingCamera) {
  92719. this._existingCamera.position = this._position;
  92720. this._scene.activeCamera = this._existingCamera;
  92721. }
  92722. this.updateButtonVisibility();
  92723. if (this._interactionsEnabled) {
  92724. this._scene.unregisterBeforeRender(this.beforeRender);
  92725. }
  92726. // resize to update width and height when exiting vr exits fullscreen
  92727. this._scene.getEngine().resize();
  92728. };
  92729. Object.defineProperty(VRExperienceHelper.prototype, "position", {
  92730. /**
  92731. * The position of the vr experience helper.
  92732. */
  92733. get: function () {
  92734. return this._position;
  92735. },
  92736. /**
  92737. * Sets the position of the vr experience helper.
  92738. */
  92739. set: function (value) {
  92740. this._position = value;
  92741. if (this._scene.activeCamera) {
  92742. this._scene.activeCamera.position = value;
  92743. }
  92744. },
  92745. enumerable: true,
  92746. configurable: true
  92747. });
  92748. /**
  92749. * Enables controllers and user interactions suck as selecting and object or clicking on an object.
  92750. */
  92751. VRExperienceHelper.prototype.enableInteractions = function () {
  92752. var _this = this;
  92753. if (!this._interactionsEnabled) {
  92754. this._interactionsRequested = true;
  92755. if (this.leftController) {
  92756. this._enableInteractionOnController(this.leftController);
  92757. }
  92758. if (this.rightController) {
  92759. this._enableInteractionOnController(this.rightController);
  92760. }
  92761. this.raySelectionPredicate = function (mesh) {
  92762. return mesh.isVisible;
  92763. };
  92764. this.meshSelectionPredicate = function (mesh) {
  92765. return true;
  92766. };
  92767. this._raySelectionPredicate = function (mesh) {
  92768. if (_this._isTeleportationFloor(mesh) || (mesh.name.indexOf("gazeTracker") === -1
  92769. && mesh.name.indexOf("teleportationTarget") === -1
  92770. && mesh.name.indexOf("torusTeleportation") === -1
  92771. && mesh.name.indexOf("laserPointer") === -1)) {
  92772. return _this.raySelectionPredicate(mesh);
  92773. }
  92774. return false;
  92775. };
  92776. this._interactionsEnabled = true;
  92777. }
  92778. };
  92779. Object.defineProperty(VRExperienceHelper.prototype, "_noControllerIsActive", {
  92780. get: function () {
  92781. return !(this.leftController && this.leftController._activePointer) && !(this.rightController && this.rightController._activePointer);
  92782. },
  92783. enumerable: true,
  92784. configurable: true
  92785. });
  92786. VRExperienceHelper.prototype._isTeleportationFloor = function (mesh) {
  92787. for (var i = 0; i < this._floorMeshesCollection.length; i++) {
  92788. if (this._floorMeshesCollection[i].id === mesh.id) {
  92789. return true;
  92790. }
  92791. }
  92792. if (this._floorMeshName && mesh.name === this._floorMeshName) {
  92793. return true;
  92794. }
  92795. return false;
  92796. };
  92797. /**
  92798. * Adds a floor mesh to be used for teleportation.
  92799. * @param floorMesh the mesh to be used for teleportation.
  92800. */
  92801. VRExperienceHelper.prototype.addFloorMesh = function (floorMesh) {
  92802. if (!this._floorMeshesCollection) {
  92803. return;
  92804. }
  92805. if (this._floorMeshesCollection.indexOf(floorMesh) > -1) {
  92806. return;
  92807. }
  92808. this._floorMeshesCollection.push(floorMesh);
  92809. };
  92810. /**
  92811. * Removes a floor mesh from being used for teleportation.
  92812. * @param floorMesh the mesh to be removed.
  92813. */
  92814. VRExperienceHelper.prototype.removeFloorMesh = function (floorMesh) {
  92815. if (!this._floorMeshesCollection) {
  92816. return;
  92817. }
  92818. var meshIndex = this._floorMeshesCollection.indexOf(floorMesh);
  92819. if (meshIndex !== -1) {
  92820. this._floorMeshesCollection.splice(meshIndex, 1);
  92821. }
  92822. };
  92823. /**
  92824. * Enables interactions and teleportation using the VR controllers and gaze.
  92825. * @param vrTeleportationOptions options to modify teleportation behavior.
  92826. */
  92827. VRExperienceHelper.prototype.enableTeleportation = function (vrTeleportationOptions) {
  92828. if (vrTeleportationOptions === void 0) { vrTeleportationOptions = {}; }
  92829. if (!this._teleportationInitialized) {
  92830. this._teleportationRequested = true;
  92831. this.enableInteractions();
  92832. if (vrTeleportationOptions.floorMeshName) {
  92833. this._floorMeshName = vrTeleportationOptions.floorMeshName;
  92834. }
  92835. if (vrTeleportationOptions.floorMeshes) {
  92836. this._floorMeshesCollection = vrTeleportationOptions.floorMeshes;
  92837. }
  92838. if (this.leftController != null) {
  92839. this._enableTeleportationOnController(this.leftController);
  92840. }
  92841. if (this.rightController != null) {
  92842. this._enableTeleportationOnController(this.rightController);
  92843. }
  92844. // Creates an image processing post process for the vignette not relying
  92845. // on the main scene configuration for image processing to reduce setup and spaces
  92846. // (gamma/linear) conflicts.
  92847. var imageProcessingConfiguration = new BABYLON.ImageProcessingConfiguration();
  92848. imageProcessingConfiguration.vignetteColor = new BABYLON.Color4(0, 0, 0, 0);
  92849. imageProcessingConfiguration.vignetteEnabled = true;
  92850. this._postProcessMove = new BABYLON.ImageProcessingPostProcess("postProcessMove", 1.0, this._webVRCamera, undefined, undefined, undefined, undefined, imageProcessingConfiguration);
  92851. this._webVRCamera.detachPostProcess(this._postProcessMove);
  92852. this._teleportationInitialized = true;
  92853. if (this._isDefaultTeleportationTarget) {
  92854. this._createTeleportationCircles();
  92855. this._teleportationTarget.scaling.scaleInPlace(this._webVRCamera.deviceScaleFactor);
  92856. }
  92857. }
  92858. };
  92859. VRExperienceHelper.prototype._enableInteractionOnController = function (controller) {
  92860. var _this = this;
  92861. var controllerMesh = controller.webVRController.mesh;
  92862. if (controllerMesh) {
  92863. controller._interactionsEnabled = true;
  92864. controller._activatePointer();
  92865. if (this.webVROptions.laserToggle) {
  92866. controller.webVRController.onMainButtonStateChangedObservable.add(function (stateObject) {
  92867. // Enabling / disabling laserPointer
  92868. if (_this._displayLaserPointer && stateObject.value === 1) {
  92869. if (controller._activePointer) {
  92870. controller._deactivatePointer();
  92871. }
  92872. else {
  92873. controller._activatePointer();
  92874. }
  92875. if (_this.displayGaze) {
  92876. controller._gazeTracker.isVisible = controller._activePointer;
  92877. }
  92878. }
  92879. });
  92880. }
  92881. controller.webVRController.onTriggerStateChangedObservable.add(function (stateObject) {
  92882. var gazer = controller;
  92883. if (_this._noControllerIsActive) {
  92884. gazer = _this._cameraGazer;
  92885. }
  92886. if (!gazer._pointerDownOnMeshAsked) {
  92887. if (stateObject.value > _this._padSensibilityUp) {
  92888. gazer._selectionPointerDown();
  92889. }
  92890. }
  92891. else if (stateObject.value < _this._padSensibilityDown) {
  92892. gazer._selectionPointerUp();
  92893. }
  92894. });
  92895. }
  92896. };
  92897. VRExperienceHelper.prototype._checkTeleportWithRay = function (stateObject, gazer) {
  92898. // Dont teleport if another gaze already requested teleportation
  92899. if (this._teleportationRequestInitiated && !gazer._teleportationRequestInitiated) {
  92900. return;
  92901. }
  92902. if (!gazer._teleportationRequestInitiated) {
  92903. if (stateObject.y < -this._padSensibilityUp && gazer._dpadPressed) {
  92904. gazer._activatePointer();
  92905. gazer._teleportationRequestInitiated = true;
  92906. }
  92907. }
  92908. else {
  92909. // Listening to the proper controller values changes to confirm teleportation
  92910. if (Math.sqrt(stateObject.y * stateObject.y + stateObject.x * stateObject.x) < this._padSensibilityDown) {
  92911. if (this._teleportActive) {
  92912. this._teleportCamera(this._haloCenter);
  92913. }
  92914. gazer._teleportationRequestInitiated = false;
  92915. }
  92916. }
  92917. };
  92918. VRExperienceHelper.prototype._checkRotate = function (stateObject, gazer) {
  92919. // Only rotate when user is not currently selecting a teleportation location
  92920. if (gazer._teleportationRequestInitiated) {
  92921. return;
  92922. }
  92923. if (!gazer._rotationLeftAsked) {
  92924. if (stateObject.x < -this._padSensibilityUp && gazer._dpadPressed) {
  92925. gazer._rotationLeftAsked = true;
  92926. if (this._rotationAllowed) {
  92927. this._rotateCamera(false);
  92928. }
  92929. }
  92930. }
  92931. else {
  92932. if (stateObject.x > -this._padSensibilityDown) {
  92933. gazer._rotationLeftAsked = false;
  92934. }
  92935. }
  92936. if (!gazer._rotationRightAsked) {
  92937. if (stateObject.x > this._padSensibilityUp && gazer._dpadPressed) {
  92938. gazer._rotationRightAsked = true;
  92939. if (this._rotationAllowed) {
  92940. this._rotateCamera(true);
  92941. }
  92942. }
  92943. }
  92944. else {
  92945. if (stateObject.x < this._padSensibilityDown) {
  92946. gazer._rotationRightAsked = false;
  92947. }
  92948. }
  92949. };
  92950. VRExperienceHelper.prototype._checkTeleportBackwards = function (stateObject, gazer) {
  92951. // Only teleport backwards when user is not currently selecting a teleportation location
  92952. if (gazer._teleportationRequestInitiated) {
  92953. return;
  92954. }
  92955. // Teleport backwards
  92956. if (stateObject.y > this._padSensibilityUp && gazer._dpadPressed) {
  92957. if (!gazer._teleportationBackRequestInitiated) {
  92958. if (!this.currentVRCamera) {
  92959. return;
  92960. }
  92961. // Get rotation and position of the current camera
  92962. var rotation = BABYLON.Quaternion.FromRotationMatrix(this.currentVRCamera.getWorldMatrix().getRotationMatrix());
  92963. var position = this.currentVRCamera.position;
  92964. // If the camera has device position, use that instead
  92965. if (this.currentVRCamera.devicePosition && this.currentVRCamera.deviceRotationQuaternion) {
  92966. rotation = this.currentVRCamera.deviceRotationQuaternion;
  92967. position = this.currentVRCamera.devicePosition;
  92968. }
  92969. // Get matrix with only the y rotation of the device rotation
  92970. rotation.toEulerAnglesToRef(this._workingVector);
  92971. this._workingVector.z = 0;
  92972. this._workingVector.x = 0;
  92973. BABYLON.Quaternion.RotationYawPitchRollToRef(this._workingVector.y, this._workingVector.x, this._workingVector.z, this._workingQuaternion);
  92974. this._workingQuaternion.toRotationMatrix(this._workingMatrix);
  92975. // Rotate backwards ray by device rotation to cast at the ground behind the user
  92976. BABYLON.Vector3.TransformCoordinatesToRef(this._teleportBackwardsVector, this._workingMatrix, this._workingVector);
  92977. // Teleport if ray hit the ground and is not to far away eg. backwards off a cliff
  92978. var ray = new BABYLON.Ray(position, this._workingVector);
  92979. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  92980. if (hit && hit.pickedPoint && hit.pickedMesh && this._isTeleportationFloor(hit.pickedMesh) && hit.distance < 5) {
  92981. this._teleportCamera(hit.pickedPoint);
  92982. }
  92983. gazer._teleportationBackRequestInitiated = true;
  92984. }
  92985. }
  92986. else {
  92987. gazer._teleportationBackRequestInitiated = false;
  92988. }
  92989. };
  92990. VRExperienceHelper.prototype._enableTeleportationOnController = function (controller) {
  92991. var _this = this;
  92992. var controllerMesh = controller.webVRController.mesh;
  92993. if (controllerMesh) {
  92994. if (!controller._interactionsEnabled) {
  92995. this._enableInteractionOnController(controller);
  92996. }
  92997. controller._interactionsEnabled = true;
  92998. controller._teleportationEnabled = true;
  92999. if (controller.webVRController.controllerType === BABYLON.PoseEnabledControllerType.VIVE) {
  93000. controller._dpadPressed = false;
  93001. controller.webVRController.onPadStateChangedObservable.add(function (stateObject) {
  93002. controller._dpadPressed = stateObject.pressed;
  93003. if (!controller._dpadPressed) {
  93004. controller._rotationLeftAsked = false;
  93005. controller._rotationRightAsked = false;
  93006. controller._teleportationBackRequestInitiated = false;
  93007. }
  93008. });
  93009. }
  93010. controller.webVRController.onPadValuesChangedObservable.add(function (stateObject) {
  93011. if (_this.teleportationEnabled) {
  93012. _this._checkTeleportBackwards(stateObject, controller);
  93013. _this._checkTeleportWithRay(stateObject, controller);
  93014. }
  93015. _this._checkRotate(stateObject, controller);
  93016. });
  93017. }
  93018. };
  93019. VRExperienceHelper.prototype._createTeleportationCircles = function () {
  93020. this._teleportationTarget = BABYLON.Mesh.CreateGround("teleportationTarget", 2, 2, 2, this._scene);
  93021. this._teleportationTarget.isPickable = false;
  93022. var length = 512;
  93023. var dynamicTexture = new BABYLON.DynamicTexture("DynamicTexture", length, this._scene, true);
  93024. dynamicTexture.hasAlpha = true;
  93025. var context = dynamicTexture.getContext();
  93026. var centerX = length / 2;
  93027. var centerY = length / 2;
  93028. var radius = 200;
  93029. context.beginPath();
  93030. context.arc(centerX, centerY, radius, 0, 2 * Math.PI, false);
  93031. context.fillStyle = this._teleportationFillColor;
  93032. context.fill();
  93033. context.lineWidth = 10;
  93034. context.strokeStyle = this._teleportationBorderColor;
  93035. context.stroke();
  93036. context.closePath();
  93037. dynamicTexture.update();
  93038. var teleportationCircleMaterial = new BABYLON.StandardMaterial("TextPlaneMaterial", this._scene);
  93039. teleportationCircleMaterial.diffuseTexture = dynamicTexture;
  93040. this._teleportationTarget.material = teleportationCircleMaterial;
  93041. var torus = BABYLON.Mesh.CreateTorus("torusTeleportation", 0.75, 0.1, 25, this._scene, false);
  93042. torus.isPickable = false;
  93043. torus.parent = this._teleportationTarget;
  93044. var animationInnerCircle = new BABYLON.Animation("animationInnerCircle", "position.y", 30, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  93045. var keys = [];
  93046. keys.push({
  93047. frame: 0,
  93048. value: 0
  93049. });
  93050. keys.push({
  93051. frame: 30,
  93052. value: 0.4
  93053. });
  93054. keys.push({
  93055. frame: 60,
  93056. value: 0
  93057. });
  93058. animationInnerCircle.setKeys(keys);
  93059. var easingFunction = new BABYLON.SineEase();
  93060. easingFunction.setEasingMode(BABYLON.EasingFunction.EASINGMODE_EASEINOUT);
  93061. animationInnerCircle.setEasingFunction(easingFunction);
  93062. torus.animations = [];
  93063. torus.animations.push(animationInnerCircle);
  93064. this._scene.beginAnimation(torus, 0, 60, true);
  93065. this._hideTeleportationTarget();
  93066. };
  93067. VRExperienceHelper.prototype._displayTeleportationTarget = function () {
  93068. this._teleportActive = true;
  93069. if (this._teleportationInitialized) {
  93070. this._teleportationTarget.isVisible = true;
  93071. if (this._isDefaultTeleportationTarget) {
  93072. this._teleportationTarget.getChildren()[0].isVisible = true;
  93073. }
  93074. }
  93075. };
  93076. VRExperienceHelper.prototype._hideTeleportationTarget = function () {
  93077. this._teleportActive = false;
  93078. if (this._teleportationInitialized) {
  93079. this._teleportationTarget.isVisible = false;
  93080. if (this._isDefaultTeleportationTarget) {
  93081. this._teleportationTarget.getChildren()[0].isVisible = false;
  93082. }
  93083. }
  93084. };
  93085. VRExperienceHelper.prototype._rotateCamera = function (right) {
  93086. var _this = this;
  93087. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93088. return;
  93089. }
  93090. if (right) {
  93091. this._rotationAngle++;
  93092. }
  93093. else {
  93094. this._rotationAngle--;
  93095. }
  93096. this.currentVRCamera.animations = [];
  93097. var target = BABYLON.Quaternion.FromRotationMatrix(BABYLON.Matrix.RotationY(Math.PI / 4 * this._rotationAngle));
  93098. var animationRotation = new BABYLON.Animation("animationRotation", "rotationQuaternion", 90, BABYLON.Animation.ANIMATIONTYPE_QUATERNION, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93099. var animationRotationKeys = [];
  93100. animationRotationKeys.push({
  93101. frame: 0,
  93102. value: this.currentVRCamera.rotationQuaternion
  93103. });
  93104. animationRotationKeys.push({
  93105. frame: 6,
  93106. value: target
  93107. });
  93108. animationRotation.setKeys(animationRotationKeys);
  93109. animationRotation.setEasingFunction(this._circleEase);
  93110. this.currentVRCamera.animations.push(animationRotation);
  93111. this._postProcessMove.animations = [];
  93112. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93113. var vignetteWeightKeys = [];
  93114. vignetteWeightKeys.push({
  93115. frame: 0,
  93116. value: 0
  93117. });
  93118. vignetteWeightKeys.push({
  93119. frame: 3,
  93120. value: 4
  93121. });
  93122. vignetteWeightKeys.push({
  93123. frame: 6,
  93124. value: 0
  93125. });
  93126. animationPP.setKeys(vignetteWeightKeys);
  93127. animationPP.setEasingFunction(this._circleEase);
  93128. this._postProcessMove.animations.push(animationPP);
  93129. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93130. var vignetteStretchKeys = [];
  93131. vignetteStretchKeys.push({
  93132. frame: 0,
  93133. value: 0
  93134. });
  93135. vignetteStretchKeys.push({
  93136. frame: 3,
  93137. value: 10
  93138. });
  93139. vignetteStretchKeys.push({
  93140. frame: 6,
  93141. value: 0
  93142. });
  93143. animationPP2.setKeys(vignetteStretchKeys);
  93144. animationPP2.setEasingFunction(this._circleEase);
  93145. this._postProcessMove.animations.push(animationPP2);
  93146. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93147. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93148. this._postProcessMove.samples = 4;
  93149. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93150. this._scene.beginAnimation(this._postProcessMove, 0, 6, false, 1, function () {
  93151. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93152. });
  93153. this._scene.beginAnimation(this.currentVRCamera, 0, 6, false, 1);
  93154. };
  93155. VRExperienceHelper.prototype._moveTeleportationSelectorTo = function (hit, gazer, ray) {
  93156. if (hit.pickedPoint) {
  93157. if (gazer._teleportationRequestInitiated) {
  93158. this._displayTeleportationTarget();
  93159. this._haloCenter.copyFrom(hit.pickedPoint);
  93160. this._teleportationTarget.position.copyFrom(hit.pickedPoint);
  93161. }
  93162. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(true, false), ray);
  93163. if (pickNormal) {
  93164. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93165. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93166. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, this._teleportationTarget.rotation);
  93167. }
  93168. this._teleportationTarget.position.y += 0.1;
  93169. }
  93170. };
  93171. VRExperienceHelper.prototype._teleportCamera = function (location) {
  93172. var _this = this;
  93173. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93174. return;
  93175. }
  93176. // Teleport the hmd to where the user is looking by moving the anchor to where they are looking minus the
  93177. // offset of the headset from the anchor.
  93178. if (this.webVRCamera.leftCamera) {
  93179. this._workingVector.copyFrom(this.webVRCamera.leftCamera.globalPosition);
  93180. this._workingVector.subtractInPlace(this.webVRCamera.position);
  93181. location.subtractToRef(this._workingVector, this._workingVector);
  93182. }
  93183. else {
  93184. this._workingVector.copyFrom(location);
  93185. }
  93186. // Add height to account for user's height offset
  93187. if (this.isInVRMode) {
  93188. this._workingVector.y += this.webVRCamera.deviceDistanceToRoomGround() * this._webVRCamera.deviceScaleFactor;
  93189. }
  93190. else {
  93191. this._workingVector.y += this._defaultHeight;
  93192. }
  93193. this.onBeforeCameraTeleport.notifyObservers(this._workingVector);
  93194. // Create animation from the camera's position to the new location
  93195. this.currentVRCamera.animations = [];
  93196. var animationCameraTeleportation = new BABYLON.Animation("animationCameraTeleportation", "position", 90, BABYLON.Animation.ANIMATIONTYPE_VECTOR3, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93197. var animationCameraTeleportationKeys = [{
  93198. frame: 0,
  93199. value: this.currentVRCamera.position
  93200. },
  93201. {
  93202. frame: 11,
  93203. value: this._workingVector
  93204. }
  93205. ];
  93206. animationCameraTeleportation.setKeys(animationCameraTeleportationKeys);
  93207. animationCameraTeleportation.setEasingFunction(this._circleEase);
  93208. this.currentVRCamera.animations.push(animationCameraTeleportation);
  93209. this._postProcessMove.animations = [];
  93210. var animationPP = new BABYLON.Animation("animationPP", "vignetteWeight", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93211. var vignetteWeightKeys = [];
  93212. vignetteWeightKeys.push({
  93213. frame: 0,
  93214. value: 0
  93215. });
  93216. vignetteWeightKeys.push({
  93217. frame: 5,
  93218. value: 8
  93219. });
  93220. vignetteWeightKeys.push({
  93221. frame: 11,
  93222. value: 0
  93223. });
  93224. animationPP.setKeys(vignetteWeightKeys);
  93225. this._postProcessMove.animations.push(animationPP);
  93226. var animationPP2 = new BABYLON.Animation("animationPP2", "vignetteStretch", 90, BABYLON.Animation.ANIMATIONTYPE_FLOAT, BABYLON.Animation.ANIMATIONLOOPMODE_CONSTANT);
  93227. var vignetteStretchKeys = [];
  93228. vignetteStretchKeys.push({
  93229. frame: 0,
  93230. value: 0
  93231. });
  93232. vignetteStretchKeys.push({
  93233. frame: 5,
  93234. value: 10
  93235. });
  93236. vignetteStretchKeys.push({
  93237. frame: 11,
  93238. value: 0
  93239. });
  93240. animationPP2.setKeys(vignetteStretchKeys);
  93241. this._postProcessMove.animations.push(animationPP2);
  93242. this._postProcessMove.imageProcessingConfiguration.vignetteWeight = 0;
  93243. this._postProcessMove.imageProcessingConfiguration.vignetteStretch = 0;
  93244. this._webVRCamera.attachPostProcess(this._postProcessMove);
  93245. this._scene.beginAnimation(this._postProcessMove, 0, 11, false, 1, function () {
  93246. _this._webVRCamera.detachPostProcess(_this._postProcessMove);
  93247. });
  93248. this._scene.beginAnimation(this.currentVRCamera, 0, 11, false, 1, function () {
  93249. _this.onAfterCameraTeleport.notifyObservers(_this._workingVector);
  93250. });
  93251. this._hideTeleportationTarget();
  93252. };
  93253. VRExperienceHelper.prototype._convertNormalToDirectionOfRay = function (normal, ray) {
  93254. if (normal) {
  93255. var angle = Math.acos(BABYLON.Vector3.Dot(normal, ray.direction));
  93256. if (angle < Math.PI / 2) {
  93257. normal.scaleInPlace(-1);
  93258. }
  93259. }
  93260. return normal;
  93261. };
  93262. VRExperienceHelper.prototype._castRayAndSelectObject = function (gazer) {
  93263. if (!(this.currentVRCamera instanceof BABYLON.FreeCamera)) {
  93264. return;
  93265. }
  93266. var ray = gazer._getForwardRay(this._rayLength);
  93267. var hit = this._scene.pickWithRay(ray, this._raySelectionPredicate);
  93268. if (hit) {
  93269. // Populate the contrllers mesh that can be used for drag/drop
  93270. if (gazer._laserPointer) {
  93271. hit.originMesh = gazer._laserPointer.parent;
  93272. }
  93273. this._scene.simulatePointerMove(hit, { pointerId: gazer._id });
  93274. }
  93275. gazer._currentHit = hit;
  93276. // Moving the gazeTracker on the mesh face targetted
  93277. if (hit && hit.pickedPoint) {
  93278. if (this._displayGaze) {
  93279. var multiplier = 1;
  93280. gazer._gazeTracker.isVisible = true;
  93281. if (gazer._isActionableMesh) {
  93282. multiplier = 3;
  93283. }
  93284. gazer._gazeTracker.scaling.x = hit.distance * multiplier;
  93285. gazer._gazeTracker.scaling.y = hit.distance * multiplier;
  93286. gazer._gazeTracker.scaling.z = hit.distance * multiplier;
  93287. var pickNormal = this._convertNormalToDirectionOfRay(hit.getNormal(), ray);
  93288. // To avoid z-fighting
  93289. var deltaFighting = 0.002;
  93290. if (pickNormal) {
  93291. var axis1 = BABYLON.Vector3.Cross(BABYLON.Axis.Y, pickNormal);
  93292. var axis2 = BABYLON.Vector3.Cross(pickNormal, axis1);
  93293. BABYLON.Vector3.RotationFromAxisToRef(axis2, pickNormal, axis1, gazer._gazeTracker.rotation);
  93294. }
  93295. gazer._gazeTracker.position.copyFrom(hit.pickedPoint);
  93296. if (gazer._gazeTracker.position.x < 0) {
  93297. gazer._gazeTracker.position.x += deltaFighting;
  93298. }
  93299. else {
  93300. gazer._gazeTracker.position.x -= deltaFighting;
  93301. }
  93302. if (gazer._gazeTracker.position.y < 0) {
  93303. gazer._gazeTracker.position.y += deltaFighting;
  93304. }
  93305. else {
  93306. gazer._gazeTracker.position.y -= deltaFighting;
  93307. }
  93308. if (gazer._gazeTracker.position.z < 0) {
  93309. gazer._gazeTracker.position.z += deltaFighting;
  93310. }
  93311. else {
  93312. gazer._gazeTracker.position.z -= deltaFighting;
  93313. }
  93314. }
  93315. // Changing the size of the laser pointer based on the distance from the targetted point
  93316. gazer._updatePointerDistance(hit.distance);
  93317. }
  93318. else {
  93319. gazer._updatePointerDistance();
  93320. gazer._gazeTracker.isVisible = false;
  93321. }
  93322. if (hit && hit.pickedMesh) {
  93323. // The object selected is the floor, we're in a teleportation scenario
  93324. if (this._teleportationInitialized && this._isTeleportationFloor(hit.pickedMesh) && hit.pickedPoint) {
  93325. // Moving the teleportation area to this targetted point
  93326. //Raise onSelectedMeshUnselected observable if ray collided floor mesh/meshes and a non floor mesh was previously selected
  93327. if (gazer._currentMeshSelected && !this._isTeleportationFloor(gazer._currentMeshSelected)) {
  93328. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93329. }
  93330. gazer._currentMeshSelected = null;
  93331. if (gazer._teleportationRequestInitiated) {
  93332. this._moveTeleportationSelectorTo(hit, gazer, ray);
  93333. }
  93334. return;
  93335. }
  93336. // If not, we're in a selection scenario
  93337. //this._teleportationAllowed = false;
  93338. if (hit.pickedMesh !== gazer._currentMeshSelected) {
  93339. if (this.meshSelectionPredicate(hit.pickedMesh)) {
  93340. this.onNewMeshPicked.notifyObservers(hit);
  93341. gazer._currentMeshSelected = hit.pickedMesh;
  93342. if (hit.pickedMesh.isPickable && hit.pickedMesh.actionManager) {
  93343. this.changeGazeColor(new BABYLON.Color3(0, 0, 1));
  93344. this.changeLaserColor(new BABYLON.Color3(0.2, 0.2, 1));
  93345. gazer._isActionableMesh = true;
  93346. }
  93347. else {
  93348. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93349. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93350. gazer._isActionableMesh = false;
  93351. }
  93352. try {
  93353. this.onNewMeshSelected.notifyObservers(hit.pickedMesh);
  93354. }
  93355. catch (err) {
  93356. BABYLON.Tools.Warn("Error in your custom logic onNewMeshSelected: " + err);
  93357. }
  93358. }
  93359. else {
  93360. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93361. gazer._currentMeshSelected = null;
  93362. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93363. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93364. }
  93365. }
  93366. }
  93367. else {
  93368. this._notifySelectedMeshUnselected(gazer._currentMeshSelected);
  93369. gazer._currentMeshSelected = null;
  93370. //this._teleportationAllowed = false;
  93371. this.changeGazeColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93372. this.changeLaserColor(new BABYLON.Color3(0.7, 0.7, 0.7));
  93373. }
  93374. };
  93375. VRExperienceHelper.prototype._notifySelectedMeshUnselected = function (mesh) {
  93376. if (mesh) {
  93377. this.onSelectedMeshUnselected.notifyObservers(mesh);
  93378. }
  93379. };
  93380. /**
  93381. * Sets the color of the laser ray from the vr controllers.
  93382. * @param color new color for the ray.
  93383. */
  93384. VRExperienceHelper.prototype.changeLaserColor = function (color) {
  93385. if (this.leftController) {
  93386. this.leftController._setLaserPointerColor(color);
  93387. }
  93388. if (this.rightController) {
  93389. this.rightController._setLaserPointerColor(color);
  93390. }
  93391. };
  93392. /**
  93393. * Sets the color of the ray from the vr headsets gaze.
  93394. * @param color new color for the ray.
  93395. */
  93396. VRExperienceHelper.prototype.changeGazeColor = function (color) {
  93397. if (!this._cameraGazer._gazeTracker.material) {
  93398. return;
  93399. }
  93400. this._cameraGazer._gazeTracker.material.emissiveColor = color;
  93401. if (this.leftController) {
  93402. this.leftController._gazeTracker.material.emissiveColor = color;
  93403. }
  93404. if (this.rightController) {
  93405. this.rightController._gazeTracker.material.emissiveColor = color;
  93406. }
  93407. };
  93408. /**
  93409. * Exits VR and disposes of the vr experience helper
  93410. */
  93411. VRExperienceHelper.prototype.dispose = function () {
  93412. if (this.isInVRMode) {
  93413. this.exitVR();
  93414. }
  93415. if (this._postProcessMove) {
  93416. this._postProcessMove.dispose();
  93417. }
  93418. if (this._webVRCamera) {
  93419. this._webVRCamera.dispose();
  93420. }
  93421. if (this._vrDeviceOrientationCamera) {
  93422. this._vrDeviceOrientationCamera.dispose();
  93423. }
  93424. if (!this._useCustomVRButton && this._btnVR.parentNode) {
  93425. document.body.removeChild(this._btnVR);
  93426. }
  93427. if (this._deviceOrientationCamera && (this._scene.activeCamera != this._deviceOrientationCamera)) {
  93428. this._deviceOrientationCamera.dispose();
  93429. }
  93430. if (this._cameraGazer) {
  93431. this._cameraGazer.dispose();
  93432. }
  93433. if (this.leftController) {
  93434. this.leftController.dispose();
  93435. }
  93436. if (this.rightController) {
  93437. this.rightController.dispose();
  93438. }
  93439. if (this._teleportationTarget) {
  93440. this._teleportationTarget.dispose();
  93441. }
  93442. this._floorMeshesCollection = [];
  93443. document.removeEventListener("keydown", this._onKeyDown);
  93444. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93445. window.removeEventListener("resize", this._onResize);
  93446. document.removeEventListener("fullscreenchange", this._onFullscreenChange);
  93447. document.removeEventListener("mozfullscreenchange", this._onFullscreenChange);
  93448. document.removeEventListener("webkitfullscreenchange", this._onFullscreenChange);
  93449. document.removeEventListener("msfullscreenchange", this._onFullscreenChange);
  93450. document.onmsfullscreenchange = null;
  93451. this._scene.getEngine().onVRDisplayChangedObservable.removeCallback(this._onVRDisplayChanged);
  93452. this._scene.getEngine().onVRRequestPresentStart.removeCallback(this._onVRRequestPresentStart);
  93453. this._scene.getEngine().onVRRequestPresentComplete.removeCallback(this._onVRRequestPresentComplete);
  93454. window.removeEventListener('vrdisplaypresentchange', this._onVrDisplayPresentChange);
  93455. this._scene.gamepadManager.onGamepadConnectedObservable.removeCallback(this._onNewGamepadConnected);
  93456. this._scene.gamepadManager.onGamepadDisconnectedObservable.removeCallback(this._onNewGamepadDisconnected);
  93457. this._scene.unregisterBeforeRender(this.beforeRender);
  93458. };
  93459. /**
  93460. * Gets the name of the VRExperienceHelper class
  93461. * @returns "VRExperienceHelper"
  93462. */
  93463. VRExperienceHelper.prototype.getClassName = function () {
  93464. return "VRExperienceHelper";
  93465. };
  93466. return VRExperienceHelper;
  93467. }());
  93468. BABYLON.VRExperienceHelper = VRExperienceHelper;
  93469. })(BABYLON || (BABYLON = {}));
  93470. //# sourceMappingURL=babylon.vrExperienceHelper.js.map
  93471. // Mainly based on these 2 articles :
  93472. // 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
  93473. // & on Seb Lee-Delisle original work: http://seb.ly/2011/04/multi-touch-game-controller-in-javascripthtml5-for-ipad/
  93474. var BABYLON;
  93475. (function (BABYLON) {
  93476. /**
  93477. * Defines the potential axis of a Joystick
  93478. */
  93479. var JoystickAxis;
  93480. (function (JoystickAxis) {
  93481. /** X axis */
  93482. JoystickAxis[JoystickAxis["X"] = 0] = "X";
  93483. /** Y axis */
  93484. JoystickAxis[JoystickAxis["Y"] = 1] = "Y";
  93485. /** Z axis */
  93486. JoystickAxis[JoystickAxis["Z"] = 2] = "Z";
  93487. })(JoystickAxis = BABYLON.JoystickAxis || (BABYLON.JoystickAxis = {}));
  93488. /**
  93489. * Class used to define virtual joystick (used in touch mode)
  93490. */
  93491. var VirtualJoystick = /** @class */ (function () {
  93492. /**
  93493. * Creates a new virtual joystick
  93494. * @param leftJoystick defines that the joystick is for left hand (false by default)
  93495. */
  93496. function VirtualJoystick(leftJoystick) {
  93497. var _this = this;
  93498. if (leftJoystick) {
  93499. this._leftJoystick = true;
  93500. }
  93501. else {
  93502. this._leftJoystick = false;
  93503. }
  93504. VirtualJoystick._globalJoystickIndex++;
  93505. // By default left & right arrow keys are moving the X
  93506. // and up & down keys are moving the Y
  93507. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93508. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93509. this.reverseLeftRight = false;
  93510. this.reverseUpDown = false;
  93511. // collections of pointers
  93512. this._touches = new BABYLON.StringDictionary();
  93513. this.deltaPosition = BABYLON.Vector3.Zero();
  93514. this._joystickSensibility = 25;
  93515. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93516. this._onResize = function (evt) {
  93517. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93518. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93519. if (VirtualJoystick.vjCanvas) {
  93520. VirtualJoystick.vjCanvas.width = VirtualJoystick.vjCanvasWidth;
  93521. VirtualJoystick.vjCanvas.height = VirtualJoystick.vjCanvasHeight;
  93522. }
  93523. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvasWidth / 2;
  93524. };
  93525. // injecting a canvas element on top of the canvas 3D game
  93526. if (!VirtualJoystick.vjCanvas) {
  93527. window.addEventListener("resize", this._onResize, false);
  93528. VirtualJoystick.vjCanvas = document.createElement("canvas");
  93529. VirtualJoystick.vjCanvasWidth = window.innerWidth;
  93530. VirtualJoystick.vjCanvasHeight = window.innerHeight;
  93531. VirtualJoystick.vjCanvas.width = window.innerWidth;
  93532. VirtualJoystick.vjCanvas.height = window.innerHeight;
  93533. VirtualJoystick.vjCanvas.style.width = "100%";
  93534. VirtualJoystick.vjCanvas.style.height = "100%";
  93535. VirtualJoystick.vjCanvas.style.position = "absolute";
  93536. VirtualJoystick.vjCanvas.style.backgroundColor = "transparent";
  93537. VirtualJoystick.vjCanvas.style.top = "0px";
  93538. VirtualJoystick.vjCanvas.style.left = "0px";
  93539. VirtualJoystick.vjCanvas.style.zIndex = "5";
  93540. VirtualJoystick.vjCanvas.style.msTouchAction = "none";
  93541. // Support for jQuery PEP polyfill
  93542. VirtualJoystick.vjCanvas.setAttribute("touch-action", "none");
  93543. var context = VirtualJoystick.vjCanvas.getContext('2d');
  93544. if (!context) {
  93545. throw new Error("Unable to create canvas for virtual joystick");
  93546. }
  93547. VirtualJoystick.vjCanvasContext = context;
  93548. VirtualJoystick.vjCanvasContext.strokeStyle = "#ffffff";
  93549. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93550. document.body.appendChild(VirtualJoystick.vjCanvas);
  93551. }
  93552. VirtualJoystick.halfWidth = VirtualJoystick.vjCanvas.width / 2;
  93553. this.pressed = false;
  93554. // default joystick color
  93555. this._joystickColor = "cyan";
  93556. this._joystickPointerID = -1;
  93557. // current joystick position
  93558. this._joystickPointerPos = new BABYLON.Vector2(0, 0);
  93559. this._joystickPreviousPointerPos = new BABYLON.Vector2(0, 0);
  93560. // origin joystick position
  93561. this._joystickPointerStartPos = new BABYLON.Vector2(0, 0);
  93562. this._deltaJoystickVector = new BABYLON.Vector2(0, 0);
  93563. this._onPointerDownHandlerRef = function (evt) {
  93564. _this._onPointerDown(evt);
  93565. };
  93566. this._onPointerMoveHandlerRef = function (evt) {
  93567. _this._onPointerMove(evt);
  93568. };
  93569. this._onPointerUpHandlerRef = function (evt) {
  93570. _this._onPointerUp(evt);
  93571. };
  93572. VirtualJoystick.vjCanvas.addEventListener('pointerdown', this._onPointerDownHandlerRef, false);
  93573. VirtualJoystick.vjCanvas.addEventListener('pointermove', this._onPointerMoveHandlerRef, false);
  93574. VirtualJoystick.vjCanvas.addEventListener('pointerup', this._onPointerUpHandlerRef, false);
  93575. VirtualJoystick.vjCanvas.addEventListener('pointerout', this._onPointerUpHandlerRef, false);
  93576. VirtualJoystick.vjCanvas.addEventListener("contextmenu", function (evt) {
  93577. evt.preventDefault(); // Disables system menu
  93578. }, false);
  93579. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93580. }
  93581. /**
  93582. * Defines joystick sensibility (ie. the ratio beteen a physical move and virtual joystick position change)
  93583. * @param newJoystickSensibility defines the new sensibility
  93584. */
  93585. VirtualJoystick.prototype.setJoystickSensibility = function (newJoystickSensibility) {
  93586. this._joystickSensibility = newJoystickSensibility;
  93587. this._inversedSensibility = 1 / (this._joystickSensibility / 1000);
  93588. };
  93589. VirtualJoystick.prototype._onPointerDown = function (e) {
  93590. var positionOnScreenCondition;
  93591. e.preventDefault();
  93592. if (this._leftJoystick === true) {
  93593. positionOnScreenCondition = (e.clientX < VirtualJoystick.halfWidth);
  93594. }
  93595. else {
  93596. positionOnScreenCondition = (e.clientX > VirtualJoystick.halfWidth);
  93597. }
  93598. if (positionOnScreenCondition && this._joystickPointerID < 0) {
  93599. // First contact will be dedicated to the virtual joystick
  93600. this._joystickPointerID = e.pointerId;
  93601. this._joystickPointerStartPos.x = e.clientX;
  93602. this._joystickPointerStartPos.y = e.clientY;
  93603. this._joystickPointerPos = this._joystickPointerStartPos.clone();
  93604. this._joystickPreviousPointerPos = this._joystickPointerStartPos.clone();
  93605. this._deltaJoystickVector.x = 0;
  93606. this._deltaJoystickVector.y = 0;
  93607. this.pressed = true;
  93608. this._touches.add(e.pointerId.toString(), e);
  93609. }
  93610. else {
  93611. // You can only trigger the action buttons with a joystick declared
  93612. if (VirtualJoystick._globalJoystickIndex < 2 && this._action) {
  93613. this._action();
  93614. this._touches.add(e.pointerId.toString(), { x: e.clientX, y: e.clientY, prevX: e.clientX, prevY: e.clientY });
  93615. }
  93616. }
  93617. };
  93618. VirtualJoystick.prototype._onPointerMove = function (e) {
  93619. // If the current pointer is the one associated to the joystick (first touch contact)
  93620. if (this._joystickPointerID == e.pointerId) {
  93621. this._joystickPointerPos.x = e.clientX;
  93622. this._joystickPointerPos.y = e.clientY;
  93623. this._deltaJoystickVector = this._joystickPointerPos.clone();
  93624. this._deltaJoystickVector = this._deltaJoystickVector.subtract(this._joystickPointerStartPos);
  93625. var directionLeftRight = this.reverseLeftRight ? -1 : 1;
  93626. var deltaJoystickX = directionLeftRight * this._deltaJoystickVector.x / this._inversedSensibility;
  93627. switch (this._axisTargetedByLeftAndRight) {
  93628. case JoystickAxis.X:
  93629. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickX));
  93630. break;
  93631. case JoystickAxis.Y:
  93632. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickX));
  93633. break;
  93634. case JoystickAxis.Z:
  93635. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickX));
  93636. break;
  93637. }
  93638. var directionUpDown = this.reverseUpDown ? 1 : -1;
  93639. var deltaJoystickY = directionUpDown * this._deltaJoystickVector.y / this._inversedSensibility;
  93640. switch (this._axisTargetedByUpAndDown) {
  93641. case JoystickAxis.X:
  93642. this.deltaPosition.x = Math.min(1, Math.max(-1, deltaJoystickY));
  93643. break;
  93644. case JoystickAxis.Y:
  93645. this.deltaPosition.y = Math.min(1, Math.max(-1, deltaJoystickY));
  93646. break;
  93647. case JoystickAxis.Z:
  93648. this.deltaPosition.z = Math.min(1, Math.max(-1, deltaJoystickY));
  93649. break;
  93650. }
  93651. }
  93652. else {
  93653. var data = this._touches.get(e.pointerId.toString());
  93654. if (data) {
  93655. data.x = e.clientX;
  93656. data.y = e.clientY;
  93657. }
  93658. }
  93659. };
  93660. VirtualJoystick.prototype._onPointerUp = function (e) {
  93661. if (this._joystickPointerID == e.pointerId) {
  93662. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPointerStartPos.x - 64, this._joystickPointerStartPos.y - 64, 128, 128);
  93663. VirtualJoystick.vjCanvasContext.clearRect(this._joystickPreviousPointerPos.x - 42, this._joystickPreviousPointerPos.y - 42, 84, 84);
  93664. this._joystickPointerID = -1;
  93665. this.pressed = false;
  93666. }
  93667. else {
  93668. var touch = this._touches.get(e.pointerId.toString());
  93669. if (touch) {
  93670. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93671. }
  93672. }
  93673. this._deltaJoystickVector.x = 0;
  93674. this._deltaJoystickVector.y = 0;
  93675. this._touches.remove(e.pointerId.toString());
  93676. };
  93677. /**
  93678. * Change the color of the virtual joystick
  93679. * @param newColor a string that must be a CSS color value (like "red") or the hexa value (like "#FF0000")
  93680. */
  93681. VirtualJoystick.prototype.setJoystickColor = function (newColor) {
  93682. this._joystickColor = newColor;
  93683. };
  93684. /**
  93685. * Defines a callback to call when the joystick is touched
  93686. * @param action defines the callback
  93687. */
  93688. VirtualJoystick.prototype.setActionOnTouch = function (action) {
  93689. this._action = action;
  93690. };
  93691. /**
  93692. * Defines which axis you'd like to control for left & right
  93693. * @param axis defines the axis to use
  93694. */
  93695. VirtualJoystick.prototype.setAxisForLeftRight = function (axis) {
  93696. switch (axis) {
  93697. case JoystickAxis.X:
  93698. case JoystickAxis.Y:
  93699. case JoystickAxis.Z:
  93700. this._axisTargetedByLeftAndRight = axis;
  93701. break;
  93702. default:
  93703. this._axisTargetedByLeftAndRight = JoystickAxis.X;
  93704. break;
  93705. }
  93706. };
  93707. /**
  93708. * Defines which axis you'd like to control for up & down
  93709. * @param axis defines the axis to use
  93710. */
  93711. VirtualJoystick.prototype.setAxisForUpDown = function (axis) {
  93712. switch (axis) {
  93713. case JoystickAxis.X:
  93714. case JoystickAxis.Y:
  93715. case JoystickAxis.Z:
  93716. this._axisTargetedByUpAndDown = axis;
  93717. break;
  93718. default:
  93719. this._axisTargetedByUpAndDown = JoystickAxis.Y;
  93720. break;
  93721. }
  93722. };
  93723. VirtualJoystick.prototype._drawVirtualJoystick = function () {
  93724. var _this = this;
  93725. if (this.pressed) {
  93726. this._touches.forEach(function (key, touch) {
  93727. if (touch.pointerId === _this._joystickPointerID) {
  93728. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPointerStartPos.x - 64, _this._joystickPointerStartPos.y - 64, 128, 128);
  93729. VirtualJoystick.vjCanvasContext.clearRect(_this._joystickPreviousPointerPos.x - 42, _this._joystickPreviousPointerPos.y - 42, 84, 84);
  93730. VirtualJoystick.vjCanvasContext.beginPath();
  93731. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93732. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93733. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 40, 0, Math.PI * 2, true);
  93734. VirtualJoystick.vjCanvasContext.stroke();
  93735. VirtualJoystick.vjCanvasContext.closePath();
  93736. VirtualJoystick.vjCanvasContext.beginPath();
  93737. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93738. VirtualJoystick.vjCanvasContext.lineWidth = 2;
  93739. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerStartPos.x, _this._joystickPointerStartPos.y, 60, 0, Math.PI * 2, true);
  93740. VirtualJoystick.vjCanvasContext.stroke();
  93741. VirtualJoystick.vjCanvasContext.closePath();
  93742. VirtualJoystick.vjCanvasContext.beginPath();
  93743. VirtualJoystick.vjCanvasContext.strokeStyle = _this._joystickColor;
  93744. VirtualJoystick.vjCanvasContext.arc(_this._joystickPointerPos.x, _this._joystickPointerPos.y, 40, 0, Math.PI * 2, true);
  93745. VirtualJoystick.vjCanvasContext.stroke();
  93746. VirtualJoystick.vjCanvasContext.closePath();
  93747. _this._joystickPreviousPointerPos = _this._joystickPointerPos.clone();
  93748. }
  93749. else {
  93750. VirtualJoystick.vjCanvasContext.clearRect(touch.prevX - 44, touch.prevY - 44, 88, 88);
  93751. VirtualJoystick.vjCanvasContext.beginPath();
  93752. VirtualJoystick.vjCanvasContext.fillStyle = "white";
  93753. VirtualJoystick.vjCanvasContext.beginPath();
  93754. VirtualJoystick.vjCanvasContext.strokeStyle = "red";
  93755. VirtualJoystick.vjCanvasContext.lineWidth = 6;
  93756. VirtualJoystick.vjCanvasContext.arc(touch.x, touch.y, 40, 0, Math.PI * 2, true);
  93757. VirtualJoystick.vjCanvasContext.stroke();
  93758. VirtualJoystick.vjCanvasContext.closePath();
  93759. touch.prevX = touch.x;
  93760. touch.prevY = touch.y;
  93761. }
  93762. ;
  93763. });
  93764. }
  93765. requestAnimationFrame(function () { _this._drawVirtualJoystick(); });
  93766. };
  93767. /**
  93768. * Release internal HTML canvas
  93769. */
  93770. VirtualJoystick.prototype.releaseCanvas = function () {
  93771. if (VirtualJoystick.vjCanvas) {
  93772. VirtualJoystick.vjCanvas.removeEventListener('pointerdown', this._onPointerDownHandlerRef);
  93773. VirtualJoystick.vjCanvas.removeEventListener('pointermove', this._onPointerMoveHandlerRef);
  93774. VirtualJoystick.vjCanvas.removeEventListener('pointerup', this._onPointerUpHandlerRef);
  93775. VirtualJoystick.vjCanvas.removeEventListener('pointerout', this._onPointerUpHandlerRef);
  93776. window.removeEventListener("resize", this._onResize);
  93777. document.body.removeChild(VirtualJoystick.vjCanvas);
  93778. VirtualJoystick.vjCanvas = null;
  93779. }
  93780. };
  93781. // Used to draw the virtual joystick inside a 2D canvas on top of the WebGL rendering canvas
  93782. VirtualJoystick._globalJoystickIndex = 0;
  93783. return VirtualJoystick;
  93784. }());
  93785. BABYLON.VirtualJoystick = VirtualJoystick;
  93786. })(BABYLON || (BABYLON = {}));
  93787. //# sourceMappingURL=babylon.virtualJoystick.js.map
  93788. var BABYLON;
  93789. (function (BABYLON) {
  93790. // We're mainly based on the logic defined into the FreeCamera code
  93791. var VirtualJoysticksCamera = /** @class */ (function (_super) {
  93792. __extends(VirtualJoysticksCamera, _super);
  93793. function VirtualJoysticksCamera(name, position, scene) {
  93794. var _this = _super.call(this, name, position, scene) || this;
  93795. _this.inputs.addVirtualJoystick();
  93796. return _this;
  93797. }
  93798. VirtualJoysticksCamera.prototype.getClassName = function () {
  93799. return "VirtualJoysticksCamera";
  93800. };
  93801. return VirtualJoysticksCamera;
  93802. }(BABYLON.FreeCamera));
  93803. BABYLON.VirtualJoysticksCamera = VirtualJoysticksCamera;
  93804. })(BABYLON || (BABYLON = {}));
  93805. //# sourceMappingURL=babylon.virtualJoysticksCamera.js.map
  93806. var BABYLON;
  93807. (function (BABYLON) {
  93808. var FreeCameraVirtualJoystickInput = /** @class */ (function () {
  93809. function FreeCameraVirtualJoystickInput() {
  93810. }
  93811. FreeCameraVirtualJoystickInput.prototype.getLeftJoystick = function () {
  93812. return this._leftjoystick;
  93813. };
  93814. FreeCameraVirtualJoystickInput.prototype.getRightJoystick = function () {
  93815. return this._rightjoystick;
  93816. };
  93817. FreeCameraVirtualJoystickInput.prototype.checkInputs = function () {
  93818. if (this._leftjoystick) {
  93819. var camera = this.camera;
  93820. var speed = camera._computeLocalCameraSpeed() * 50;
  93821. var cameraTransform = BABYLON.Matrix.RotationYawPitchRoll(camera.rotation.y, camera.rotation.x, 0);
  93822. var deltaTransform = BABYLON.Vector3.TransformCoordinates(new BABYLON.Vector3(this._leftjoystick.deltaPosition.x * speed, this._leftjoystick.deltaPosition.y * speed, this._leftjoystick.deltaPosition.z * speed), cameraTransform);
  93823. camera.cameraDirection = camera.cameraDirection.add(deltaTransform);
  93824. camera.cameraRotation = camera.cameraRotation.addVector3(this._rightjoystick.deltaPosition);
  93825. if (!this._leftjoystick.pressed) {
  93826. this._leftjoystick.deltaPosition = this._leftjoystick.deltaPosition.scale(0.9);
  93827. }
  93828. if (!this._rightjoystick.pressed) {
  93829. this._rightjoystick.deltaPosition = this._rightjoystick.deltaPosition.scale(0.9);
  93830. }
  93831. }
  93832. };
  93833. FreeCameraVirtualJoystickInput.prototype.attachControl = function (element, noPreventDefault) {
  93834. this._leftjoystick = new BABYLON.VirtualJoystick(true);
  93835. this._leftjoystick.setAxisForUpDown(BABYLON.JoystickAxis.Z);
  93836. this._leftjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.X);
  93837. this._leftjoystick.setJoystickSensibility(0.15);
  93838. this._rightjoystick = new BABYLON.VirtualJoystick(false);
  93839. this._rightjoystick.setAxisForUpDown(BABYLON.JoystickAxis.X);
  93840. this._rightjoystick.setAxisForLeftRight(BABYLON.JoystickAxis.Y);
  93841. this._rightjoystick.reverseUpDown = true;
  93842. this._rightjoystick.setJoystickSensibility(0.05);
  93843. this._rightjoystick.setJoystickColor("yellow");
  93844. };
  93845. FreeCameraVirtualJoystickInput.prototype.detachControl = function (element) {
  93846. this._leftjoystick.releaseCanvas();
  93847. this._rightjoystick.releaseCanvas();
  93848. };
  93849. FreeCameraVirtualJoystickInput.prototype.getClassName = function () {
  93850. return "FreeCameraVirtualJoystickInput";
  93851. };
  93852. FreeCameraVirtualJoystickInput.prototype.getSimpleName = function () {
  93853. return "virtualJoystick";
  93854. };
  93855. return FreeCameraVirtualJoystickInput;
  93856. }());
  93857. BABYLON.FreeCameraVirtualJoystickInput = FreeCameraVirtualJoystickInput;
  93858. BABYLON.CameraInputTypes["FreeCameraVirtualJoystickInput"] = FreeCameraVirtualJoystickInput;
  93859. })(BABYLON || (BABYLON = {}));
  93860. //# sourceMappingURL=babylon.freeCameraVirtualJoystickInput.js.map
  93861. var BABYLON;
  93862. (function (BABYLON) {
  93863. var SimplificationSettings = /** @class */ (function () {
  93864. function SimplificationSettings(quality, distance, optimizeMesh) {
  93865. this.quality = quality;
  93866. this.distance = distance;
  93867. this.optimizeMesh = optimizeMesh;
  93868. }
  93869. return SimplificationSettings;
  93870. }());
  93871. BABYLON.SimplificationSettings = SimplificationSettings;
  93872. var SimplificationQueue = /** @class */ (function () {
  93873. function SimplificationQueue() {
  93874. this.running = false;
  93875. this._simplificationArray = [];
  93876. }
  93877. SimplificationQueue.prototype.addTask = function (task) {
  93878. this._simplificationArray.push(task);
  93879. };
  93880. SimplificationQueue.prototype.executeNext = function () {
  93881. var task = this._simplificationArray.pop();
  93882. if (task) {
  93883. this.running = true;
  93884. this.runSimplification(task);
  93885. }
  93886. else {
  93887. this.running = false;
  93888. }
  93889. };
  93890. SimplificationQueue.prototype.runSimplification = function (task) {
  93891. var _this = this;
  93892. if (task.parallelProcessing) {
  93893. //parallel simplifier
  93894. task.settings.forEach(function (setting) {
  93895. var simplifier = _this.getSimplifier(task);
  93896. simplifier.simplify(setting, function (newMesh) {
  93897. task.mesh.addLODLevel(setting.distance, newMesh);
  93898. newMesh.isVisible = true;
  93899. //check if it is the last
  93900. if (setting.quality === task.settings[task.settings.length - 1].quality && task.successCallback) {
  93901. //all done, run the success callback.
  93902. task.successCallback();
  93903. }
  93904. _this.executeNext();
  93905. });
  93906. });
  93907. }
  93908. else {
  93909. //single simplifier.
  93910. var simplifier = this.getSimplifier(task);
  93911. var runDecimation = function (setting, callback) {
  93912. simplifier.simplify(setting, function (newMesh) {
  93913. task.mesh.addLODLevel(setting.distance, newMesh);
  93914. newMesh.isVisible = true;
  93915. //run the next quality level
  93916. callback();
  93917. });
  93918. };
  93919. BABYLON.AsyncLoop.Run(task.settings.length, function (loop) {
  93920. runDecimation(task.settings[loop.index], function () {
  93921. loop.executeNext();
  93922. });
  93923. }, function () {
  93924. //execution ended, run the success callback.
  93925. if (task.successCallback) {
  93926. task.successCallback();
  93927. }
  93928. _this.executeNext();
  93929. });
  93930. }
  93931. };
  93932. SimplificationQueue.prototype.getSimplifier = function (task) {
  93933. switch (task.simplificationType) {
  93934. case SimplificationType.QUADRATIC:
  93935. default:
  93936. return new QuadraticErrorSimplification(task.mesh);
  93937. }
  93938. };
  93939. return SimplificationQueue;
  93940. }());
  93941. BABYLON.SimplificationQueue = SimplificationQueue;
  93942. /**
  93943. * The implemented types of simplification
  93944. * At the moment only Quadratic Error Decimation is implemented
  93945. */
  93946. var SimplificationType;
  93947. (function (SimplificationType) {
  93948. /** Quadratic error decimation */
  93949. SimplificationType[SimplificationType["QUADRATIC"] = 0] = "QUADRATIC";
  93950. })(SimplificationType = BABYLON.SimplificationType || (BABYLON.SimplificationType = {}));
  93951. var DecimationTriangle = /** @class */ (function () {
  93952. function DecimationTriangle(vertices) {
  93953. this.vertices = vertices;
  93954. this.error = new Array(4);
  93955. this.deleted = false;
  93956. this.isDirty = false;
  93957. this.deletePending = false;
  93958. this.borderFactor = 0;
  93959. }
  93960. return DecimationTriangle;
  93961. }());
  93962. BABYLON.DecimationTriangle = DecimationTriangle;
  93963. var DecimationVertex = /** @class */ (function () {
  93964. function DecimationVertex(position, id) {
  93965. this.position = position;
  93966. this.id = id;
  93967. this.isBorder = true;
  93968. this.q = new QuadraticMatrix();
  93969. this.triangleCount = 0;
  93970. this.triangleStart = 0;
  93971. this.originalOffsets = [];
  93972. }
  93973. DecimationVertex.prototype.updatePosition = function (newPosition) {
  93974. this.position.copyFrom(newPosition);
  93975. };
  93976. return DecimationVertex;
  93977. }());
  93978. BABYLON.DecimationVertex = DecimationVertex;
  93979. var QuadraticMatrix = /** @class */ (function () {
  93980. function QuadraticMatrix(data) {
  93981. this.data = new Array(10);
  93982. for (var i = 0; i < 10; ++i) {
  93983. if (data && data[i]) {
  93984. this.data[i] = data[i];
  93985. }
  93986. else {
  93987. this.data[i] = 0;
  93988. }
  93989. }
  93990. }
  93991. QuadraticMatrix.prototype.det = function (a11, a12, a13, a21, a22, a23, a31, a32, a33) {
  93992. var det = this.data[a11] * this.data[a22] * this.data[a33] + this.data[a13] * this.data[a21] * this.data[a32] +
  93993. this.data[a12] * this.data[a23] * this.data[a31] - this.data[a13] * this.data[a22] * this.data[a31] -
  93994. this.data[a11] * this.data[a23] * this.data[a32] - this.data[a12] * this.data[a21] * this.data[a33];
  93995. return det;
  93996. };
  93997. QuadraticMatrix.prototype.addInPlace = function (matrix) {
  93998. for (var i = 0; i < 10; ++i) {
  93999. this.data[i] += matrix.data[i];
  94000. }
  94001. };
  94002. QuadraticMatrix.prototype.addArrayInPlace = function (data) {
  94003. for (var i = 0; i < 10; ++i) {
  94004. this.data[i] += data[i];
  94005. }
  94006. };
  94007. QuadraticMatrix.prototype.add = function (matrix) {
  94008. var m = new QuadraticMatrix();
  94009. for (var i = 0; i < 10; ++i) {
  94010. m.data[i] = this.data[i] + matrix.data[i];
  94011. }
  94012. return m;
  94013. };
  94014. QuadraticMatrix.FromData = function (a, b, c, d) {
  94015. return new QuadraticMatrix(QuadraticMatrix.DataFromNumbers(a, b, c, d));
  94016. };
  94017. //returning an array to avoid garbage collection
  94018. QuadraticMatrix.DataFromNumbers = function (a, b, c, d) {
  94019. return [a * a, a * b, a * c, a * d, b * b, b * c, b * d, c * c, c * d, d * d];
  94020. };
  94021. return QuadraticMatrix;
  94022. }());
  94023. BABYLON.QuadraticMatrix = QuadraticMatrix;
  94024. var Reference = /** @class */ (function () {
  94025. function Reference(vertexId, triangleId) {
  94026. this.vertexId = vertexId;
  94027. this.triangleId = triangleId;
  94028. }
  94029. return Reference;
  94030. }());
  94031. BABYLON.Reference = Reference;
  94032. /**
  94033. * An implementation of the Quadratic Error simplification algorithm.
  94034. * Original paper : http://www1.cs.columbia.edu/~cs4162/html05s/garland97.pdf
  94035. * Ported mostly from QSlim and http://voxels.blogspot.de/2014/05/quadric-mesh-simplification-with-source.html to babylon JS
  94036. * @author RaananW
  94037. */
  94038. var QuadraticErrorSimplification = /** @class */ (function () {
  94039. function QuadraticErrorSimplification(_mesh) {
  94040. this._mesh = _mesh;
  94041. this.syncIterations = 5000;
  94042. this.aggressiveness = 7;
  94043. this.decimationIterations = 100;
  94044. this.boundingBoxEpsilon = BABYLON.Epsilon;
  94045. }
  94046. QuadraticErrorSimplification.prototype.simplify = function (settings, successCallback) {
  94047. var _this = this;
  94048. this.initDecimatedMesh();
  94049. //iterating through the submeshes array, one after the other.
  94050. BABYLON.AsyncLoop.Run(this._mesh.subMeshes.length, function (loop) {
  94051. _this.initWithMesh(loop.index, function () {
  94052. _this.runDecimation(settings, loop.index, function () {
  94053. loop.executeNext();
  94054. });
  94055. }, settings.optimizeMesh);
  94056. }, function () {
  94057. setTimeout(function () {
  94058. successCallback(_this._reconstructedMesh);
  94059. }, 0);
  94060. });
  94061. };
  94062. QuadraticErrorSimplification.prototype.runDecimation = function (settings, submeshIndex, successCallback) {
  94063. var _this = this;
  94064. var targetCount = ~~(this.triangles.length * settings.quality);
  94065. var deletedTriangles = 0;
  94066. var triangleCount = this.triangles.length;
  94067. var iterationFunction = function (iteration, callback) {
  94068. setTimeout(function () {
  94069. if (iteration % 5 === 0) {
  94070. _this.updateMesh(iteration === 0);
  94071. }
  94072. for (var i = 0; i < _this.triangles.length; ++i) {
  94073. _this.triangles[i].isDirty = false;
  94074. }
  94075. var threshold = 0.000000001 * Math.pow((iteration + 3), _this.aggressiveness);
  94076. var trianglesIterator = function (i) {
  94077. var tIdx = ~~(((_this.triangles.length / 2) + i) % _this.triangles.length);
  94078. var t = _this.triangles[tIdx];
  94079. if (!t)
  94080. return;
  94081. if (t.error[3] > threshold || t.deleted || t.isDirty) {
  94082. return;
  94083. }
  94084. for (var j = 0; j < 3; ++j) {
  94085. if (t.error[j] < threshold) {
  94086. var deleted0 = [];
  94087. var deleted1 = [];
  94088. var v0 = t.vertices[j];
  94089. var v1 = t.vertices[(j + 1) % 3];
  94090. if (v0.isBorder || v1.isBorder)
  94091. continue;
  94092. var p = BABYLON.Vector3.Zero();
  94093. var n = BABYLON.Vector3.Zero();
  94094. var uv = BABYLON.Vector2.Zero();
  94095. var color = new BABYLON.Color4(0, 0, 0, 1);
  94096. _this.calculateError(v0, v1, p, n, uv, color);
  94097. var delTr = new Array();
  94098. if (_this.isFlipped(v0, v1, p, deleted0, t.borderFactor, delTr))
  94099. continue;
  94100. if (_this.isFlipped(v1, v0, p, deleted1, t.borderFactor, delTr))
  94101. continue;
  94102. if (deleted0.indexOf(true) < 0 || deleted1.indexOf(true) < 0)
  94103. continue;
  94104. var uniqueArray = new Array();
  94105. delTr.forEach(function (deletedT) {
  94106. if (uniqueArray.indexOf(deletedT) === -1) {
  94107. deletedT.deletePending = true;
  94108. uniqueArray.push(deletedT);
  94109. }
  94110. });
  94111. if (uniqueArray.length % 2 !== 0) {
  94112. continue;
  94113. }
  94114. v0.q = v1.q.add(v0.q);
  94115. v0.updatePosition(p);
  94116. var tStart = _this.references.length;
  94117. deletedTriangles = _this.updateTriangles(v0, v0, deleted0, deletedTriangles);
  94118. deletedTriangles = _this.updateTriangles(v0, v1, deleted1, deletedTriangles);
  94119. var tCount = _this.references.length - tStart;
  94120. if (tCount <= v0.triangleCount) {
  94121. if (tCount) {
  94122. for (var c = 0; c < tCount; c++) {
  94123. _this.references[v0.triangleStart + c] = _this.references[tStart + c];
  94124. }
  94125. }
  94126. }
  94127. else {
  94128. v0.triangleStart = tStart;
  94129. }
  94130. v0.triangleCount = tCount;
  94131. break;
  94132. }
  94133. }
  94134. };
  94135. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, trianglesIterator, callback, function () { return (triangleCount - deletedTriangles <= targetCount); });
  94136. }, 0);
  94137. };
  94138. BABYLON.AsyncLoop.Run(this.decimationIterations, function (loop) {
  94139. if (triangleCount - deletedTriangles <= targetCount)
  94140. loop.breakLoop();
  94141. else {
  94142. iterationFunction(loop.index, function () {
  94143. loop.executeNext();
  94144. });
  94145. }
  94146. }, function () {
  94147. setTimeout(function () {
  94148. //reconstruct this part of the mesh
  94149. _this.reconstructMesh(submeshIndex);
  94150. successCallback();
  94151. }, 0);
  94152. });
  94153. };
  94154. QuadraticErrorSimplification.prototype.initWithMesh = function (submeshIndex, callback, optimizeMesh) {
  94155. var _this = this;
  94156. this.vertices = [];
  94157. this.triangles = [];
  94158. var positionData = this._mesh.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  94159. var indices = this._mesh.getIndices();
  94160. var submesh = this._mesh.subMeshes[submeshIndex];
  94161. var findInVertices = function (positionToSearch) {
  94162. if (optimizeMesh) {
  94163. for (var ii = 0; ii < _this.vertices.length; ++ii) {
  94164. if (_this.vertices[ii].position.equals(positionToSearch)) {
  94165. return _this.vertices[ii];
  94166. }
  94167. }
  94168. }
  94169. return null;
  94170. };
  94171. var vertexReferences = [];
  94172. var vertexInit = function (i) {
  94173. if (!positionData) {
  94174. return;
  94175. }
  94176. var offset = i + submesh.verticesStart;
  94177. var position = BABYLON.Vector3.FromArray(positionData, offset * 3);
  94178. var vertex = findInVertices(position) || new DecimationVertex(position, _this.vertices.length);
  94179. vertex.originalOffsets.push(offset);
  94180. if (vertex.id === _this.vertices.length) {
  94181. _this.vertices.push(vertex);
  94182. }
  94183. vertexReferences.push(vertex.id);
  94184. };
  94185. //var totalVertices = mesh.getTotalVertices();
  94186. var totalVertices = submesh.verticesCount;
  94187. BABYLON.AsyncLoop.SyncAsyncForLoop(totalVertices, (this.syncIterations / 4) >> 0, vertexInit, function () {
  94188. var indicesInit = function (i) {
  94189. if (!indices) {
  94190. return;
  94191. }
  94192. var offset = (submesh.indexStart / 3) + i;
  94193. var pos = (offset * 3);
  94194. var i0 = indices[pos + 0];
  94195. var i1 = indices[pos + 1];
  94196. var i2 = indices[pos + 2];
  94197. var v0 = _this.vertices[vertexReferences[i0 - submesh.verticesStart]];
  94198. var v1 = _this.vertices[vertexReferences[i1 - submesh.verticesStart]];
  94199. var v2 = _this.vertices[vertexReferences[i2 - submesh.verticesStart]];
  94200. var triangle = new DecimationTriangle([v0, v1, v2]);
  94201. triangle.originalOffset = pos;
  94202. _this.triangles.push(triangle);
  94203. };
  94204. BABYLON.AsyncLoop.SyncAsyncForLoop(submesh.indexCount / 3, _this.syncIterations, indicesInit, function () {
  94205. _this.init(callback);
  94206. });
  94207. });
  94208. };
  94209. QuadraticErrorSimplification.prototype.init = function (callback) {
  94210. var _this = this;
  94211. var triangleInit1 = function (i) {
  94212. var t = _this.triangles[i];
  94213. t.normal = BABYLON.Vector3.Cross(t.vertices[1].position.subtract(t.vertices[0].position), t.vertices[2].position.subtract(t.vertices[0].position)).normalize();
  94214. for (var j = 0; j < 3; j++) {
  94215. 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))));
  94216. }
  94217. };
  94218. BABYLON.AsyncLoop.SyncAsyncForLoop(this.triangles.length, this.syncIterations, triangleInit1, function () {
  94219. var triangleInit2 = function (i) {
  94220. var t = _this.triangles[i];
  94221. for (var j = 0; j < 3; ++j) {
  94222. t.error[j] = _this.calculateError(t.vertices[j], t.vertices[(j + 1) % 3]);
  94223. }
  94224. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94225. };
  94226. BABYLON.AsyncLoop.SyncAsyncForLoop(_this.triangles.length, _this.syncIterations, triangleInit2, function () {
  94227. callback();
  94228. });
  94229. });
  94230. };
  94231. QuadraticErrorSimplification.prototype.reconstructMesh = function (submeshIndex) {
  94232. var newTriangles = [];
  94233. var i;
  94234. for (i = 0; i < this.vertices.length; ++i) {
  94235. this.vertices[i].triangleCount = 0;
  94236. }
  94237. var t;
  94238. var j;
  94239. for (i = 0; i < this.triangles.length; ++i) {
  94240. if (!this.triangles[i].deleted) {
  94241. t = this.triangles[i];
  94242. for (j = 0; j < 3; ++j) {
  94243. t.vertices[j].triangleCount = 1;
  94244. }
  94245. newTriangles.push(t);
  94246. }
  94247. }
  94248. var newPositionData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.PositionKind) || []);
  94249. var newNormalData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.NormalKind) || []);
  94250. var newUVsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.UVKind) || []);
  94251. var newColorsData = (this._reconstructedMesh.getVerticesData(BABYLON.VertexBuffer.ColorKind) || []);
  94252. var normalData = this._mesh.getVerticesData(BABYLON.VertexBuffer.NormalKind);
  94253. var uvs = this._mesh.getVerticesData(BABYLON.VertexBuffer.UVKind);
  94254. var colorsData = this._mesh.getVerticesData(BABYLON.VertexBuffer.ColorKind);
  94255. var vertexCount = 0;
  94256. for (i = 0; i < this.vertices.length; ++i) {
  94257. var vertex = this.vertices[i];
  94258. vertex.id = vertexCount;
  94259. if (vertex.triangleCount) {
  94260. vertex.originalOffsets.forEach(function (originalOffset) {
  94261. if (!normalData) {
  94262. return;
  94263. }
  94264. newPositionData.push(vertex.position.x);
  94265. newPositionData.push(vertex.position.y);
  94266. newPositionData.push(vertex.position.z);
  94267. newNormalData.push(normalData[originalOffset * 3]);
  94268. newNormalData.push(normalData[(originalOffset * 3) + 1]);
  94269. newNormalData.push(normalData[(originalOffset * 3) + 2]);
  94270. if (uvs && uvs.length) {
  94271. newUVsData.push(uvs[(originalOffset * 2)]);
  94272. newUVsData.push(uvs[(originalOffset * 2) + 1]);
  94273. }
  94274. else if (colorsData && colorsData.length) {
  94275. newColorsData.push(colorsData[(originalOffset * 4)]);
  94276. newColorsData.push(colorsData[(originalOffset * 4) + 1]);
  94277. newColorsData.push(colorsData[(originalOffset * 4) + 2]);
  94278. newColorsData.push(colorsData[(originalOffset * 4) + 3]);
  94279. }
  94280. ++vertexCount;
  94281. });
  94282. }
  94283. }
  94284. var startingIndex = this._reconstructedMesh.getTotalIndices();
  94285. var startingVertex = this._reconstructedMesh.getTotalVertices();
  94286. var submeshesArray = this._reconstructedMesh.subMeshes;
  94287. this._reconstructedMesh.subMeshes = [];
  94288. var newIndicesArray = this._reconstructedMesh.getIndices(); //[];
  94289. var originalIndices = this._mesh.getIndices();
  94290. for (i = 0; i < newTriangles.length; ++i) {
  94291. t = newTriangles[i]; //now get the new referencing point for each vertex
  94292. [0, 1, 2].forEach(function (idx) {
  94293. var id = originalIndices[t.originalOffset + idx];
  94294. var offset = t.vertices[idx].originalOffsets.indexOf(id);
  94295. if (offset < 0)
  94296. offset = 0;
  94297. newIndicesArray.push(t.vertices[idx].id + offset + startingVertex);
  94298. });
  94299. }
  94300. //overwriting the old vertex buffers and indices.
  94301. this._reconstructedMesh.setIndices(newIndicesArray);
  94302. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, newPositionData);
  94303. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, newNormalData);
  94304. if (newUVsData.length > 0)
  94305. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.UVKind, newUVsData);
  94306. if (newColorsData.length > 0)
  94307. this._reconstructedMesh.setVerticesData(BABYLON.VertexBuffer.ColorKind, newColorsData);
  94308. //create submesh
  94309. var originalSubmesh = this._mesh.subMeshes[submeshIndex];
  94310. if (submeshIndex > 0) {
  94311. this._reconstructedMesh.subMeshes = [];
  94312. submeshesArray.forEach(function (submesh) {
  94313. BABYLON.SubMesh.AddToMesh(submesh.materialIndex, submesh.verticesStart, submesh.verticesCount, /* 0, newPositionData.length/3, */ submesh.indexStart, submesh.indexCount, submesh.getMesh());
  94314. });
  94315. BABYLON.SubMesh.AddToMesh(originalSubmesh.materialIndex, startingVertex, vertexCount, /* 0, newPositionData.length / 3, */ startingIndex, newTriangles.length * 3, this._reconstructedMesh);
  94316. }
  94317. };
  94318. QuadraticErrorSimplification.prototype.initDecimatedMesh = function () {
  94319. this._reconstructedMesh = new BABYLON.Mesh(this._mesh.name + "Decimated", this._mesh.getScene());
  94320. this._reconstructedMesh.material = this._mesh.material;
  94321. this._reconstructedMesh.parent = this._mesh.parent;
  94322. this._reconstructedMesh.isVisible = false;
  94323. this._reconstructedMesh.renderingGroupId = this._mesh.renderingGroupId;
  94324. };
  94325. QuadraticErrorSimplification.prototype.isFlipped = function (vertex1, vertex2, point, deletedArray, borderFactor, delTr) {
  94326. for (var i = 0; i < vertex1.triangleCount; ++i) {
  94327. var t = this.triangles[this.references[vertex1.triangleStart + i].triangleId];
  94328. if (t.deleted)
  94329. continue;
  94330. var s = this.references[vertex1.triangleStart + i].vertexId;
  94331. var v1 = t.vertices[(s + 1) % 3];
  94332. var v2 = t.vertices[(s + 2) % 3];
  94333. if ((v1 === vertex2 || v2 === vertex2)) {
  94334. deletedArray[i] = true;
  94335. delTr.push(t);
  94336. continue;
  94337. }
  94338. var d1 = v1.position.subtract(point);
  94339. d1 = d1.normalize();
  94340. var d2 = v2.position.subtract(point);
  94341. d2 = d2.normalize();
  94342. if (Math.abs(BABYLON.Vector3.Dot(d1, d2)) > 0.999)
  94343. return true;
  94344. var normal = BABYLON.Vector3.Cross(d1, d2).normalize();
  94345. deletedArray[i] = false;
  94346. if (BABYLON.Vector3.Dot(normal, t.normal) < 0.2)
  94347. return true;
  94348. }
  94349. return false;
  94350. };
  94351. QuadraticErrorSimplification.prototype.updateTriangles = function (origVertex, vertex, deletedArray, deletedTriangles) {
  94352. var newDeleted = deletedTriangles;
  94353. for (var i = 0; i < vertex.triangleCount; ++i) {
  94354. var ref = this.references[vertex.triangleStart + i];
  94355. var t = this.triangles[ref.triangleId];
  94356. if (t.deleted)
  94357. continue;
  94358. if (deletedArray[i] && t.deletePending) {
  94359. t.deleted = true;
  94360. newDeleted++;
  94361. continue;
  94362. }
  94363. t.vertices[ref.vertexId] = origVertex;
  94364. t.isDirty = true;
  94365. t.error[0] = this.calculateError(t.vertices[0], t.vertices[1]) + (t.borderFactor / 2);
  94366. t.error[1] = this.calculateError(t.vertices[1], t.vertices[2]) + (t.borderFactor / 2);
  94367. t.error[2] = this.calculateError(t.vertices[2], t.vertices[0]) + (t.borderFactor / 2);
  94368. t.error[3] = Math.min(t.error[0], t.error[1], t.error[2]);
  94369. this.references.push(ref);
  94370. }
  94371. return newDeleted;
  94372. };
  94373. QuadraticErrorSimplification.prototype.identifyBorder = function () {
  94374. for (var i = 0; i < this.vertices.length; ++i) {
  94375. var vCount = [];
  94376. var vId = [];
  94377. var v = this.vertices[i];
  94378. var j;
  94379. for (j = 0; j < v.triangleCount; ++j) {
  94380. var triangle = this.triangles[this.references[v.triangleStart + j].triangleId];
  94381. for (var ii = 0; ii < 3; ii++) {
  94382. var ofs = 0;
  94383. var vv = triangle.vertices[ii];
  94384. while (ofs < vCount.length) {
  94385. if (vId[ofs] === vv.id)
  94386. break;
  94387. ++ofs;
  94388. }
  94389. if (ofs === vCount.length) {
  94390. vCount.push(1);
  94391. vId.push(vv.id);
  94392. }
  94393. else {
  94394. vCount[ofs]++;
  94395. }
  94396. }
  94397. }
  94398. for (j = 0; j < vCount.length; ++j) {
  94399. if (vCount[j] === 1) {
  94400. this.vertices[vId[j]].isBorder = true;
  94401. }
  94402. else {
  94403. this.vertices[vId[j]].isBorder = false;
  94404. }
  94405. }
  94406. }
  94407. };
  94408. QuadraticErrorSimplification.prototype.updateMesh = function (identifyBorders) {
  94409. if (identifyBorders === void 0) { identifyBorders = false; }
  94410. var i;
  94411. if (!identifyBorders) {
  94412. var newTrianglesVector = [];
  94413. for (i = 0; i < this.triangles.length; ++i) {
  94414. if (!this.triangles[i].deleted) {
  94415. newTrianglesVector.push(this.triangles[i]);
  94416. }
  94417. }
  94418. this.triangles = newTrianglesVector;
  94419. }
  94420. for (i = 0; i < this.vertices.length; ++i) {
  94421. this.vertices[i].triangleCount = 0;
  94422. this.vertices[i].triangleStart = 0;
  94423. }
  94424. var t;
  94425. var j;
  94426. var v;
  94427. for (i = 0; i < this.triangles.length; ++i) {
  94428. t = this.triangles[i];
  94429. for (j = 0; j < 3; ++j) {
  94430. v = t.vertices[j];
  94431. v.triangleCount++;
  94432. }
  94433. }
  94434. var tStart = 0;
  94435. for (i = 0; i < this.vertices.length; ++i) {
  94436. this.vertices[i].triangleStart = tStart;
  94437. tStart += this.vertices[i].triangleCount;
  94438. this.vertices[i].triangleCount = 0;
  94439. }
  94440. var newReferences = new Array(this.triangles.length * 3);
  94441. for (i = 0; i < this.triangles.length; ++i) {
  94442. t = this.triangles[i];
  94443. for (j = 0; j < 3; ++j) {
  94444. v = t.vertices[j];
  94445. newReferences[v.triangleStart + v.triangleCount] = new Reference(j, i);
  94446. v.triangleCount++;
  94447. }
  94448. }
  94449. this.references = newReferences;
  94450. if (identifyBorders) {
  94451. this.identifyBorder();
  94452. }
  94453. };
  94454. QuadraticErrorSimplification.prototype.vertexError = function (q, point) {
  94455. var x = point.x;
  94456. var y = point.y;
  94457. var z = point.z;
  94458. 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
  94459. + 2 * q.data[5] * y * z + 2 * q.data[6] * y + q.data[7] * z * z + 2 * q.data[8] * z + q.data[9];
  94460. };
  94461. QuadraticErrorSimplification.prototype.calculateError = function (vertex1, vertex2, pointResult, normalResult, uvResult, colorResult) {
  94462. var q = vertex1.q.add(vertex2.q);
  94463. var border = vertex1.isBorder && vertex2.isBorder;
  94464. var error = 0;
  94465. var qDet = q.det(0, 1, 2, 1, 4, 5, 2, 5, 7);
  94466. if (qDet !== 0 && !border) {
  94467. if (!pointResult) {
  94468. pointResult = BABYLON.Vector3.Zero();
  94469. }
  94470. pointResult.x = -1 / qDet * (q.det(1, 2, 3, 4, 5, 6, 5, 7, 8));
  94471. pointResult.y = 1 / qDet * (q.det(0, 2, 3, 1, 5, 6, 2, 7, 8));
  94472. pointResult.z = -1 / qDet * (q.det(0, 1, 3, 1, 4, 6, 2, 5, 8));
  94473. error = this.vertexError(q, pointResult);
  94474. }
  94475. else {
  94476. var p3 = (vertex1.position.add(vertex2.position)).divide(new BABYLON.Vector3(2, 2, 2));
  94477. //var norm3 = (vertex1.normal.add(vertex2.normal)).divide(new Vector3(2, 2, 2)).normalize();
  94478. var error1 = this.vertexError(q, vertex1.position);
  94479. var error2 = this.vertexError(q, vertex2.position);
  94480. var error3 = this.vertexError(q, p3);
  94481. error = Math.min(error1, error2, error3);
  94482. if (error === error1) {
  94483. if (pointResult) {
  94484. pointResult.copyFrom(vertex1.position);
  94485. }
  94486. }
  94487. else if (error === error2) {
  94488. if (pointResult) {
  94489. pointResult.copyFrom(vertex2.position);
  94490. }
  94491. }
  94492. else {
  94493. if (pointResult) {
  94494. pointResult.copyFrom(p3);
  94495. }
  94496. }
  94497. }
  94498. return error;
  94499. };
  94500. return QuadraticErrorSimplification;
  94501. }());
  94502. BABYLON.QuadraticErrorSimplification = QuadraticErrorSimplification;
  94503. })(BABYLON || (BABYLON = {}));
  94504. //# sourceMappingURL=babylon.meshSimplification.js.map
  94505. var BABYLON;
  94506. (function (BABYLON) {
  94507. var MeshLODLevel = /** @class */ (function () {
  94508. function MeshLODLevel(distance, mesh) {
  94509. this.distance = distance;
  94510. this.mesh = mesh;
  94511. }
  94512. return MeshLODLevel;
  94513. }());
  94514. BABYLON.MeshLODLevel = MeshLODLevel;
  94515. })(BABYLON || (BABYLON = {}));
  94516. //# sourceMappingURL=babylon.meshLODLevel.js.map
  94517. var BABYLON;
  94518. (function (BABYLON) {
  94519. /**
  94520. * Defines the root class used to create scene optimization to use with SceneOptimizer
  94521. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94522. */
  94523. var SceneOptimization = /** @class */ (function () {
  94524. /**
  94525. * Creates the SceneOptimization object
  94526. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94527. * @param desc defines the description associated with the optimization
  94528. */
  94529. function SceneOptimization(
  94530. /**
  94531. * Defines the priority of this optimization (0 by default which means first in the list)
  94532. */
  94533. priority) {
  94534. if (priority === void 0) { priority = 0; }
  94535. this.priority = priority;
  94536. }
  94537. /**
  94538. * Gets a string describing the action executed by the current optimization
  94539. * @returns description string
  94540. */
  94541. SceneOptimization.prototype.getDescription = function () {
  94542. return "";
  94543. };
  94544. /**
  94545. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94546. * @param scene defines the current scene where to apply this optimization
  94547. * @param optimizer defines the current optimizer
  94548. * @returns true if everything that can be done was applied
  94549. */
  94550. SceneOptimization.prototype.apply = function (scene, optimizer) {
  94551. return true;
  94552. };
  94553. ;
  94554. return SceneOptimization;
  94555. }());
  94556. BABYLON.SceneOptimization = SceneOptimization;
  94557. /**
  94558. * Defines an optimization used to reduce the size of render target textures
  94559. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94560. */
  94561. var TextureOptimization = /** @class */ (function (_super) {
  94562. __extends(TextureOptimization, _super);
  94563. /**
  94564. * Creates the TextureOptimization object
  94565. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94566. * @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
  94567. * @param step defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94568. */
  94569. function TextureOptimization(
  94570. /**
  94571. * Defines the priority of this optimization (0 by default which means first in the list)
  94572. */
  94573. priority,
  94574. /**
  94575. * 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
  94576. */
  94577. maximumSize,
  94578. /**
  94579. * Defines the factor (0.5 by default) used to scale down textures bigger than maximum sized allowed.
  94580. */
  94581. step) {
  94582. if (priority === void 0) { priority = 0; }
  94583. if (maximumSize === void 0) { maximumSize = 1024; }
  94584. if (step === void 0) { step = 0.5; }
  94585. var _this = _super.call(this, priority) || this;
  94586. _this.priority = priority;
  94587. _this.maximumSize = maximumSize;
  94588. _this.step = step;
  94589. return _this;
  94590. }
  94591. /**
  94592. * Gets a string describing the action executed by the current optimization
  94593. * @returns description string
  94594. */
  94595. TextureOptimization.prototype.getDescription = function () {
  94596. return "Reducing render target texture size to " + this.maximumSize;
  94597. };
  94598. /**
  94599. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94600. * @param scene defines the current scene where to apply this optimization
  94601. * @param optimizer defines the current optimizer
  94602. * @returns true if everything that can be done was applied
  94603. */
  94604. TextureOptimization.prototype.apply = function (scene, optimizer) {
  94605. var allDone = true;
  94606. for (var index = 0; index < scene.textures.length; index++) {
  94607. var texture = scene.textures[index];
  94608. if (!texture.canRescale || texture.getContext) {
  94609. continue;
  94610. }
  94611. var currentSize = texture.getSize();
  94612. var maxDimension = Math.max(currentSize.width, currentSize.height);
  94613. if (maxDimension > this.maximumSize) {
  94614. texture.scale(this.step);
  94615. allDone = false;
  94616. }
  94617. }
  94618. return allDone;
  94619. };
  94620. return TextureOptimization;
  94621. }(SceneOptimization));
  94622. BABYLON.TextureOptimization = TextureOptimization;
  94623. /**
  94624. * Defines an optimization used to increase or decrease the rendering resolution
  94625. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94626. */
  94627. var HardwareScalingOptimization = /** @class */ (function (_super) {
  94628. __extends(HardwareScalingOptimization, _super);
  94629. /**
  94630. * Creates the HardwareScalingOptimization object
  94631. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  94632. * @param maximumScale defines the maximum scale to use (2 by default)
  94633. * @param step defines the step to use between two passes (0.5 by default)
  94634. */
  94635. function HardwareScalingOptimization(
  94636. /**
  94637. * Defines the priority of this optimization (0 by default which means first in the list)
  94638. */
  94639. priority,
  94640. /**
  94641. * Defines the maximum scale to use (2 by default)
  94642. */
  94643. maximumScale,
  94644. /**
  94645. * Defines the step to use between two passes (0.5 by default)
  94646. */
  94647. step) {
  94648. if (priority === void 0) { priority = 0; }
  94649. if (maximumScale === void 0) { maximumScale = 2; }
  94650. if (step === void 0) { step = 0.25; }
  94651. var _this = _super.call(this, priority) || this;
  94652. _this.priority = priority;
  94653. _this.maximumScale = maximumScale;
  94654. _this.step = step;
  94655. _this._currentScale = -1;
  94656. _this._directionOffset = 1;
  94657. return _this;
  94658. }
  94659. /**
  94660. * Gets a string describing the action executed by the current optimization
  94661. * @return description string
  94662. */
  94663. HardwareScalingOptimization.prototype.getDescription = function () {
  94664. return "Setting hardware scaling level to " + this._currentScale;
  94665. };
  94666. /**
  94667. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94668. * @param scene defines the current scene where to apply this optimization
  94669. * @param optimizer defines the current optimizer
  94670. * @returns true if everything that can be done was applied
  94671. */
  94672. HardwareScalingOptimization.prototype.apply = function (scene, optimizer) {
  94673. if (this._currentScale === -1) {
  94674. this._currentScale = scene.getEngine().getHardwareScalingLevel();
  94675. if (this._currentScale > this.maximumScale) {
  94676. this._directionOffset = -1;
  94677. }
  94678. }
  94679. this._currentScale += this._directionOffset * this.step;
  94680. scene.getEngine().setHardwareScalingLevel(this._currentScale);
  94681. return this._directionOffset === 1 ? this._currentScale >= this.maximumScale : this._currentScale <= this.maximumScale;
  94682. };
  94683. ;
  94684. return HardwareScalingOptimization;
  94685. }(SceneOptimization));
  94686. BABYLON.HardwareScalingOptimization = HardwareScalingOptimization;
  94687. /**
  94688. * Defines an optimization used to remove shadows
  94689. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94690. */
  94691. var ShadowsOptimization = /** @class */ (function (_super) {
  94692. __extends(ShadowsOptimization, _super);
  94693. function ShadowsOptimization() {
  94694. return _super !== null && _super.apply(this, arguments) || this;
  94695. }
  94696. /**
  94697. * Gets a string describing the action executed by the current optimization
  94698. * @return description string
  94699. */
  94700. ShadowsOptimization.prototype.getDescription = function () {
  94701. return "Turning shadows on/off";
  94702. };
  94703. /**
  94704. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94705. * @param scene defines the current scene where to apply this optimization
  94706. * @param optimizer defines the current optimizer
  94707. * @returns true if everything that can be done was applied
  94708. */
  94709. ShadowsOptimization.prototype.apply = function (scene, optimizer) {
  94710. scene.shadowsEnabled = optimizer.isInImprovementMode;
  94711. return true;
  94712. };
  94713. ;
  94714. return ShadowsOptimization;
  94715. }(SceneOptimization));
  94716. BABYLON.ShadowsOptimization = ShadowsOptimization;
  94717. /**
  94718. * Defines an optimization used to turn post-processes off
  94719. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94720. */
  94721. var PostProcessesOptimization = /** @class */ (function (_super) {
  94722. __extends(PostProcessesOptimization, _super);
  94723. function PostProcessesOptimization() {
  94724. return _super !== null && _super.apply(this, arguments) || this;
  94725. }
  94726. /**
  94727. * Gets a string describing the action executed by the current optimization
  94728. * @return description string
  94729. */
  94730. PostProcessesOptimization.prototype.getDescription = function () {
  94731. return "Turning post-processes on/off";
  94732. };
  94733. /**
  94734. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94735. * @param scene defines the current scene where to apply this optimization
  94736. * @param optimizer defines the current optimizer
  94737. * @returns true if everything that can be done was applied
  94738. */
  94739. PostProcessesOptimization.prototype.apply = function (scene, optimizer) {
  94740. scene.postProcessesEnabled = optimizer.isInImprovementMode;
  94741. return true;
  94742. };
  94743. ;
  94744. return PostProcessesOptimization;
  94745. }(SceneOptimization));
  94746. BABYLON.PostProcessesOptimization = PostProcessesOptimization;
  94747. /**
  94748. * Defines an optimization used to turn lens flares off
  94749. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94750. */
  94751. var LensFlaresOptimization = /** @class */ (function (_super) {
  94752. __extends(LensFlaresOptimization, _super);
  94753. function LensFlaresOptimization() {
  94754. return _super !== null && _super.apply(this, arguments) || this;
  94755. }
  94756. /**
  94757. * Gets a string describing the action executed by the current optimization
  94758. * @return description string
  94759. */
  94760. LensFlaresOptimization.prototype.getDescription = function () {
  94761. return "Turning lens flares on/off";
  94762. };
  94763. /**
  94764. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94765. * @param scene defines the current scene where to apply this optimization
  94766. * @param optimizer defines the current optimizer
  94767. * @returns true if everything that can be done was applied
  94768. */
  94769. LensFlaresOptimization.prototype.apply = function (scene, optimizer) {
  94770. scene.lensFlaresEnabled = optimizer.isInImprovementMode;
  94771. return true;
  94772. };
  94773. ;
  94774. return LensFlaresOptimization;
  94775. }(SceneOptimization));
  94776. BABYLON.LensFlaresOptimization = LensFlaresOptimization;
  94777. /**
  94778. * Defines an optimization based on user defined callback.
  94779. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94780. */
  94781. var CustomOptimization = /** @class */ (function (_super) {
  94782. __extends(CustomOptimization, _super);
  94783. function CustomOptimization() {
  94784. return _super !== null && _super.apply(this, arguments) || this;
  94785. }
  94786. /**
  94787. * Gets a string describing the action executed by the current optimization
  94788. * @returns description string
  94789. */
  94790. CustomOptimization.prototype.getDescription = function () {
  94791. if (this.onGetDescription) {
  94792. return this.onGetDescription();
  94793. }
  94794. return "Running user defined callback";
  94795. };
  94796. /**
  94797. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94798. * @param scene defines the current scene where to apply this optimization
  94799. * @param optimizer defines the current optimizer
  94800. * @returns true if everything that can be done was applied
  94801. */
  94802. CustomOptimization.prototype.apply = function (scene, optimizer) {
  94803. if (this.onApply) {
  94804. return this.onApply(scene, optimizer);
  94805. }
  94806. return true;
  94807. };
  94808. ;
  94809. return CustomOptimization;
  94810. }(SceneOptimization));
  94811. BABYLON.CustomOptimization = CustomOptimization;
  94812. /**
  94813. * Defines an optimization used to turn particles off
  94814. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94815. */
  94816. var ParticlesOptimization = /** @class */ (function (_super) {
  94817. __extends(ParticlesOptimization, _super);
  94818. function ParticlesOptimization() {
  94819. return _super !== null && _super.apply(this, arguments) || this;
  94820. }
  94821. /**
  94822. * Gets a string describing the action executed by the current optimization
  94823. * @return description string
  94824. */
  94825. ParticlesOptimization.prototype.getDescription = function () {
  94826. return "Turning particles on/off";
  94827. };
  94828. /**
  94829. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94830. * @param scene defines the current scene where to apply this optimization
  94831. * @param optimizer defines the current optimizer
  94832. * @returns true if everything that can be done was applied
  94833. */
  94834. ParticlesOptimization.prototype.apply = function (scene, optimizer) {
  94835. scene.particlesEnabled = optimizer.isInImprovementMode;
  94836. return true;
  94837. };
  94838. ;
  94839. return ParticlesOptimization;
  94840. }(SceneOptimization));
  94841. BABYLON.ParticlesOptimization = ParticlesOptimization;
  94842. /**
  94843. * Defines an optimization used to turn render targets off
  94844. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94845. */
  94846. var RenderTargetsOptimization = /** @class */ (function (_super) {
  94847. __extends(RenderTargetsOptimization, _super);
  94848. function RenderTargetsOptimization() {
  94849. return _super !== null && _super.apply(this, arguments) || this;
  94850. }
  94851. /**
  94852. * Gets a string describing the action executed by the current optimization
  94853. * @return description string
  94854. */
  94855. RenderTargetsOptimization.prototype.getDescription = function () {
  94856. return "Turning render targets off";
  94857. };
  94858. /**
  94859. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94860. * @param scene defines the current scene where to apply this optimization
  94861. * @param optimizer defines the current optimizer
  94862. * @returns true if everything that can be done was applied
  94863. */
  94864. RenderTargetsOptimization.prototype.apply = function (scene, optimizer) {
  94865. scene.renderTargetsEnabled = optimizer.isInImprovementMode;
  94866. return true;
  94867. };
  94868. ;
  94869. return RenderTargetsOptimization;
  94870. }(SceneOptimization));
  94871. BABYLON.RenderTargetsOptimization = RenderTargetsOptimization;
  94872. /**
  94873. * Defines an optimization used to merge meshes with compatible materials
  94874. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94875. */
  94876. var MergeMeshesOptimization = /** @class */ (function (_super) {
  94877. __extends(MergeMeshesOptimization, _super);
  94878. function MergeMeshesOptimization() {
  94879. var _this = _super !== null && _super.apply(this, arguments) || this;
  94880. _this._canBeMerged = function (abstractMesh) {
  94881. if (!(abstractMesh instanceof BABYLON.Mesh)) {
  94882. return false;
  94883. }
  94884. var mesh = abstractMesh;
  94885. if (!mesh.isVisible || !mesh.isEnabled()) {
  94886. return false;
  94887. }
  94888. if (mesh.instances.length > 0) {
  94889. return false;
  94890. }
  94891. if (mesh.skeleton || mesh.hasLODLevels) {
  94892. return false;
  94893. }
  94894. if (mesh.parent) {
  94895. return false;
  94896. }
  94897. return true;
  94898. };
  94899. return _this;
  94900. }
  94901. Object.defineProperty(MergeMeshesOptimization, "UpdateSelectionTree", {
  94902. /**
  94903. * Gets or sets a boolean which defines if optimization octree has to be updated
  94904. */
  94905. get: function () {
  94906. return MergeMeshesOptimization._UpdateSelectionTree;
  94907. },
  94908. /**
  94909. * Gets or sets a boolean which defines if optimization octree has to be updated
  94910. */
  94911. set: function (value) {
  94912. MergeMeshesOptimization._UpdateSelectionTree = value;
  94913. },
  94914. enumerable: true,
  94915. configurable: true
  94916. });
  94917. /**
  94918. * Gets a string describing the action executed by the current optimization
  94919. * @return description string
  94920. */
  94921. MergeMeshesOptimization.prototype.getDescription = function () {
  94922. return "Merging similar meshes together";
  94923. };
  94924. /**
  94925. * This function will be called by the SceneOptimizer when its priority is reached in order to apply the change required by the current optimization
  94926. * @param scene defines the current scene where to apply this optimization
  94927. * @param optimizer defines the current optimizer
  94928. * @param updateSelectionTree defines that the selection octree has to be updated (false by default)
  94929. * @returns true if everything that can be done was applied
  94930. */
  94931. MergeMeshesOptimization.prototype.apply = function (scene, optimizer, updateSelectionTree) {
  94932. var globalPool = scene.meshes.slice(0);
  94933. var globalLength = globalPool.length;
  94934. for (var index = 0; index < globalLength; index++) {
  94935. var currentPool = new Array();
  94936. var current = globalPool[index];
  94937. // Checks
  94938. if (!this._canBeMerged(current)) {
  94939. continue;
  94940. }
  94941. currentPool.push(current);
  94942. // Find compatible meshes
  94943. for (var subIndex = index + 1; subIndex < globalLength; subIndex++) {
  94944. var otherMesh = globalPool[subIndex];
  94945. if (!this._canBeMerged(otherMesh)) {
  94946. continue;
  94947. }
  94948. if (otherMesh.material !== current.material) {
  94949. continue;
  94950. }
  94951. if (otherMesh.checkCollisions !== current.checkCollisions) {
  94952. continue;
  94953. }
  94954. currentPool.push(otherMesh);
  94955. globalLength--;
  94956. globalPool.splice(subIndex, 1);
  94957. subIndex--;
  94958. }
  94959. if (currentPool.length < 2) {
  94960. continue;
  94961. }
  94962. // Merge meshes
  94963. BABYLON.Mesh.MergeMeshes(currentPool, undefined, true);
  94964. }
  94965. if (updateSelectionTree != undefined) {
  94966. if (updateSelectionTree) {
  94967. scene.createOrUpdateSelectionOctree();
  94968. }
  94969. }
  94970. else if (MergeMeshesOptimization.UpdateSelectionTree) {
  94971. scene.createOrUpdateSelectionOctree();
  94972. }
  94973. return true;
  94974. };
  94975. ;
  94976. MergeMeshesOptimization._UpdateSelectionTree = false;
  94977. return MergeMeshesOptimization;
  94978. }(SceneOptimization));
  94979. BABYLON.MergeMeshesOptimization = MergeMeshesOptimization;
  94980. /**
  94981. * Defines a list of options used by SceneOptimizer
  94982. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  94983. */
  94984. var SceneOptimizerOptions = /** @class */ (function () {
  94985. /**
  94986. * Creates a new list of options used by SceneOptimizer
  94987. * @param targetFrameRate defines the target frame rate to reach (60 by default)
  94988. * @param trackerDuration defines the interval between two checkes (2000ms by default)
  94989. */
  94990. function SceneOptimizerOptions(
  94991. /**
  94992. * Defines the target frame rate to reach (60 by default)
  94993. */
  94994. targetFrameRate,
  94995. /**
  94996. * Defines the interval between two checkes (2000ms by default)
  94997. */
  94998. trackerDuration) {
  94999. if (targetFrameRate === void 0) { targetFrameRate = 60; }
  95000. if (trackerDuration === void 0) { trackerDuration = 2000; }
  95001. this.targetFrameRate = targetFrameRate;
  95002. this.trackerDuration = trackerDuration;
  95003. /**
  95004. * Gets the list of optimizations to apply
  95005. */
  95006. this.optimizations = new Array();
  95007. }
  95008. /**
  95009. * Add a new optimization
  95010. * @param optimization defines the SceneOptimization to add to the list of active optimizations
  95011. * @returns the current SceneOptimizerOptions
  95012. */
  95013. SceneOptimizerOptions.prototype.addOptimization = function (optimization) {
  95014. this.optimizations.push(optimization);
  95015. return this;
  95016. };
  95017. /**
  95018. * Add a new custom optimization
  95019. * @param onApply defines the callback called to apply the custom optimization (true if everything that can be done was applied)
  95020. * @param onGetDescription defines the callback called to get the description attached with the optimization.
  95021. * @param priority defines the priority of this optimization (0 by default which means first in the list)
  95022. * @returns the current SceneOptimizerOptions
  95023. */
  95024. SceneOptimizerOptions.prototype.addCustomOptimization = function (onApply, onGetDescription, priority) {
  95025. if (priority === void 0) { priority = 0; }
  95026. var optimization = new CustomOptimization(priority);
  95027. optimization.onApply = onApply;
  95028. optimization.onGetDescription = onGetDescription;
  95029. this.optimizations.push(optimization);
  95030. return this;
  95031. };
  95032. /**
  95033. * Creates a list of pre-defined optimizations aimed to reduce the visual impact on the scene
  95034. * @param targetFrameRate defines the target frame rate (60 by default)
  95035. * @returns a SceneOptimizerOptions object
  95036. */
  95037. SceneOptimizerOptions.LowDegradationAllowed = function (targetFrameRate) {
  95038. var result = new SceneOptimizerOptions(targetFrameRate);
  95039. var priority = 0;
  95040. result.addOptimization(new MergeMeshesOptimization(priority));
  95041. result.addOptimization(new ShadowsOptimization(priority));
  95042. result.addOptimization(new LensFlaresOptimization(priority));
  95043. // Next priority
  95044. priority++;
  95045. result.addOptimization(new PostProcessesOptimization(priority));
  95046. result.addOptimization(new ParticlesOptimization(priority));
  95047. // Next priority
  95048. priority++;
  95049. result.addOptimization(new TextureOptimization(priority, 1024));
  95050. return result;
  95051. };
  95052. /**
  95053. * Creates a list of pre-defined optimizations aimed to have a moderate impact on the scene visual
  95054. * @param targetFrameRate defines the target frame rate (60 by default)
  95055. * @returns a SceneOptimizerOptions object
  95056. */
  95057. SceneOptimizerOptions.ModerateDegradationAllowed = function (targetFrameRate) {
  95058. var result = new SceneOptimizerOptions(targetFrameRate);
  95059. var priority = 0;
  95060. result.addOptimization(new MergeMeshesOptimization(priority));
  95061. result.addOptimization(new ShadowsOptimization(priority));
  95062. result.addOptimization(new LensFlaresOptimization(priority));
  95063. // Next priority
  95064. priority++;
  95065. result.addOptimization(new PostProcessesOptimization(priority));
  95066. result.addOptimization(new ParticlesOptimization(priority));
  95067. // Next priority
  95068. priority++;
  95069. result.addOptimization(new TextureOptimization(priority, 512));
  95070. // Next priority
  95071. priority++;
  95072. result.addOptimization(new RenderTargetsOptimization(priority));
  95073. // Next priority
  95074. priority++;
  95075. result.addOptimization(new HardwareScalingOptimization(priority, 2));
  95076. return result;
  95077. };
  95078. /**
  95079. * Creates a list of pre-defined optimizations aimed to have a big impact on the scene visual
  95080. * @param targetFrameRate defines the target frame rate (60 by default)
  95081. * @returns a SceneOptimizerOptions object
  95082. */
  95083. SceneOptimizerOptions.HighDegradationAllowed = function (targetFrameRate) {
  95084. var result = new SceneOptimizerOptions(targetFrameRate);
  95085. var priority = 0;
  95086. result.addOptimization(new MergeMeshesOptimization(priority));
  95087. result.addOptimization(new ShadowsOptimization(priority));
  95088. result.addOptimization(new LensFlaresOptimization(priority));
  95089. // Next priority
  95090. priority++;
  95091. result.addOptimization(new PostProcessesOptimization(priority));
  95092. result.addOptimization(new ParticlesOptimization(priority));
  95093. // Next priority
  95094. priority++;
  95095. result.addOptimization(new TextureOptimization(priority, 256));
  95096. // Next priority
  95097. priority++;
  95098. result.addOptimization(new RenderTargetsOptimization(priority));
  95099. // Next priority
  95100. priority++;
  95101. result.addOptimization(new HardwareScalingOptimization(priority, 4));
  95102. return result;
  95103. };
  95104. return SceneOptimizerOptions;
  95105. }());
  95106. BABYLON.SceneOptimizerOptions = SceneOptimizerOptions;
  95107. /**
  95108. * Class used to run optimizations in order to reach a target frame rate
  95109. * @description More details at http://doc.babylonjs.com/how_to/how_to_use_sceneoptimizer
  95110. */
  95111. var SceneOptimizer = /** @class */ (function () {
  95112. /**
  95113. * Creates a new SceneOptimizer
  95114. * @param scene defines the scene to work on
  95115. * @param options defines the options to use with the SceneOptimizer
  95116. * @param autoGeneratePriorities defines if priorities must be generated and not read from SceneOptimization property (true by default)
  95117. * @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)
  95118. */
  95119. function SceneOptimizer(scene, options, autoGeneratePriorities, improvementMode) {
  95120. if (autoGeneratePriorities === void 0) { autoGeneratePriorities = true; }
  95121. if (improvementMode === void 0) { improvementMode = false; }
  95122. var _this = this;
  95123. this._isRunning = false;
  95124. this._currentPriorityLevel = 0;
  95125. this._targetFrameRate = 60;
  95126. this._trackerDuration = 2000;
  95127. this._currentFrameRate = 0;
  95128. this._improvementMode = false;
  95129. /**
  95130. * Defines an observable called when the optimizer reaches the target frame rate
  95131. */
  95132. this.onSuccessObservable = new BABYLON.Observable();
  95133. /**
  95134. * Defines an observable called when the optimizer enables an optimization
  95135. */
  95136. this.onNewOptimizationAppliedObservable = new BABYLON.Observable();
  95137. /**
  95138. * Defines an observable called when the optimizer is not able to reach the target frame rate
  95139. */
  95140. this.onFailureObservable = new BABYLON.Observable();
  95141. if (!options) {
  95142. this._options = new SceneOptimizerOptions();
  95143. }
  95144. else {
  95145. this._options = options;
  95146. }
  95147. if (this._options.targetFrameRate) {
  95148. this._targetFrameRate = this._options.targetFrameRate;
  95149. }
  95150. if (this._options.trackerDuration) {
  95151. this._trackerDuration = this._options.trackerDuration;
  95152. }
  95153. if (autoGeneratePriorities) {
  95154. var priority = 0;
  95155. for (var _i = 0, _a = this._options.optimizations; _i < _a.length; _i++) {
  95156. var optim = _a[_i];
  95157. optim.priority = priority++;
  95158. }
  95159. }
  95160. this._improvementMode = improvementMode;
  95161. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95162. this._sceneDisposeObserver = this._scene.onDisposeObservable.add(function () {
  95163. _this._sceneDisposeObserver = null;
  95164. _this.dispose();
  95165. });
  95166. }
  95167. Object.defineProperty(SceneOptimizer.prototype, "isInImprovementMode", {
  95168. /**
  95169. * Gets a boolean indicating if the optimizer is in improvement mode
  95170. */
  95171. get: function () {
  95172. return this._improvementMode;
  95173. },
  95174. enumerable: true,
  95175. configurable: true
  95176. });
  95177. Object.defineProperty(SceneOptimizer.prototype, "currentPriorityLevel", {
  95178. /**
  95179. * Gets the current priority level (0 at start)
  95180. */
  95181. get: function () {
  95182. return this._currentPriorityLevel;
  95183. },
  95184. enumerable: true,
  95185. configurable: true
  95186. });
  95187. Object.defineProperty(SceneOptimizer.prototype, "currentFrameRate", {
  95188. /**
  95189. * Gets the current frame rate checked by the SceneOptimizer
  95190. */
  95191. get: function () {
  95192. return this._currentFrameRate;
  95193. },
  95194. enumerable: true,
  95195. configurable: true
  95196. });
  95197. Object.defineProperty(SceneOptimizer.prototype, "targetFrameRate", {
  95198. /**
  95199. * Gets or sets the current target frame rate (60 by default)
  95200. */
  95201. get: function () {
  95202. return this._targetFrameRate;
  95203. },
  95204. /**
  95205. * Gets or sets the current target frame rate (60 by default)
  95206. */
  95207. set: function (value) {
  95208. this._targetFrameRate = value;
  95209. },
  95210. enumerable: true,
  95211. configurable: true
  95212. });
  95213. Object.defineProperty(SceneOptimizer.prototype, "trackerDuration", {
  95214. /**
  95215. * Gets or sets the current interval between two checks (every 2000ms by default)
  95216. */
  95217. get: function () {
  95218. return this._trackerDuration;
  95219. },
  95220. /**
  95221. * Gets or sets the current interval between two checks (every 2000ms by default)
  95222. */
  95223. set: function (value) {
  95224. this._trackerDuration = value;
  95225. },
  95226. enumerable: true,
  95227. configurable: true
  95228. });
  95229. Object.defineProperty(SceneOptimizer.prototype, "optimizations", {
  95230. /**
  95231. * Gets the list of active optimizations
  95232. */
  95233. get: function () {
  95234. return this._options.optimizations;
  95235. },
  95236. enumerable: true,
  95237. configurable: true
  95238. });
  95239. /**
  95240. * Stops the current optimizer
  95241. */
  95242. SceneOptimizer.prototype.stop = function () {
  95243. this._isRunning = false;
  95244. };
  95245. /**
  95246. * Reset the optimizer to initial step (current priority level = 0)
  95247. */
  95248. SceneOptimizer.prototype.reset = function () {
  95249. this._currentPriorityLevel = 0;
  95250. };
  95251. /**
  95252. * Start the optimizer. By default it will try to reach a specific framerate
  95253. * but if the optimizer is set with improvementMode === true then it will run all optimiatiation while frame rate is above the target frame rate
  95254. */
  95255. SceneOptimizer.prototype.start = function () {
  95256. var _this = this;
  95257. if (this._isRunning) {
  95258. return;
  95259. }
  95260. this._isRunning = true;
  95261. // Let's wait for the scene to be ready before running our check
  95262. this._scene.executeWhenReady(function () {
  95263. setTimeout(function () {
  95264. _this._checkCurrentState();
  95265. }, _this._trackerDuration);
  95266. });
  95267. };
  95268. SceneOptimizer.prototype._checkCurrentState = function () {
  95269. var _this = this;
  95270. if (!this._isRunning) {
  95271. return;
  95272. }
  95273. var scene = this._scene;
  95274. var options = this._options;
  95275. this._currentFrameRate = Math.round(scene.getEngine().getFps());
  95276. if (this._improvementMode && this._currentFrameRate <= this._targetFrameRate ||
  95277. !this._improvementMode && this._currentFrameRate >= this._targetFrameRate) {
  95278. this._isRunning = false;
  95279. this.onSuccessObservable.notifyObservers(this);
  95280. return;
  95281. }
  95282. // Apply current level of optimizations
  95283. var allDone = true;
  95284. var noOptimizationApplied = true;
  95285. for (var index = 0; index < options.optimizations.length; index++) {
  95286. var optimization = options.optimizations[index];
  95287. if (optimization.priority === this._currentPriorityLevel) {
  95288. noOptimizationApplied = false;
  95289. allDone = allDone && optimization.apply(scene, this);
  95290. this.onNewOptimizationAppliedObservable.notifyObservers(optimization);
  95291. }
  95292. }
  95293. // If no optimization was applied, this is a failure :(
  95294. if (noOptimizationApplied) {
  95295. this._isRunning = false;
  95296. this.onFailureObservable.notifyObservers(this);
  95297. return;
  95298. }
  95299. // If all optimizations were done, move to next level
  95300. if (allDone) {
  95301. this._currentPriorityLevel++;
  95302. }
  95303. // Let's the system running for a specific amount of time before checking FPS
  95304. scene.executeWhenReady(function () {
  95305. setTimeout(function () {
  95306. _this._checkCurrentState();
  95307. }, _this._trackerDuration);
  95308. });
  95309. };
  95310. /**
  95311. * Release all resources
  95312. */
  95313. SceneOptimizer.prototype.dispose = function () {
  95314. this.stop();
  95315. this.onSuccessObservable.clear();
  95316. this.onFailureObservable.clear();
  95317. this.onNewOptimizationAppliedObservable.clear();
  95318. if (this._sceneDisposeObserver) {
  95319. this._scene.onDisposeObservable.remove(this._sceneDisposeObserver);
  95320. }
  95321. };
  95322. /**
  95323. * Helper function to create a SceneOptimizer with one single line of code
  95324. * @param scene defines the scene to work on
  95325. * @param options defines the options to use with the SceneOptimizer
  95326. * @param onSuccess defines a callback to call on success
  95327. * @param onFailure defines a callback to call on failure
  95328. * @returns the new SceneOptimizer object
  95329. */
  95330. SceneOptimizer.OptimizeAsync = function (scene, options, onSuccess, onFailure) {
  95331. var optimizer = new SceneOptimizer(scene, options || SceneOptimizerOptions.ModerateDegradationAllowed(), false);
  95332. if (onSuccess) {
  95333. optimizer.onSuccessObservable.add(function () {
  95334. onSuccess();
  95335. });
  95336. }
  95337. if (onFailure) {
  95338. optimizer.onFailureObservable.add(function () {
  95339. onFailure();
  95340. });
  95341. }
  95342. optimizer.start();
  95343. return optimizer;
  95344. };
  95345. return SceneOptimizer;
  95346. }());
  95347. BABYLON.SceneOptimizer = SceneOptimizer;
  95348. })(BABYLON || (BABYLON = {}));
  95349. //# sourceMappingURL=babylon.sceneOptimizer.js.map
  95350. var BABYLON;
  95351. (function (BABYLON) {
  95352. var OutlineRenderer = /** @class */ (function () {
  95353. function OutlineRenderer(scene) {
  95354. this.zOffset = 1;
  95355. this._scene = scene;
  95356. }
  95357. OutlineRenderer.prototype.render = function (subMesh, batch, useOverlay) {
  95358. var _this = this;
  95359. if (useOverlay === void 0) { useOverlay = false; }
  95360. var scene = this._scene;
  95361. var engine = this._scene.getEngine();
  95362. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  95363. if (!this.isReady(subMesh, hardwareInstancedRendering)) {
  95364. return;
  95365. }
  95366. var mesh = subMesh.getRenderingMesh();
  95367. var material = subMesh.getMaterial();
  95368. if (!material || !scene.activeCamera) {
  95369. return;
  95370. }
  95371. engine.enableEffect(this._effect);
  95372. // Logarithmic depth
  95373. if (material.useLogarithmicDepth) {
  95374. this._effect.setFloat("logarithmicDepthConstant", 2.0 / (Math.log(scene.activeCamera.maxZ + 1.0) / Math.LN2));
  95375. }
  95376. this._effect.setFloat("offset", useOverlay ? 0 : mesh.outlineWidth);
  95377. this._effect.setColor4("color", useOverlay ? mesh.overlayColor : mesh.outlineColor, useOverlay ? mesh.overlayAlpha : material.alpha);
  95378. this._effect.setMatrix("viewProjection", scene.getTransformMatrix());
  95379. // Bones
  95380. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  95381. this._effect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  95382. }
  95383. mesh._bind(subMesh, this._effect, BABYLON.Material.TriangleFillMode);
  95384. // Alpha test
  95385. if (material && material.needAlphaTesting()) {
  95386. var alphaTexture = material.getAlphaTestTexture();
  95387. if (alphaTexture) {
  95388. this._effect.setTexture("diffuseSampler", alphaTexture);
  95389. this._effect.setMatrix("diffuseMatrix", alphaTexture.getTextureMatrix());
  95390. }
  95391. }
  95392. engine.setZOffset(-this.zOffset);
  95393. mesh._processRendering(subMesh, this._effect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { _this._effect.setMatrix("world", world); });
  95394. engine.setZOffset(0);
  95395. };
  95396. OutlineRenderer.prototype.isReady = function (subMesh, useInstances) {
  95397. var defines = [];
  95398. var attribs = [BABYLON.VertexBuffer.PositionKind, BABYLON.VertexBuffer.NormalKind];
  95399. var mesh = subMesh.getMesh();
  95400. var material = subMesh.getMaterial();
  95401. if (material) {
  95402. // Alpha test
  95403. if (material.needAlphaTesting()) {
  95404. defines.push("#define ALPHATEST");
  95405. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95406. attribs.push(BABYLON.VertexBuffer.UVKind);
  95407. defines.push("#define UV1");
  95408. }
  95409. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind)) {
  95410. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95411. defines.push("#define UV2");
  95412. }
  95413. }
  95414. //Logarithmic depth
  95415. if (material.useLogarithmicDepth) {
  95416. defines.push("#define LOGARITHMICDEPTH");
  95417. }
  95418. }
  95419. // Bones
  95420. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95421. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95422. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95423. if (mesh.numBoneInfluencers > 4) {
  95424. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95425. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95426. }
  95427. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95428. defines.push("#define BonesPerMesh " + (mesh.skeleton ? mesh.skeleton.bones.length + 1 : 0));
  95429. }
  95430. else {
  95431. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95432. }
  95433. // Instances
  95434. if (useInstances) {
  95435. defines.push("#define INSTANCES");
  95436. attribs.push("world0");
  95437. attribs.push("world1");
  95438. attribs.push("world2");
  95439. attribs.push("world3");
  95440. }
  95441. // Get correct effect
  95442. var join = defines.join("\n");
  95443. if (this._cachedDefines !== join) {
  95444. this._cachedDefines = join;
  95445. this._effect = this._scene.getEngine().createEffect("outline", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "offset", "color", "logarithmicDepthConstant"], ["diffuseSampler"], join);
  95446. }
  95447. return this._effect.isReady();
  95448. };
  95449. return OutlineRenderer;
  95450. }());
  95451. BABYLON.OutlineRenderer = OutlineRenderer;
  95452. })(BABYLON || (BABYLON = {}));
  95453. //# sourceMappingURL=babylon.outlineRenderer.js.map
  95454. var BABYLON;
  95455. (function (BABYLON) {
  95456. var FaceAdjacencies = /** @class */ (function () {
  95457. function FaceAdjacencies() {
  95458. this.edges = new Array();
  95459. this.edgesConnectedCount = 0;
  95460. }
  95461. return FaceAdjacencies;
  95462. }());
  95463. var EdgesRenderer = /** @class */ (function () {
  95464. // Beware when you use this class with complex objects as the adjacencies computation can be really long
  95465. function EdgesRenderer(source, epsilon, checkVerticesInsteadOfIndices) {
  95466. if (epsilon === void 0) { epsilon = 0.95; }
  95467. if (checkVerticesInsteadOfIndices === void 0) { checkVerticesInsteadOfIndices = false; }
  95468. this.edgesWidthScalerForOrthographic = 1000.0;
  95469. this.edgesWidthScalerForPerspective = 50.0;
  95470. this._linesPositions = new Array();
  95471. this._linesNormals = new Array();
  95472. this._linesIndices = new Array();
  95473. this._buffers = {};
  95474. this._checkVerticesInsteadOfIndices = false;
  95475. /** Gets or sets a boolean indicating if the edgesRenderer is active */
  95476. this.isEnabled = true;
  95477. this._source = source;
  95478. this._checkVerticesInsteadOfIndices = checkVerticesInsteadOfIndices;
  95479. this._epsilon = epsilon;
  95480. this._prepareRessources();
  95481. this._generateEdgesLines();
  95482. }
  95483. EdgesRenderer.prototype._prepareRessources = function () {
  95484. if (this._lineShader) {
  95485. return;
  95486. }
  95487. this._lineShader = new BABYLON.ShaderMaterial("lineShader", this._source.getScene(), "line", {
  95488. attributes: ["position", "normal"],
  95489. uniforms: ["worldViewProjection", "color", "width", "aspectRatio"]
  95490. });
  95491. this._lineShader.disableDepthWrite = true;
  95492. this._lineShader.backFaceCulling = false;
  95493. };
  95494. EdgesRenderer.prototype._rebuild = function () {
  95495. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95496. if (buffer) {
  95497. buffer._rebuild();
  95498. }
  95499. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95500. if (buffer) {
  95501. buffer._rebuild();
  95502. }
  95503. var scene = this._source.getScene();
  95504. var engine = scene.getEngine();
  95505. this._ib = engine.createIndexBuffer(this._linesIndices);
  95506. };
  95507. EdgesRenderer.prototype.dispose = function () {
  95508. var buffer = this._buffers[BABYLON.VertexBuffer.PositionKind];
  95509. if (buffer) {
  95510. buffer.dispose();
  95511. this._buffers[BABYLON.VertexBuffer.PositionKind] = null;
  95512. }
  95513. buffer = this._buffers[BABYLON.VertexBuffer.NormalKind];
  95514. if (buffer) {
  95515. buffer.dispose();
  95516. this._buffers[BABYLON.VertexBuffer.NormalKind] = null;
  95517. }
  95518. this._source.getScene().getEngine()._releaseBuffer(this._ib);
  95519. this._lineShader.dispose();
  95520. };
  95521. EdgesRenderer.prototype._processEdgeForAdjacencies = function (pa, pb, p0, p1, p2) {
  95522. if (pa === p0 && pb === p1 || pa === p1 && pb === p0) {
  95523. return 0;
  95524. }
  95525. if (pa === p1 && pb === p2 || pa === p2 && pb === p1) {
  95526. return 1;
  95527. }
  95528. if (pa === p2 && pb === p0 || pa === p0 && pb === p2) {
  95529. return 2;
  95530. }
  95531. return -1;
  95532. };
  95533. EdgesRenderer.prototype._processEdgeForAdjacenciesWithVertices = function (pa, pb, p0, p1, p2) {
  95534. if (pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p1) || pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p0)) {
  95535. return 0;
  95536. }
  95537. if (pa.equalsWithEpsilon(p1) && pb.equalsWithEpsilon(p2) || pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p1)) {
  95538. return 1;
  95539. }
  95540. if (pa.equalsWithEpsilon(p2) && pb.equalsWithEpsilon(p0) || pa.equalsWithEpsilon(p0) && pb.equalsWithEpsilon(p2)) {
  95541. return 2;
  95542. }
  95543. return -1;
  95544. };
  95545. EdgesRenderer.prototype._checkEdge = function (faceIndex, edge, faceNormals, p0, p1) {
  95546. var needToCreateLine;
  95547. if (edge === undefined) {
  95548. needToCreateLine = true;
  95549. }
  95550. else {
  95551. var dotProduct = BABYLON.Vector3.Dot(faceNormals[faceIndex], faceNormals[edge]);
  95552. needToCreateLine = dotProduct < this._epsilon;
  95553. }
  95554. if (needToCreateLine) {
  95555. var offset = this._linesPositions.length / 3;
  95556. var normal = p0.subtract(p1);
  95557. normal.normalize();
  95558. // Positions
  95559. this._linesPositions.push(p0.x);
  95560. this._linesPositions.push(p0.y);
  95561. this._linesPositions.push(p0.z);
  95562. this._linesPositions.push(p0.x);
  95563. this._linesPositions.push(p0.y);
  95564. this._linesPositions.push(p0.z);
  95565. this._linesPositions.push(p1.x);
  95566. this._linesPositions.push(p1.y);
  95567. this._linesPositions.push(p1.z);
  95568. this._linesPositions.push(p1.x);
  95569. this._linesPositions.push(p1.y);
  95570. this._linesPositions.push(p1.z);
  95571. // Normals
  95572. this._linesNormals.push(p1.x);
  95573. this._linesNormals.push(p1.y);
  95574. this._linesNormals.push(p1.z);
  95575. this._linesNormals.push(-1);
  95576. this._linesNormals.push(p1.x);
  95577. this._linesNormals.push(p1.y);
  95578. this._linesNormals.push(p1.z);
  95579. this._linesNormals.push(1);
  95580. this._linesNormals.push(p0.x);
  95581. this._linesNormals.push(p0.y);
  95582. this._linesNormals.push(p0.z);
  95583. this._linesNormals.push(-1);
  95584. this._linesNormals.push(p0.x);
  95585. this._linesNormals.push(p0.y);
  95586. this._linesNormals.push(p0.z);
  95587. this._linesNormals.push(1);
  95588. // Indices
  95589. this._linesIndices.push(offset);
  95590. this._linesIndices.push(offset + 1);
  95591. this._linesIndices.push(offset + 2);
  95592. this._linesIndices.push(offset);
  95593. this._linesIndices.push(offset + 2);
  95594. this._linesIndices.push(offset + 3);
  95595. }
  95596. };
  95597. EdgesRenderer.prototype._generateEdgesLines = function () {
  95598. var positions = this._source.getVerticesData(BABYLON.VertexBuffer.PositionKind);
  95599. var indices = this._source.getIndices();
  95600. if (!indices || !positions) {
  95601. return;
  95602. }
  95603. // First let's find adjacencies
  95604. var adjacencies = new Array();
  95605. var faceNormals = new Array();
  95606. var index;
  95607. var faceAdjacencies;
  95608. // Prepare faces
  95609. for (index = 0; index < indices.length; index += 3) {
  95610. faceAdjacencies = new FaceAdjacencies();
  95611. var p0Index = indices[index];
  95612. var p1Index = indices[index + 1];
  95613. var p2Index = indices[index + 2];
  95614. faceAdjacencies.p0 = new BABYLON.Vector3(positions[p0Index * 3], positions[p0Index * 3 + 1], positions[p0Index * 3 + 2]);
  95615. faceAdjacencies.p1 = new BABYLON.Vector3(positions[p1Index * 3], positions[p1Index * 3 + 1], positions[p1Index * 3 + 2]);
  95616. faceAdjacencies.p2 = new BABYLON.Vector3(positions[p2Index * 3], positions[p2Index * 3 + 1], positions[p2Index * 3 + 2]);
  95617. var faceNormal = BABYLON.Vector3.Cross(faceAdjacencies.p1.subtract(faceAdjacencies.p0), faceAdjacencies.p2.subtract(faceAdjacencies.p1));
  95618. faceNormal.normalize();
  95619. faceNormals.push(faceNormal);
  95620. adjacencies.push(faceAdjacencies);
  95621. }
  95622. // Scan
  95623. for (index = 0; index < adjacencies.length; index++) {
  95624. faceAdjacencies = adjacencies[index];
  95625. for (var otherIndex = index + 1; otherIndex < adjacencies.length; otherIndex++) {
  95626. var otherFaceAdjacencies = adjacencies[otherIndex];
  95627. if (faceAdjacencies.edgesConnectedCount === 3) { // Full
  95628. break;
  95629. }
  95630. if (otherFaceAdjacencies.edgesConnectedCount === 3) { // Full
  95631. continue;
  95632. }
  95633. var otherP0 = indices[otherIndex * 3];
  95634. var otherP1 = indices[otherIndex * 3 + 1];
  95635. var otherP2 = indices[otherIndex * 3 + 2];
  95636. for (var edgeIndex = 0; edgeIndex < 3; edgeIndex++) {
  95637. var otherEdgeIndex = 0;
  95638. if (faceAdjacencies.edges[edgeIndex] !== undefined) {
  95639. continue;
  95640. }
  95641. switch (edgeIndex) {
  95642. case 0:
  95643. if (this._checkVerticesInsteadOfIndices) {
  95644. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p0, faceAdjacencies.p1, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95645. }
  95646. else {
  95647. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3], indices[index * 3 + 1], otherP0, otherP1, otherP2);
  95648. }
  95649. break;
  95650. case 1:
  95651. if (this._checkVerticesInsteadOfIndices) {
  95652. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p1, faceAdjacencies.p2, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95653. }
  95654. else {
  95655. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 1], indices[index * 3 + 2], otherP0, otherP1, otherP2);
  95656. }
  95657. break;
  95658. case 2:
  95659. if (this._checkVerticesInsteadOfIndices) {
  95660. otherEdgeIndex = this._processEdgeForAdjacenciesWithVertices(faceAdjacencies.p2, faceAdjacencies.p0, otherFaceAdjacencies.p0, otherFaceAdjacencies.p1, otherFaceAdjacencies.p2);
  95661. }
  95662. else {
  95663. otherEdgeIndex = this._processEdgeForAdjacencies(indices[index * 3 + 2], indices[index * 3], otherP0, otherP1, otherP2);
  95664. }
  95665. break;
  95666. }
  95667. if (otherEdgeIndex === -1) {
  95668. continue;
  95669. }
  95670. faceAdjacencies.edges[edgeIndex] = otherIndex;
  95671. otherFaceAdjacencies.edges[otherEdgeIndex] = index;
  95672. faceAdjacencies.edgesConnectedCount++;
  95673. otherFaceAdjacencies.edgesConnectedCount++;
  95674. if (faceAdjacencies.edgesConnectedCount === 3) {
  95675. break;
  95676. }
  95677. }
  95678. }
  95679. }
  95680. // Create lines
  95681. for (index = 0; index < adjacencies.length; index++) {
  95682. // 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
  95683. var current = adjacencies[index];
  95684. this._checkEdge(index, current.edges[0], faceNormals, current.p0, current.p1);
  95685. this._checkEdge(index, current.edges[1], faceNormals, current.p1, current.p2);
  95686. this._checkEdge(index, current.edges[2], faceNormals, current.p2, current.p0);
  95687. }
  95688. // Merge into a single mesh
  95689. var engine = this._source.getScene().getEngine();
  95690. this._buffers[BABYLON.VertexBuffer.PositionKind] = new BABYLON.VertexBuffer(engine, this._linesPositions, BABYLON.VertexBuffer.PositionKind, false);
  95691. this._buffers[BABYLON.VertexBuffer.NormalKind] = new BABYLON.VertexBuffer(engine, this._linesNormals, BABYLON.VertexBuffer.NormalKind, false, false, 4);
  95692. this._ib = engine.createIndexBuffer(this._linesIndices);
  95693. this._indicesCount = this._linesIndices.length;
  95694. };
  95695. EdgesRenderer.prototype.render = function () {
  95696. var scene = this._source.getScene();
  95697. if (!this._lineShader.isReady() || !scene.activeCamera) {
  95698. return;
  95699. }
  95700. var engine = scene.getEngine();
  95701. this._lineShader._preBind();
  95702. // VBOs
  95703. engine.bindBuffers(this._buffers, this._ib, this._lineShader.getEffect());
  95704. scene.resetCachedMaterial();
  95705. this._lineShader.setColor4("color", this._source.edgesColor);
  95706. if (scene.activeCamera.mode === BABYLON.Camera.ORTHOGRAPHIC_CAMERA) {
  95707. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForOrthographic);
  95708. }
  95709. else {
  95710. this._lineShader.setFloat("width", this._source.edgesWidth / this.edgesWidthScalerForPerspective);
  95711. }
  95712. this._lineShader.setFloat("aspectRatio", engine.getAspectRatio(scene.activeCamera));
  95713. this._lineShader.bind(this._source.getWorldMatrix());
  95714. // Draw order
  95715. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, this._indicesCount);
  95716. this._lineShader.unbind();
  95717. engine.setDepthWrite(true);
  95718. };
  95719. return EdgesRenderer;
  95720. }());
  95721. BABYLON.EdgesRenderer = EdgesRenderer;
  95722. })(BABYLON || (BABYLON = {}));
  95723. //# sourceMappingURL=babylon.edgesRenderer.js.map
  95724. var __assign = (this && this.__assign) || Object.assign || function(t) {
  95725. for (var s, i = 1, n = arguments.length; i < n; i++) {
  95726. s = arguments[i];
  95727. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  95728. t[p] = s[p];
  95729. }
  95730. return t;
  95731. };
  95732. var BABYLON;
  95733. (function (BABYLON) {
  95734. /**
  95735. * The effect layer Helps adding post process effect blended with the main pass.
  95736. *
  95737. * This can be for instance use to generate glow or higlight effects on the scene.
  95738. *
  95739. * The effect layer class can not be used directly and is intented to inherited from to be
  95740. * customized per effects.
  95741. */
  95742. var EffectLayer = /** @class */ (function () {
  95743. /**
  95744. * Instantiates a new effect Layer and references it in the scene.
  95745. * @param name The name of the layer
  95746. * @param scene The scene to use the layer in
  95747. */
  95748. function EffectLayer(
  95749. /** The Friendly of the effect in the scene */
  95750. name, scene) {
  95751. this._vertexBuffers = {};
  95752. this._maxSize = 0;
  95753. this._mainTextureDesiredSize = { width: 0, height: 0 };
  95754. this._shouldRender = true;
  95755. this._postProcesses = [];
  95756. this._textures = [];
  95757. this._emissiveTextureAndColor = { texture: null, color: new BABYLON.Color4() };
  95758. /**
  95759. * The clear color of the texture used to generate the glow map.
  95760. */
  95761. this.neutralColor = new BABYLON.Color4();
  95762. /**
  95763. * Specifies wether the highlight layer is enabled or not.
  95764. */
  95765. this.isEnabled = true;
  95766. /**
  95767. * An event triggered when the effect layer has been disposed.
  95768. */
  95769. this.onDisposeObservable = new BABYLON.Observable();
  95770. /**
  95771. * An event triggered when the effect layer is about rendering the main texture with the glowy parts.
  95772. */
  95773. this.onBeforeRenderMainTextureObservable = new BABYLON.Observable();
  95774. /**
  95775. * An event triggered when the generated texture is being merged in the scene.
  95776. */
  95777. this.onBeforeComposeObservable = new BABYLON.Observable();
  95778. /**
  95779. * An event triggered when the generated texture has been merged in the scene.
  95780. */
  95781. this.onAfterComposeObservable = new BABYLON.Observable();
  95782. /**
  95783. * An event triggered when the efffect layer changes its size.
  95784. */
  95785. this.onSizeChangedObservable = new BABYLON.Observable();
  95786. this.name = name;
  95787. this._scene = scene || BABYLON.Engine.LastCreatedScene;
  95788. this._engine = scene.getEngine();
  95789. this._maxSize = this._engine.getCaps().maxTextureSize;
  95790. this._scene.effectLayers.push(this);
  95791. // Generate Buffers
  95792. this._generateIndexBuffer();
  95793. this._genrateVertexBuffer();
  95794. }
  95795. Object.defineProperty(EffectLayer.prototype, "camera", {
  95796. /**
  95797. * Gets the camera attached to the layer.
  95798. */
  95799. get: function () {
  95800. return this._effectLayerOptions.camera;
  95801. },
  95802. enumerable: true,
  95803. configurable: true
  95804. });
  95805. /**
  95806. * Initializes the effect layer with the required options.
  95807. * @param options Sets of none mandatory options to use with the layer (see IEffectLayerOptions for more information)
  95808. */
  95809. EffectLayer.prototype._init = function (options) {
  95810. // Adapt options
  95811. this._effectLayerOptions = __assign({ mainTextureRatio: 0.5, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  95812. this._setMainTextureSize();
  95813. this._createMainTexture();
  95814. this._createTextureAndPostProcesses();
  95815. this._mergeEffect = this._createMergeEffect();
  95816. };
  95817. /**
  95818. * Generates the index buffer of the full screen quad blending to the main canvas.
  95819. */
  95820. EffectLayer.prototype._generateIndexBuffer = function () {
  95821. // Indices
  95822. var indices = [];
  95823. indices.push(0);
  95824. indices.push(1);
  95825. indices.push(2);
  95826. indices.push(0);
  95827. indices.push(2);
  95828. indices.push(3);
  95829. this._indexBuffer = this._engine.createIndexBuffer(indices);
  95830. };
  95831. /**
  95832. * Generates the vertex buffer of the full screen quad blending to the main canvas.
  95833. */
  95834. EffectLayer.prototype._genrateVertexBuffer = function () {
  95835. // VBO
  95836. var vertices = [];
  95837. vertices.push(1, 1);
  95838. vertices.push(-1, 1);
  95839. vertices.push(-1, -1);
  95840. vertices.push(1, -1);
  95841. var vertexBuffer = new BABYLON.VertexBuffer(this._engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  95842. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  95843. };
  95844. /**
  95845. * Sets the main texture desired size which is the closest power of two
  95846. * of the engine canvas size.
  95847. */
  95848. EffectLayer.prototype._setMainTextureSize = function () {
  95849. if (this._effectLayerOptions.mainTextureFixedSize) {
  95850. this._mainTextureDesiredSize.width = this._effectLayerOptions.mainTextureFixedSize;
  95851. this._mainTextureDesiredSize.height = this._effectLayerOptions.mainTextureFixedSize;
  95852. }
  95853. else {
  95854. this._mainTextureDesiredSize.width = this._engine.getRenderWidth() * this._effectLayerOptions.mainTextureRatio;
  95855. this._mainTextureDesiredSize.height = this._engine.getRenderHeight() * this._effectLayerOptions.mainTextureRatio;
  95856. this._mainTextureDesiredSize.width = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.width, this._maxSize) : this._mainTextureDesiredSize.width;
  95857. this._mainTextureDesiredSize.height = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(this._mainTextureDesiredSize.height, this._maxSize) : this._mainTextureDesiredSize.height;
  95858. }
  95859. this._mainTextureDesiredSize.width = Math.floor(this._mainTextureDesiredSize.width);
  95860. this._mainTextureDesiredSize.height = Math.floor(this._mainTextureDesiredSize.height);
  95861. };
  95862. /**
  95863. * Creates the main texture for the effect layer.
  95864. */
  95865. EffectLayer.prototype._createMainTexture = function () {
  95866. var _this = this;
  95867. this._mainTexture = new BABYLON.RenderTargetTexture("HighlightLayerMainRTT", {
  95868. width: this._mainTextureDesiredSize.width,
  95869. height: this._mainTextureDesiredSize.height
  95870. }, this._scene, false, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  95871. this._mainTexture.activeCamera = this._effectLayerOptions.camera;
  95872. this._mainTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95873. this._mainTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  95874. this._mainTexture.anisotropicFilteringLevel = 1;
  95875. this._mainTexture.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  95876. this._mainTexture.renderParticles = false;
  95877. this._mainTexture.renderList = null;
  95878. this._mainTexture.ignoreCameraViewport = true;
  95879. // Custom render function
  95880. this._mainTexture.customRenderFunction = function (opaqueSubMeshes, alphaTestSubMeshes, transparentSubMeshes, depthOnlySubMeshes) {
  95881. _this.onBeforeRenderMainTextureObservable.notifyObservers(_this);
  95882. var index;
  95883. var engine = _this._scene.getEngine();
  95884. if (depthOnlySubMeshes.length) {
  95885. engine.setColorWrite(false);
  95886. for (index = 0; index < depthOnlySubMeshes.length; index++) {
  95887. _this._renderSubMesh(depthOnlySubMeshes.data[index]);
  95888. }
  95889. engine.setColorWrite(true);
  95890. }
  95891. for (index = 0; index < opaqueSubMeshes.length; index++) {
  95892. _this._renderSubMesh(opaqueSubMeshes.data[index]);
  95893. }
  95894. for (index = 0; index < alphaTestSubMeshes.length; index++) {
  95895. _this._renderSubMesh(alphaTestSubMeshes.data[index]);
  95896. }
  95897. for (index = 0; index < transparentSubMeshes.length; index++) {
  95898. _this._renderSubMesh(transparentSubMeshes.data[index]);
  95899. }
  95900. };
  95901. this._mainTexture.onClearObservable.add(function (engine) {
  95902. engine.clear(_this.neutralColor, true, true, true);
  95903. });
  95904. };
  95905. /**
  95906. * Checks for the readiness of the element composing the layer.
  95907. * @param subMesh the mesh to check for
  95908. * @param useInstances specify wether or not to use instances to render the mesh
  95909. * @param emissiveTexture the associated emissive texture used to generate the glow
  95910. * @return true if ready otherwise, false
  95911. */
  95912. EffectLayer.prototype._isReady = function (subMesh, useInstances, emissiveTexture) {
  95913. var material = subMesh.getMaterial();
  95914. if (!material) {
  95915. return false;
  95916. }
  95917. if (!material.isReady(subMesh.getMesh(), useInstances)) {
  95918. return false;
  95919. }
  95920. var defines = [];
  95921. var attribs = [BABYLON.VertexBuffer.PositionKind];
  95922. var mesh = subMesh.getMesh();
  95923. var uv1 = false;
  95924. var uv2 = false;
  95925. // Alpha test
  95926. if (material && material.needAlphaTesting()) {
  95927. var alphaTexture = material.getAlphaTestTexture();
  95928. if (alphaTexture) {
  95929. defines.push("#define ALPHATEST");
  95930. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95931. alphaTexture.coordinatesIndex === 1) {
  95932. defines.push("#define DIFFUSEUV2");
  95933. uv2 = true;
  95934. }
  95935. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95936. defines.push("#define DIFFUSEUV1");
  95937. uv1 = true;
  95938. }
  95939. }
  95940. }
  95941. // Emissive
  95942. if (emissiveTexture) {
  95943. defines.push("#define EMISSIVE");
  95944. if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UV2Kind) &&
  95945. emissiveTexture.coordinatesIndex === 1) {
  95946. defines.push("#define EMISSIVEUV2");
  95947. uv2 = true;
  95948. }
  95949. else if (mesh.isVerticesDataPresent(BABYLON.VertexBuffer.UVKind)) {
  95950. defines.push("#define EMISSIVEUV1");
  95951. uv1 = true;
  95952. }
  95953. }
  95954. if (uv1) {
  95955. attribs.push(BABYLON.VertexBuffer.UVKind);
  95956. defines.push("#define UV1");
  95957. }
  95958. if (uv2) {
  95959. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  95960. defines.push("#define UV2");
  95961. }
  95962. // Bones
  95963. if (mesh.useBones && mesh.computeBonesUsingShaders) {
  95964. attribs.push(BABYLON.VertexBuffer.MatricesIndicesKind);
  95965. attribs.push(BABYLON.VertexBuffer.MatricesWeightsKind);
  95966. if (mesh.numBoneInfluencers > 4) {
  95967. attribs.push(BABYLON.VertexBuffer.MatricesIndicesExtraKind);
  95968. attribs.push(BABYLON.VertexBuffer.MatricesWeightsExtraKind);
  95969. }
  95970. defines.push("#define NUM_BONE_INFLUENCERS " + mesh.numBoneInfluencers);
  95971. defines.push("#define BonesPerMesh " + (mesh.skeleton ? (mesh.skeleton.bones.length + 1) : 0));
  95972. }
  95973. else {
  95974. defines.push("#define NUM_BONE_INFLUENCERS 0");
  95975. }
  95976. // Morph targets
  95977. var manager = mesh.morphTargetManager;
  95978. var morphInfluencers = 0;
  95979. if (manager) {
  95980. if (manager.numInfluencers > 0) {
  95981. defines.push("#define MORPHTARGETS");
  95982. morphInfluencers = manager.numInfluencers;
  95983. defines.push("#define NUM_MORPH_INFLUENCERS " + morphInfluencers);
  95984. BABYLON.MaterialHelper.PrepareAttributesForMorphTargets(attribs, mesh, { "NUM_MORPH_INFLUENCERS": morphInfluencers });
  95985. }
  95986. }
  95987. // Instances
  95988. if (useInstances) {
  95989. defines.push("#define INSTANCES");
  95990. attribs.push("world0");
  95991. attribs.push("world1");
  95992. attribs.push("world2");
  95993. attribs.push("world3");
  95994. }
  95995. // Get correct effect
  95996. var join = defines.join("\n");
  95997. if (this._cachedDefines !== join) {
  95998. this._cachedDefines = join;
  95999. this._effectLayerMapGenerationEffect = this._scene.getEngine().createEffect("glowMapGeneration", attribs, ["world", "mBones", "viewProjection", "diffuseMatrix", "color", "emissiveMatrix", "morphTargetInfluences"], ["diffuseSampler", "emissiveSampler"], join, undefined, undefined, undefined, { maxSimultaneousMorphTargets: morphInfluencers });
  96000. }
  96001. return this._effectLayerMapGenerationEffect.isReady();
  96002. };
  96003. /**
  96004. * Renders the glowing part of the scene by blending the blurred glowing meshes on top of the rendered scene.
  96005. */
  96006. EffectLayer.prototype.render = function () {
  96007. var currentEffect = this._mergeEffect;
  96008. // Check
  96009. if (!currentEffect.isReady())
  96010. return;
  96011. for (var i = 0; i < this._postProcesses.length; i++) {
  96012. if (!this._postProcesses[i].isReady()) {
  96013. return;
  96014. }
  96015. }
  96016. var engine = this._scene.getEngine();
  96017. this.onBeforeComposeObservable.notifyObservers(this);
  96018. // Render
  96019. engine.enableEffect(currentEffect);
  96020. engine.setState(false);
  96021. // VBOs
  96022. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  96023. // Cache
  96024. var previousAlphaMode = engine.getAlphaMode();
  96025. // Go Blend.
  96026. engine.setAlphaMode(this._effectLayerOptions.alphaBlendingMode);
  96027. // Blends the map on the main canvas.
  96028. this._internalRender(currentEffect);
  96029. // Restore Alpha
  96030. engine.setAlphaMode(previousAlphaMode);
  96031. this.onAfterComposeObservable.notifyObservers(this);
  96032. // Handle size changes.
  96033. var size = this._mainTexture.getSize();
  96034. this._setMainTextureSize();
  96035. if (size.width !== this._mainTextureDesiredSize.width || size.height !== this._mainTextureDesiredSize.height) {
  96036. // Recreate RTT and post processes on size change.
  96037. this.onSizeChangedObservable.notifyObservers(this);
  96038. this._disposeTextureAndPostProcesses();
  96039. this._createMainTexture();
  96040. this._createTextureAndPostProcesses();
  96041. }
  96042. };
  96043. /**
  96044. * Determine if a given mesh will be used in the current effect.
  96045. * @param mesh mesh to test
  96046. * @returns true if the mesh will be used
  96047. */
  96048. EffectLayer.prototype.hasMesh = function (mesh) {
  96049. return true;
  96050. };
  96051. /**
  96052. * Returns true if the layer contains information to display, otherwise false.
  96053. * @returns true if the glow layer should be rendered
  96054. */
  96055. EffectLayer.prototype.shouldRender = function () {
  96056. return this.isEnabled && this._shouldRender;
  96057. };
  96058. /**
  96059. * Returns true if the mesh should render, otherwise false.
  96060. * @param mesh The mesh to render
  96061. * @returns true if it should render otherwise false
  96062. */
  96063. EffectLayer.prototype._shouldRenderMesh = function (mesh) {
  96064. return true;
  96065. };
  96066. /**
  96067. * Returns true if the mesh should render, otherwise false.
  96068. * @param mesh The mesh to render
  96069. * @returns true if it should render otherwise false
  96070. */
  96071. EffectLayer.prototype._shouldRenderEmissiveTextureForMesh = function (mesh) {
  96072. return true;
  96073. };
  96074. /**
  96075. * Renders the submesh passed in parameter to the generation map.
  96076. */
  96077. EffectLayer.prototype._renderSubMesh = function (subMesh) {
  96078. var _this = this;
  96079. if (!this.shouldRender()) {
  96080. return;
  96081. }
  96082. var material = subMesh.getMaterial();
  96083. var mesh = subMesh.getRenderingMesh();
  96084. var scene = this._scene;
  96085. var engine = scene.getEngine();
  96086. if (!material) {
  96087. return;
  96088. }
  96089. // Do not block in blend mode.
  96090. if (material.needAlphaBlendingForMesh(mesh)) {
  96091. return;
  96092. }
  96093. // Culling
  96094. engine.setState(material.backFaceCulling);
  96095. // Managing instances
  96096. var batch = mesh._getInstancesRenderList(subMesh._id);
  96097. if (batch.mustReturn) {
  96098. return;
  96099. }
  96100. // Early Exit per mesh
  96101. if (!this._shouldRenderMesh(mesh)) {
  96102. return;
  96103. }
  96104. var hardwareInstancedRendering = (engine.getCaps().instancedArrays) && (batch.visibleInstances[subMesh._id] !== null) && (batch.visibleInstances[subMesh._id] !== undefined);
  96105. this._setEmissiveTextureAndColor(mesh, subMesh, material);
  96106. if (this._isReady(subMesh, hardwareInstancedRendering, this._emissiveTextureAndColor.texture)) {
  96107. engine.enableEffect(this._effectLayerMapGenerationEffect);
  96108. mesh._bind(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode);
  96109. this._effectLayerMapGenerationEffect.setMatrix("viewProjection", scene.getTransformMatrix());
  96110. this._effectLayerMapGenerationEffect.setFloat4("color", this._emissiveTextureAndColor.color.r, this._emissiveTextureAndColor.color.g, this._emissiveTextureAndColor.color.b, this._emissiveTextureAndColor.color.a);
  96111. // Alpha test
  96112. if (material && material.needAlphaTesting()) {
  96113. var alphaTexture = material.getAlphaTestTexture();
  96114. if (alphaTexture) {
  96115. this._effectLayerMapGenerationEffect.setTexture("diffuseSampler", alphaTexture);
  96116. var textureMatrix = alphaTexture.getTextureMatrix();
  96117. if (textureMatrix) {
  96118. this._effectLayerMapGenerationEffect.setMatrix("diffuseMatrix", textureMatrix);
  96119. }
  96120. }
  96121. }
  96122. // Glow emissive only
  96123. if (this._emissiveTextureAndColor.texture) {
  96124. this._effectLayerMapGenerationEffect.setTexture("emissiveSampler", this._emissiveTextureAndColor.texture);
  96125. this._effectLayerMapGenerationEffect.setMatrix("emissiveMatrix", this._emissiveTextureAndColor.texture.getTextureMatrix());
  96126. }
  96127. // Bones
  96128. if (mesh.useBones && mesh.computeBonesUsingShaders && mesh.skeleton) {
  96129. this._effectLayerMapGenerationEffect.setMatrices("mBones", mesh.skeleton.getTransformMatrices(mesh));
  96130. }
  96131. // Morph targets
  96132. BABYLON.MaterialHelper.BindMorphTargetParameters(mesh, this._effectLayerMapGenerationEffect);
  96133. // Draw
  96134. mesh._processRendering(subMesh, this._effectLayerMapGenerationEffect, BABYLON.Material.TriangleFillMode, batch, hardwareInstancedRendering, function (isInstance, world) { return _this._effectLayerMapGenerationEffect.setMatrix("world", world); });
  96135. }
  96136. else {
  96137. // Need to reset refresh rate of the shadowMap
  96138. this._mainTexture.resetRefreshCounter();
  96139. }
  96140. };
  96141. /**
  96142. * Rebuild the required buffers.
  96143. * @hidden Internal use only.
  96144. */
  96145. EffectLayer.prototype._rebuild = function () {
  96146. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96147. if (vb) {
  96148. vb._rebuild();
  96149. }
  96150. this._generateIndexBuffer();
  96151. };
  96152. /**
  96153. * Dispose only the render target textures and post process.
  96154. */
  96155. EffectLayer.prototype._disposeTextureAndPostProcesses = function () {
  96156. this._mainTexture.dispose();
  96157. for (var i = 0; i < this._postProcesses.length; i++) {
  96158. if (this._postProcesses[i]) {
  96159. this._postProcesses[i].dispose();
  96160. }
  96161. }
  96162. this._postProcesses = [];
  96163. for (var i = 0; i < this._textures.length; i++) {
  96164. if (this._textures[i]) {
  96165. this._textures[i].dispose();
  96166. }
  96167. }
  96168. this._textures = [];
  96169. };
  96170. /**
  96171. * Dispose the highlight layer and free resources.
  96172. */
  96173. EffectLayer.prototype.dispose = function () {
  96174. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  96175. if (vertexBuffer) {
  96176. vertexBuffer.dispose();
  96177. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  96178. }
  96179. if (this._indexBuffer) {
  96180. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  96181. this._indexBuffer = null;
  96182. }
  96183. // Clean textures and post processes
  96184. this._disposeTextureAndPostProcesses();
  96185. // Remove from scene
  96186. var index = this._scene.effectLayers.indexOf(this, 0);
  96187. if (index > -1) {
  96188. this._scene.effectLayers.splice(index, 1);
  96189. }
  96190. // Callback
  96191. this.onDisposeObservable.notifyObservers(this);
  96192. this.onDisposeObservable.clear();
  96193. this.onBeforeRenderMainTextureObservable.clear();
  96194. this.onBeforeComposeObservable.clear();
  96195. this.onAfterComposeObservable.clear();
  96196. this.onSizeChangedObservable.clear();
  96197. };
  96198. /**
  96199. * Gets the class name of the effect layer
  96200. * @returns the string with the class name of the effect layer
  96201. */
  96202. EffectLayer.prototype.getClassName = function () {
  96203. return "EffectLayer";
  96204. };
  96205. /**
  96206. * Creates an effect layer from parsed effect layer data
  96207. * @param parsedEffectLayer defines effect layer data
  96208. * @param scene defines the current scene
  96209. * @param rootUrl defines the root URL containing the effect layer information
  96210. * @returns a parsed effect Layer
  96211. */
  96212. EffectLayer.Parse = function (parsedEffectLayer, scene, rootUrl) {
  96213. var effectLayerType = BABYLON.Tools.Instantiate(parsedEffectLayer.customType);
  96214. return effectLayerType.Parse(parsedEffectLayer, scene, rootUrl);
  96215. };
  96216. __decorate([
  96217. BABYLON.serialize()
  96218. ], EffectLayer.prototype, "name", void 0);
  96219. __decorate([
  96220. BABYLON.serializeAsColor4()
  96221. ], EffectLayer.prototype, "neutralColor", void 0);
  96222. __decorate([
  96223. BABYLON.serialize()
  96224. ], EffectLayer.prototype, "isEnabled", void 0);
  96225. __decorate([
  96226. BABYLON.serializeAsCameraReference()
  96227. ], EffectLayer.prototype, "camera", null);
  96228. return EffectLayer;
  96229. }());
  96230. BABYLON.EffectLayer = EffectLayer;
  96231. })(BABYLON || (BABYLON = {}));
  96232. //# sourceMappingURL=babylon.effectLayer.js.map
  96233. var BABYLON;
  96234. (function (BABYLON) {
  96235. /**
  96236. * Special Glow Blur post process only blurring the alpha channel
  96237. * It enforces keeping the most luminous color in the color channel.
  96238. */
  96239. var GlowBlurPostProcess = /** @class */ (function (_super) {
  96240. __extends(GlowBlurPostProcess, _super);
  96241. function GlowBlurPostProcess(name, direction, kernel, options, camera, samplingMode, engine, reusable) {
  96242. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE; }
  96243. var _this = _super.call(this, name, "glowBlurPostProcess", ["screenSize", "direction", "blurWidth"], null, options, camera, samplingMode, engine, reusable) || this;
  96244. _this.direction = direction;
  96245. _this.kernel = kernel;
  96246. _this.onApplyObservable.add(function (effect) {
  96247. effect.setFloat2("screenSize", _this.width, _this.height);
  96248. effect.setVector2("direction", _this.direction);
  96249. effect.setFloat("blurWidth", _this.kernel);
  96250. });
  96251. return _this;
  96252. }
  96253. return GlowBlurPostProcess;
  96254. }(BABYLON.PostProcess));
  96255. /**
  96256. * The highlight layer Helps adding a glow effect around a mesh.
  96257. *
  96258. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96259. * glowy meshes to your scene.
  96260. *
  96261. * !!! THIS REQUIRES AN ACTIVE STENCIL BUFFER ON THE CANVAS !!!
  96262. */
  96263. var HighlightLayer = /** @class */ (function (_super) {
  96264. __extends(HighlightLayer, _super);
  96265. /**
  96266. * Instantiates a new highlight Layer and references it to the scene..
  96267. * @param name The name of the layer
  96268. * @param scene The scene to use the layer in
  96269. * @param options Sets of none mandatory options to use with the layer (see IHighlightLayerOptions for more information)
  96270. */
  96271. function HighlightLayer(name, scene, options) {
  96272. var _this = _super.call(this, name, scene) || this;
  96273. _this.name = name;
  96274. /**
  96275. * Specifies whether or not the inner glow is ACTIVE in the layer.
  96276. */
  96277. _this.innerGlow = true;
  96278. /**
  96279. * Specifies whether or not the outer glow is ACTIVE in the layer.
  96280. */
  96281. _this.outerGlow = true;
  96282. /**
  96283. * An event triggered when the highlight layer is being blurred.
  96284. */
  96285. _this.onBeforeBlurObservable = new BABYLON.Observable();
  96286. /**
  96287. * An event triggered when the highlight layer has been blurred.
  96288. */
  96289. _this.onAfterBlurObservable = new BABYLON.Observable();
  96290. _this._instanceGlowingMeshStencilReference = HighlightLayer.GlowingMeshStencilReference++;
  96291. _this._meshes = {};
  96292. _this._excludedMeshes = {};
  96293. _this.neutralColor = HighlightLayer.NeutralColor;
  96294. // Warn on stencil
  96295. if (!_this._engine.isStencilEnable) {
  96296. 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 }");
  96297. }
  96298. // Adapt options
  96299. _this._options = __assign({ mainTextureRatio: 0.5, blurTextureSizeRatio: 0.5, blurHorizontalSize: 1.0, blurVerticalSize: 1.0, alphaBlendingMode: BABYLON.Engine.ALPHA_COMBINE, camera: null }, options);
  96300. // Initialize the layer
  96301. _this._init({
  96302. alphaBlendingMode: _this._options.alphaBlendingMode,
  96303. camera: _this._options.camera,
  96304. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96305. mainTextureRatio: _this._options.mainTextureRatio
  96306. });
  96307. // Do not render as long as no meshes have been added
  96308. _this._shouldRender = false;
  96309. return _this;
  96310. }
  96311. Object.defineProperty(HighlightLayer.prototype, "blurHorizontalSize", {
  96312. /**
  96313. * Gets the horizontal size of the blur.
  96314. */
  96315. get: function () {
  96316. return this._horizontalBlurPostprocess.kernel;
  96317. },
  96318. /**
  96319. * Specifies the horizontal size of the blur.
  96320. */
  96321. set: function (value) {
  96322. this._horizontalBlurPostprocess.kernel = value;
  96323. },
  96324. enumerable: true,
  96325. configurable: true
  96326. });
  96327. Object.defineProperty(HighlightLayer.prototype, "blurVerticalSize", {
  96328. /**
  96329. * Gets the vertical size of the blur.
  96330. */
  96331. get: function () {
  96332. return this._verticalBlurPostprocess.kernel;
  96333. },
  96334. /**
  96335. * Specifies the vertical size of the blur.
  96336. */
  96337. set: function (value) {
  96338. this._verticalBlurPostprocess.kernel = value;
  96339. },
  96340. enumerable: true,
  96341. configurable: true
  96342. });
  96343. /**
  96344. * Get the effect name of the layer.
  96345. * @return The effect name
  96346. */
  96347. HighlightLayer.prototype.getEffectName = function () {
  96348. return HighlightLayer.EffectName;
  96349. };
  96350. /**
  96351. * Create the merge effect. This is the shader use to blit the information back
  96352. * to the main canvas at the end of the scene rendering.
  96353. */
  96354. HighlightLayer.prototype._createMergeEffect = function () {
  96355. // Effect
  96356. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler"], this._options.isStroke ? "#define STROKE \n" : undefined);
  96357. };
  96358. /**
  96359. * Creates the render target textures and post processes used in the highlight layer.
  96360. */
  96361. HighlightLayer.prototype._createTextureAndPostProcesses = function () {
  96362. var _this = this;
  96363. var blurTextureWidth = this._mainTextureDesiredSize.width * this._options.blurTextureSizeRatio;
  96364. var blurTextureHeight = this._mainTextureDesiredSize.height * this._options.blurTextureSizeRatio;
  96365. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96366. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96367. var textureType = 0;
  96368. if (this._engine.getCaps().textureHalfFloatRender) {
  96369. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96370. }
  96371. else {
  96372. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96373. }
  96374. this._blurTexture = new BABYLON.RenderTargetTexture("HighlightLayerBlurRTT", {
  96375. width: blurTextureWidth,
  96376. height: blurTextureHeight
  96377. }, this._scene, false, true, textureType);
  96378. this._blurTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96379. this._blurTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96380. this._blurTexture.anisotropicFilteringLevel = 16;
  96381. this._blurTexture.updateSamplingMode(BABYLON.Texture.TRILINEAR_SAMPLINGMODE);
  96382. this._blurTexture.renderParticles = false;
  96383. this._blurTexture.ignoreCameraViewport = true;
  96384. this._textures = [this._blurTexture];
  96385. if (this._options.alphaBlendingMode === BABYLON.Engine.ALPHA_COMBINE) {
  96386. this._downSamplePostprocess = new BABYLON.PassPostProcess("HighlightLayerPPP", this._options.blurTextureSizeRatio, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96387. this._downSamplePostprocess.onApplyObservable.add(function (effect) {
  96388. effect.setTexture("textureSampler", _this._mainTexture);
  96389. });
  96390. this._horizontalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96391. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96392. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96393. });
  96394. this._verticalBlurPostprocess = new GlowBlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize, 1, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine());
  96395. this._verticalBlurPostprocess.onApplyObservable.add(function (effect) {
  96396. effect.setFloat2("screenSize", blurTextureWidth, blurTextureHeight);
  96397. });
  96398. this._postProcesses = [this._downSamplePostprocess, this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96399. }
  96400. else {
  96401. this._horizontalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerHBP", new BABYLON.Vector2(1.0, 0), this._options.blurHorizontalSize / 2, {
  96402. width: blurTextureWidth,
  96403. height: blurTextureHeight
  96404. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96405. this._horizontalBlurPostprocess.width = blurTextureWidth;
  96406. this._horizontalBlurPostprocess.height = blurTextureHeight;
  96407. this._horizontalBlurPostprocess.onApplyObservable.add(function (effect) {
  96408. effect.setTexture("textureSampler", _this._mainTexture);
  96409. });
  96410. this._verticalBlurPostprocess = new BABYLON.BlurPostProcess("HighlightLayerVBP", new BABYLON.Vector2(0, 1.0), this._options.blurVerticalSize / 2, {
  96411. width: blurTextureWidth,
  96412. height: blurTextureHeight
  96413. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96414. this._postProcesses = [this._horizontalBlurPostprocess, this._verticalBlurPostprocess];
  96415. }
  96416. this._mainTexture.onAfterUnbindObservable.add(function () {
  96417. _this.onBeforeBlurObservable.notifyObservers(_this);
  96418. var internalTexture = _this._blurTexture.getInternalTexture();
  96419. if (internalTexture) {
  96420. _this._scene.postProcessManager.directRender(_this._postProcesses, internalTexture, true);
  96421. }
  96422. _this.onAfterBlurObservable.notifyObservers(_this);
  96423. });
  96424. // Prevent autoClear.
  96425. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96426. };
  96427. /**
  96428. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96429. */
  96430. HighlightLayer.prototype.needStencil = function () {
  96431. return true;
  96432. };
  96433. /**
  96434. * Checks for the readiness of the element composing the layer.
  96435. * @param subMesh the mesh to check for
  96436. * @param useInstances specify wether or not to use instances to render the mesh
  96437. * @param emissiveTexture the associated emissive texture used to generate the glow
  96438. * @return true if ready otherwise, false
  96439. */
  96440. HighlightLayer.prototype.isReady = function (subMesh, useInstances) {
  96441. var material = subMesh.getMaterial();
  96442. var mesh = subMesh.getRenderingMesh();
  96443. if (!material || !mesh || !this._meshes) {
  96444. return false;
  96445. }
  96446. var emissiveTexture = null;
  96447. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96448. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96449. emissiveTexture = material.emissiveTexture;
  96450. }
  96451. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96452. };
  96453. /**
  96454. * Implementation specific of rendering the generating effect on the main canvas.
  96455. * @param effect The effect used to render through
  96456. */
  96457. HighlightLayer.prototype._internalRender = function (effect) {
  96458. // Texture
  96459. effect.setTexture("textureSampler", this._blurTexture);
  96460. // Cache
  96461. var engine = this._engine;
  96462. var previousStencilBuffer = engine.getStencilBuffer();
  96463. var previousStencilFunction = engine.getStencilFunction();
  96464. var previousStencilMask = engine.getStencilMask();
  96465. var previousStencilOperationPass = engine.getStencilOperationPass();
  96466. var previousStencilOperationFail = engine.getStencilOperationFail();
  96467. var previousStencilOperationDepthFail = engine.getStencilOperationDepthFail();
  96468. var previousStencilReference = engine.getStencilFunctionReference();
  96469. // Stencil operations
  96470. engine.setStencilOperationPass(BABYLON.Engine.REPLACE);
  96471. engine.setStencilOperationFail(BABYLON.Engine.KEEP);
  96472. engine.setStencilOperationDepthFail(BABYLON.Engine.KEEP);
  96473. // Draw order
  96474. engine.setStencilMask(0x00);
  96475. engine.setStencilBuffer(true);
  96476. engine.setStencilFunctionReference(this._instanceGlowingMeshStencilReference);
  96477. // 2 passes inner outer
  96478. if (this.outerGlow) {
  96479. effect.setFloat("offset", 0);
  96480. engine.setStencilFunction(BABYLON.Engine.NOTEQUAL);
  96481. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96482. }
  96483. if (this.innerGlow) {
  96484. effect.setFloat("offset", 1);
  96485. engine.setStencilFunction(BABYLON.Engine.EQUAL);
  96486. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  96487. }
  96488. // Restore Cache
  96489. engine.setStencilFunction(previousStencilFunction);
  96490. engine.setStencilMask(previousStencilMask);
  96491. engine.setStencilBuffer(previousStencilBuffer);
  96492. engine.setStencilOperationPass(previousStencilOperationPass);
  96493. engine.setStencilOperationFail(previousStencilOperationFail);
  96494. engine.setStencilOperationDepthFail(previousStencilOperationDepthFail);
  96495. engine.setStencilFunctionReference(previousStencilReference);
  96496. };
  96497. /**
  96498. * Returns true if the layer contains information to display, otherwise false.
  96499. */
  96500. HighlightLayer.prototype.shouldRender = function () {
  96501. if (_super.prototype.shouldRender.call(this)) {
  96502. return this._meshes ? true : false;
  96503. }
  96504. return false;
  96505. };
  96506. /**
  96507. * Returns true if the mesh should render, otherwise false.
  96508. * @param mesh The mesh to render
  96509. * @returns true if it should render otherwise false
  96510. */
  96511. HighlightLayer.prototype._shouldRenderMesh = function (mesh) {
  96512. // Excluded Mesh
  96513. if (this._excludedMeshes && this._excludedMeshes[mesh.uniqueId]) {
  96514. return false;
  96515. }
  96516. ;
  96517. return true;
  96518. };
  96519. /**
  96520. * Sets the required values for both the emissive texture and and the main color.
  96521. */
  96522. HighlightLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  96523. var highlightLayerMesh = this._meshes[mesh.uniqueId];
  96524. if (highlightLayerMesh) {
  96525. this._emissiveTextureAndColor.color.set(highlightLayerMesh.color.r, highlightLayerMesh.color.g, highlightLayerMesh.color.b, 1.0);
  96526. }
  96527. else {
  96528. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  96529. }
  96530. if (highlightLayerMesh && highlightLayerMesh.glowEmissiveOnly && material) {
  96531. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  96532. this._emissiveTextureAndColor.color.set(1.0, 1.0, 1.0, 1.0);
  96533. }
  96534. else {
  96535. this._emissiveTextureAndColor.texture = null;
  96536. }
  96537. };
  96538. /**
  96539. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the highlight layer.
  96540. * @param mesh The mesh to exclude from the highlight layer
  96541. */
  96542. HighlightLayer.prototype.addExcludedMesh = function (mesh) {
  96543. if (!this._excludedMeshes) {
  96544. return;
  96545. }
  96546. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96547. if (!meshExcluded) {
  96548. this._excludedMeshes[mesh.uniqueId] = {
  96549. mesh: mesh,
  96550. beforeRender: mesh.onBeforeRenderObservable.add(function (mesh) {
  96551. mesh.getEngine().setStencilBuffer(false);
  96552. }),
  96553. afterRender: mesh.onAfterRenderObservable.add(function (mesh) {
  96554. mesh.getEngine().setStencilBuffer(true);
  96555. }),
  96556. };
  96557. }
  96558. };
  96559. /**
  96560. * Remove a mesh from the exclusion list to let it impact or being impacted by the highlight layer.
  96561. * @param mesh The mesh to highlight
  96562. */
  96563. HighlightLayer.prototype.removeExcludedMesh = function (mesh) {
  96564. if (!this._excludedMeshes) {
  96565. return;
  96566. }
  96567. var meshExcluded = this._excludedMeshes[mesh.uniqueId];
  96568. if (meshExcluded) {
  96569. if (meshExcluded.beforeRender) {
  96570. mesh.onBeforeRenderObservable.remove(meshExcluded.beforeRender);
  96571. }
  96572. if (meshExcluded.afterRender) {
  96573. mesh.onAfterRenderObservable.remove(meshExcluded.afterRender);
  96574. }
  96575. }
  96576. this._excludedMeshes[mesh.uniqueId] = null;
  96577. };
  96578. /**
  96579. * Determine if a given mesh will be highlighted by the current HighlightLayer
  96580. * @param mesh mesh to test
  96581. * @returns true if the mesh will be highlighted by the current HighlightLayer
  96582. */
  96583. HighlightLayer.prototype.hasMesh = function (mesh) {
  96584. if (!this._meshes) {
  96585. return false;
  96586. }
  96587. return this._meshes[mesh.uniqueId] !== undefined && this._meshes[mesh.uniqueId] !== null;
  96588. };
  96589. /**
  96590. * Add a mesh in the highlight layer in order to make it glow with the chosen color.
  96591. * @param mesh The mesh to highlight
  96592. * @param color The color of the highlight
  96593. * @param glowEmissiveOnly Extract the glow from the emissive texture
  96594. */
  96595. HighlightLayer.prototype.addMesh = function (mesh, color, glowEmissiveOnly) {
  96596. var _this = this;
  96597. if (glowEmissiveOnly === void 0) { glowEmissiveOnly = false; }
  96598. if (!this._meshes) {
  96599. return;
  96600. }
  96601. var meshHighlight = this._meshes[mesh.uniqueId];
  96602. if (meshHighlight) {
  96603. meshHighlight.color = color;
  96604. }
  96605. else {
  96606. this._meshes[mesh.uniqueId] = {
  96607. mesh: mesh,
  96608. color: color,
  96609. // Lambda required for capture due to Observable this context
  96610. observerHighlight: mesh.onBeforeRenderObservable.add(function (mesh) {
  96611. if (_this._excludedMeshes && _this._excludedMeshes[mesh.uniqueId]) {
  96612. _this._defaultStencilReference(mesh);
  96613. }
  96614. else {
  96615. mesh.getScene().getEngine().setStencilFunctionReference(_this._instanceGlowingMeshStencilReference);
  96616. }
  96617. }),
  96618. observerDefault: mesh.onAfterRenderObservable.add(this._defaultStencilReference),
  96619. glowEmissiveOnly: glowEmissiveOnly
  96620. };
  96621. }
  96622. this._shouldRender = true;
  96623. };
  96624. /**
  96625. * Remove a mesh from the highlight layer in order to make it stop glowing.
  96626. * @param mesh The mesh to highlight
  96627. */
  96628. HighlightLayer.prototype.removeMesh = function (mesh) {
  96629. if (!this._meshes) {
  96630. return;
  96631. }
  96632. var meshHighlight = this._meshes[mesh.uniqueId];
  96633. if (meshHighlight) {
  96634. if (meshHighlight.observerHighlight) {
  96635. mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96636. }
  96637. if (meshHighlight.observerDefault) {
  96638. mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96639. }
  96640. delete this._meshes[mesh.uniqueId];
  96641. }
  96642. this._shouldRender = false;
  96643. for (var meshHighlightToCheck in this._meshes) {
  96644. if (this._meshes[meshHighlightToCheck]) {
  96645. this._shouldRender = true;
  96646. break;
  96647. }
  96648. }
  96649. };
  96650. /**
  96651. * Force the stencil to the normal expected value for none glowing parts
  96652. */
  96653. HighlightLayer.prototype._defaultStencilReference = function (mesh) {
  96654. mesh.getScene().getEngine().setStencilFunctionReference(HighlightLayer.NormalMeshStencilReference);
  96655. };
  96656. /**
  96657. * Free any resources and references associated to a mesh.
  96658. * Internal use
  96659. * @param mesh The mesh to free.
  96660. */
  96661. HighlightLayer.prototype._disposeMesh = function (mesh) {
  96662. this.removeMesh(mesh);
  96663. this.removeExcludedMesh(mesh);
  96664. };
  96665. /**
  96666. * Dispose the highlight layer and free resources.
  96667. */
  96668. HighlightLayer.prototype.dispose = function () {
  96669. if (this._meshes) {
  96670. // Clean mesh references
  96671. for (var id in this._meshes) {
  96672. var meshHighlight = this._meshes[id];
  96673. if (meshHighlight && meshHighlight.mesh) {
  96674. if (meshHighlight.observerHighlight) {
  96675. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.observerHighlight);
  96676. }
  96677. if (meshHighlight.observerDefault) {
  96678. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.observerDefault);
  96679. }
  96680. }
  96681. }
  96682. this._meshes = null;
  96683. }
  96684. if (this._excludedMeshes) {
  96685. for (var id in this._excludedMeshes) {
  96686. var meshHighlight = this._excludedMeshes[id];
  96687. if (meshHighlight) {
  96688. if (meshHighlight.beforeRender) {
  96689. meshHighlight.mesh.onBeforeRenderObservable.remove(meshHighlight.beforeRender);
  96690. }
  96691. if (meshHighlight.afterRender) {
  96692. meshHighlight.mesh.onAfterRenderObservable.remove(meshHighlight.afterRender);
  96693. }
  96694. }
  96695. }
  96696. this._excludedMeshes = null;
  96697. }
  96698. _super.prototype.dispose.call(this);
  96699. };
  96700. /**
  96701. * Gets the class name of the effect layer
  96702. * @returns the string with the class name of the effect layer
  96703. */
  96704. HighlightLayer.prototype.getClassName = function () {
  96705. return "HighlightLayer";
  96706. };
  96707. /**
  96708. * Serializes this Highlight layer
  96709. * @returns a serialized Highlight layer object
  96710. */
  96711. HighlightLayer.prototype.serialize = function () {
  96712. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  96713. serializationObject.customType = "BABYLON.HighlightLayer";
  96714. // Highlighted meshes
  96715. serializationObject.meshes = [];
  96716. if (this._meshes) {
  96717. for (var m in this._meshes) {
  96718. var mesh = this._meshes[m];
  96719. if (mesh) {
  96720. serializationObject.meshes.push({
  96721. glowEmissiveOnly: mesh.glowEmissiveOnly,
  96722. color: mesh.color.asArray(),
  96723. meshId: mesh.mesh.id
  96724. });
  96725. }
  96726. }
  96727. }
  96728. // Excluded meshes
  96729. serializationObject.excludedMeshes = [];
  96730. if (this._excludedMeshes) {
  96731. for (var e in this._excludedMeshes) {
  96732. var excludedMesh = this._excludedMeshes[e];
  96733. if (excludedMesh) {
  96734. serializationObject.excludedMeshes.push(excludedMesh.mesh.id);
  96735. }
  96736. }
  96737. }
  96738. return serializationObject;
  96739. };
  96740. /**
  96741. * Creates a Highlight layer from parsed Highlight layer data
  96742. * @param parsedHightlightLayer defines the Highlight layer data
  96743. * @param scene defines the current scene
  96744. * @param rootUrl defines the root URL containing the Highlight layer information
  96745. * @returns a parsed Highlight layer
  96746. */
  96747. HighlightLayer.Parse = function (parsedHightlightLayer, scene, rootUrl) {
  96748. var hl = BABYLON.SerializationHelper.Parse(function () { return new HighlightLayer(parsedHightlightLayer.name, scene, parsedHightlightLayer.options); }, parsedHightlightLayer, scene, rootUrl);
  96749. var index;
  96750. // Excluded meshes
  96751. for (index = 0; index < parsedHightlightLayer.excludedMeshes.length; index++) {
  96752. var mesh = scene.getMeshByID(parsedHightlightLayer.excludedMeshes[index]);
  96753. if (mesh) {
  96754. hl.addExcludedMesh(mesh);
  96755. }
  96756. }
  96757. // Included meshes
  96758. for (index = 0; index < parsedHightlightLayer.meshes.length; index++) {
  96759. var highlightedMesh = parsedHightlightLayer.meshes[index];
  96760. var mesh = scene.getMeshByID(highlightedMesh.meshId);
  96761. if (mesh) {
  96762. hl.addMesh(mesh, BABYLON.Color3.FromArray(highlightedMesh.color), highlightedMesh.glowEmissiveOnly);
  96763. }
  96764. }
  96765. return hl;
  96766. };
  96767. /**
  96768. * Effect Name of the highlight layer.
  96769. */
  96770. HighlightLayer.EffectName = "HighlightLayer";
  96771. /**
  96772. * The neutral color used during the preparation of the glow effect.
  96773. * This is black by default as the blend operation is a blend operation.
  96774. */
  96775. HighlightLayer.NeutralColor = new BABYLON.Color4(0, 0, 0, 0);
  96776. /**
  96777. * Stencil value used for glowing meshes.
  96778. */
  96779. HighlightLayer.GlowingMeshStencilReference = 0x02;
  96780. /**
  96781. * Stencil value used for the other meshes in the scene.
  96782. */
  96783. HighlightLayer.NormalMeshStencilReference = 0x01;
  96784. __decorate([
  96785. BABYLON.serialize()
  96786. ], HighlightLayer.prototype, "innerGlow", void 0);
  96787. __decorate([
  96788. BABYLON.serialize()
  96789. ], HighlightLayer.prototype, "outerGlow", void 0);
  96790. __decorate([
  96791. BABYLON.serialize()
  96792. ], HighlightLayer.prototype, "blurHorizontalSize", null);
  96793. __decorate([
  96794. BABYLON.serialize()
  96795. ], HighlightLayer.prototype, "blurVerticalSize", null);
  96796. __decorate([
  96797. BABYLON.serialize("options")
  96798. ], HighlightLayer.prototype, "_options", void 0);
  96799. return HighlightLayer;
  96800. }(BABYLON.EffectLayer));
  96801. BABYLON.HighlightLayer = HighlightLayer;
  96802. })(BABYLON || (BABYLON = {}));
  96803. //# sourceMappingURL=babylon.highlightLayer.js.map
  96804. var BABYLON;
  96805. (function (BABYLON) {
  96806. /**
  96807. * The glow layer Helps adding a glow effect around the emissive parts of a mesh.
  96808. *
  96809. * Once instantiated in a scene, simply use the pushMesh or removeMesh method to add or remove
  96810. * glowy meshes to your scene.
  96811. *
  96812. * Documentation: https://doc.babylonjs.com/how_to/glow_layer
  96813. */
  96814. var GlowLayer = /** @class */ (function (_super) {
  96815. __extends(GlowLayer, _super);
  96816. /**
  96817. * Instantiates a new glow Layer and references it to the scene.
  96818. * @param name The name of the layer
  96819. * @param scene The scene to use the layer in
  96820. * @param options Sets of none mandatory options to use with the layer (see IGlowLayerOptions for more information)
  96821. */
  96822. function GlowLayer(name, scene, options) {
  96823. var _this = _super.call(this, name, scene) || this;
  96824. _this._intensity = 1.0;
  96825. _this._includedOnlyMeshes = [];
  96826. _this._excludedMeshes = [];
  96827. _this.neutralColor = new BABYLON.Color4(0, 0, 0, 1);
  96828. // Adapt options
  96829. _this._options = __assign({ mainTextureRatio: GlowLayer.DefaultTextureRatio, blurKernelSize: 32, mainTextureFixedSize: undefined, camera: null, mainTextureSamples: 1 }, options);
  96830. // Initialize the layer
  96831. _this._init({
  96832. alphaBlendingMode: BABYLON.Engine.ALPHA_ADD,
  96833. camera: _this._options.camera,
  96834. mainTextureFixedSize: _this._options.mainTextureFixedSize,
  96835. mainTextureRatio: _this._options.mainTextureRatio
  96836. });
  96837. return _this;
  96838. }
  96839. Object.defineProperty(GlowLayer.prototype, "blurKernelSize", {
  96840. /**
  96841. * Gets the kernel size of the blur.
  96842. */
  96843. get: function () {
  96844. return this._horizontalBlurPostprocess1.kernel;
  96845. },
  96846. /**
  96847. * Sets the kernel size of the blur.
  96848. */
  96849. set: function (value) {
  96850. this._horizontalBlurPostprocess1.kernel = value;
  96851. this._verticalBlurPostprocess1.kernel = value;
  96852. this._horizontalBlurPostprocess2.kernel = value;
  96853. this._verticalBlurPostprocess2.kernel = value;
  96854. },
  96855. enumerable: true,
  96856. configurable: true
  96857. });
  96858. Object.defineProperty(GlowLayer.prototype, "intensity", {
  96859. /**
  96860. * Gets the glow intensity.
  96861. */
  96862. get: function () {
  96863. return this._intensity;
  96864. },
  96865. /**
  96866. * Sets the glow intensity.
  96867. */
  96868. set: function (value) {
  96869. this._intensity = value;
  96870. },
  96871. enumerable: true,
  96872. configurable: true
  96873. });
  96874. /**
  96875. * Get the effect name of the layer.
  96876. * @return The effect name
  96877. */
  96878. GlowLayer.prototype.getEffectName = function () {
  96879. return GlowLayer.EffectName;
  96880. };
  96881. /**
  96882. * Create the merge effect. This is the shader use to blit the information back
  96883. * to the main canvas at the end of the scene rendering.
  96884. */
  96885. GlowLayer.prototype._createMergeEffect = function () {
  96886. // Effect
  96887. return this._engine.createEffect("glowMapMerge", [BABYLON.VertexBuffer.PositionKind], ["offset"], ["textureSampler", "textureSampler2"], "#define EMISSIVE \n");
  96888. };
  96889. /**
  96890. * Creates the render target textures and post processes used in the glow layer.
  96891. */
  96892. GlowLayer.prototype._createTextureAndPostProcesses = function () {
  96893. var _this = this;
  96894. var blurTextureWidth = this._mainTextureDesiredSize.width;
  96895. var blurTextureHeight = this._mainTextureDesiredSize.height;
  96896. blurTextureWidth = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureWidth, this._maxSize) : blurTextureWidth;
  96897. blurTextureHeight = this._engine.needPOTTextures ? BABYLON.Tools.GetExponentOfTwo(blurTextureHeight, this._maxSize) : blurTextureHeight;
  96898. var textureType = 0;
  96899. if (this._engine.getCaps().textureHalfFloatRender) {
  96900. textureType = BABYLON.Engine.TEXTURETYPE_HALF_FLOAT;
  96901. }
  96902. else {
  96903. textureType = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  96904. }
  96905. this._blurTexture1 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT", {
  96906. width: blurTextureWidth,
  96907. height: blurTextureHeight
  96908. }, this._scene, false, true, textureType);
  96909. this._blurTexture1.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96910. this._blurTexture1.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96911. this._blurTexture1.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96912. this._blurTexture1.renderParticles = false;
  96913. this._blurTexture1.ignoreCameraViewport = true;
  96914. var blurTextureWidth2 = Math.floor(blurTextureWidth / 2);
  96915. var blurTextureHeight2 = Math.floor(blurTextureHeight / 2);
  96916. this._blurTexture2 = new BABYLON.RenderTargetTexture("GlowLayerBlurRTT2", {
  96917. width: blurTextureWidth2,
  96918. height: blurTextureHeight2
  96919. }, this._scene, false, true, textureType);
  96920. this._blurTexture2.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96921. this._blurTexture2.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  96922. this._blurTexture2.updateSamplingMode(BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  96923. this._blurTexture2.renderParticles = false;
  96924. this._blurTexture2.ignoreCameraViewport = true;
  96925. this._textures = [this._blurTexture1, this._blurTexture2];
  96926. this._horizontalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerHBP1", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96927. width: blurTextureWidth,
  96928. height: blurTextureHeight
  96929. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96930. this._horizontalBlurPostprocess1.width = blurTextureWidth;
  96931. this._horizontalBlurPostprocess1.height = blurTextureHeight;
  96932. this._horizontalBlurPostprocess1.onApplyObservable.add(function (effect) {
  96933. effect.setTexture("textureSampler", _this._mainTexture);
  96934. });
  96935. this._verticalBlurPostprocess1 = new BABYLON.BlurPostProcess("GlowLayerVBP1", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96936. width: blurTextureWidth,
  96937. height: blurTextureHeight
  96938. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96939. this._horizontalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerHBP2", new BABYLON.Vector2(1.0, 0), this._options.blurKernelSize / 2, {
  96940. width: blurTextureWidth2,
  96941. height: blurTextureHeight2
  96942. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96943. this._horizontalBlurPostprocess2.width = blurTextureWidth2;
  96944. this._horizontalBlurPostprocess2.height = blurTextureHeight2;
  96945. this._horizontalBlurPostprocess2.onApplyObservable.add(function (effect) {
  96946. effect.setTexture("textureSampler", _this._blurTexture1);
  96947. });
  96948. this._verticalBlurPostprocess2 = new BABYLON.BlurPostProcess("GlowLayerVBP2", new BABYLON.Vector2(0, 1.0), this._options.blurKernelSize / 2, {
  96949. width: blurTextureWidth2,
  96950. height: blurTextureHeight2
  96951. }, null, BABYLON.Texture.BILINEAR_SAMPLINGMODE, this._scene.getEngine(), false, textureType);
  96952. this._postProcesses = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1, this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96953. this._postProcesses1 = [this._horizontalBlurPostprocess1, this._verticalBlurPostprocess1];
  96954. this._postProcesses2 = [this._horizontalBlurPostprocess2, this._verticalBlurPostprocess2];
  96955. this._mainTexture.samples = this._options.mainTextureSamples;
  96956. this._mainTexture.onAfterUnbindObservable.add(function () {
  96957. var internalTexture = _this._blurTexture1.getInternalTexture();
  96958. if (internalTexture) {
  96959. _this._scene.postProcessManager.directRender(_this._postProcesses1, internalTexture, true);
  96960. internalTexture = _this._blurTexture2.getInternalTexture();
  96961. if (internalTexture) {
  96962. _this._scene.postProcessManager.directRender(_this._postProcesses2, internalTexture, true);
  96963. }
  96964. }
  96965. });
  96966. // Prevent autoClear.
  96967. this._postProcesses.map(function (pp) { pp.autoClear = false; });
  96968. };
  96969. /**
  96970. * Checks for the readiness of the element composing the layer.
  96971. * @param subMesh the mesh to check for
  96972. * @param useInstances specify wether or not to use instances to render the mesh
  96973. * @param emissiveTexture the associated emissive texture used to generate the glow
  96974. * @return true if ready otherwise, false
  96975. */
  96976. GlowLayer.prototype.isReady = function (subMesh, useInstances) {
  96977. var material = subMesh.getMaterial();
  96978. var mesh = subMesh.getRenderingMesh();
  96979. if (!material || !mesh) {
  96980. return false;
  96981. }
  96982. var emissiveTexture = material.emissiveTexture;
  96983. return _super.prototype._isReady.call(this, subMesh, useInstances, emissiveTexture);
  96984. };
  96985. /**
  96986. * Returns wether or nood the layer needs stencil enabled during the mesh rendering.
  96987. */
  96988. GlowLayer.prototype.needStencil = function () {
  96989. return false;
  96990. };
  96991. /**
  96992. * Implementation specific of rendering the generating effect on the main canvas.
  96993. * @param effect The effect used to render through
  96994. */
  96995. GlowLayer.prototype._internalRender = function (effect) {
  96996. // Texture
  96997. effect.setTexture("textureSampler", this._blurTexture1);
  96998. effect.setTexture("textureSampler2", this._blurTexture2);
  96999. effect.setFloat("offset", this._intensity);
  97000. // Cache
  97001. var engine = this._engine;
  97002. var previousStencilBuffer = engine.getStencilBuffer();
  97003. // Draw order
  97004. engine.setStencilBuffer(false);
  97005. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  97006. // Draw order
  97007. engine.setStencilBuffer(previousStencilBuffer);
  97008. };
  97009. /**
  97010. * Sets the required values for both the emissive texture and and the main color.
  97011. */
  97012. GlowLayer.prototype._setEmissiveTextureAndColor = function (mesh, subMesh, material) {
  97013. var textureLevel = 1.0;
  97014. if (this.customEmissiveTextureSelector) {
  97015. this._emissiveTextureAndColor.texture = this.customEmissiveTextureSelector(mesh, subMesh, material);
  97016. }
  97017. else {
  97018. if (material) {
  97019. this._emissiveTextureAndColor.texture = material.emissiveTexture;
  97020. if (this._emissiveTextureAndColor.texture) {
  97021. textureLevel = this._emissiveTextureAndColor.texture.level;
  97022. }
  97023. }
  97024. else {
  97025. this._emissiveTextureAndColor.texture = null;
  97026. }
  97027. }
  97028. if (this.customEmissiveColorSelector) {
  97029. this.customEmissiveColorSelector(mesh, subMesh, material, this._emissiveTextureAndColor.color);
  97030. }
  97031. else {
  97032. if (material.emissiveColor) {
  97033. this._emissiveTextureAndColor.color.set(material.emissiveColor.r * textureLevel, material.emissiveColor.g * textureLevel, material.emissiveColor.b * textureLevel, 1.0);
  97034. }
  97035. else {
  97036. this._emissiveTextureAndColor.color.set(this.neutralColor.r, this.neutralColor.g, this.neutralColor.b, this.neutralColor.a);
  97037. }
  97038. }
  97039. };
  97040. /**
  97041. * Returns true if the mesh should render, otherwise false.
  97042. * @param mesh The mesh to render
  97043. * @returns true if it should render otherwise false
  97044. */
  97045. GlowLayer.prototype._shouldRenderMesh = function (mesh) {
  97046. return this.hasMesh(mesh);
  97047. };
  97048. /**
  97049. * Add a mesh in the exclusion list to prevent it to impact or being impacted by the glow layer.
  97050. * @param mesh The mesh to exclude from the glow layer
  97051. */
  97052. GlowLayer.prototype.addExcludedMesh = function (mesh) {
  97053. if (this._excludedMeshes.indexOf(mesh.uniqueId) === -1) {
  97054. this._excludedMeshes.push(mesh.uniqueId);
  97055. }
  97056. };
  97057. /**
  97058. * Remove a mesh from the exclusion list to let it impact or being impacted by the glow layer.
  97059. * @param mesh The mesh to remove
  97060. */
  97061. GlowLayer.prototype.removeExcludedMesh = function (mesh) {
  97062. var index = this._excludedMeshes.indexOf(mesh.uniqueId);
  97063. if (index !== -1) {
  97064. this._excludedMeshes.splice(index, 1);
  97065. }
  97066. };
  97067. /**
  97068. * Add a mesh in the inclusion list to impact or being impacted by the glow layer.
  97069. * @param mesh The mesh to include in the glow layer
  97070. */
  97071. GlowLayer.prototype.addIncludedOnlyMesh = function (mesh) {
  97072. if (this._includedOnlyMeshes.indexOf(mesh.uniqueId) === -1) {
  97073. this._includedOnlyMeshes.push(mesh.uniqueId);
  97074. }
  97075. };
  97076. /**
  97077. * Remove a mesh from the Inclusion list to prevent it to impact or being impacted by the glow layer.
  97078. * @param mesh The mesh to remove
  97079. */
  97080. GlowLayer.prototype.removeIncludedOnlyMesh = function (mesh) {
  97081. var index = this._includedOnlyMeshes.indexOf(mesh.uniqueId);
  97082. if (index !== -1) {
  97083. this._includedOnlyMeshes.splice(index, 1);
  97084. }
  97085. };
  97086. /**
  97087. * Determine if a given mesh will be used in the glow layer
  97088. * @param mesh The mesh to test
  97089. * @returns true if the mesh will be highlighted by the current glow layer
  97090. */
  97091. GlowLayer.prototype.hasMesh = function (mesh) {
  97092. // Included Mesh
  97093. if (this._includedOnlyMeshes.length) {
  97094. return this._includedOnlyMeshes.indexOf(mesh.uniqueId) !== -1;
  97095. }
  97096. ;
  97097. // Excluded Mesh
  97098. if (this._excludedMeshes.length) {
  97099. return this._excludedMeshes.indexOf(mesh.uniqueId) === -1;
  97100. }
  97101. ;
  97102. return true;
  97103. };
  97104. /**
  97105. * Free any resources and references associated to a mesh.
  97106. * Internal use
  97107. * @param mesh The mesh to free.
  97108. */
  97109. GlowLayer.prototype._disposeMesh = function (mesh) {
  97110. this.removeIncludedOnlyMesh(mesh);
  97111. this.removeExcludedMesh(mesh);
  97112. };
  97113. /**
  97114. * Gets the class name of the effect layer
  97115. * @returns the string with the class name of the effect layer
  97116. */
  97117. GlowLayer.prototype.getClassName = function () {
  97118. return "GlowLayer";
  97119. };
  97120. /**
  97121. * Serializes this glow layer
  97122. * @returns a serialized glow layer object
  97123. */
  97124. GlowLayer.prototype.serialize = function () {
  97125. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  97126. serializationObject.customType = "BABYLON.GlowLayer";
  97127. var index;
  97128. // Included meshes
  97129. serializationObject.includedMeshes = [];
  97130. if (this._includedOnlyMeshes.length) {
  97131. for (index = 0; index < this._includedOnlyMeshes.length; index++) {
  97132. var mesh = this._scene.getMeshByUniqueID(this._includedOnlyMeshes[index]);
  97133. if (mesh) {
  97134. serializationObject.includedMeshes.push(mesh.id);
  97135. }
  97136. }
  97137. }
  97138. // Excluded meshes
  97139. serializationObject.excludedMeshes = [];
  97140. if (this._excludedMeshes.length) {
  97141. for (index = 0; index < this._excludedMeshes.length; index++) {
  97142. var mesh = this._scene.getMeshByUniqueID(this._excludedMeshes[index]);
  97143. if (mesh) {
  97144. serializationObject.excludedMeshes.push(mesh.id);
  97145. }
  97146. }
  97147. }
  97148. return serializationObject;
  97149. };
  97150. /**
  97151. * Creates a Glow Layer from parsed glow layer data
  97152. * @param parsedGlowLayer defines glow layer data
  97153. * @param scene defines the current scene
  97154. * @param rootUrl defines the root URL containing the glow layer information
  97155. * @returns a parsed Glow Layer
  97156. */
  97157. GlowLayer.Parse = function (parsedGlowLayer, scene, rootUrl) {
  97158. var gl = BABYLON.SerializationHelper.Parse(function () { return new GlowLayer(parsedGlowLayer.name, scene, parsedGlowLayer.options); }, parsedGlowLayer, scene, rootUrl);
  97159. var index;
  97160. // Excluded meshes
  97161. for (index = 0; index < parsedGlowLayer.excludedMeshes.length; index++) {
  97162. var mesh = scene.getMeshByID(parsedGlowLayer.excludedMeshes[index]);
  97163. if (mesh) {
  97164. gl.addExcludedMesh(mesh);
  97165. }
  97166. }
  97167. // Included meshes
  97168. for (index = 0; index < parsedGlowLayer.includedMeshes.length; index++) {
  97169. var mesh = scene.getMeshByID(parsedGlowLayer.includedMeshes[index]);
  97170. if (mesh) {
  97171. gl.addIncludedOnlyMesh(mesh);
  97172. }
  97173. }
  97174. return gl;
  97175. };
  97176. /**
  97177. * Effect Name of the layer.
  97178. */
  97179. GlowLayer.EffectName = "GlowLayer";
  97180. /**
  97181. * The default blur kernel size used for the glow.
  97182. */
  97183. GlowLayer.DefaultBlurKernelSize = 32;
  97184. /**
  97185. * The default texture size ratio used for the glow.
  97186. */
  97187. GlowLayer.DefaultTextureRatio = 0.5;
  97188. __decorate([
  97189. BABYLON.serialize()
  97190. ], GlowLayer.prototype, "blurKernelSize", null);
  97191. __decorate([
  97192. BABYLON.serialize()
  97193. ], GlowLayer.prototype, "intensity", null);
  97194. __decorate([
  97195. BABYLON.serialize("options")
  97196. ], GlowLayer.prototype, "_options", void 0);
  97197. return GlowLayer;
  97198. }(BABYLON.EffectLayer));
  97199. BABYLON.GlowLayer = GlowLayer;
  97200. })(BABYLON || (BABYLON = {}));
  97201. //# sourceMappingURL=babylon.glowLayer.js.map
  97202. var BABYLON;
  97203. (function (BABYLON) {
  97204. /**
  97205. * Defines the list of states available for a task inside a {BABYLON.AssetsManager}
  97206. */
  97207. var AssetTaskState;
  97208. (function (AssetTaskState) {
  97209. /**
  97210. * Initialization
  97211. */
  97212. AssetTaskState[AssetTaskState["INIT"] = 0] = "INIT";
  97213. /**
  97214. * Running
  97215. */
  97216. AssetTaskState[AssetTaskState["RUNNING"] = 1] = "RUNNING";
  97217. /**
  97218. * Done
  97219. */
  97220. AssetTaskState[AssetTaskState["DONE"] = 2] = "DONE";
  97221. /**
  97222. * Error
  97223. */
  97224. AssetTaskState[AssetTaskState["ERROR"] = 3] = "ERROR";
  97225. })(AssetTaskState = BABYLON.AssetTaskState || (BABYLON.AssetTaskState = {}));
  97226. /**
  97227. * Define an abstract asset task used with a {BABYLON.AssetsManager} class to load assets into a scene
  97228. */
  97229. var AbstractAssetTask = /** @class */ (function () {
  97230. /**
  97231. * Creates a new {BABYLON.AssetsManager}
  97232. * @param name defines the name of the task
  97233. */
  97234. function AbstractAssetTask(
  97235. /**
  97236. * Task name
  97237. */ name) {
  97238. this.name = name;
  97239. this._isCompleted = false;
  97240. this._taskState = AssetTaskState.INIT;
  97241. }
  97242. Object.defineProperty(AbstractAssetTask.prototype, "isCompleted", {
  97243. /**
  97244. * Get if the task is completed
  97245. */
  97246. get: function () {
  97247. return this._isCompleted;
  97248. },
  97249. enumerable: true,
  97250. configurable: true
  97251. });
  97252. Object.defineProperty(AbstractAssetTask.prototype, "taskState", {
  97253. /**
  97254. * Gets the current state of the task
  97255. */
  97256. get: function () {
  97257. return this._taskState;
  97258. },
  97259. enumerable: true,
  97260. configurable: true
  97261. });
  97262. Object.defineProperty(AbstractAssetTask.prototype, "errorObject", {
  97263. /**
  97264. * Gets the current error object (if task is in error)
  97265. */
  97266. get: function () {
  97267. return this._errorObject;
  97268. },
  97269. enumerable: true,
  97270. configurable: true
  97271. });
  97272. /**
  97273. * Internal only
  97274. * @hidden
  97275. */
  97276. AbstractAssetTask.prototype._setErrorObject = function (message, exception) {
  97277. if (this._errorObject) {
  97278. return;
  97279. }
  97280. this._errorObject = {
  97281. message: message,
  97282. exception: exception
  97283. };
  97284. };
  97285. /**
  97286. * Execute the current task
  97287. * @param scene defines the scene where you want your assets to be loaded
  97288. * @param onSuccess is a callback called when the task is successfully executed
  97289. * @param onError is a callback called if an error occurs
  97290. */
  97291. AbstractAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97292. var _this = this;
  97293. this._taskState = AssetTaskState.RUNNING;
  97294. this.runTask(scene, function () {
  97295. _this.onDoneCallback(onSuccess, onError);
  97296. }, function (msg, exception) {
  97297. _this.onErrorCallback(onError, msg, exception);
  97298. });
  97299. };
  97300. /**
  97301. * Execute the current task
  97302. * @param scene defines the scene where you want your assets to be loaded
  97303. * @param onSuccess is a callback called when the task is successfully executed
  97304. * @param onError is a callback called if an error occurs
  97305. */
  97306. AbstractAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97307. throw new Error("runTask is not implemented");
  97308. };
  97309. /**
  97310. * Reset will set the task state back to INIT, so the next load call of the assets manager will execute this task again.
  97311. * This can be used with failed tasks that have the reason for failure fixed.
  97312. */
  97313. AbstractAssetTask.prototype.reset = function () {
  97314. this._taskState = AssetTaskState.INIT;
  97315. };
  97316. AbstractAssetTask.prototype.onErrorCallback = function (onError, message, exception) {
  97317. this._taskState = AssetTaskState.ERROR;
  97318. this._errorObject = {
  97319. message: message,
  97320. exception: exception
  97321. };
  97322. if (this.onError) {
  97323. this.onError(this, message, exception);
  97324. }
  97325. onError();
  97326. };
  97327. AbstractAssetTask.prototype.onDoneCallback = function (onSuccess, onError) {
  97328. try {
  97329. this._taskState = AssetTaskState.DONE;
  97330. this._isCompleted = true;
  97331. if (this.onSuccess) {
  97332. this.onSuccess(this);
  97333. }
  97334. onSuccess();
  97335. }
  97336. catch (e) {
  97337. this.onErrorCallback(onError, "Task is done, error executing success callback(s)", e);
  97338. }
  97339. };
  97340. return AbstractAssetTask;
  97341. }());
  97342. BABYLON.AbstractAssetTask = AbstractAssetTask;
  97343. /**
  97344. * Class used to share progress information about assets loading
  97345. */
  97346. var AssetsProgressEvent = /** @class */ (function () {
  97347. /**
  97348. * Creates a {BABYLON.AssetsProgressEvent}
  97349. * @param remainingCount defines the number of remaining tasks to process
  97350. * @param totalCount defines the total number of tasks
  97351. * @param task defines the task that was just processed
  97352. */
  97353. function AssetsProgressEvent(remainingCount, totalCount, task) {
  97354. this.remainingCount = remainingCount;
  97355. this.totalCount = totalCount;
  97356. this.task = task;
  97357. }
  97358. return AssetsProgressEvent;
  97359. }());
  97360. BABYLON.AssetsProgressEvent = AssetsProgressEvent;
  97361. /**
  97362. * Define a task used by {BABYLON.AssetsManager} to load meshes
  97363. */
  97364. var MeshAssetTask = /** @class */ (function (_super) {
  97365. __extends(MeshAssetTask, _super);
  97366. /**
  97367. * Creates a new {BABYLON.MeshAssetTask}
  97368. * @param name defines the name of the task
  97369. * @param meshesNames defines the list of mesh's names you want to load
  97370. * @param rootUrl defines the root url to use as a base to load your meshes and associated resources
  97371. * @param sceneFilename defines the filename of the scene to load from
  97372. */
  97373. function MeshAssetTask(
  97374. /**
  97375. * Defines the name of the task
  97376. */
  97377. name,
  97378. /**
  97379. * Defines the list of mesh's names you want to load
  97380. */
  97381. meshesNames,
  97382. /**
  97383. * Defines the root url to use as a base to load your meshes and associated resources
  97384. */
  97385. rootUrl,
  97386. /**
  97387. * Defines the filename of the scene to load from
  97388. */
  97389. sceneFilename) {
  97390. var _this = _super.call(this, name) || this;
  97391. _this.name = name;
  97392. _this.meshesNames = meshesNames;
  97393. _this.rootUrl = rootUrl;
  97394. _this.sceneFilename = sceneFilename;
  97395. return _this;
  97396. }
  97397. /**
  97398. * Execute the current task
  97399. * @param scene defines the scene where you want your assets to be loaded
  97400. * @param onSuccess is a callback called when the task is successfully executed
  97401. * @param onError is a callback called if an error occurs
  97402. */
  97403. MeshAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97404. var _this = this;
  97405. BABYLON.SceneLoader.ImportMesh(this.meshesNames, this.rootUrl, this.sceneFilename, scene, function (meshes, particleSystems, skeletons) {
  97406. _this.loadedMeshes = meshes;
  97407. _this.loadedParticleSystems = particleSystems;
  97408. _this.loadedSkeletons = skeletons;
  97409. onSuccess();
  97410. }, null, function (scene, message, exception) {
  97411. onError(message, exception);
  97412. });
  97413. };
  97414. return MeshAssetTask;
  97415. }(AbstractAssetTask));
  97416. BABYLON.MeshAssetTask = MeshAssetTask;
  97417. /**
  97418. * Define a task used by {BABYLON.AssetsManager} to load text content
  97419. */
  97420. var TextFileAssetTask = /** @class */ (function (_super) {
  97421. __extends(TextFileAssetTask, _super);
  97422. /**
  97423. * Creates a new TextFileAssetTask object
  97424. * @param name defines the name of the task
  97425. * @param url defines the location of the file to load
  97426. */
  97427. function TextFileAssetTask(
  97428. /**
  97429. * Defines the name of the task
  97430. */
  97431. name,
  97432. /**
  97433. * Defines the location of the file to load
  97434. */
  97435. url) {
  97436. var _this = _super.call(this, name) || this;
  97437. _this.name = name;
  97438. _this.url = url;
  97439. return _this;
  97440. }
  97441. /**
  97442. * Execute the current task
  97443. * @param scene defines the scene where you want your assets to be loaded
  97444. * @param onSuccess is a callback called when the task is successfully executed
  97445. * @param onError is a callback called if an error occurs
  97446. */
  97447. TextFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97448. var _this = this;
  97449. scene._loadFile(this.url, function (data) {
  97450. _this.text = data;
  97451. onSuccess();
  97452. }, undefined, false, false, function (request, exception) {
  97453. if (request) {
  97454. onError(request.status + " " + request.statusText, exception);
  97455. }
  97456. });
  97457. };
  97458. return TextFileAssetTask;
  97459. }(AbstractAssetTask));
  97460. BABYLON.TextFileAssetTask = TextFileAssetTask;
  97461. /**
  97462. * Define a task used by {BABYLON.AssetsManager} to load binary data
  97463. */
  97464. var BinaryFileAssetTask = /** @class */ (function (_super) {
  97465. __extends(BinaryFileAssetTask, _super);
  97466. /**
  97467. * Creates a new BinaryFileAssetTask object
  97468. * @param name defines the name of the new task
  97469. * @param url defines the location of the file to load
  97470. */
  97471. function BinaryFileAssetTask(
  97472. /**
  97473. * Defines the name of the task
  97474. */
  97475. name,
  97476. /**
  97477. * Defines the location of the file to load
  97478. */
  97479. url) {
  97480. var _this = _super.call(this, name) || this;
  97481. _this.name = name;
  97482. _this.url = url;
  97483. return _this;
  97484. }
  97485. /**
  97486. * Execute the current task
  97487. * @param scene defines the scene where you want your assets to be loaded
  97488. * @param onSuccess is a callback called when the task is successfully executed
  97489. * @param onError is a callback called if an error occurs
  97490. */
  97491. BinaryFileAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97492. var _this = this;
  97493. scene._loadFile(this.url, function (data) {
  97494. _this.data = data;
  97495. onSuccess();
  97496. }, undefined, true, true, function (request, exception) {
  97497. if (request) {
  97498. onError(request.status + " " + request.statusText, exception);
  97499. }
  97500. });
  97501. };
  97502. return BinaryFileAssetTask;
  97503. }(AbstractAssetTask));
  97504. BABYLON.BinaryFileAssetTask = BinaryFileAssetTask;
  97505. /**
  97506. * Define a task used by {BABYLON.AssetsManager} to load images
  97507. */
  97508. var ImageAssetTask = /** @class */ (function (_super) {
  97509. __extends(ImageAssetTask, _super);
  97510. /**
  97511. * Creates a new ImageAssetTask
  97512. * @param name defines the name of the task
  97513. * @param url defines the location of the image to load
  97514. */
  97515. function ImageAssetTask(
  97516. /**
  97517. * Defines the name of the task
  97518. */
  97519. name,
  97520. /**
  97521. * Defines the location of the image to load
  97522. */
  97523. url) {
  97524. var _this = _super.call(this, name) || this;
  97525. _this.name = name;
  97526. _this.url = url;
  97527. return _this;
  97528. }
  97529. /**
  97530. * Execute the current task
  97531. * @param scene defines the scene where you want your assets to be loaded
  97532. * @param onSuccess is a callback called when the task is successfully executed
  97533. * @param onError is a callback called if an error occurs
  97534. */
  97535. ImageAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97536. var _this = this;
  97537. var img = new Image();
  97538. BABYLON.Tools.SetCorsBehavior(this.url, img);
  97539. img.onload = function () {
  97540. _this.image = img;
  97541. onSuccess();
  97542. };
  97543. img.onerror = function (err) {
  97544. onError("Error loading image", err);
  97545. };
  97546. img.src = this.url;
  97547. };
  97548. return ImageAssetTask;
  97549. }(AbstractAssetTask));
  97550. BABYLON.ImageAssetTask = ImageAssetTask;
  97551. /**
  97552. * Define a task used by {BABYLON.AssetsManager} to load 2D textures
  97553. */
  97554. var TextureAssetTask = /** @class */ (function (_super) {
  97555. __extends(TextureAssetTask, _super);
  97556. /**
  97557. * Creates a new TextureAssetTask object
  97558. * @param name defines the name of the task
  97559. * @param url defines the location of the file to load
  97560. * @param noMipmap defines if mipmap should not be generated (default is false)
  97561. * @param invertY defines if texture must be inverted on Y axis (default is false)
  97562. * @param samplingMode defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97563. */
  97564. function TextureAssetTask(
  97565. /**
  97566. * Defines the name of the task
  97567. */
  97568. name,
  97569. /**
  97570. * Defines the location of the file to load
  97571. */
  97572. url,
  97573. /**
  97574. * Defines if mipmap should not be generated (default is false)
  97575. */
  97576. noMipmap,
  97577. /**
  97578. * Defines if texture must be inverted on Y axis (default is false)
  97579. */
  97580. invertY,
  97581. /**
  97582. * Defines the sampling mode to use (default is BABYLON.Texture.TRILINEAR_SAMPLINGMODE)
  97583. */
  97584. samplingMode) {
  97585. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97586. var _this = _super.call(this, name) || this;
  97587. _this.name = name;
  97588. _this.url = url;
  97589. _this.noMipmap = noMipmap;
  97590. _this.invertY = invertY;
  97591. _this.samplingMode = samplingMode;
  97592. return _this;
  97593. }
  97594. /**
  97595. * Execute the current task
  97596. * @param scene defines the scene where you want your assets to be loaded
  97597. * @param onSuccess is a callback called when the task is successfully executed
  97598. * @param onError is a callback called if an error occurs
  97599. */
  97600. TextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97601. var onload = function () {
  97602. onSuccess();
  97603. };
  97604. var onerror = function (message, exception) {
  97605. onError(message, exception);
  97606. };
  97607. this.texture = new BABYLON.Texture(this.url, scene, this.noMipmap, this.invertY, this.samplingMode, onload, onerror);
  97608. };
  97609. return TextureAssetTask;
  97610. }(AbstractAssetTask));
  97611. BABYLON.TextureAssetTask = TextureAssetTask;
  97612. /**
  97613. * Define a task used by {BABYLON.AssetsManager} to load cube textures
  97614. */
  97615. var CubeTextureAssetTask = /** @class */ (function (_super) {
  97616. __extends(CubeTextureAssetTask, _super);
  97617. /**
  97618. * Creates a new CubeTextureAssetTask
  97619. * @param name defines the name of the task
  97620. * @param url defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97621. * @param extensions defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97622. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97623. * @param files defines the explicit list of files (undefined by default)
  97624. */
  97625. function CubeTextureAssetTask(
  97626. /**
  97627. * Defines the name of the task
  97628. */
  97629. name,
  97630. /**
  97631. * Defines the location of the files to load (You have to specify the folder where the files are + filename with no extension)
  97632. */
  97633. url,
  97634. /**
  97635. * Defines the extensions to use to load files (["_px", "_py", "_pz", "_nx", "_ny", "_nz"] by default)
  97636. */
  97637. extensions,
  97638. /**
  97639. * Defines if mipmaps should not be generated (default is false)
  97640. */
  97641. noMipmap,
  97642. /**
  97643. * Defines the explicit list of files (undefined by default)
  97644. */
  97645. files) {
  97646. var _this = _super.call(this, name) || this;
  97647. _this.name = name;
  97648. _this.url = url;
  97649. _this.extensions = extensions;
  97650. _this.noMipmap = noMipmap;
  97651. _this.files = files;
  97652. return _this;
  97653. }
  97654. /**
  97655. * Execute the current task
  97656. * @param scene defines the scene where you want your assets to be loaded
  97657. * @param onSuccess is a callback called when the task is successfully executed
  97658. * @param onError is a callback called if an error occurs
  97659. */
  97660. CubeTextureAssetTask.prototype.runTask = function (scene, onSuccess, onError) {
  97661. var onload = function () {
  97662. onSuccess();
  97663. };
  97664. var onerror = function (message, exception) {
  97665. onError(message, exception);
  97666. };
  97667. this.texture = new BABYLON.CubeTexture(this.url, scene, this.extensions, this.noMipmap, this.files, onload, onerror);
  97668. };
  97669. return CubeTextureAssetTask;
  97670. }(AbstractAssetTask));
  97671. BABYLON.CubeTextureAssetTask = CubeTextureAssetTask;
  97672. /**
  97673. * Define a task used by {BABYLON.AssetsManager} to load HDR cube textures
  97674. */
  97675. var HDRCubeTextureAssetTask = /** @class */ (function (_super) {
  97676. __extends(HDRCubeTextureAssetTask, _super);
  97677. /**
  97678. * Creates a new HDRCubeTextureAssetTask object
  97679. * @param name defines the name of the task
  97680. * @param url defines the location of the file to load
  97681. * @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.
  97682. * @param noMipmap defines if mipmaps should not be generated (default is false)
  97683. * @param generateHarmonics specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97684. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  97685. * @param reserved Internal use only
  97686. */
  97687. function HDRCubeTextureAssetTask(
  97688. /**
  97689. * Defines the name of the task
  97690. */
  97691. name,
  97692. /**
  97693. * Defines the location of the file to load
  97694. */
  97695. url,
  97696. /**
  97697. * Defines the desired size (the more it increases the longer the generation will be)
  97698. */
  97699. size,
  97700. /**
  97701. * Defines if mipmaps should not be generated (default is false)
  97702. */
  97703. noMipmap,
  97704. /**
  97705. * Specifies whether you want to extract the polynomial harmonics during the generation process (default is true)
  97706. */
  97707. generateHarmonics,
  97708. /**
  97709. * 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)
  97710. */
  97711. gammaSpace,
  97712. /**
  97713. * Internal Use Only
  97714. */
  97715. reserved) {
  97716. if (noMipmap === void 0) { noMipmap = false; }
  97717. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97718. if (gammaSpace === void 0) { gammaSpace = false; }
  97719. if (reserved === void 0) { reserved = false; }
  97720. var _this = _super.call(this, name) || this;
  97721. _this.name = name;
  97722. _this.url = url;
  97723. _this.size = size;
  97724. _this.noMipmap = noMipmap;
  97725. _this.generateHarmonics = generateHarmonics;
  97726. _this.gammaSpace = gammaSpace;
  97727. _this.reserved = reserved;
  97728. return _this;
  97729. }
  97730. /**
  97731. * Execute the current task
  97732. * @param scene defines the scene where you want your assets to be loaded
  97733. * @param onSuccess is a callback called when the task is successfully executed
  97734. * @param onError is a callback called if an error occurs
  97735. */
  97736. HDRCubeTextureAssetTask.prototype.run = function (scene, onSuccess, onError) {
  97737. var onload = function () {
  97738. onSuccess();
  97739. };
  97740. var onerror = function (message, exception) {
  97741. onError(message, exception);
  97742. };
  97743. this.texture = new BABYLON.HDRCubeTexture(this.url, scene, this.size, this.noMipmap, this.generateHarmonics, this.gammaSpace, this.reserved, onload, onerror);
  97744. };
  97745. return HDRCubeTextureAssetTask;
  97746. }(AbstractAssetTask));
  97747. BABYLON.HDRCubeTextureAssetTask = HDRCubeTextureAssetTask;
  97748. /**
  97749. * This class can be used to easily import assets into a scene
  97750. * @see http://doc.babylonjs.com/how_to/how_to_use_assetsmanager
  97751. */
  97752. var AssetsManager = /** @class */ (function () {
  97753. /**
  97754. * Creates a new AssetsManager
  97755. * @param scene defines the scene to work on
  97756. */
  97757. function AssetsManager(scene) {
  97758. this._isLoading = false;
  97759. this._tasks = new Array();
  97760. this._waitingTasksCount = 0;
  97761. this._totalTasksCount = 0;
  97762. /**
  97763. * Observable called when all tasks are processed
  97764. */
  97765. this.onTaskSuccessObservable = new BABYLON.Observable();
  97766. /**
  97767. * Observable called when a task had an error
  97768. */
  97769. this.onTaskErrorObservable = new BABYLON.Observable();
  97770. /**
  97771. * Observable called when a task is successful
  97772. */
  97773. this.onTasksDoneObservable = new BABYLON.Observable();
  97774. /**
  97775. * Observable called when a task is done (whatever the result is)
  97776. */
  97777. this.onProgressObservable = new BABYLON.Observable();
  97778. /**
  97779. * Gets or sets a boolean defining if the {BABYLON.AssetsManager} should use the default loading screen
  97780. * @see http://doc.babylonjs.com/how_to/creating_a_custom_loading_screen
  97781. */
  97782. this.useDefaultLoadingScreen = true;
  97783. this._scene = scene;
  97784. }
  97785. /**
  97786. * Add a {BABYLON.MeshAssetTask} to the list of active tasks
  97787. * @param taskName defines the name of the new task
  97788. * @param meshesNames defines the name of meshes to load
  97789. * @param rootUrl defines the root url to use to locate files
  97790. * @param sceneFilename defines the filename of the scene file
  97791. * @returns a new {BABYLON.MeshAssetTask} object
  97792. */
  97793. AssetsManager.prototype.addMeshTask = function (taskName, meshesNames, rootUrl, sceneFilename) {
  97794. var task = new MeshAssetTask(taskName, meshesNames, rootUrl, sceneFilename);
  97795. this._tasks.push(task);
  97796. return task;
  97797. };
  97798. /**
  97799. * Add a {BABYLON.TextFileAssetTask} to the list of active tasks
  97800. * @param taskName defines the name of the new task
  97801. * @param url defines the url of the file to load
  97802. * @returns a new {BABYLON.TextFileAssetTask} object
  97803. */
  97804. AssetsManager.prototype.addTextFileTask = function (taskName, url) {
  97805. var task = new TextFileAssetTask(taskName, url);
  97806. this._tasks.push(task);
  97807. return task;
  97808. };
  97809. /**
  97810. * Add a {BABYLON.BinaryFileAssetTask} to the list of active tasks
  97811. * @param taskName defines the name of the new task
  97812. * @param url defines the url of the file to load
  97813. * @returns a new {BABYLON.BinaryFileAssetTask} object
  97814. */
  97815. AssetsManager.prototype.addBinaryFileTask = function (taskName, url) {
  97816. var task = new BinaryFileAssetTask(taskName, url);
  97817. this._tasks.push(task);
  97818. return task;
  97819. };
  97820. /**
  97821. * Add a {BABYLON.ImageAssetTask} to the list of active tasks
  97822. * @param taskName defines the name of the new task
  97823. * @param url defines the url of the file to load
  97824. * @returns a new {BABYLON.ImageAssetTask} object
  97825. */
  97826. AssetsManager.prototype.addImageTask = function (taskName, url) {
  97827. var task = new ImageAssetTask(taskName, url);
  97828. this._tasks.push(task);
  97829. return task;
  97830. };
  97831. /**
  97832. * Add a {BABYLON.TextureAssetTask} to the list of active tasks
  97833. * @param taskName defines the name of the new task
  97834. * @param url defines the url of the file to load
  97835. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97836. * @param invertY defines if you want to invert Y axis of the loaded texture (false by default)
  97837. * @param samplingMode defines the sampling mode to use (BABYLON.Texture.TRILINEAR_SAMPLINGMODE by default)
  97838. * @returns a new {BABYLON.TextureAssetTask} object
  97839. */
  97840. AssetsManager.prototype.addTextureTask = function (taskName, url, noMipmap, invertY, samplingMode) {
  97841. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  97842. var task = new TextureAssetTask(taskName, url, noMipmap, invertY, samplingMode);
  97843. this._tasks.push(task);
  97844. return task;
  97845. };
  97846. /**
  97847. * Add a {BABYLON.CubeTextureAssetTask} to the list of active tasks
  97848. * @param taskName defines the name of the new task
  97849. * @param url defines the url of the file to load
  97850. * @param extensions defines the extension to use to load the cube map (can be null)
  97851. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97852. * @param files defines the list of files to load (can be null)
  97853. * @returns a new {BABYLON.CubeTextureAssetTask} object
  97854. */
  97855. AssetsManager.prototype.addCubeTextureTask = function (taskName, url, extensions, noMipmap, files) {
  97856. var task = new CubeTextureAssetTask(taskName, url, extensions, noMipmap, files);
  97857. this._tasks.push(task);
  97858. return task;
  97859. };
  97860. /**
  97861. *
  97862. * Add a {BABYLON.HDRCubeTextureAssetTask} to the list of active tasks
  97863. * @param taskName defines the name of the new task
  97864. * @param url defines the url of the file to load
  97865. * @param size defines the size you want for the cubemap (can be null)
  97866. * @param noMipmap defines if the texture must not receive mipmaps (false by default)
  97867. * @param generateHarmonics defines if you want to automatically generate (true by default)
  97868. * @param gammaSpace specifies if the texture will be use in gamma or linear space (the PBR material requires those texture in linear space, but the standard material would require them in Gamma space) (default is false)
  97869. * @param reserved Internal use only
  97870. * @returns a new {BABYLON.HDRCubeTextureAssetTask} object
  97871. */
  97872. AssetsManager.prototype.addHDRCubeTextureTask = function (taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved) {
  97873. if (noMipmap === void 0) { noMipmap = false; }
  97874. if (generateHarmonics === void 0) { generateHarmonics = true; }
  97875. if (gammaSpace === void 0) { gammaSpace = false; }
  97876. if (reserved === void 0) { reserved = false; }
  97877. var task = new HDRCubeTextureAssetTask(taskName, url, size, noMipmap, generateHarmonics, gammaSpace, reserved);
  97878. this._tasks.push(task);
  97879. return task;
  97880. };
  97881. /**
  97882. * Remove a task from the assets manager.
  97883. * @param task the task to remove
  97884. */
  97885. AssetsManager.prototype.removeTask = function (task) {
  97886. var index = this._tasks.indexOf(task);
  97887. if (index > -1) {
  97888. this._tasks.splice(index, 1);
  97889. }
  97890. };
  97891. AssetsManager.prototype._decreaseWaitingTasksCount = function (task) {
  97892. this._waitingTasksCount--;
  97893. try {
  97894. if (this.onProgress) {
  97895. this.onProgress(this._waitingTasksCount, this._totalTasksCount, task);
  97896. }
  97897. this.onProgressObservable.notifyObservers(new AssetsProgressEvent(this._waitingTasksCount, this._totalTasksCount, task));
  97898. }
  97899. catch (e) {
  97900. BABYLON.Tools.Error("Error running progress callbacks.");
  97901. console.log(e);
  97902. }
  97903. if (this._waitingTasksCount === 0) {
  97904. try {
  97905. if (this.onFinish) {
  97906. this.onFinish(this._tasks);
  97907. }
  97908. // Let's remove successfull tasks
  97909. var currentTasks = this._tasks.slice();
  97910. for (var _i = 0, currentTasks_1 = currentTasks; _i < currentTasks_1.length; _i++) {
  97911. var task = currentTasks_1[_i];
  97912. if (task.taskState === AssetTaskState.DONE) {
  97913. var index = this._tasks.indexOf(task);
  97914. if (index > -1) {
  97915. this._tasks.splice(index, 1);
  97916. }
  97917. }
  97918. }
  97919. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97920. }
  97921. catch (e) {
  97922. BABYLON.Tools.Error("Error running tasks-done callbacks.");
  97923. console.log(e);
  97924. }
  97925. this._isLoading = false;
  97926. this._scene.getEngine().hideLoadingUI();
  97927. }
  97928. };
  97929. AssetsManager.prototype._runTask = function (task) {
  97930. var _this = this;
  97931. var done = function () {
  97932. try {
  97933. if (_this.onTaskSuccess) {
  97934. _this.onTaskSuccess(task);
  97935. }
  97936. _this.onTaskSuccessObservable.notifyObservers(task);
  97937. _this._decreaseWaitingTasksCount(task);
  97938. }
  97939. catch (e) {
  97940. error("Error executing task success callbacks", e);
  97941. }
  97942. };
  97943. var error = function (message, exception) {
  97944. task._setErrorObject(message, exception);
  97945. if (_this.onTaskError) {
  97946. _this.onTaskError(task);
  97947. }
  97948. _this.onTaskErrorObservable.notifyObservers(task);
  97949. _this._decreaseWaitingTasksCount(task);
  97950. };
  97951. task.run(this._scene, done, error);
  97952. };
  97953. /**
  97954. * Reset the {BABYLON.AssetsManager} and remove all tasks
  97955. * @return the current instance of the {BABYLON.AssetsManager}
  97956. */
  97957. AssetsManager.prototype.reset = function () {
  97958. this._isLoading = false;
  97959. this._tasks = new Array();
  97960. return this;
  97961. };
  97962. /**
  97963. * Start the loading process
  97964. * @return the current instance of the {BABYLON.AssetsManager}
  97965. */
  97966. AssetsManager.prototype.load = function () {
  97967. if (this._isLoading) {
  97968. return this;
  97969. }
  97970. this._isLoading = true;
  97971. this._waitingTasksCount = this._tasks.length;
  97972. this._totalTasksCount = this._tasks.length;
  97973. if (this._waitingTasksCount === 0) {
  97974. this._isLoading = false;
  97975. if (this.onFinish) {
  97976. this.onFinish(this._tasks);
  97977. }
  97978. this.onTasksDoneObservable.notifyObservers(this._tasks);
  97979. return this;
  97980. }
  97981. if (this.useDefaultLoadingScreen) {
  97982. this._scene.getEngine().displayLoadingUI();
  97983. }
  97984. for (var index = 0; index < this._tasks.length; index++) {
  97985. var task = this._tasks[index];
  97986. if (task.taskState === AssetTaskState.INIT) {
  97987. this._runTask(task);
  97988. }
  97989. }
  97990. return this;
  97991. };
  97992. return AssetsManager;
  97993. }());
  97994. BABYLON.AssetsManager = AssetsManager;
  97995. })(BABYLON || (BABYLON = {}));
  97996. //# sourceMappingURL=babylon.assetsManager.js.map
  97997. var BABYLON;
  97998. (function (BABYLON) {
  97999. var serializedGeometries = [];
  98000. var serializeGeometry = function (geometry, serializationGeometries) {
  98001. if (serializedGeometries[geometry.id]) {
  98002. return;
  98003. }
  98004. if (geometry.doNotSerialize) {
  98005. return;
  98006. }
  98007. if (geometry instanceof BABYLON.BoxGeometry) {
  98008. serializationGeometries.boxes.push(geometry.serialize());
  98009. }
  98010. else if (geometry instanceof BABYLON.SphereGeometry) {
  98011. serializationGeometries.spheres.push(geometry.serialize());
  98012. }
  98013. else if (geometry instanceof BABYLON.CylinderGeometry) {
  98014. serializationGeometries.cylinders.push(geometry.serialize());
  98015. }
  98016. else if (geometry instanceof BABYLON.TorusGeometry) {
  98017. serializationGeometries.toruses.push(geometry.serialize());
  98018. }
  98019. else if (geometry instanceof BABYLON.GroundGeometry) {
  98020. serializationGeometries.grounds.push(geometry.serialize());
  98021. }
  98022. else if (geometry instanceof BABYLON.Plane) {
  98023. serializationGeometries.planes.push(geometry.serialize());
  98024. }
  98025. else if (geometry instanceof BABYLON.TorusKnotGeometry) {
  98026. serializationGeometries.torusKnots.push(geometry.serialize());
  98027. }
  98028. else if (geometry instanceof BABYLON._PrimitiveGeometry) {
  98029. throw new Error("Unknown primitive type");
  98030. }
  98031. else {
  98032. serializationGeometries.vertexData.push(geometry.serializeVerticeData());
  98033. }
  98034. serializedGeometries[geometry.id] = true;
  98035. };
  98036. var serializeMesh = function (mesh, serializationScene) {
  98037. var serializationObject = {};
  98038. // Geometry
  98039. var geometry = mesh._geometry;
  98040. if (geometry) {
  98041. if (!mesh.getScene().getGeometryByID(geometry.id)) {
  98042. // 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
  98043. serializeGeometry(geometry, serializationScene.geometries);
  98044. }
  98045. }
  98046. // Custom
  98047. if (mesh.serialize) {
  98048. mesh.serialize(serializationObject);
  98049. }
  98050. return serializationObject;
  98051. };
  98052. var finalizeSingleMesh = function (mesh, serializationObject) {
  98053. //only works if the mesh is already loaded
  98054. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98055. //serialize material
  98056. if (mesh.material) {
  98057. if (mesh.material instanceof BABYLON.MultiMaterial) {
  98058. serializationObject.multiMaterials = serializationObject.multiMaterials || [];
  98059. if (!serializationObject.multiMaterials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98060. serializationObject.multiMaterials.push(mesh.material.serialize());
  98061. }
  98062. }
  98063. else {
  98064. serializationObject.materials = serializationObject.materials || [];
  98065. if (!serializationObject.materials.some(function (mat) { return (mat.id === mesh.material.id); })) {
  98066. serializationObject.materials.push(mesh.material.serialize());
  98067. }
  98068. }
  98069. }
  98070. //serialize geometry
  98071. var geometry = mesh._geometry;
  98072. if (geometry) {
  98073. if (!serializationObject.geometries) {
  98074. serializationObject.geometries = {};
  98075. serializationObject.geometries.boxes = [];
  98076. serializationObject.geometries.spheres = [];
  98077. serializationObject.geometries.cylinders = [];
  98078. serializationObject.geometries.toruses = [];
  98079. serializationObject.geometries.grounds = [];
  98080. serializationObject.geometries.planes = [];
  98081. serializationObject.geometries.torusKnots = [];
  98082. serializationObject.geometries.vertexData = [];
  98083. }
  98084. serializeGeometry(geometry, serializationObject.geometries);
  98085. }
  98086. // Skeletons
  98087. if (mesh.skeleton) {
  98088. serializationObject.skeletons = serializationObject.skeletons || [];
  98089. serializationObject.skeletons.push(mesh.skeleton.serialize());
  98090. }
  98091. //serialize the actual mesh
  98092. serializationObject.meshes = serializationObject.meshes || [];
  98093. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98094. }
  98095. };
  98096. var SceneSerializer = /** @class */ (function () {
  98097. function SceneSerializer() {
  98098. }
  98099. SceneSerializer.ClearCache = function () {
  98100. serializedGeometries = [];
  98101. };
  98102. SceneSerializer.Serialize = function (scene) {
  98103. var serializationObject = {};
  98104. SceneSerializer.ClearCache();
  98105. // Scene
  98106. serializationObject.useDelayedTextureLoading = scene.useDelayedTextureLoading;
  98107. serializationObject.autoClear = scene.autoClear;
  98108. serializationObject.clearColor = scene.clearColor.asArray();
  98109. serializationObject.ambientColor = scene.ambientColor.asArray();
  98110. serializationObject.gravity = scene.gravity.asArray();
  98111. serializationObject.collisionsEnabled = scene.collisionsEnabled;
  98112. serializationObject.workerCollisions = scene.workerCollisions;
  98113. // Fog
  98114. if (scene.fogMode && scene.fogMode !== 0) {
  98115. serializationObject.fogMode = scene.fogMode;
  98116. serializationObject.fogColor = scene.fogColor.asArray();
  98117. serializationObject.fogStart = scene.fogStart;
  98118. serializationObject.fogEnd = scene.fogEnd;
  98119. serializationObject.fogDensity = scene.fogDensity;
  98120. }
  98121. //Physics
  98122. if (scene.isPhysicsEnabled()) {
  98123. var physicEngine = scene.getPhysicsEngine();
  98124. if (physicEngine) {
  98125. serializationObject.physicsEnabled = true;
  98126. serializationObject.physicsGravity = physicEngine.gravity.asArray();
  98127. serializationObject.physicsEngine = physicEngine.getPhysicsPluginName();
  98128. }
  98129. }
  98130. // Metadata
  98131. if (scene.metadata) {
  98132. serializationObject.metadata = scene.metadata;
  98133. }
  98134. // Morph targets
  98135. serializationObject.morphTargetManagers = [];
  98136. for (var _i = 0, _a = scene.meshes; _i < _a.length; _i++) {
  98137. var abstractMesh = _a[_i];
  98138. var manager = abstractMesh.morphTargetManager;
  98139. if (manager) {
  98140. serializationObject.morphTargetManagers.push(manager.serialize());
  98141. }
  98142. }
  98143. // Lights
  98144. serializationObject.lights = [];
  98145. var index;
  98146. var light;
  98147. for (index = 0; index < scene.lights.length; index++) {
  98148. light = scene.lights[index];
  98149. if (!light.doNotSerialize) {
  98150. serializationObject.lights.push(light.serialize());
  98151. }
  98152. }
  98153. // Cameras
  98154. serializationObject.cameras = [];
  98155. for (index = 0; index < scene.cameras.length; index++) {
  98156. var camera = scene.cameras[index];
  98157. if (!camera.doNotSerialize) {
  98158. serializationObject.cameras.push(camera.serialize());
  98159. }
  98160. }
  98161. if (scene.activeCamera) {
  98162. serializationObject.activeCameraID = scene.activeCamera.id;
  98163. }
  98164. // Animations
  98165. BABYLON.Animation.AppendSerializedAnimations(scene, serializationObject);
  98166. // Materials
  98167. serializationObject.materials = [];
  98168. serializationObject.multiMaterials = [];
  98169. var material;
  98170. for (index = 0; index < scene.materials.length; index++) {
  98171. material = scene.materials[index];
  98172. if (!material.doNotSerialize) {
  98173. serializationObject.materials.push(material.serialize());
  98174. }
  98175. }
  98176. // MultiMaterials
  98177. serializationObject.multiMaterials = [];
  98178. for (index = 0; index < scene.multiMaterials.length; index++) {
  98179. var multiMaterial = scene.multiMaterials[index];
  98180. serializationObject.multiMaterials.push(multiMaterial.serialize());
  98181. }
  98182. // Environment texture
  98183. if (scene.environmentTexture) {
  98184. serializationObject.environmentTexture = scene.environmentTexture.name;
  98185. }
  98186. // Skeletons
  98187. serializationObject.skeletons = [];
  98188. for (index = 0; index < scene.skeletons.length; index++) {
  98189. var skeleton = scene.skeletons[index];
  98190. if (!skeleton.doNotSerialize) {
  98191. serializationObject.skeletons.push(skeleton.serialize());
  98192. }
  98193. }
  98194. // Transform nodes
  98195. serializationObject.transformNodes = [];
  98196. for (index = 0; index < scene.transformNodes.length; index++) {
  98197. serializationObject.transformNodes.push(scene.transformNodes[index].serialize());
  98198. }
  98199. // Geometries
  98200. serializationObject.geometries = {};
  98201. serializationObject.geometries.boxes = [];
  98202. serializationObject.geometries.spheres = [];
  98203. serializationObject.geometries.cylinders = [];
  98204. serializationObject.geometries.toruses = [];
  98205. serializationObject.geometries.grounds = [];
  98206. serializationObject.geometries.planes = [];
  98207. serializationObject.geometries.torusKnots = [];
  98208. serializationObject.geometries.vertexData = [];
  98209. serializedGeometries = [];
  98210. var geometries = scene.getGeometries();
  98211. for (index = 0; index < geometries.length; index++) {
  98212. var geometry = geometries[index];
  98213. if (geometry.isReady()) {
  98214. serializeGeometry(geometry, serializationObject.geometries);
  98215. }
  98216. }
  98217. // Meshes
  98218. serializationObject.meshes = [];
  98219. for (index = 0; index < scene.meshes.length; index++) {
  98220. var abstractMesh = scene.meshes[index];
  98221. if (abstractMesh instanceof BABYLON.Mesh) {
  98222. var mesh = abstractMesh;
  98223. if (!mesh.doNotSerialize) {
  98224. if (mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_LOADED || mesh.delayLoadState === BABYLON.Engine.DELAYLOADSTATE_NONE) {
  98225. serializationObject.meshes.push(serializeMesh(mesh, serializationObject));
  98226. }
  98227. }
  98228. }
  98229. }
  98230. // Particles Systems
  98231. serializationObject.particleSystems = [];
  98232. for (index = 0; index < scene.particleSystems.length; index++) {
  98233. serializationObject.particleSystems.push(scene.particleSystems[index].serialize());
  98234. }
  98235. // Lens flares
  98236. serializationObject.lensFlareSystems = [];
  98237. for (index = 0; index < scene.lensFlareSystems.length; index++) {
  98238. serializationObject.lensFlareSystems.push(scene.lensFlareSystems[index].serialize());
  98239. }
  98240. // Shadows
  98241. serializationObject.shadowGenerators = [];
  98242. for (index = 0; index < scene.lights.length; index++) {
  98243. light = scene.lights[index];
  98244. var shadowGenerator = light.getShadowGenerator();
  98245. if (shadowGenerator) {
  98246. serializationObject.shadowGenerators.push(shadowGenerator.serialize());
  98247. }
  98248. }
  98249. // Action Manager
  98250. if (scene.actionManager) {
  98251. serializationObject.actions = scene.actionManager.serialize("scene");
  98252. }
  98253. // Audio
  98254. serializationObject.sounds = [];
  98255. for (index = 0; index < scene.soundTracks.length; index++) {
  98256. var soundtrack = scene.soundTracks[index];
  98257. for (var soundId = 0; soundId < soundtrack.soundCollection.length; soundId++) {
  98258. serializationObject.sounds.push(soundtrack.soundCollection[soundId].serialize());
  98259. }
  98260. }
  98261. // Effect layers
  98262. serializationObject.effectLayers = [];
  98263. for (index = 0; index < scene.effectLayers.length; index++) {
  98264. var layer = scene.effectLayers[index];
  98265. if (layer.serialize) {
  98266. serializationObject.effectLayers.push(layer.serialize());
  98267. }
  98268. }
  98269. return serializationObject;
  98270. };
  98271. SceneSerializer.SerializeMesh = function (toSerialize /* Mesh || Mesh[] */, withParents, withChildren) {
  98272. if (withParents === void 0) { withParents = false; }
  98273. if (withChildren === void 0) { withChildren = false; }
  98274. var serializationObject = {};
  98275. SceneSerializer.ClearCache();
  98276. toSerialize = (toSerialize instanceof Array) ? toSerialize : [toSerialize];
  98277. if (withParents || withChildren) {
  98278. //deliberate for loop! not for each, appended should be processed as well.
  98279. for (var i = 0; i < toSerialize.length; ++i) {
  98280. if (withChildren) {
  98281. toSerialize[i].getDescendants().forEach(function (node) {
  98282. if (node instanceof BABYLON.Mesh && (toSerialize.indexOf(node) < 0)) {
  98283. toSerialize.push(node);
  98284. }
  98285. });
  98286. }
  98287. //make sure the array doesn't contain the object already
  98288. if (withParents && toSerialize[i].parent && (toSerialize.indexOf(toSerialize[i].parent) < 0)) {
  98289. toSerialize.push(toSerialize[i].parent);
  98290. }
  98291. }
  98292. }
  98293. toSerialize.forEach(function (mesh) {
  98294. finalizeSingleMesh(mesh, serializationObject);
  98295. });
  98296. return serializationObject;
  98297. };
  98298. return SceneSerializer;
  98299. }());
  98300. BABYLON.SceneSerializer = SceneSerializer;
  98301. })(BABYLON || (BABYLON = {}));
  98302. //# sourceMappingURL=babylon.sceneSerializer.js.map
  98303. var BABYLON;
  98304. (function (BABYLON) {
  98305. var ReflectionProbe = /** @class */ (function () {
  98306. function ReflectionProbe(name, size, scene, generateMipMaps) {
  98307. if (generateMipMaps === void 0) { generateMipMaps = true; }
  98308. var _this = this;
  98309. this.name = name;
  98310. this._viewMatrix = BABYLON.Matrix.Identity();
  98311. this._target = BABYLON.Vector3.Zero();
  98312. this._add = BABYLON.Vector3.Zero();
  98313. this._invertYAxis = false;
  98314. this.position = BABYLON.Vector3.Zero();
  98315. this._scene = scene;
  98316. this._scene.reflectionProbes.push(this);
  98317. this._renderTargetTexture = new BABYLON.RenderTargetTexture(name, size, scene, generateMipMaps, true, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT, true);
  98318. this._renderTargetTexture.onBeforeRenderObservable.add(function (faceIndex) {
  98319. switch (faceIndex) {
  98320. case 0:
  98321. _this._add.copyFromFloats(1, 0, 0);
  98322. break;
  98323. case 1:
  98324. _this._add.copyFromFloats(-1, 0, 0);
  98325. break;
  98326. case 2:
  98327. _this._add.copyFromFloats(0, _this._invertYAxis ? 1 : -1, 0);
  98328. break;
  98329. case 3:
  98330. _this._add.copyFromFloats(0, _this._invertYAxis ? -1 : 1, 0);
  98331. break;
  98332. case 4:
  98333. _this._add.copyFromFloats(0, 0, 1);
  98334. break;
  98335. case 5:
  98336. _this._add.copyFromFloats(0, 0, -1);
  98337. break;
  98338. }
  98339. if (_this._attachedMesh) {
  98340. _this.position.copyFrom(_this._attachedMesh.getAbsolutePosition());
  98341. }
  98342. _this.position.addToRef(_this._add, _this._target);
  98343. BABYLON.Matrix.LookAtLHToRef(_this.position, _this._target, BABYLON.Vector3.Up(), _this._viewMatrix);
  98344. scene.setTransformMatrix(_this._viewMatrix, _this._projectionMatrix);
  98345. scene._forcedViewPosition = _this.position;
  98346. });
  98347. this._renderTargetTexture.onAfterUnbindObservable.add(function () {
  98348. scene._forcedViewPosition = null;
  98349. scene.updateTransformMatrix(true);
  98350. });
  98351. if (scene.activeCamera) {
  98352. this._projectionMatrix = BABYLON.Matrix.PerspectiveFovLH(Math.PI / 2, 1, scene.activeCamera.minZ, scene.activeCamera.maxZ);
  98353. }
  98354. }
  98355. Object.defineProperty(ReflectionProbe.prototype, "samples", {
  98356. get: function () {
  98357. return this._renderTargetTexture.samples;
  98358. },
  98359. set: function (value) {
  98360. this._renderTargetTexture.samples = value;
  98361. },
  98362. enumerable: true,
  98363. configurable: true
  98364. });
  98365. Object.defineProperty(ReflectionProbe.prototype, "refreshRate", {
  98366. get: function () {
  98367. return this._renderTargetTexture.refreshRate;
  98368. },
  98369. set: function (value) {
  98370. this._renderTargetTexture.refreshRate = value;
  98371. },
  98372. enumerable: true,
  98373. configurable: true
  98374. });
  98375. ReflectionProbe.prototype.getScene = function () {
  98376. return this._scene;
  98377. };
  98378. Object.defineProperty(ReflectionProbe.prototype, "cubeTexture", {
  98379. get: function () {
  98380. return this._renderTargetTexture;
  98381. },
  98382. enumerable: true,
  98383. configurable: true
  98384. });
  98385. Object.defineProperty(ReflectionProbe.prototype, "renderList", {
  98386. get: function () {
  98387. return this._renderTargetTexture.renderList;
  98388. },
  98389. enumerable: true,
  98390. configurable: true
  98391. });
  98392. ReflectionProbe.prototype.attachToMesh = function (mesh) {
  98393. this._attachedMesh = mesh;
  98394. };
  98395. /**
  98396. * Specifies whether or not the stencil and depth buffer are cleared between two rendering groups.
  98397. *
  98398. * @param renderingGroupId The rendering group id corresponding to its index
  98399. * @param autoClearDepthStencil Automatically clears depth and stencil between groups if true.
  98400. */
  98401. ReflectionProbe.prototype.setRenderingAutoClearDepthStencil = function (renderingGroupId, autoClearDepthStencil) {
  98402. this._renderTargetTexture.setRenderingAutoClearDepthStencil(renderingGroupId, autoClearDepthStencil);
  98403. };
  98404. ReflectionProbe.prototype.dispose = function () {
  98405. var index = this._scene.reflectionProbes.indexOf(this);
  98406. if (index !== -1) {
  98407. // Remove from the scene if found
  98408. this._scene.reflectionProbes.splice(index, 1);
  98409. }
  98410. if (this._renderTargetTexture) {
  98411. this._renderTargetTexture.dispose();
  98412. this._renderTargetTexture = null;
  98413. }
  98414. };
  98415. return ReflectionProbe;
  98416. }());
  98417. BABYLON.ReflectionProbe = ReflectionProbe;
  98418. })(BABYLON || (BABYLON = {}));
  98419. //# sourceMappingURL=babylon.reflectionProbe.js.map
  98420. var BABYLON;
  98421. (function (BABYLON) {
  98422. var Layer = /** @class */ (function () {
  98423. function Layer(name, imgUrl, scene, isBackground, color) {
  98424. this.name = name;
  98425. this.scale = new BABYLON.Vector2(1, 1);
  98426. this.offset = new BABYLON.Vector2(0, 0);
  98427. this.alphaBlendingMode = BABYLON.Engine.ALPHA_COMBINE;
  98428. this.layerMask = 0x0FFFFFFF;
  98429. this._vertexBuffers = {};
  98430. // Events
  98431. /**
  98432. * An event triggered when the layer is disposed.
  98433. */
  98434. this.onDisposeObservable = new BABYLON.Observable();
  98435. /**
  98436. * An event triggered before rendering the scene
  98437. */
  98438. this.onBeforeRenderObservable = new BABYLON.Observable();
  98439. /**
  98440. * An event triggered after rendering the scene
  98441. */
  98442. this.onAfterRenderObservable = new BABYLON.Observable();
  98443. this.texture = imgUrl ? new BABYLON.Texture(imgUrl, scene, true) : null;
  98444. this.isBackground = isBackground === undefined ? true : isBackground;
  98445. this.color = color === undefined ? new BABYLON.Color4(1, 1, 1, 1) : color;
  98446. this._scene = (scene || BABYLON.Engine.LastCreatedScene);
  98447. this._scene.layers.push(this);
  98448. var engine = this._scene.getEngine();
  98449. // VBO
  98450. var vertices = [];
  98451. vertices.push(1, 1);
  98452. vertices.push(-1, 1);
  98453. vertices.push(-1, -1);
  98454. vertices.push(1, -1);
  98455. var vertexBuffer = new BABYLON.VertexBuffer(engine, vertices, BABYLON.VertexBuffer.PositionKind, false, false, 2);
  98456. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = vertexBuffer;
  98457. this._createIndexBuffer();
  98458. // Effects
  98459. this._effect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "");
  98460. this._alphaTestEffect = engine.createEffect("layer", [BABYLON.VertexBuffer.PositionKind], ["textureMatrix", "color", "scale", "offset"], ["textureSampler"], "#define ALPHATEST");
  98461. }
  98462. Object.defineProperty(Layer.prototype, "onDispose", {
  98463. set: function (callback) {
  98464. if (this._onDisposeObserver) {
  98465. this.onDisposeObservable.remove(this._onDisposeObserver);
  98466. }
  98467. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  98468. },
  98469. enumerable: true,
  98470. configurable: true
  98471. });
  98472. Object.defineProperty(Layer.prototype, "onBeforeRender", {
  98473. set: function (callback) {
  98474. if (this._onBeforeRenderObserver) {
  98475. this.onBeforeRenderObservable.remove(this._onBeforeRenderObserver);
  98476. }
  98477. this._onBeforeRenderObserver = this.onBeforeRenderObservable.add(callback);
  98478. },
  98479. enumerable: true,
  98480. configurable: true
  98481. });
  98482. Object.defineProperty(Layer.prototype, "onAfterRender", {
  98483. set: function (callback) {
  98484. if (this._onAfterRenderObserver) {
  98485. this.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  98486. }
  98487. this._onAfterRenderObserver = this.onAfterRenderObservable.add(callback);
  98488. },
  98489. enumerable: true,
  98490. configurable: true
  98491. });
  98492. Layer.prototype._createIndexBuffer = function () {
  98493. var engine = this._scene.getEngine();
  98494. // Indices
  98495. var indices = [];
  98496. indices.push(0);
  98497. indices.push(1);
  98498. indices.push(2);
  98499. indices.push(0);
  98500. indices.push(2);
  98501. indices.push(3);
  98502. this._indexBuffer = engine.createIndexBuffer(indices);
  98503. };
  98504. Layer.prototype._rebuild = function () {
  98505. var vb = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98506. if (vb) {
  98507. vb._rebuild();
  98508. }
  98509. this._createIndexBuffer();
  98510. };
  98511. Layer.prototype.render = function () {
  98512. var currentEffect = this.alphaTest ? this._alphaTestEffect : this._effect;
  98513. // Check
  98514. if (!currentEffect.isReady() || !this.texture || !this.texture.isReady())
  98515. return;
  98516. var engine = this._scene.getEngine();
  98517. this.onBeforeRenderObservable.notifyObservers(this);
  98518. // Render
  98519. engine.enableEffect(currentEffect);
  98520. engine.setState(false);
  98521. // Texture
  98522. currentEffect.setTexture("textureSampler", this.texture);
  98523. currentEffect.setMatrix("textureMatrix", this.texture.getTextureMatrix());
  98524. // Color
  98525. currentEffect.setFloat4("color", this.color.r, this.color.g, this.color.b, this.color.a);
  98526. // Scale / offset
  98527. currentEffect.setVector2("offset", this.offset);
  98528. currentEffect.setVector2("scale", this.scale);
  98529. // VBOs
  98530. engine.bindBuffers(this._vertexBuffers, this._indexBuffer, currentEffect);
  98531. // Draw order
  98532. if (!this.alphaTest) {
  98533. engine.setAlphaMode(this.alphaBlendingMode);
  98534. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98535. engine.setAlphaMode(BABYLON.Engine.ALPHA_DISABLE);
  98536. }
  98537. else {
  98538. engine.drawElementsType(BABYLON.Material.TriangleFillMode, 0, 6);
  98539. }
  98540. this.onAfterRenderObservable.notifyObservers(this);
  98541. };
  98542. Layer.prototype.dispose = function () {
  98543. var vertexBuffer = this._vertexBuffers[BABYLON.VertexBuffer.PositionKind];
  98544. if (vertexBuffer) {
  98545. vertexBuffer.dispose();
  98546. this._vertexBuffers[BABYLON.VertexBuffer.PositionKind] = null;
  98547. }
  98548. if (this._indexBuffer) {
  98549. this._scene.getEngine()._releaseBuffer(this._indexBuffer);
  98550. this._indexBuffer = null;
  98551. }
  98552. if (this.texture) {
  98553. this.texture.dispose();
  98554. this.texture = null;
  98555. }
  98556. // Remove from scene
  98557. var index = this._scene.layers.indexOf(this);
  98558. this._scene.layers.splice(index, 1);
  98559. // Callback
  98560. this.onDisposeObservable.notifyObservers(this);
  98561. this.onDisposeObservable.clear();
  98562. this.onAfterRenderObservable.clear();
  98563. this.onBeforeRenderObservable.clear();
  98564. };
  98565. return Layer;
  98566. }());
  98567. BABYLON.Layer = Layer;
  98568. })(BABYLON || (BABYLON = {}));
  98569. //# sourceMappingURL=babylon.layer.js.map
  98570. var BABYLON;
  98571. (function (BABYLON) {
  98572. var TextureTools = /** @class */ (function () {
  98573. function TextureTools() {
  98574. }
  98575. /**
  98576. * Uses the GPU to create a copy texture rescaled at a given size
  98577. * @param texture Texture to copy from
  98578. * @param width Desired width
  98579. * @param height Desired height
  98580. * @return Generated texture
  98581. */
  98582. TextureTools.CreateResizedCopy = function (texture, width, height, useBilinearMode) {
  98583. if (useBilinearMode === void 0) { useBilinearMode = true; }
  98584. var scene = texture.getScene();
  98585. var engine = scene.getEngine();
  98586. var rtt = new BABYLON.RenderTargetTexture('resized' + texture.name, { width: width, height: height }, scene, !texture.noMipmap, true, texture._texture.type, false, texture._samplingMode, false);
  98587. rtt.wrapU = texture.wrapU;
  98588. rtt.wrapV = texture.wrapV;
  98589. rtt.uOffset = texture.uOffset;
  98590. rtt.vOffset = texture.vOffset;
  98591. rtt.uScale = texture.uScale;
  98592. rtt.vScale = texture.vScale;
  98593. rtt.uAng = texture.uAng;
  98594. rtt.vAng = texture.vAng;
  98595. rtt.wAng = texture.wAng;
  98596. rtt.coordinatesIndex = texture.coordinatesIndex;
  98597. rtt.level = texture.level;
  98598. rtt.anisotropicFilteringLevel = texture.anisotropicFilteringLevel;
  98599. rtt._texture.isReady = false;
  98600. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98601. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98602. var passPostProcess = new BABYLON.PassPostProcess("pass", 1, null, useBilinearMode ? BABYLON.Texture.BILINEAR_SAMPLINGMODE : BABYLON.Texture.NEAREST_SAMPLINGMODE, engine, false, BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT);
  98603. passPostProcess.getEffect().executeWhenCompiled(function () {
  98604. passPostProcess.onApply = function (effect) {
  98605. effect.setTexture("textureSampler", texture);
  98606. };
  98607. var internalTexture = rtt.getInternalTexture();
  98608. if (internalTexture) {
  98609. scene.postProcessManager.directRender([passPostProcess], internalTexture);
  98610. engine.unBindFramebuffer(internalTexture);
  98611. rtt.disposeFramebufferObjects();
  98612. passPostProcess.dispose();
  98613. internalTexture.isReady = true;
  98614. }
  98615. });
  98616. return rtt;
  98617. };
  98618. TextureTools.GetEnvironmentBRDFTexture = function (scene) {
  98619. if (!scene._environmentBRDFTexture) {
  98620. var texture = BABYLON.Texture.CreateFromBase64String(this._environmentBRDFBase64Texture, "EnvironmentBRDFTexture", scene, true, false, BABYLON.Texture.BILINEAR_SAMPLINGMODE);
  98621. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98622. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  98623. scene._environmentBRDFTexture = texture;
  98624. }
  98625. return scene._environmentBRDFTexture;
  98626. };
  98627. TextureTools._environmentBRDFBase64Texture = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAQAAAAEACAYAAABccqhmAAAgAElEQVR4Xu19Z7PtTHbW1g3jMMbGmGDAZAMm5xxMLDAU0WSKWOQcCoqccw6eGdtgk4yNbZxnvvAL+Af8Af6AsQl+06ako9X36dXPSi3pnPu+cz/cOntL3S1pq5+w1mrpLs/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Hj/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=";
  98628. return TextureTools;
  98629. }());
  98630. BABYLON.TextureTools = TextureTools;
  98631. })(BABYLON || (BABYLON = {}));
  98632. //# sourceMappingURL=babylon.textureTools.js.map
  98633. var BABYLON;
  98634. (function (BABYLON) {
  98635. var FramingBehavior = /** @class */ (function () {
  98636. function FramingBehavior() {
  98637. this._mode = FramingBehavior.FitFrustumSidesMode;
  98638. this._radiusScale = 1.0;
  98639. this._positionScale = 0.5;
  98640. this._defaultElevation = 0.3;
  98641. this._elevationReturnTime = 1500;
  98642. this._elevationReturnWaitTime = 1000;
  98643. this._zoomStopsAnimation = false;
  98644. this._framingTime = 1500;
  98645. this._isPointerDown = false;
  98646. this._lastInteractionTime = -Infinity;
  98647. // Framing control
  98648. this._animatables = new Array();
  98649. this._betaIsAnimating = false;
  98650. }
  98651. Object.defineProperty(FramingBehavior.prototype, "name", {
  98652. get: function () {
  98653. return "Framing";
  98654. },
  98655. enumerable: true,
  98656. configurable: true
  98657. });
  98658. Object.defineProperty(FramingBehavior.prototype, "mode", {
  98659. /**
  98660. * Gets current mode used by the behavior.
  98661. */
  98662. get: function () {
  98663. return this._mode;
  98664. },
  98665. /**
  98666. * Sets the current mode used by the behavior
  98667. */
  98668. set: function (mode) {
  98669. this._mode = mode;
  98670. },
  98671. enumerable: true,
  98672. configurable: true
  98673. });
  98674. Object.defineProperty(FramingBehavior.prototype, "radiusScale", {
  98675. /**
  98676. * Gets the scale applied to the radius
  98677. */
  98678. get: function () {
  98679. return this._radiusScale;
  98680. },
  98681. /**
  98682. * Sets the scale applied to the radius (1 by default)
  98683. */
  98684. set: function (radius) {
  98685. this._radiusScale = radius;
  98686. },
  98687. enumerable: true,
  98688. configurable: true
  98689. });
  98690. Object.defineProperty(FramingBehavior.prototype, "positionScale", {
  98691. /**
  98692. * Gets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98693. */
  98694. get: function () {
  98695. return this._positionScale;
  98696. },
  98697. /**
  98698. * Sets the scale to apply on Y axis to position camera focus. 0.5 by default which means the center of the bounding box.
  98699. */
  98700. set: function (scale) {
  98701. this._positionScale = scale;
  98702. },
  98703. enumerable: true,
  98704. configurable: true
  98705. });
  98706. Object.defineProperty(FramingBehavior.prototype, "defaultElevation", {
  98707. /**
  98708. * Gets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98709. * behaviour is triggered, in radians.
  98710. */
  98711. get: function () {
  98712. return this._defaultElevation;
  98713. },
  98714. /**
  98715. * Sets the angle above/below the horizontal plane to return to when the return to default elevation idle
  98716. * behaviour is triggered, in radians.
  98717. */
  98718. set: function (elevation) {
  98719. this._defaultElevation = elevation;
  98720. },
  98721. enumerable: true,
  98722. configurable: true
  98723. });
  98724. Object.defineProperty(FramingBehavior.prototype, "elevationReturnTime", {
  98725. /**
  98726. * Gets the time (in milliseconds) taken to return to the default beta position.
  98727. * Negative value indicates camera should not return to default.
  98728. */
  98729. get: function () {
  98730. return this._elevationReturnTime;
  98731. },
  98732. /**
  98733. * Sets the time (in milliseconds) taken to return to the default beta position.
  98734. * Negative value indicates camera should not return to default.
  98735. */
  98736. set: function (speed) {
  98737. this._elevationReturnTime = speed;
  98738. },
  98739. enumerable: true,
  98740. configurable: true
  98741. });
  98742. Object.defineProperty(FramingBehavior.prototype, "elevationReturnWaitTime", {
  98743. /**
  98744. * Gets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98745. */
  98746. get: function () {
  98747. return this._elevationReturnWaitTime;
  98748. },
  98749. /**
  98750. * Sets the delay (in milliseconds) taken before the camera returns to the default beta position.
  98751. */
  98752. set: function (time) {
  98753. this._elevationReturnWaitTime = time;
  98754. },
  98755. enumerable: true,
  98756. configurable: true
  98757. });
  98758. Object.defineProperty(FramingBehavior.prototype, "zoomStopsAnimation", {
  98759. /**
  98760. * Gets the flag that indicates if user zooming should stop animation.
  98761. */
  98762. get: function () {
  98763. return this._zoomStopsAnimation;
  98764. },
  98765. /**
  98766. * Sets the flag that indicates if user zooming should stop animation.
  98767. */
  98768. set: function (flag) {
  98769. this._zoomStopsAnimation = flag;
  98770. },
  98771. enumerable: true,
  98772. configurable: true
  98773. });
  98774. Object.defineProperty(FramingBehavior.prototype, "framingTime", {
  98775. /**
  98776. * Gets the transition time when framing the mesh, in milliseconds
  98777. */
  98778. get: function () {
  98779. return this._framingTime;
  98780. },
  98781. /**
  98782. * Sets the transition time when framing the mesh, in milliseconds
  98783. */
  98784. set: function (time) {
  98785. this._framingTime = time;
  98786. },
  98787. enumerable: true,
  98788. configurable: true
  98789. });
  98790. FramingBehavior.prototype.init = function () {
  98791. // Do notihng
  98792. };
  98793. FramingBehavior.prototype.attach = function (camera) {
  98794. var _this = this;
  98795. this._attachedCamera = camera;
  98796. var scene = this._attachedCamera.getScene();
  98797. FramingBehavior.EasingFunction.setEasingMode(FramingBehavior.EasingMode);
  98798. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  98799. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  98800. _this._isPointerDown = true;
  98801. return;
  98802. }
  98803. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  98804. _this._isPointerDown = false;
  98805. }
  98806. });
  98807. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  98808. if (mesh) {
  98809. _this.zoomOnMesh(mesh);
  98810. }
  98811. });
  98812. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  98813. // Stop the animation if there is user interaction and the animation should stop for this interaction
  98814. _this._applyUserInteraction();
  98815. // Maintain the camera above the ground. If the user pulls the camera beneath the ground plane, lift it
  98816. // back to the default position after a given timeout
  98817. _this._maintainCameraAboveGround();
  98818. });
  98819. };
  98820. FramingBehavior.prototype.detach = function () {
  98821. if (!this._attachedCamera) {
  98822. return;
  98823. }
  98824. var scene = this._attachedCamera.getScene();
  98825. if (this._onPrePointerObservableObserver) {
  98826. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  98827. }
  98828. if (this._onAfterCheckInputsObserver) {
  98829. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  98830. }
  98831. if (this._onMeshTargetChangedObserver) {
  98832. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  98833. }
  98834. this._attachedCamera = null;
  98835. };
  98836. /**
  98837. * Targets the given mesh and updates zoom level accordingly.
  98838. * @param mesh The mesh to target.
  98839. * @param radius Optional. If a cached radius position already exists, overrides default.
  98840. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98841. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98842. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98843. */
  98844. FramingBehavior.prototype.zoomOnMesh = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98845. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98846. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98847. mesh.computeWorldMatrix(true);
  98848. var boundingBox = mesh.getBoundingInfo().boundingBox;
  98849. this.zoomOnBoundingInfo(boundingBox.minimumWorld, boundingBox.maximumWorld, focusOnOriginXZ, onAnimationEnd);
  98850. };
  98851. /**
  98852. * Targets the given mesh with its children and updates zoom level accordingly.
  98853. * @param mesh The mesh to target.
  98854. * @param radius Optional. If a cached radius position already exists, overrides default.
  98855. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98856. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98857. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98858. */
  98859. FramingBehavior.prototype.zoomOnMeshHierarchy = function (mesh, focusOnOriginXZ, onAnimationEnd) {
  98860. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98861. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98862. mesh.computeWorldMatrix(true);
  98863. var boundingBox = mesh.getHierarchyBoundingVectors(true);
  98864. this.zoomOnBoundingInfo(boundingBox.min, boundingBox.max, focusOnOriginXZ, onAnimationEnd);
  98865. };
  98866. /**
  98867. * Targets the given meshes with their children and updates zoom level accordingly.
  98868. * @param meshes The mesh to target.
  98869. * @param radius Optional. If a cached radius position already exists, overrides default.
  98870. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98871. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98872. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98873. */
  98874. FramingBehavior.prototype.zoomOnMeshesHierarchy = function (meshes, focusOnOriginXZ, onAnimationEnd) {
  98875. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98876. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98877. var min = new BABYLON.Vector3(Number.MAX_VALUE, Number.MAX_VALUE, Number.MAX_VALUE);
  98878. var max = new BABYLON.Vector3(-Number.MAX_VALUE, -Number.MAX_VALUE, -Number.MAX_VALUE);
  98879. for (var i = 0; i < meshes.length; i++) {
  98880. var boundingInfo = meshes[i].getHierarchyBoundingVectors(true);
  98881. BABYLON.Tools.CheckExtends(boundingInfo.min, min, max);
  98882. BABYLON.Tools.CheckExtends(boundingInfo.max, min, max);
  98883. }
  98884. this.zoomOnBoundingInfo(min, max, focusOnOriginXZ, onAnimationEnd);
  98885. };
  98886. /**
  98887. * Targets the given mesh and updates zoom level accordingly.
  98888. * @param mesh The mesh to target.
  98889. * @param radius Optional. If a cached radius position already exists, overrides default.
  98890. * @param framingPositionY Position on mesh to center camera focus where 0 corresponds bottom of its bounding box and 1, the top
  98891. * @param focusOnOriginXZ Determines if the camera should focus on 0 in the X and Z axis instead of the mesh
  98892. * @param onAnimationEnd Callback triggered at the end of the framing animation
  98893. */
  98894. FramingBehavior.prototype.zoomOnBoundingInfo = function (minimumWorld, maximumWorld, focusOnOriginXZ, onAnimationEnd) {
  98895. var _this = this;
  98896. if (focusOnOriginXZ === void 0) { focusOnOriginXZ = false; }
  98897. if (onAnimationEnd === void 0) { onAnimationEnd = null; }
  98898. var zoomTarget;
  98899. if (!this._attachedCamera) {
  98900. return;
  98901. }
  98902. // Find target by interpolating from bottom of bounding box in world-space to top via framingPositionY
  98903. var bottom = minimumWorld.y;
  98904. var top = maximumWorld.y;
  98905. var zoomTargetY = bottom + (top - bottom) * this._positionScale;
  98906. var radiusWorld = maximumWorld.subtract(minimumWorld).scale(0.5);
  98907. if (focusOnOriginXZ) {
  98908. zoomTarget = new BABYLON.Vector3(0, zoomTargetY, 0);
  98909. }
  98910. else {
  98911. var centerWorld = minimumWorld.add(radiusWorld);
  98912. zoomTarget = new BABYLON.Vector3(centerWorld.x, zoomTargetY, centerWorld.z);
  98913. }
  98914. if (!this._vectorTransition) {
  98915. this._vectorTransition = BABYLON.Animation.CreateAnimation("target", BABYLON.Animation.ANIMATIONTYPE_VECTOR3, 60, FramingBehavior.EasingFunction);
  98916. }
  98917. this._betaIsAnimating = true;
  98918. var animatable = BABYLON.Animation.TransitionTo("target", zoomTarget, this._attachedCamera, this._attachedCamera.getScene(), 60, this._vectorTransition, this._framingTime);
  98919. if (animatable) {
  98920. this._animatables.push(animatable);
  98921. }
  98922. // sets the radius and lower radius bounds
  98923. // Small delta ensures camera is not always at lower zoom limit.
  98924. var radius = 0;
  98925. if (this._mode === FramingBehavior.FitFrustumSidesMode) {
  98926. var position = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98927. this._attachedCamera.lowerRadiusLimit = radiusWorld.length() + this._attachedCamera.minZ;
  98928. radius = position;
  98929. }
  98930. else if (this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98931. radius = this._calculateLowerRadiusFromModelBoundingSphere(minimumWorld, maximumWorld);
  98932. if (this._attachedCamera.lowerRadiusLimit === null) {
  98933. this._attachedCamera.lowerRadiusLimit = this._attachedCamera.minZ;
  98934. }
  98935. }
  98936. // Set sensibilities
  98937. var extend = maximumWorld.subtract(minimumWorld).length();
  98938. this._attachedCamera.panningSensibility = 5000 / extend;
  98939. this._attachedCamera.wheelPrecision = 100 / radius;
  98940. // transition to new radius
  98941. if (!this._radiusTransition) {
  98942. this._radiusTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  98943. }
  98944. animatable = BABYLON.Animation.TransitionTo("radius", radius, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusTransition, this._framingTime, function () {
  98945. _this.stopAllAnimations();
  98946. if (onAnimationEnd) {
  98947. onAnimationEnd();
  98948. }
  98949. if (_this._attachedCamera) {
  98950. _this._attachedCamera.storeState();
  98951. }
  98952. });
  98953. if (animatable) {
  98954. this._animatables.push(animatable);
  98955. }
  98956. };
  98957. /**
  98958. * Calculates the lowest radius for the camera based on the bounding box of the mesh.
  98959. * @param mesh The mesh on which to base the calculation. mesh boundingInfo used to estimate necessary
  98960. * frustum width.
  98961. * @return The minimum distance from the primary mesh's center point at which the camera must be kept in order
  98962. * to fully enclose the mesh in the viewing frustum.
  98963. */
  98964. FramingBehavior.prototype._calculateLowerRadiusFromModelBoundingSphere = function (minimumWorld, maximumWorld) {
  98965. var size = maximumWorld.subtract(minimumWorld);
  98966. var boxVectorGlobalDiagonal = size.length();
  98967. var frustumSlope = this._getFrustumSlope();
  98968. // Formula for setting distance
  98969. // (Good explanation: http://stackoverflow.com/questions/2866350/move-camera-to-fit-3d-scene)
  98970. var radiusWithoutFraming = boxVectorGlobalDiagonal * 0.5;
  98971. // Horizon distance
  98972. var radius = radiusWithoutFraming * this._radiusScale;
  98973. var distanceForHorizontalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.x * frustumSlope.x));
  98974. var distanceForVerticalFrustum = radius * Math.sqrt(1.0 + 1.0 / (frustumSlope.y * frustumSlope.y));
  98975. var distance = Math.max(distanceForHorizontalFrustum, distanceForVerticalFrustum);
  98976. var camera = this._attachedCamera;
  98977. if (!camera) {
  98978. return 0;
  98979. }
  98980. if (camera.lowerRadiusLimit && this._mode === FramingBehavior.IgnoreBoundsSizeMode) {
  98981. // Don't exceed the requested limit
  98982. distance = distance < camera.lowerRadiusLimit ? camera.lowerRadiusLimit : distance;
  98983. }
  98984. // Don't exceed the upper radius limit
  98985. if (camera.upperRadiusLimit) {
  98986. distance = distance > camera.upperRadiusLimit ? camera.upperRadiusLimit : distance;
  98987. }
  98988. return distance;
  98989. };
  98990. /**
  98991. * Keeps the camera above the ground plane. If the user pulls the camera below the ground plane, the camera
  98992. * is automatically returned to its default position (expected to be above ground plane).
  98993. */
  98994. FramingBehavior.prototype._maintainCameraAboveGround = function () {
  98995. var _this = this;
  98996. if (this._elevationReturnTime < 0) {
  98997. return;
  98998. }
  98999. var timeSinceInteraction = BABYLON.Tools.Now - this._lastInteractionTime;
  99000. var defaultBeta = Math.PI * 0.5 - this._defaultElevation;
  99001. var limitBeta = Math.PI * 0.5;
  99002. // Bring the camera back up if below the ground plane
  99003. if (this._attachedCamera && !this._betaIsAnimating && this._attachedCamera.beta > limitBeta && timeSinceInteraction >= this._elevationReturnWaitTime) {
  99004. this._betaIsAnimating = true;
  99005. //Transition to new position
  99006. this.stopAllAnimations();
  99007. if (!this._betaTransition) {
  99008. this._betaTransition = BABYLON.Animation.CreateAnimation("beta", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, FramingBehavior.EasingFunction);
  99009. }
  99010. var animatabe = BABYLON.Animation.TransitionTo("beta", defaultBeta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._betaTransition, this._elevationReturnTime, function () {
  99011. _this._clearAnimationLocks();
  99012. _this.stopAllAnimations();
  99013. });
  99014. if (animatabe) {
  99015. this._animatables.push(animatabe);
  99016. }
  99017. }
  99018. };
  99019. /**
  99020. * Returns the frustum slope based on the canvas ratio and camera FOV
  99021. * @returns The frustum slope represented as a Vector2 with X and Y slopes
  99022. */
  99023. FramingBehavior.prototype._getFrustumSlope = function () {
  99024. // Calculate the viewport ratio
  99025. // Aspect Ratio is Height/Width.
  99026. var camera = this._attachedCamera;
  99027. if (!camera) {
  99028. return BABYLON.Vector2.Zero();
  99029. }
  99030. var engine = camera.getScene().getEngine();
  99031. var aspectRatio = engine.getAspectRatio(camera);
  99032. // Camera FOV is the vertical field of view (top-bottom) in radians.
  99033. // Slope of the frustum top/bottom planes in view space, relative to the forward vector.
  99034. var frustumSlopeY = Math.tan(camera.fov / 2);
  99035. // Slope of the frustum left/right planes in view space, relative to the forward vector.
  99036. // Provides the amount that one side (e.g. left) of the frustum gets wider for every unit
  99037. // along the forward vector.
  99038. var frustumSlopeX = frustumSlopeY * aspectRatio;
  99039. return new BABYLON.Vector2(frustumSlopeX, frustumSlopeY);
  99040. };
  99041. /**
  99042. * Removes all animation locks. Allows new animations to be added to any of the arcCamera properties.
  99043. */
  99044. FramingBehavior.prototype._clearAnimationLocks = function () {
  99045. this._betaIsAnimating = false;
  99046. };
  99047. /**
  99048. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99049. */
  99050. FramingBehavior.prototype._applyUserInteraction = function () {
  99051. if (this.isUserIsMoving) {
  99052. this._lastInteractionTime = BABYLON.Tools.Now;
  99053. this.stopAllAnimations();
  99054. this._clearAnimationLocks();
  99055. }
  99056. };
  99057. /**
  99058. * Stops and removes all animations that have been applied to the camera
  99059. */
  99060. FramingBehavior.prototype.stopAllAnimations = function () {
  99061. if (this._attachedCamera) {
  99062. this._attachedCamera.animations = [];
  99063. }
  99064. while (this._animatables.length) {
  99065. if (this._animatables[0]) {
  99066. this._animatables[0].onAnimationEnd = null;
  99067. this._animatables[0].stop();
  99068. }
  99069. this._animatables.shift();
  99070. }
  99071. };
  99072. Object.defineProperty(FramingBehavior.prototype, "isUserIsMoving", {
  99073. /**
  99074. * Gets a value indicating if the user is moving the camera
  99075. */
  99076. get: function () {
  99077. if (!this._attachedCamera) {
  99078. return false;
  99079. }
  99080. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99081. this._attachedCamera.inertialBetaOffset !== 0 ||
  99082. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99083. this._attachedCamera.inertialPanningX !== 0 ||
  99084. this._attachedCamera.inertialPanningY !== 0 ||
  99085. this._isPointerDown;
  99086. },
  99087. enumerable: true,
  99088. configurable: true
  99089. });
  99090. /**
  99091. * The easing function used by animations
  99092. */
  99093. FramingBehavior.EasingFunction = new BABYLON.ExponentialEase();
  99094. /**
  99095. * The easing mode used by animations
  99096. */
  99097. FramingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT;
  99098. // Statics
  99099. /**
  99100. * The camera can move all the way towards the mesh.
  99101. */
  99102. FramingBehavior.IgnoreBoundsSizeMode = 0;
  99103. /**
  99104. * The camera is not allowed to zoom closer to the mesh than the point at which the adjusted bounding sphere touches the frustum sides
  99105. */
  99106. FramingBehavior.FitFrustumSidesMode = 1;
  99107. return FramingBehavior;
  99108. }());
  99109. BABYLON.FramingBehavior = FramingBehavior;
  99110. })(BABYLON || (BABYLON = {}));
  99111. //# sourceMappingURL=babylon.framingBehavior.js.map
  99112. var BABYLON;
  99113. (function (BABYLON) {
  99114. /**
  99115. * Add a bouncing effect to an ArcRotateCamera when reaching a specified minimum and maximum radius
  99116. */
  99117. var BouncingBehavior = /** @class */ (function () {
  99118. function BouncingBehavior() {
  99119. /**
  99120. * The duration of the animation, in milliseconds
  99121. */
  99122. this.transitionDuration = 450;
  99123. /**
  99124. * Length of the distance animated by the transition when lower radius is reached
  99125. */
  99126. this.lowerRadiusTransitionRange = 2;
  99127. /**
  99128. * Length of the distance animated by the transition when upper radius is reached
  99129. */
  99130. this.upperRadiusTransitionRange = -2;
  99131. this._autoTransitionRange = false;
  99132. // Animations
  99133. this._radiusIsAnimating = false;
  99134. this._radiusBounceTransition = null;
  99135. this._animatables = new Array();
  99136. }
  99137. Object.defineProperty(BouncingBehavior.prototype, "name", {
  99138. get: function () {
  99139. return "Bouncing";
  99140. },
  99141. enumerable: true,
  99142. configurable: true
  99143. });
  99144. Object.defineProperty(BouncingBehavior.prototype, "autoTransitionRange", {
  99145. /**
  99146. * Gets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99147. */
  99148. get: function () {
  99149. return this._autoTransitionRange;
  99150. },
  99151. /**
  99152. * Sets a value indicating if the lowerRadiusTransitionRange and upperRadiusTransitionRange are defined automatically
  99153. * Transition ranges will be set to 5% of the bounding box diagonal in world space
  99154. */
  99155. set: function (value) {
  99156. var _this = this;
  99157. if (this._autoTransitionRange === value) {
  99158. return;
  99159. }
  99160. this._autoTransitionRange = value;
  99161. var camera = this._attachedCamera;
  99162. if (!camera) {
  99163. return;
  99164. }
  99165. if (value) {
  99166. this._onMeshTargetChangedObserver = camera.onMeshTargetChangedObservable.add(function (mesh) {
  99167. if (!mesh) {
  99168. return;
  99169. }
  99170. mesh.computeWorldMatrix(true);
  99171. var diagonal = mesh.getBoundingInfo().diagonalLength;
  99172. _this.lowerRadiusTransitionRange = diagonal * 0.05;
  99173. _this.upperRadiusTransitionRange = diagonal * 0.05;
  99174. });
  99175. }
  99176. else if (this._onMeshTargetChangedObserver) {
  99177. camera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99178. }
  99179. },
  99180. enumerable: true,
  99181. configurable: true
  99182. });
  99183. BouncingBehavior.prototype.init = function () {
  99184. // Do notihng
  99185. };
  99186. BouncingBehavior.prototype.attach = function (camera) {
  99187. var _this = this;
  99188. this._attachedCamera = camera;
  99189. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99190. if (!_this._attachedCamera) {
  99191. return;
  99192. }
  99193. // Add the bounce animation to the lower radius limit
  99194. if (_this._isRadiusAtLimit(_this._attachedCamera.lowerRadiusLimit)) {
  99195. _this._applyBoundRadiusAnimation(_this.lowerRadiusTransitionRange);
  99196. }
  99197. // Add the bounce animation to the upper radius limit
  99198. if (_this._isRadiusAtLimit(_this._attachedCamera.upperRadiusLimit)) {
  99199. _this._applyBoundRadiusAnimation(_this.upperRadiusTransitionRange);
  99200. }
  99201. });
  99202. };
  99203. BouncingBehavior.prototype.detach = function () {
  99204. if (!this._attachedCamera) {
  99205. return;
  99206. }
  99207. if (this._onAfterCheckInputsObserver) {
  99208. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99209. }
  99210. if (this._onMeshTargetChangedObserver) {
  99211. this._attachedCamera.onMeshTargetChangedObservable.remove(this._onMeshTargetChangedObserver);
  99212. }
  99213. this._attachedCamera = null;
  99214. };
  99215. /**
  99216. * Checks if the camera radius is at the specified limit. Takes into account animation locks.
  99217. * @param radiusLimit The limit to check against.
  99218. * @return Bool to indicate if at limit.
  99219. */
  99220. BouncingBehavior.prototype._isRadiusAtLimit = function (radiusLimit) {
  99221. if (!this._attachedCamera) {
  99222. return false;
  99223. }
  99224. if (this._attachedCamera.radius === radiusLimit && !this._radiusIsAnimating) {
  99225. return true;
  99226. }
  99227. return false;
  99228. };
  99229. /**
  99230. * Applies an animation to the radius of the camera, extending by the radiusDelta.
  99231. * @param radiusDelta The delta by which to animate to. Can be negative.
  99232. */
  99233. BouncingBehavior.prototype._applyBoundRadiusAnimation = function (radiusDelta) {
  99234. var _this = this;
  99235. if (!this._attachedCamera) {
  99236. return;
  99237. }
  99238. if (!this._radiusBounceTransition) {
  99239. BouncingBehavior.EasingFunction.setEasingMode(BouncingBehavior.EasingMode);
  99240. this._radiusBounceTransition = BABYLON.Animation.CreateAnimation("radius", BABYLON.Animation.ANIMATIONTYPE_FLOAT, 60, BouncingBehavior.EasingFunction);
  99241. }
  99242. // Prevent zoom until bounce has completed
  99243. this._cachedWheelPrecision = this._attachedCamera.wheelPrecision;
  99244. this._attachedCamera.wheelPrecision = Infinity;
  99245. this._attachedCamera.inertialRadiusOffset = 0;
  99246. // Animate to the radius limit
  99247. this.stopAllAnimations();
  99248. this._radiusIsAnimating = true;
  99249. var animatable = BABYLON.Animation.TransitionTo("radius", this._attachedCamera.radius + radiusDelta, this._attachedCamera, this._attachedCamera.getScene(), 60, this._radiusBounceTransition, this.transitionDuration, function () { return _this._clearAnimationLocks(); });
  99250. if (animatable) {
  99251. this._animatables.push(animatable);
  99252. }
  99253. };
  99254. /**
  99255. * Removes all animation locks. Allows new animations to be added to any of the camera properties.
  99256. */
  99257. BouncingBehavior.prototype._clearAnimationLocks = function () {
  99258. this._radiusIsAnimating = false;
  99259. if (this._attachedCamera) {
  99260. this._attachedCamera.wheelPrecision = this._cachedWheelPrecision;
  99261. }
  99262. };
  99263. /**
  99264. * Stops and removes all animations that have been applied to the camera
  99265. */
  99266. BouncingBehavior.prototype.stopAllAnimations = function () {
  99267. if (this._attachedCamera) {
  99268. this._attachedCamera.animations = [];
  99269. }
  99270. while (this._animatables.length) {
  99271. this._animatables[0].onAnimationEnd = null;
  99272. this._animatables[0].stop();
  99273. this._animatables.shift();
  99274. }
  99275. };
  99276. /**
  99277. * The easing function used by animations
  99278. */
  99279. BouncingBehavior.EasingFunction = new BABYLON.BackEase(0.3);
  99280. /**
  99281. * The easing mode used by animations
  99282. */
  99283. BouncingBehavior.EasingMode = BABYLON.EasingFunction.EASINGMODE_EASEOUT;
  99284. return BouncingBehavior;
  99285. }());
  99286. BABYLON.BouncingBehavior = BouncingBehavior;
  99287. })(BABYLON || (BABYLON = {}));
  99288. //# sourceMappingURL=babylon.bouncingBehavior.js.map
  99289. var BABYLON;
  99290. (function (BABYLON) {
  99291. var AutoRotationBehavior = /** @class */ (function () {
  99292. function AutoRotationBehavior() {
  99293. this._zoomStopsAnimation = false;
  99294. this._idleRotationSpeed = 0.05;
  99295. this._idleRotationWaitTime = 2000;
  99296. this._idleRotationSpinupTime = 2000;
  99297. this._isPointerDown = false;
  99298. this._lastFrameTime = null;
  99299. this._lastInteractionTime = -Infinity;
  99300. this._cameraRotationSpeed = 0;
  99301. this._lastFrameRadius = 0;
  99302. }
  99303. Object.defineProperty(AutoRotationBehavior.prototype, "name", {
  99304. get: function () {
  99305. return "AutoRotation";
  99306. },
  99307. enumerable: true,
  99308. configurable: true
  99309. });
  99310. Object.defineProperty(AutoRotationBehavior.prototype, "zoomStopsAnimation", {
  99311. /**
  99312. * Gets the flag that indicates if user zooming should stop animation.
  99313. */
  99314. get: function () {
  99315. return this._zoomStopsAnimation;
  99316. },
  99317. /**
  99318. * Sets the flag that indicates if user zooming should stop animation.
  99319. */
  99320. set: function (flag) {
  99321. this._zoomStopsAnimation = flag;
  99322. },
  99323. enumerable: true,
  99324. configurable: true
  99325. });
  99326. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpeed", {
  99327. /**
  99328. * Gets the default speed at which the camera rotates around the model.
  99329. */
  99330. get: function () {
  99331. return this._idleRotationSpeed;
  99332. },
  99333. /**
  99334. * Sets the default speed at which the camera rotates around the model.
  99335. */
  99336. set: function (speed) {
  99337. this._idleRotationSpeed = speed;
  99338. },
  99339. enumerable: true,
  99340. configurable: true
  99341. });
  99342. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationWaitTime", {
  99343. /**
  99344. * Gets the time (milliseconds) to wait after user interaction before the camera starts rotating.
  99345. */
  99346. get: function () {
  99347. return this._idleRotationWaitTime;
  99348. },
  99349. /**
  99350. * Sets the time (in milliseconds) to wait after user interaction before the camera starts rotating.
  99351. */
  99352. set: function (time) {
  99353. this._idleRotationWaitTime = time;
  99354. },
  99355. enumerable: true,
  99356. configurable: true
  99357. });
  99358. Object.defineProperty(AutoRotationBehavior.prototype, "idleRotationSpinupTime", {
  99359. /**
  99360. * Gets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99361. */
  99362. get: function () {
  99363. return this._idleRotationSpinupTime;
  99364. },
  99365. /**
  99366. * Sets the time (milliseconds) to take to spin up to the full idle rotation speed.
  99367. */
  99368. set: function (time) {
  99369. this._idleRotationSpinupTime = time;
  99370. },
  99371. enumerable: true,
  99372. configurable: true
  99373. });
  99374. Object.defineProperty(AutoRotationBehavior.prototype, "rotationInProgress", {
  99375. /**
  99376. * Gets a value indicating if the camera is currently rotating because of this behavior
  99377. */
  99378. get: function () {
  99379. return Math.abs(this._cameraRotationSpeed) > 0;
  99380. },
  99381. enumerable: true,
  99382. configurable: true
  99383. });
  99384. AutoRotationBehavior.prototype.init = function () {
  99385. // Do notihng
  99386. };
  99387. AutoRotationBehavior.prototype.attach = function (camera) {
  99388. var _this = this;
  99389. this._attachedCamera = camera;
  99390. var scene = this._attachedCamera.getScene();
  99391. this._onPrePointerObservableObserver = scene.onPrePointerObservable.add(function (pointerInfoPre) {
  99392. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERDOWN) {
  99393. _this._isPointerDown = true;
  99394. return;
  99395. }
  99396. if (pointerInfoPre.type === BABYLON.PointerEventTypes.POINTERUP) {
  99397. _this._isPointerDown = false;
  99398. }
  99399. });
  99400. this._onAfterCheckInputsObserver = camera.onAfterCheckInputsObservable.add(function () {
  99401. var now = BABYLON.Tools.Now;
  99402. var dt = 0;
  99403. if (_this._lastFrameTime != null) {
  99404. dt = now - _this._lastFrameTime;
  99405. }
  99406. _this._lastFrameTime = now;
  99407. // Stop the animation if there is user interaction and the animation should stop for this interaction
  99408. _this._applyUserInteraction();
  99409. var timeToRotation = now - _this._lastInteractionTime - _this._idleRotationWaitTime;
  99410. var scale = Math.max(Math.min(timeToRotation / (_this._idleRotationSpinupTime), 1), 0);
  99411. _this._cameraRotationSpeed = _this._idleRotationSpeed * scale;
  99412. // Step camera rotation by rotation speed
  99413. if (_this._attachedCamera) {
  99414. _this._attachedCamera.alpha -= _this._cameraRotationSpeed * (dt / 1000);
  99415. }
  99416. });
  99417. };
  99418. AutoRotationBehavior.prototype.detach = function () {
  99419. if (!this._attachedCamera) {
  99420. return;
  99421. }
  99422. var scene = this._attachedCamera.getScene();
  99423. if (this._onPrePointerObservableObserver) {
  99424. scene.onPrePointerObservable.remove(this._onPrePointerObservableObserver);
  99425. }
  99426. this._attachedCamera.onAfterCheckInputsObservable.remove(this._onAfterCheckInputsObserver);
  99427. this._attachedCamera = null;
  99428. };
  99429. /**
  99430. * Returns true if user is scrolling.
  99431. * @return true if user is scrolling.
  99432. */
  99433. AutoRotationBehavior.prototype._userIsZooming = function () {
  99434. if (!this._attachedCamera) {
  99435. return false;
  99436. }
  99437. return this._attachedCamera.inertialRadiusOffset !== 0;
  99438. };
  99439. AutoRotationBehavior.prototype._shouldAnimationStopForInteraction = function () {
  99440. if (!this._attachedCamera) {
  99441. return false;
  99442. }
  99443. var zoomHasHitLimit = false;
  99444. if (this._lastFrameRadius === this._attachedCamera.radius && this._attachedCamera.inertialRadiusOffset !== 0) {
  99445. zoomHasHitLimit = true;
  99446. }
  99447. // Update the record of previous radius - works as an approx. indicator of hitting radius limits
  99448. this._lastFrameRadius = this._attachedCamera.radius;
  99449. return this._zoomStopsAnimation ? zoomHasHitLimit : this._userIsZooming();
  99450. };
  99451. /**
  99452. * Applies any current user interaction to the camera. Takes into account maximum alpha rotation.
  99453. */
  99454. AutoRotationBehavior.prototype._applyUserInteraction = function () {
  99455. if (this._userIsMoving() && !this._shouldAnimationStopForInteraction()) {
  99456. this._lastInteractionTime = BABYLON.Tools.Now;
  99457. }
  99458. };
  99459. // Tools
  99460. AutoRotationBehavior.prototype._userIsMoving = function () {
  99461. if (!this._attachedCamera) {
  99462. return false;
  99463. }
  99464. return this._attachedCamera.inertialAlphaOffset !== 0 ||
  99465. this._attachedCamera.inertialBetaOffset !== 0 ||
  99466. this._attachedCamera.inertialRadiusOffset !== 0 ||
  99467. this._attachedCamera.inertialPanningX !== 0 ||
  99468. this._attachedCamera.inertialPanningY !== 0 ||
  99469. this._isPointerDown;
  99470. };
  99471. return AutoRotationBehavior;
  99472. }());
  99473. BABYLON.AutoRotationBehavior = AutoRotationBehavior;
  99474. })(BABYLON || (BABYLON = {}));
  99475. //# sourceMappingURL=babylon.autoRotationBehavior.js.map
  99476. var BABYLON;
  99477. (function (BABYLON) {
  99478. var NullEngineOptions = /** @class */ (function () {
  99479. function NullEngineOptions() {
  99480. this.renderWidth = 512;
  99481. this.renderHeight = 256;
  99482. this.textureSize = 512;
  99483. this.deterministicLockstep = false;
  99484. this.lockstepMaxSteps = 4;
  99485. }
  99486. return NullEngineOptions;
  99487. }());
  99488. BABYLON.NullEngineOptions = NullEngineOptions;
  99489. /**
  99490. * The null engine class provides support for headless version of babylon.js.
  99491. * This can be used in server side scenario or for testing purposes
  99492. */
  99493. var NullEngine = /** @class */ (function (_super) {
  99494. __extends(NullEngine, _super);
  99495. function NullEngine(options) {
  99496. if (options === void 0) { options = new NullEngineOptions(); }
  99497. var _this = _super.call(this, null) || this;
  99498. if (options.deterministicLockstep === undefined) {
  99499. options.deterministicLockstep = false;
  99500. }
  99501. if (options.lockstepMaxSteps === undefined) {
  99502. options.lockstepMaxSteps = 4;
  99503. }
  99504. _this._options = options;
  99505. // Init caps
  99506. // We consider we are on a webgl1 capable device
  99507. _this._caps = new BABYLON.EngineCapabilities();
  99508. _this._caps.maxTexturesImageUnits = 16;
  99509. _this._caps.maxVertexTextureImageUnits = 16;
  99510. _this._caps.maxTextureSize = 512;
  99511. _this._caps.maxCubemapTextureSize = 512;
  99512. _this._caps.maxRenderTextureSize = 512;
  99513. _this._caps.maxVertexAttribs = 16;
  99514. _this._caps.maxVaryingVectors = 16;
  99515. _this._caps.maxFragmentUniformVectors = 16;
  99516. _this._caps.maxVertexUniformVectors = 16;
  99517. // Extensions
  99518. _this._caps.standardDerivatives = false;
  99519. _this._caps.astc = null;
  99520. _this._caps.s3tc = null;
  99521. _this._caps.pvrtc = null;
  99522. _this._caps.etc1 = null;
  99523. _this._caps.etc2 = null;
  99524. _this._caps.textureAnisotropicFilterExtension = null;
  99525. _this._caps.maxAnisotropy = 0;
  99526. _this._caps.uintIndices = false;
  99527. _this._caps.fragmentDepthSupported = false;
  99528. _this._caps.highPrecisionShaderSupported = true;
  99529. _this._caps.colorBufferFloat = false;
  99530. _this._caps.textureFloat = false;
  99531. _this._caps.textureFloatLinearFiltering = false;
  99532. _this._caps.textureFloatRender = false;
  99533. _this._caps.textureHalfFloat = false;
  99534. _this._caps.textureHalfFloatLinearFiltering = false;
  99535. _this._caps.textureHalfFloatRender = false;
  99536. _this._caps.textureLOD = false;
  99537. _this._caps.drawBuffersExtension = false;
  99538. _this._caps.depthTextureExtension = false;
  99539. _this._caps.vertexArrayObject = false;
  99540. _this._caps.instancedArrays = false;
  99541. BABYLON.Tools.Log("Babylon.js null engine (v" + BABYLON.Engine.Version + ") launched");
  99542. // Wrappers
  99543. if (typeof URL === "undefined") {
  99544. URL = {
  99545. createObjectURL: function () { },
  99546. revokeObjectURL: function () { }
  99547. };
  99548. }
  99549. if (typeof Blob === "undefined") {
  99550. Blob = function () { };
  99551. }
  99552. return _this;
  99553. }
  99554. NullEngine.prototype.isDeterministicLockStep = function () {
  99555. return this._options.deterministicLockstep;
  99556. };
  99557. NullEngine.prototype.getLockstepMaxSteps = function () {
  99558. return this._options.lockstepMaxSteps;
  99559. };
  99560. NullEngine.prototype.getHardwareScalingLevel = function () {
  99561. return 1.0;
  99562. };
  99563. NullEngine.prototype.createVertexBuffer = function (vertices) {
  99564. return {
  99565. capacity: 0,
  99566. references: 1,
  99567. is32Bits: false
  99568. };
  99569. };
  99570. NullEngine.prototype.createIndexBuffer = function (indices) {
  99571. return {
  99572. capacity: 0,
  99573. references: 1,
  99574. is32Bits: false
  99575. };
  99576. };
  99577. NullEngine.prototype.clear = function (color, backBuffer, depth, stencil) {
  99578. if (stencil === void 0) { stencil = false; }
  99579. };
  99580. NullEngine.prototype.getRenderWidth = function (useScreen) {
  99581. if (useScreen === void 0) { useScreen = false; }
  99582. if (!useScreen && this._currentRenderTarget) {
  99583. return this._currentRenderTarget.width;
  99584. }
  99585. return this._options.renderWidth;
  99586. };
  99587. NullEngine.prototype.getRenderHeight = function (useScreen) {
  99588. if (useScreen === void 0) { useScreen = false; }
  99589. if (!useScreen && this._currentRenderTarget) {
  99590. return this._currentRenderTarget.height;
  99591. }
  99592. return this._options.renderHeight;
  99593. };
  99594. NullEngine.prototype.setViewport = function (viewport, requiredWidth, requiredHeight) {
  99595. this._cachedViewport = viewport;
  99596. };
  99597. NullEngine.prototype.createShaderProgram = function (vertexCode, fragmentCode, defines, context) {
  99598. return {
  99599. transformFeedback: null,
  99600. __SPECTOR_rebuildProgram: null
  99601. };
  99602. };
  99603. NullEngine.prototype.getUniforms = function (shaderProgram, uniformsNames) {
  99604. return [];
  99605. };
  99606. NullEngine.prototype.getAttributes = function (shaderProgram, attributesNames) {
  99607. return [];
  99608. };
  99609. NullEngine.prototype.bindSamplers = function (effect) {
  99610. this._currentEffect = null;
  99611. };
  99612. NullEngine.prototype.enableEffect = function (effect) {
  99613. this._currentEffect = effect;
  99614. if (effect.onBind) {
  99615. effect.onBind(effect);
  99616. }
  99617. effect.onBindObservable.notifyObservers(effect);
  99618. };
  99619. NullEngine.prototype.setState = function (culling, zOffset, force, reverseSide) {
  99620. if (zOffset === void 0) { zOffset = 0; }
  99621. if (reverseSide === void 0) { reverseSide = false; }
  99622. };
  99623. NullEngine.prototype.setIntArray = function (uniform, array) {
  99624. };
  99625. NullEngine.prototype.setIntArray2 = function (uniform, array) {
  99626. };
  99627. NullEngine.prototype.setIntArray3 = function (uniform, array) {
  99628. };
  99629. NullEngine.prototype.setIntArray4 = function (uniform, array) {
  99630. };
  99631. NullEngine.prototype.setFloatArray = function (uniform, array) {
  99632. };
  99633. NullEngine.prototype.setFloatArray2 = function (uniform, array) {
  99634. };
  99635. NullEngine.prototype.setFloatArray3 = function (uniform, array) {
  99636. };
  99637. NullEngine.prototype.setFloatArray4 = function (uniform, array) {
  99638. };
  99639. NullEngine.prototype.setArray = function (uniform, array) {
  99640. };
  99641. NullEngine.prototype.setArray2 = function (uniform, array) {
  99642. };
  99643. NullEngine.prototype.setArray3 = function (uniform, array) {
  99644. };
  99645. NullEngine.prototype.setArray4 = function (uniform, array) {
  99646. };
  99647. NullEngine.prototype.setMatrices = function (uniform, matrices) {
  99648. };
  99649. NullEngine.prototype.setMatrix = function (uniform, matrix) {
  99650. };
  99651. NullEngine.prototype.setMatrix3x3 = function (uniform, matrix) {
  99652. };
  99653. NullEngine.prototype.setMatrix2x2 = function (uniform, matrix) {
  99654. };
  99655. NullEngine.prototype.setFloat = function (uniform, value) {
  99656. };
  99657. NullEngine.prototype.setFloat2 = function (uniform, x, y) {
  99658. };
  99659. NullEngine.prototype.setFloat3 = function (uniform, x, y, z) {
  99660. };
  99661. NullEngine.prototype.setBool = function (uniform, bool) {
  99662. };
  99663. NullEngine.prototype.setFloat4 = function (uniform, x, y, z, w) {
  99664. };
  99665. NullEngine.prototype.setColor3 = function (uniform, color3) {
  99666. };
  99667. NullEngine.prototype.setColor4 = function (uniform, color3, alpha) {
  99668. };
  99669. NullEngine.prototype.setAlphaMode = function (mode, noDepthWriteChange) {
  99670. if (noDepthWriteChange === void 0) { noDepthWriteChange = false; }
  99671. if (this._alphaMode === mode) {
  99672. return;
  99673. }
  99674. this._alphaState.alphaBlend = (mode !== BABYLON.Engine.ALPHA_DISABLE);
  99675. if (!noDepthWriteChange) {
  99676. this.setDepthWrite(mode === BABYLON.Engine.ALPHA_DISABLE);
  99677. }
  99678. this._alphaMode = mode;
  99679. };
  99680. NullEngine.prototype.bindBuffers = function (vertexBuffers, indexBuffer, effect) {
  99681. };
  99682. NullEngine.prototype.wipeCaches = function (bruteForce) {
  99683. if (this.preventCacheWipeBetweenFrames) {
  99684. return;
  99685. }
  99686. this.resetTextureCache();
  99687. this._currentEffect = null;
  99688. if (bruteForce) {
  99689. this._currentProgram = null;
  99690. this._stencilState.reset();
  99691. this._depthCullingState.reset();
  99692. this._alphaState.reset();
  99693. }
  99694. this._cachedVertexBuffers = null;
  99695. this._cachedIndexBuffer = null;
  99696. this._cachedEffectForVertexBuffers = null;
  99697. };
  99698. NullEngine.prototype.draw = function (useTriangles, indexStart, indexCount, instancesCount) {
  99699. };
  99700. NullEngine.prototype.drawElementsType = function (fillMode, indexStart, indexCount, instancesCount) {
  99701. };
  99702. NullEngine.prototype.drawArraysType = function (fillMode, verticesStart, verticesCount, instancesCount) {
  99703. };
  99704. NullEngine.prototype._createTexture = function () {
  99705. return {};
  99706. };
  99707. NullEngine.prototype._releaseTexture = function (texture) {
  99708. };
  99709. NullEngine.prototype.createTexture = function (urlArg, noMipmap, invertY, scene, samplingMode, onLoad, onError, buffer, fallBack, format) {
  99710. if (samplingMode === void 0) { samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE; }
  99711. if (onLoad === void 0) { onLoad = null; }
  99712. if (onError === void 0) { onError = null; }
  99713. if (buffer === void 0) { buffer = null; }
  99714. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_URL);
  99715. var url = String(urlArg);
  99716. texture.url = url;
  99717. texture.generateMipMaps = !noMipmap;
  99718. texture.samplingMode = samplingMode;
  99719. texture.invertY = invertY;
  99720. texture.baseWidth = this._options.textureSize;
  99721. texture.baseHeight = this._options.textureSize;
  99722. texture.width = this._options.textureSize;
  99723. texture.height = this._options.textureSize;
  99724. if (format) {
  99725. texture.format = format;
  99726. }
  99727. texture.isReady = true;
  99728. if (onLoad) {
  99729. onLoad();
  99730. }
  99731. this._internalTexturesCache.push(texture);
  99732. return texture;
  99733. };
  99734. NullEngine.prototype.createRenderTargetTexture = function (size, options) {
  99735. var fullOptions = new BABYLON.RenderTargetCreationOptions();
  99736. if (options !== undefined && typeof options === "object") {
  99737. fullOptions.generateMipMaps = options.generateMipMaps;
  99738. fullOptions.generateDepthBuffer = options.generateDepthBuffer === undefined ? true : options.generateDepthBuffer;
  99739. fullOptions.generateStencilBuffer = fullOptions.generateDepthBuffer && options.generateStencilBuffer;
  99740. fullOptions.type = options.type === undefined ? BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT : options.type;
  99741. fullOptions.samplingMode = options.samplingMode === undefined ? BABYLON.Texture.TRILINEAR_SAMPLINGMODE : options.samplingMode;
  99742. }
  99743. else {
  99744. fullOptions.generateMipMaps = options;
  99745. fullOptions.generateDepthBuffer = true;
  99746. fullOptions.generateStencilBuffer = false;
  99747. fullOptions.type = BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT;
  99748. fullOptions.samplingMode = BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  99749. }
  99750. var texture = new BABYLON.InternalTexture(this, BABYLON.InternalTexture.DATASOURCE_RENDERTARGET);
  99751. var width = size.width || size;
  99752. var height = size.height || size;
  99753. texture._depthStencilBuffer = {};
  99754. texture._framebuffer = {};
  99755. texture.baseWidth = width;
  99756. texture.baseHeight = height;
  99757. texture.width = width;
  99758. texture.height = height;
  99759. texture.isReady = true;
  99760. texture.samples = 1;
  99761. texture.generateMipMaps = fullOptions.generateMipMaps ? true : false;
  99762. texture.samplingMode = fullOptions.samplingMode;
  99763. texture.type = fullOptions.type;
  99764. texture._generateDepthBuffer = fullOptions.generateDepthBuffer;
  99765. texture._generateStencilBuffer = fullOptions.generateStencilBuffer ? true : false;
  99766. this._internalTexturesCache.push(texture);
  99767. return texture;
  99768. };
  99769. NullEngine.prototype.updateTextureSamplingMode = function (samplingMode, texture) {
  99770. texture.samplingMode = samplingMode;
  99771. };
  99772. NullEngine.prototype.bindFramebuffer = function (texture, faceIndex, requiredWidth, requiredHeight, forceFullscreenViewport) {
  99773. if (this._currentRenderTarget) {
  99774. this.unBindFramebuffer(this._currentRenderTarget);
  99775. }
  99776. this._currentRenderTarget = texture;
  99777. this._currentFramebuffer = texture._MSAAFramebuffer ? texture._MSAAFramebuffer : texture._framebuffer;
  99778. if (this._cachedViewport && !forceFullscreenViewport) {
  99779. this.setViewport(this._cachedViewport, requiredWidth, requiredHeight);
  99780. }
  99781. };
  99782. NullEngine.prototype.unBindFramebuffer = function (texture, disableGenerateMipMaps, onBeforeUnbind) {
  99783. if (disableGenerateMipMaps === void 0) { disableGenerateMipMaps = false; }
  99784. this._currentRenderTarget = null;
  99785. if (onBeforeUnbind) {
  99786. if (texture._MSAAFramebuffer) {
  99787. this._currentFramebuffer = texture._framebuffer;
  99788. }
  99789. onBeforeUnbind();
  99790. }
  99791. this._currentFramebuffer = null;
  99792. };
  99793. NullEngine.prototype.createDynamicVertexBuffer = function (vertices) {
  99794. var vbo = {
  99795. capacity: 1,
  99796. references: 1,
  99797. is32Bits: false
  99798. };
  99799. return vbo;
  99800. };
  99801. NullEngine.prototype.updateDynamicTexture = function (texture, canvas, invertY, premulAlpha, format) {
  99802. if (premulAlpha === void 0) { premulAlpha = false; }
  99803. };
  99804. NullEngine.prototype.updateDynamicIndexBuffer = function (indexBuffer, indices, offset) {
  99805. if (offset === void 0) { offset = 0; }
  99806. };
  99807. /**
  99808. * Updates a dynamic vertex buffer.
  99809. * @param vertexBuffer the vertex buffer to update
  99810. * @param data the data used to update the vertex buffer
  99811. * @param byteOffset the byte offset of the data (optional)
  99812. * @param byteLength the byte length of the data (optional)
  99813. */
  99814. NullEngine.prototype.updateDynamicVertexBuffer = function (vertexBuffer, vertices, byteOffset, byteLength) {
  99815. };
  99816. NullEngine.prototype._bindTextureDirectly = function (target, texture) {
  99817. if (this._boundTexturesCache[this._activeChannel] !== texture) {
  99818. this._boundTexturesCache[this._activeChannel] = texture;
  99819. return true;
  99820. }
  99821. return false;
  99822. };
  99823. NullEngine.prototype._bindTexture = function (channel, texture) {
  99824. if (channel < 0) {
  99825. return;
  99826. }
  99827. this._bindTextureDirectly(0, texture);
  99828. };
  99829. NullEngine.prototype._releaseBuffer = function (buffer) {
  99830. buffer.references--;
  99831. if (buffer.references === 0) {
  99832. return true;
  99833. }
  99834. return false;
  99835. };
  99836. NullEngine.prototype.releaseEffects = function () {
  99837. };
  99838. return NullEngine;
  99839. }(BABYLON.Engine));
  99840. BABYLON.NullEngine = NullEngine;
  99841. })(BABYLON || (BABYLON = {}));
  99842. //# sourceMappingURL=babylon.nullEngine.js.map
  99843. var BABYLON;
  99844. (function (BABYLON) {
  99845. /**
  99846. * This class can be used to get instrumentation data from a Babylon engine
  99847. */
  99848. var EngineInstrumentation = /** @class */ (function () {
  99849. function EngineInstrumentation(engine) {
  99850. this.engine = engine;
  99851. this._captureGPUFrameTime = false;
  99852. this._gpuFrameTime = new BABYLON.PerfCounter();
  99853. this._captureShaderCompilationTime = false;
  99854. this._shaderCompilationTime = new BABYLON.PerfCounter();
  99855. // Observers
  99856. this._onBeginFrameObserver = null;
  99857. this._onEndFrameObserver = null;
  99858. this._onBeforeShaderCompilationObserver = null;
  99859. this._onAfterShaderCompilationObserver = null;
  99860. }
  99861. Object.defineProperty(EngineInstrumentation.prototype, "gpuFrameTimeCounter", {
  99862. // Properties
  99863. /**
  99864. * Gets the perf counter used for GPU frame time
  99865. */
  99866. get: function () {
  99867. return this._gpuFrameTime;
  99868. },
  99869. enumerable: true,
  99870. configurable: true
  99871. });
  99872. Object.defineProperty(EngineInstrumentation.prototype, "captureGPUFrameTime", {
  99873. /**
  99874. * Gets the GPU frame time capture status
  99875. */
  99876. get: function () {
  99877. return this._captureGPUFrameTime;
  99878. },
  99879. /**
  99880. * Enable or disable the GPU frame time capture
  99881. */
  99882. set: function (value) {
  99883. var _this = this;
  99884. if (value === this._captureGPUFrameTime) {
  99885. return;
  99886. }
  99887. this._captureGPUFrameTime = value;
  99888. if (value) {
  99889. this._onBeginFrameObserver = this.engine.onBeginFrameObservable.add(function () {
  99890. if (!_this._gpuFrameTimeToken) {
  99891. _this._gpuFrameTimeToken = _this.engine.startTimeQuery();
  99892. }
  99893. });
  99894. this._onEndFrameObserver = this.engine.onEndFrameObservable.add(function () {
  99895. if (!_this._gpuFrameTimeToken) {
  99896. return;
  99897. }
  99898. var time = _this.engine.endTimeQuery(_this._gpuFrameTimeToken);
  99899. if (time > -1) {
  99900. _this._gpuFrameTimeToken = null;
  99901. _this._gpuFrameTime.fetchNewFrame();
  99902. _this._gpuFrameTime.addCount(time, true);
  99903. }
  99904. });
  99905. }
  99906. else {
  99907. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99908. this._onBeginFrameObserver = null;
  99909. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99910. this._onEndFrameObserver = null;
  99911. }
  99912. },
  99913. enumerable: true,
  99914. configurable: true
  99915. });
  99916. Object.defineProperty(EngineInstrumentation.prototype, "shaderCompilationTimeCounter", {
  99917. /**
  99918. * Gets the perf counter used for shader compilation time
  99919. */
  99920. get: function () {
  99921. return this._shaderCompilationTime;
  99922. },
  99923. enumerable: true,
  99924. configurable: true
  99925. });
  99926. Object.defineProperty(EngineInstrumentation.prototype, "captureShaderCompilationTime", {
  99927. /**
  99928. * Gets the shader compilation time capture status
  99929. */
  99930. get: function () {
  99931. return this._captureShaderCompilationTime;
  99932. },
  99933. /**
  99934. * Enable or disable the shader compilation time capture
  99935. */
  99936. set: function (value) {
  99937. var _this = this;
  99938. if (value === this._captureShaderCompilationTime) {
  99939. return;
  99940. }
  99941. this._captureShaderCompilationTime = value;
  99942. if (value) {
  99943. this._onBeforeShaderCompilationObserver = this.engine.onBeforeShaderCompilationObservable.add(function () {
  99944. _this._shaderCompilationTime.fetchNewFrame();
  99945. _this._shaderCompilationTime.beginMonitoring();
  99946. });
  99947. this._onAfterShaderCompilationObserver = this.engine.onAfterShaderCompilationObservable.add(function () {
  99948. _this._shaderCompilationTime.endMonitoring();
  99949. });
  99950. }
  99951. else {
  99952. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99953. this._onBeforeShaderCompilationObserver = null;
  99954. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99955. this._onAfterShaderCompilationObserver = null;
  99956. }
  99957. },
  99958. enumerable: true,
  99959. configurable: true
  99960. });
  99961. EngineInstrumentation.prototype.dispose = function () {
  99962. this.engine.onBeginFrameObservable.remove(this._onBeginFrameObserver);
  99963. this._onBeginFrameObserver = null;
  99964. this.engine.onEndFrameObservable.remove(this._onEndFrameObserver);
  99965. this._onEndFrameObserver = null;
  99966. this.engine.onBeforeShaderCompilationObservable.remove(this._onBeforeShaderCompilationObserver);
  99967. this._onBeforeShaderCompilationObserver = null;
  99968. this.engine.onAfterShaderCompilationObservable.remove(this._onAfterShaderCompilationObserver);
  99969. this._onAfterShaderCompilationObserver = null;
  99970. this.engine = null;
  99971. };
  99972. return EngineInstrumentation;
  99973. }());
  99974. BABYLON.EngineInstrumentation = EngineInstrumentation;
  99975. })(BABYLON || (BABYLON = {}));
  99976. //# sourceMappingURL=babylon.engineInstrumentation.js.map
  99977. var BABYLON;
  99978. (function (BABYLON) {
  99979. /**
  99980. * This class can be used to get instrumentation data from a Babylon engine
  99981. */
  99982. var SceneInstrumentation = /** @class */ (function () {
  99983. function SceneInstrumentation(scene) {
  99984. var _this = this;
  99985. this.scene = scene;
  99986. this._captureActiveMeshesEvaluationTime = false;
  99987. this._activeMeshesEvaluationTime = new BABYLON.PerfCounter();
  99988. this._captureRenderTargetsRenderTime = false;
  99989. this._renderTargetsRenderTime = new BABYLON.PerfCounter();
  99990. this._captureFrameTime = false;
  99991. this._frameTime = new BABYLON.PerfCounter();
  99992. this._captureRenderTime = false;
  99993. this._renderTime = new BABYLON.PerfCounter();
  99994. this._captureInterFrameTime = false;
  99995. this._interFrameTime = new BABYLON.PerfCounter();
  99996. this._captureParticlesRenderTime = false;
  99997. this._particlesRenderTime = new BABYLON.PerfCounter();
  99998. this._captureSpritesRenderTime = false;
  99999. this._spritesRenderTime = new BABYLON.PerfCounter();
  100000. this._capturePhysicsTime = false;
  100001. this._physicsTime = new BABYLON.PerfCounter();
  100002. this._captureAnimationsTime = false;
  100003. this._animationsTime = new BABYLON.PerfCounter();
  100004. this._captureCameraRenderTime = false;
  100005. this._cameraRenderTime = new BABYLON.PerfCounter();
  100006. // Observers
  100007. this._onBeforeActiveMeshesEvaluationObserver = null;
  100008. this._onAfterActiveMeshesEvaluationObserver = null;
  100009. this._onBeforeRenderTargetsRenderObserver = null;
  100010. this._onAfterRenderTargetsRenderObserver = null;
  100011. this._onAfterRenderObserver = null;
  100012. this._onBeforeDrawPhaseObserver = null;
  100013. this._onAfterDrawPhaseObserver = null;
  100014. this._onBeforeAnimationsObserver = null;
  100015. this._onBeforeParticlesRenderingObserver = null;
  100016. this._onAfterParticlesRenderingObserver = null;
  100017. this._onBeforeSpritesRenderingObserver = null;
  100018. this._onAfterSpritesRenderingObserver = null;
  100019. this._onBeforePhysicsObserver = null;
  100020. this._onAfterPhysicsObserver = null;
  100021. this._onAfterAnimationsObserver = null;
  100022. this._onBeforeCameraRenderObserver = null;
  100023. this._onAfterCameraRenderObserver = null;
  100024. // Before render
  100025. this._onBeforeAnimationsObserver = scene.onBeforeAnimationsObservable.add(function () {
  100026. if (_this._captureActiveMeshesEvaluationTime) {
  100027. _this._activeMeshesEvaluationTime.fetchNewFrame();
  100028. }
  100029. if (_this._captureRenderTargetsRenderTime) {
  100030. _this._renderTargetsRenderTime.fetchNewFrame();
  100031. }
  100032. if (_this._captureFrameTime) {
  100033. BABYLON.Tools.StartPerformanceCounter("Scene rendering");
  100034. _this._frameTime.beginMonitoring();
  100035. }
  100036. if (_this._captureInterFrameTime) {
  100037. _this._interFrameTime.endMonitoring();
  100038. }
  100039. if (_this._captureParticlesRenderTime) {
  100040. _this._particlesRenderTime.fetchNewFrame();
  100041. }
  100042. if (_this._captureSpritesRenderTime) {
  100043. _this._spritesRenderTime.fetchNewFrame();
  100044. }
  100045. if (_this._captureAnimationsTime) {
  100046. _this._animationsTime.beginMonitoring();
  100047. }
  100048. _this.scene.getEngine()._drawCalls.fetchNewFrame();
  100049. _this.scene.getEngine()._textureCollisions.fetchNewFrame();
  100050. });
  100051. // After render
  100052. this._onAfterRenderObserver = scene.onAfterRenderObservable.add(function () {
  100053. if (_this._captureFrameTime) {
  100054. BABYLON.Tools.EndPerformanceCounter("Scene rendering");
  100055. _this._frameTime.endMonitoring();
  100056. }
  100057. if (_this._captureRenderTime) {
  100058. _this._renderTime.endMonitoring(false);
  100059. }
  100060. if (_this._captureInterFrameTime) {
  100061. _this._interFrameTime.beginMonitoring();
  100062. }
  100063. });
  100064. }
  100065. Object.defineProperty(SceneInstrumentation.prototype, "activeMeshesEvaluationTimeCounter", {
  100066. // Properties
  100067. /**
  100068. * Gets the perf counter used for active meshes evaluation time
  100069. */
  100070. get: function () {
  100071. return this._activeMeshesEvaluationTime;
  100072. },
  100073. enumerable: true,
  100074. configurable: true
  100075. });
  100076. Object.defineProperty(SceneInstrumentation.prototype, "captureActiveMeshesEvaluationTime", {
  100077. /**
  100078. * Gets the active meshes evaluation time capture status
  100079. */
  100080. get: function () {
  100081. return this._captureActiveMeshesEvaluationTime;
  100082. },
  100083. /**
  100084. * Enable or disable the active meshes evaluation time capture
  100085. */
  100086. set: function (value) {
  100087. var _this = this;
  100088. if (value === this._captureActiveMeshesEvaluationTime) {
  100089. return;
  100090. }
  100091. this._captureActiveMeshesEvaluationTime = value;
  100092. if (value) {
  100093. this._onBeforeActiveMeshesEvaluationObserver = this.scene.onBeforeActiveMeshesEvaluationObservable.add(function () {
  100094. BABYLON.Tools.StartPerformanceCounter("Active meshes evaluation");
  100095. _this._activeMeshesEvaluationTime.beginMonitoring();
  100096. });
  100097. this._onAfterActiveMeshesEvaluationObserver = this.scene.onAfterActiveMeshesEvaluationObservable.add(function () {
  100098. BABYLON.Tools.EndPerformanceCounter("Active meshes evaluation");
  100099. _this._activeMeshesEvaluationTime.endMonitoring();
  100100. });
  100101. }
  100102. else {
  100103. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100104. this._onBeforeActiveMeshesEvaluationObserver = null;
  100105. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100106. this._onAfterActiveMeshesEvaluationObserver = null;
  100107. }
  100108. },
  100109. enumerable: true,
  100110. configurable: true
  100111. });
  100112. Object.defineProperty(SceneInstrumentation.prototype, "renderTargetsRenderTimeCounter", {
  100113. /**
  100114. * Gets the perf counter used for render targets render time
  100115. */
  100116. get: function () {
  100117. return this._renderTargetsRenderTime;
  100118. },
  100119. enumerable: true,
  100120. configurable: true
  100121. });
  100122. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTargetsRenderTime", {
  100123. /**
  100124. * Gets the render targets render time capture status
  100125. */
  100126. get: function () {
  100127. return this._captureRenderTargetsRenderTime;
  100128. },
  100129. /**
  100130. * Enable or disable the render targets render time capture
  100131. */
  100132. set: function (value) {
  100133. var _this = this;
  100134. if (value === this._captureRenderTargetsRenderTime) {
  100135. return;
  100136. }
  100137. this._captureRenderTargetsRenderTime = value;
  100138. if (value) {
  100139. this._onBeforeRenderTargetsRenderObserver = this.scene.onBeforeRenderTargetsRenderObservable.add(function () {
  100140. BABYLON.Tools.StartPerformanceCounter("Render targets rendering");
  100141. _this._renderTargetsRenderTime.beginMonitoring();
  100142. });
  100143. this._onAfterRenderTargetsRenderObserver = this.scene.onAfterRenderTargetsRenderObservable.add(function () {
  100144. BABYLON.Tools.EndPerformanceCounter("Render targets rendering");
  100145. _this._renderTargetsRenderTime.endMonitoring(false);
  100146. });
  100147. }
  100148. else {
  100149. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100150. this._onBeforeRenderTargetsRenderObserver = null;
  100151. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100152. this._onAfterRenderTargetsRenderObserver = null;
  100153. }
  100154. },
  100155. enumerable: true,
  100156. configurable: true
  100157. });
  100158. Object.defineProperty(SceneInstrumentation.prototype, "particlesRenderTimeCounter", {
  100159. /**
  100160. * Gets the perf counter used for particles render time
  100161. */
  100162. get: function () {
  100163. return this._particlesRenderTime;
  100164. },
  100165. enumerable: true,
  100166. configurable: true
  100167. });
  100168. Object.defineProperty(SceneInstrumentation.prototype, "captureParticlesRenderTime", {
  100169. /**
  100170. * Gets the particles render time capture status
  100171. */
  100172. get: function () {
  100173. return this._captureParticlesRenderTime;
  100174. },
  100175. /**
  100176. * Enable or disable the particles render time capture
  100177. */
  100178. set: function (value) {
  100179. var _this = this;
  100180. if (value === this._captureParticlesRenderTime) {
  100181. return;
  100182. }
  100183. this._captureParticlesRenderTime = value;
  100184. if (value) {
  100185. this._onBeforeParticlesRenderingObserver = this.scene.onBeforeParticlesRenderingObservable.add(function () {
  100186. BABYLON.Tools.StartPerformanceCounter("Particles");
  100187. _this._particlesRenderTime.beginMonitoring();
  100188. });
  100189. this._onAfterParticlesRenderingObserver = this.scene.onAfterParticlesRenderingObservable.add(function () {
  100190. BABYLON.Tools.EndPerformanceCounter("Particles");
  100191. _this._particlesRenderTime.endMonitoring(false);
  100192. });
  100193. }
  100194. else {
  100195. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100196. this._onBeforeParticlesRenderingObserver = null;
  100197. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100198. this._onAfterParticlesRenderingObserver = null;
  100199. }
  100200. },
  100201. enumerable: true,
  100202. configurable: true
  100203. });
  100204. Object.defineProperty(SceneInstrumentation.prototype, "spritesRenderTimeCounter", {
  100205. /**
  100206. * Gets the perf counter used for sprites render time
  100207. */
  100208. get: function () {
  100209. return this._spritesRenderTime;
  100210. },
  100211. enumerable: true,
  100212. configurable: true
  100213. });
  100214. Object.defineProperty(SceneInstrumentation.prototype, "captureSpritesRenderTime", {
  100215. /**
  100216. * Gets the sprites render time capture status
  100217. */
  100218. get: function () {
  100219. return this._captureSpritesRenderTime;
  100220. },
  100221. /**
  100222. * Enable or disable the sprites render time capture
  100223. */
  100224. set: function (value) {
  100225. var _this = this;
  100226. if (value === this._captureSpritesRenderTime) {
  100227. return;
  100228. }
  100229. this._captureSpritesRenderTime = value;
  100230. if (value) {
  100231. this._onBeforeSpritesRenderingObserver = this.scene.onBeforeSpritesRenderingObservable.add(function () {
  100232. BABYLON.Tools.StartPerformanceCounter("Sprites");
  100233. _this._spritesRenderTime.beginMonitoring();
  100234. });
  100235. this._onAfterSpritesRenderingObserver = this.scene.onAfterSpritesRenderingObservable.add(function () {
  100236. BABYLON.Tools.EndPerformanceCounter("Sprites");
  100237. _this._spritesRenderTime.endMonitoring(false);
  100238. });
  100239. }
  100240. else {
  100241. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100242. this._onBeforeSpritesRenderingObserver = null;
  100243. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100244. this._onAfterSpritesRenderingObserver = null;
  100245. }
  100246. },
  100247. enumerable: true,
  100248. configurable: true
  100249. });
  100250. Object.defineProperty(SceneInstrumentation.prototype, "physicsTimeCounter", {
  100251. /**
  100252. * Gets the perf counter used for physics time
  100253. */
  100254. get: function () {
  100255. return this._physicsTime;
  100256. },
  100257. enumerable: true,
  100258. configurable: true
  100259. });
  100260. Object.defineProperty(SceneInstrumentation.prototype, "capturePhysicsTime", {
  100261. /**
  100262. * Gets the physics time capture status
  100263. */
  100264. get: function () {
  100265. return this._capturePhysicsTime;
  100266. },
  100267. /**
  100268. * Enable or disable the physics time capture
  100269. */
  100270. set: function (value) {
  100271. var _this = this;
  100272. if (value === this._capturePhysicsTime) {
  100273. return;
  100274. }
  100275. this._capturePhysicsTime = value;
  100276. if (value) {
  100277. this._onBeforePhysicsObserver = this.scene.onBeforePhysicsObservable.add(function () {
  100278. BABYLON.Tools.StartPerformanceCounter("Physics");
  100279. _this._physicsTime.beginMonitoring();
  100280. });
  100281. this._onAfterPhysicsObserver = this.scene.onAfterPhysicsObservable.add(function () {
  100282. BABYLON.Tools.EndPerformanceCounter("Physics");
  100283. _this._physicsTime.endMonitoring();
  100284. });
  100285. }
  100286. else {
  100287. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100288. this._onBeforePhysicsObserver = null;
  100289. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100290. this._onAfterPhysicsObserver = null;
  100291. }
  100292. },
  100293. enumerable: true,
  100294. configurable: true
  100295. });
  100296. Object.defineProperty(SceneInstrumentation.prototype, "animationsTimeCounter", {
  100297. /**
  100298. * Gets the perf counter used for animations time
  100299. */
  100300. get: function () {
  100301. return this._animationsTime;
  100302. },
  100303. enumerable: true,
  100304. configurable: true
  100305. });
  100306. Object.defineProperty(SceneInstrumentation.prototype, "captureAnimationsTime", {
  100307. /**
  100308. * Gets the animations time capture status
  100309. */
  100310. get: function () {
  100311. return this._captureAnimationsTime;
  100312. },
  100313. /**
  100314. * Enable or disable the animations time capture
  100315. */
  100316. set: function (value) {
  100317. var _this = this;
  100318. if (value === this._captureAnimationsTime) {
  100319. return;
  100320. }
  100321. this._captureAnimationsTime = value;
  100322. if (value) {
  100323. this._onAfterAnimationsObserver = this.scene.onAfterAnimationsObservable.add(function () {
  100324. _this._animationsTime.endMonitoring();
  100325. });
  100326. }
  100327. else {
  100328. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100329. this._onAfterAnimationsObserver = null;
  100330. }
  100331. },
  100332. enumerable: true,
  100333. configurable: true
  100334. });
  100335. Object.defineProperty(SceneInstrumentation.prototype, "frameTimeCounter", {
  100336. /**
  100337. * Gets the perf counter used for frame time capture
  100338. */
  100339. get: function () {
  100340. return this._frameTime;
  100341. },
  100342. enumerable: true,
  100343. configurable: true
  100344. });
  100345. Object.defineProperty(SceneInstrumentation.prototype, "captureFrameTime", {
  100346. /**
  100347. * Gets the frame time capture status
  100348. */
  100349. get: function () {
  100350. return this._captureFrameTime;
  100351. },
  100352. /**
  100353. * Enable or disable the frame time capture
  100354. */
  100355. set: function (value) {
  100356. this._captureFrameTime = value;
  100357. },
  100358. enumerable: true,
  100359. configurable: true
  100360. });
  100361. Object.defineProperty(SceneInstrumentation.prototype, "interFrameTimeCounter", {
  100362. /**
  100363. * Gets the perf counter used for inter-frames time capture
  100364. */
  100365. get: function () {
  100366. return this._interFrameTime;
  100367. },
  100368. enumerable: true,
  100369. configurable: true
  100370. });
  100371. Object.defineProperty(SceneInstrumentation.prototype, "captureInterFrameTime", {
  100372. /**
  100373. * Gets the inter-frames time capture status
  100374. */
  100375. get: function () {
  100376. return this._captureInterFrameTime;
  100377. },
  100378. /**
  100379. * Enable or disable the inter-frames time capture
  100380. */
  100381. set: function (value) {
  100382. this._captureInterFrameTime = value;
  100383. },
  100384. enumerable: true,
  100385. configurable: true
  100386. });
  100387. Object.defineProperty(SceneInstrumentation.prototype, "renderTimeCounter", {
  100388. /**
  100389. * Gets the perf counter used for render time capture
  100390. */
  100391. get: function () {
  100392. return this._renderTime;
  100393. },
  100394. enumerable: true,
  100395. configurable: true
  100396. });
  100397. Object.defineProperty(SceneInstrumentation.prototype, "captureRenderTime", {
  100398. /**
  100399. * Gets the render time capture status
  100400. */
  100401. get: function () {
  100402. return this._captureRenderTime;
  100403. },
  100404. /**
  100405. * Enable or disable the render time capture
  100406. */
  100407. set: function (value) {
  100408. var _this = this;
  100409. if (value === this._captureRenderTime) {
  100410. return;
  100411. }
  100412. this._captureRenderTime = value;
  100413. if (value) {
  100414. this._onBeforeDrawPhaseObserver = this.scene.onBeforeDrawPhaseObservable.add(function () {
  100415. _this._renderTime.beginMonitoring();
  100416. BABYLON.Tools.StartPerformanceCounter("Main render");
  100417. });
  100418. this._onAfterDrawPhaseObserver = this.scene.onAfterDrawPhaseObservable.add(function () {
  100419. _this._renderTime.endMonitoring(false);
  100420. BABYLON.Tools.EndPerformanceCounter("Main render");
  100421. });
  100422. }
  100423. else {
  100424. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100425. this._onBeforeDrawPhaseObserver = null;
  100426. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100427. this._onAfterDrawPhaseObserver = null;
  100428. }
  100429. },
  100430. enumerable: true,
  100431. configurable: true
  100432. });
  100433. Object.defineProperty(SceneInstrumentation.prototype, "cameraRenderTimeCounter", {
  100434. /**
  100435. * Gets the perf counter used for camera render time capture
  100436. */
  100437. get: function () {
  100438. return this._cameraRenderTime;
  100439. },
  100440. enumerable: true,
  100441. configurable: true
  100442. });
  100443. Object.defineProperty(SceneInstrumentation.prototype, "captureCameraRenderTime", {
  100444. /**
  100445. * Gets the camera render time capture status
  100446. */
  100447. get: function () {
  100448. return this._captureCameraRenderTime;
  100449. },
  100450. /**
  100451. * Enable or disable the camera render time capture
  100452. */
  100453. set: function (value) {
  100454. var _this = this;
  100455. if (value === this._captureCameraRenderTime) {
  100456. return;
  100457. }
  100458. this._captureCameraRenderTime = value;
  100459. if (value) {
  100460. this._onBeforeCameraRenderObserver = this.scene.onBeforeCameraRenderObservable.add(function (camera) {
  100461. _this._cameraRenderTime.beginMonitoring();
  100462. BABYLON.Tools.StartPerformanceCounter("Rendering camera " + camera.name);
  100463. });
  100464. this._onAfterCameraRenderObserver = this.scene.onAfterCameraRenderObservable.add(function (camera) {
  100465. _this._cameraRenderTime.endMonitoring(false);
  100466. BABYLON.Tools.EndPerformanceCounter("Rendering camera " + camera.name);
  100467. });
  100468. }
  100469. else {
  100470. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100471. this._onBeforeCameraRenderObserver = null;
  100472. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100473. this._onAfterCameraRenderObserver = null;
  100474. }
  100475. },
  100476. enumerable: true,
  100477. configurable: true
  100478. });
  100479. Object.defineProperty(SceneInstrumentation.prototype, "drawCallsCounter", {
  100480. /**
  100481. * Gets the perf counter used for draw calls
  100482. */
  100483. get: function () {
  100484. return this.scene.getEngine()._drawCalls;
  100485. },
  100486. enumerable: true,
  100487. configurable: true
  100488. });
  100489. Object.defineProperty(SceneInstrumentation.prototype, "textureCollisionsCounter", {
  100490. /**
  100491. * Gets the perf counter used for texture collisions
  100492. */
  100493. get: function () {
  100494. return this.scene.getEngine()._textureCollisions;
  100495. },
  100496. enumerable: true,
  100497. configurable: true
  100498. });
  100499. SceneInstrumentation.prototype.dispose = function () {
  100500. this.scene.onAfterRenderObservable.remove(this._onAfterRenderObserver);
  100501. this._onAfterRenderObserver = null;
  100502. this.scene.onBeforeActiveMeshesEvaluationObservable.remove(this._onBeforeActiveMeshesEvaluationObserver);
  100503. this._onBeforeActiveMeshesEvaluationObserver = null;
  100504. this.scene.onAfterActiveMeshesEvaluationObservable.remove(this._onAfterActiveMeshesEvaluationObserver);
  100505. this._onAfterActiveMeshesEvaluationObserver = null;
  100506. this.scene.onBeforeRenderTargetsRenderObservable.remove(this._onBeforeRenderTargetsRenderObserver);
  100507. this._onBeforeRenderTargetsRenderObserver = null;
  100508. this.scene.onAfterRenderTargetsRenderObservable.remove(this._onAfterRenderTargetsRenderObserver);
  100509. this._onAfterRenderTargetsRenderObserver = null;
  100510. this.scene.onBeforeAnimationsObservable.remove(this._onBeforeAnimationsObserver);
  100511. this._onBeforeAnimationsObserver = null;
  100512. this.scene.onBeforeParticlesRenderingObservable.remove(this._onBeforeParticlesRenderingObserver);
  100513. this._onBeforeParticlesRenderingObserver = null;
  100514. this.scene.onAfterParticlesRenderingObservable.remove(this._onAfterParticlesRenderingObserver);
  100515. this._onAfterParticlesRenderingObserver = null;
  100516. this.scene.onBeforeSpritesRenderingObservable.remove(this._onBeforeSpritesRenderingObserver);
  100517. this._onBeforeSpritesRenderingObserver = null;
  100518. this.scene.onAfterSpritesRenderingObservable.remove(this._onAfterSpritesRenderingObserver);
  100519. this._onAfterSpritesRenderingObserver = null;
  100520. this.scene.onBeforeDrawPhaseObservable.remove(this._onBeforeDrawPhaseObserver);
  100521. this._onBeforeDrawPhaseObserver = null;
  100522. this.scene.onAfterDrawPhaseObservable.remove(this._onAfterDrawPhaseObserver);
  100523. this._onAfterDrawPhaseObserver = null;
  100524. this.scene.onBeforePhysicsObservable.remove(this._onBeforePhysicsObserver);
  100525. this._onBeforePhysicsObserver = null;
  100526. this.scene.onAfterPhysicsObservable.remove(this._onAfterPhysicsObserver);
  100527. this._onAfterPhysicsObserver = null;
  100528. this.scene.onAfterAnimationsObservable.remove(this._onAfterAnimationsObserver);
  100529. this._onAfterAnimationsObserver = null;
  100530. this.scene.onBeforeCameraRenderObservable.remove(this._onBeforeCameraRenderObserver);
  100531. this._onBeforeCameraRenderObserver = null;
  100532. this.scene.onAfterCameraRenderObservable.remove(this._onAfterCameraRenderObserver);
  100533. this._onAfterCameraRenderObserver = null;
  100534. this.scene = null;
  100535. };
  100536. return SceneInstrumentation;
  100537. }());
  100538. BABYLON.SceneInstrumentation = SceneInstrumentation;
  100539. })(BABYLON || (BABYLON = {}));
  100540. //# sourceMappingURL=babylon.sceneInstrumentation.js.map
  100541. var BABYLON;
  100542. (function (BABYLON) {
  100543. /**
  100544. * @hidden
  100545. **/
  100546. var _TimeToken = /** @class */ (function () {
  100547. function _TimeToken() {
  100548. this._timeElapsedQueryEnded = false;
  100549. }
  100550. return _TimeToken;
  100551. }());
  100552. BABYLON._TimeToken = _TimeToken;
  100553. })(BABYLON || (BABYLON = {}));
  100554. //# sourceMappingURL=babylon.timeToken.js.map
  100555. var BABYLON;
  100556. (function (BABYLON) {
  100557. /**
  100558. * Background material defines definition.
  100559. * @hidden Mainly internal Use
  100560. */
  100561. var BackgroundMaterialDefines = /** @class */ (function (_super) {
  100562. __extends(BackgroundMaterialDefines, _super);
  100563. /**
  100564. * Constructor of the defines.
  100565. */
  100566. function BackgroundMaterialDefines() {
  100567. var _this = _super.call(this) || this;
  100568. /**
  100569. * True if the diffuse texture is in use.
  100570. */
  100571. _this.DIFFUSE = false;
  100572. /**
  100573. * The direct UV channel to use.
  100574. */
  100575. _this.DIFFUSEDIRECTUV = 0;
  100576. /**
  100577. * True if the diffuse texture is in gamma space.
  100578. */
  100579. _this.GAMMADIFFUSE = false;
  100580. /**
  100581. * True if the diffuse texture has opacity in the alpha channel.
  100582. */
  100583. _this.DIFFUSEHASALPHA = false;
  100584. /**
  100585. * True if you want the material to fade to transparent at grazing angle.
  100586. */
  100587. _this.OPACITYFRESNEL = false;
  100588. /**
  100589. * True if an extra blur needs to be added in the reflection.
  100590. */
  100591. _this.REFLECTIONBLUR = false;
  100592. /**
  100593. * True if you want the material to fade to reflection at grazing angle.
  100594. */
  100595. _this.REFLECTIONFRESNEL = false;
  100596. /**
  100597. * True if you want the material to falloff as far as you move away from the scene center.
  100598. */
  100599. _this.REFLECTIONFALLOFF = false;
  100600. /**
  100601. * False if the current Webgl implementation does not support the texture lod extension.
  100602. */
  100603. _this.TEXTURELODSUPPORT = false;
  100604. /**
  100605. * True to ensure the data are premultiplied.
  100606. */
  100607. _this.PREMULTIPLYALPHA = false;
  100608. /**
  100609. * True if the texture contains cooked RGB values and not gray scaled multipliers.
  100610. */
  100611. _this.USERGBCOLOR = false;
  100612. /**
  100613. * True if highlight and shadow levels have been specified. It can help ensuring the main perceived color
  100614. * stays aligned with the desired configuration.
  100615. */
  100616. _this.USEHIGHLIGHTANDSHADOWCOLORS = false;
  100617. /**
  100618. * True to add noise in order to reduce the banding effect.
  100619. */
  100620. _this.NOISE = false;
  100621. /**
  100622. * is the reflection texture in BGR color scheme?
  100623. * Mainly used to solve a bug in ios10 video tag
  100624. */
  100625. _this.REFLECTIONBGR = false;
  100626. _this.IMAGEPROCESSING = false;
  100627. _this.VIGNETTE = false;
  100628. _this.VIGNETTEBLENDMODEMULTIPLY = false;
  100629. _this.VIGNETTEBLENDMODEOPAQUE = false;
  100630. _this.TONEMAPPING = false;
  100631. _this.CONTRAST = false;
  100632. _this.COLORCURVES = false;
  100633. _this.COLORGRADING = false;
  100634. _this.COLORGRADING3D = false;
  100635. _this.SAMPLER3DGREENDEPTH = false;
  100636. _this.SAMPLER3DBGRMAP = false;
  100637. _this.IMAGEPROCESSINGPOSTPROCESS = false;
  100638. _this.EXPOSURE = false;
  100639. // Reflection.
  100640. _this.REFLECTION = false;
  100641. _this.REFLECTIONMAP_3D = false;
  100642. _this.REFLECTIONMAP_SPHERICAL = false;
  100643. _this.REFLECTIONMAP_PLANAR = false;
  100644. _this.REFLECTIONMAP_CUBIC = false;
  100645. _this.REFLECTIONMAP_PROJECTION = false;
  100646. _this.REFLECTIONMAP_SKYBOX = false;
  100647. _this.REFLECTIONMAP_EXPLICIT = false;
  100648. _this.REFLECTIONMAP_EQUIRECTANGULAR = false;
  100649. _this.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  100650. _this.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  100651. _this.INVERTCUBICMAP = false;
  100652. _this.REFLECTIONMAP_OPPOSITEZ = false;
  100653. _this.LODINREFLECTIONALPHA = false;
  100654. _this.GAMMAREFLECTION = false;
  100655. _this.RGBDREFLECTION = false;
  100656. _this.EQUIRECTANGULAR_RELFECTION_FOV = false;
  100657. // Default BJS.
  100658. _this.MAINUV1 = false;
  100659. _this.MAINUV2 = false;
  100660. _this.UV1 = false;
  100661. _this.UV2 = false;
  100662. _this.CLIPPLANE = false;
  100663. _this.POINTSIZE = false;
  100664. _this.FOG = false;
  100665. _this.NORMAL = false;
  100666. _this.NUM_BONE_INFLUENCERS = 0;
  100667. _this.BonesPerMesh = 0;
  100668. _this.INSTANCES = false;
  100669. _this.SHADOWFLOAT = false;
  100670. _this.rebuild();
  100671. return _this;
  100672. }
  100673. return BackgroundMaterialDefines;
  100674. }(BABYLON.MaterialDefines));
  100675. /**
  100676. * Background material used to create an efficient environement around your scene.
  100677. */
  100678. var BackgroundMaterial = /** @class */ (function (_super) {
  100679. __extends(BackgroundMaterial, _super);
  100680. /**
  100681. * Instantiates a Background Material in the given scene
  100682. * @param name The friendly name of the material
  100683. * @param scene The scene to add the material to
  100684. */
  100685. function BackgroundMaterial(name, scene) {
  100686. var _this = _super.call(this, name, scene) || this;
  100687. /**
  100688. * Key light Color (multiply against the environement texture)
  100689. */
  100690. _this.primaryColor = BABYLON.Color3.White();
  100691. _this._primaryColorShadowLevel = 0;
  100692. _this._primaryColorHighlightLevel = 0;
  100693. /**
  100694. * Reflection Texture used in the material.
  100695. * Should be author in a specific way for the best result (refer to the documentation).
  100696. */
  100697. _this.reflectionTexture = null;
  100698. /**
  100699. * Reflection Texture level of blur.
  100700. *
  100701. * Can be use to reuse an existing HDR Texture and target a specific LOD to prevent authoring the
  100702. * texture twice.
  100703. */
  100704. _this.reflectionBlur = 0;
  100705. /**
  100706. * Diffuse Texture used in the material.
  100707. * Should be author in a specific way for the best result (refer to the documentation).
  100708. */
  100709. _this.diffuseTexture = null;
  100710. _this._shadowLights = null;
  100711. /**
  100712. * Specify the list of lights casting shadow on the material.
  100713. * All scene shadow lights will be included if null.
  100714. */
  100715. _this.shadowLights = null;
  100716. /**
  100717. * Helps adjusting the shadow to a softer level if required.
  100718. * 0 means black shadows and 1 means no shadows.
  100719. */
  100720. _this.shadowLevel = 0;
  100721. /**
  100722. * In case of opacity Fresnel or reflection falloff, this is use as a scene center.
  100723. * It is usually zero but might be interesting to modify according to your setup.
  100724. */
  100725. _this.sceneCenter = BABYLON.Vector3.Zero();
  100726. /**
  100727. * This helps specifying that the material is falling off to the sky box at grazing angle.
  100728. * This helps ensuring a nice transition when the camera goes under the ground.
  100729. */
  100730. _this.opacityFresnel = true;
  100731. /**
  100732. * This helps specifying that the material is falling off from diffuse to the reflection texture at grazing angle.
  100733. * This helps adding a mirror texture on the ground.
  100734. */
  100735. _this.reflectionFresnel = false;
  100736. /**
  100737. * This helps specifying the falloff radius off the reflection texture from the sceneCenter.
  100738. * This helps adding a nice falloff effect to the reflection if used as a mirror for instance.
  100739. */
  100740. _this.reflectionFalloffDistance = 0.0;
  100741. /**
  100742. * This specifies the weight of the reflection against the background in case of reflection Fresnel.
  100743. */
  100744. _this.reflectionAmount = 1.0;
  100745. /**
  100746. * This specifies the weight of the reflection at grazing angle.
  100747. */
  100748. _this.reflectionReflectance0 = 0.05;
  100749. /**
  100750. * This specifies the weight of the reflection at a perpendicular point of view.
  100751. */
  100752. _this.reflectionReflectance90 = 0.5;
  100753. /**
  100754. * Helps to directly use the maps channels instead of their level.
  100755. */
  100756. _this.useRGBColor = true;
  100757. /**
  100758. * This helps reducing the banding effect that could occur on the background.
  100759. */
  100760. _this.enableNoise = false;
  100761. _this._fovMultiplier = 1.0;
  100762. /**
  100763. * Enable the FOV adjustment feature controlled by fovMultiplier.
  100764. */
  100765. _this.useEquirectangularFOV = false;
  100766. _this._maxSimultaneousLights = 4;
  100767. /**
  100768. * Number of Simultaneous lights allowed on the material.
  100769. */
  100770. _this.maxSimultaneousLights = 4;
  100771. /**
  100772. * Keep track of the image processing observer to allow dispose and replace.
  100773. */
  100774. _this._imageProcessingObserver = null;
  100775. /**
  100776. * Due to a bug in iOS10, video tags (which are using the background material) are in BGR and not RGB.
  100777. * Setting this flag to true (not done automatically!) will convert it back to RGB.
  100778. */
  100779. _this.switchToBGR = false;
  100780. // Temp values kept as cache in the material.
  100781. _this._renderTargets = new BABYLON.SmartArray(16);
  100782. _this._reflectionControls = BABYLON.Vector4.Zero();
  100783. _this._white = BABYLON.Color3.White();
  100784. _this._primaryShadowColor = BABYLON.Color3.Black();
  100785. _this._primaryHighlightColor = BABYLON.Color3.Black();
  100786. // Setup the default processing configuration to the scene.
  100787. _this._attachImageProcessingConfiguration(null);
  100788. _this.getRenderTargetTextures = function () {
  100789. _this._renderTargets.reset();
  100790. if (_this._diffuseTexture && _this._diffuseTexture.isRenderTarget) {
  100791. _this._renderTargets.push(_this._diffuseTexture);
  100792. }
  100793. if (_this._reflectionTexture && _this._reflectionTexture.isRenderTarget) {
  100794. _this._renderTargets.push(_this._reflectionTexture);
  100795. }
  100796. return _this._renderTargets;
  100797. };
  100798. return _this;
  100799. }
  100800. Object.defineProperty(BackgroundMaterial.prototype, "_perceptualColor", {
  100801. /**
  100802. * Experimental Internal Use Only.
  100803. *
  100804. * Key light Color in "perceptual value" meaning the color you would like to see on screen.
  100805. * This acts as a helper to set the primary color to a more "human friendly" value.
  100806. * Conversion to linear space as well as exposure and tone mapping correction will be applied to keep the
  100807. * output color as close as possible from the chosen value.
  100808. * (This does not account for contrast color grading and color curves as they are considered post effect and not directly
  100809. * part of lighting setup.)
  100810. */
  100811. get: function () {
  100812. return this.__perceptualColor;
  100813. },
  100814. set: function (value) {
  100815. this.__perceptualColor = value;
  100816. this._computePrimaryColorFromPerceptualColor();
  100817. this._markAllSubMeshesAsLightsDirty();
  100818. },
  100819. enumerable: true,
  100820. configurable: true
  100821. });
  100822. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorShadowLevel", {
  100823. /**
  100824. * Defines the level of the shadows (dark area of the reflection map) in order to help scaling the colors.
  100825. * The color opposite to the primary color is used at the level chosen to define what the black area would look.
  100826. */
  100827. get: function () {
  100828. return this._primaryColorShadowLevel;
  100829. },
  100830. set: function (value) {
  100831. this._primaryColorShadowLevel = value;
  100832. this._computePrimaryColors();
  100833. this._markAllSubMeshesAsLightsDirty();
  100834. },
  100835. enumerable: true,
  100836. configurable: true
  100837. });
  100838. Object.defineProperty(BackgroundMaterial.prototype, "primaryColorHighlightLevel", {
  100839. /**
  100840. * Defines the level of the highliights (highlight area of the reflection map) in order to help scaling the colors.
  100841. * The primary color is used at the level chosen to define what the white area would look.
  100842. */
  100843. get: function () {
  100844. return this._primaryColorHighlightLevel;
  100845. },
  100846. set: function (value) {
  100847. this._primaryColorHighlightLevel = value;
  100848. this._computePrimaryColors();
  100849. this._markAllSubMeshesAsLightsDirty();
  100850. },
  100851. enumerable: true,
  100852. configurable: true
  100853. });
  100854. Object.defineProperty(BackgroundMaterial.prototype, "reflectionStandardFresnelWeight", {
  100855. /**
  100856. * Sets the reflection reflectance fresnel values according to the default standard
  100857. * empirically know to work well :-)
  100858. */
  100859. set: function (value) {
  100860. var reflectionWeight = value;
  100861. if (reflectionWeight < 0.5) {
  100862. reflectionWeight = reflectionWeight * 2.0;
  100863. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 * reflectionWeight;
  100864. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 * reflectionWeight;
  100865. }
  100866. else {
  100867. reflectionWeight = reflectionWeight * 2.0 - 1.0;
  100868. this.reflectionReflectance0 = BackgroundMaterial.StandardReflectance0 + (1.0 - BackgroundMaterial.StandardReflectance0) * reflectionWeight;
  100869. this.reflectionReflectance90 = BackgroundMaterial.StandardReflectance90 + (1.0 - BackgroundMaterial.StandardReflectance90) * reflectionWeight;
  100870. }
  100871. },
  100872. enumerable: true,
  100873. configurable: true
  100874. });
  100875. Object.defineProperty(BackgroundMaterial.prototype, "fovMultiplier", {
  100876. /**
  100877. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  100878. * Best used when trying to implement visual zoom effects like fish-eye or binoculars while not adjusting camera fov.
  100879. * Recommended to be keep at 1.0 except for special cases.
  100880. */
  100881. get: function () {
  100882. return this._fovMultiplier;
  100883. },
  100884. set: function (value) {
  100885. if (isNaN(value)) {
  100886. value = 1.0;
  100887. }
  100888. this._fovMultiplier = Math.max(0.0, Math.min(2.0, value));
  100889. },
  100890. enumerable: true,
  100891. configurable: true
  100892. });
  100893. /**
  100894. * Attaches a new image processing configuration to the PBR Material.
  100895. * @param configuration (if null the scene configuration will be use)
  100896. */
  100897. BackgroundMaterial.prototype._attachImageProcessingConfiguration = function (configuration) {
  100898. var _this = this;
  100899. if (configuration === this._imageProcessingConfiguration) {
  100900. return;
  100901. }
  100902. // Detaches observer.
  100903. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  100904. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  100905. }
  100906. // Pick the scene configuration if needed.
  100907. if (!configuration) {
  100908. this._imageProcessingConfiguration = this.getScene().imageProcessingConfiguration;
  100909. }
  100910. else {
  100911. this._imageProcessingConfiguration = configuration;
  100912. }
  100913. // Attaches observer.
  100914. if (this._imageProcessingConfiguration) {
  100915. this._imageProcessingObserver = this._imageProcessingConfiguration.onUpdateParameters.add(function (conf) {
  100916. _this._computePrimaryColorFromPerceptualColor();
  100917. _this._markAllSubMeshesAsImageProcessingDirty();
  100918. });
  100919. }
  100920. };
  100921. Object.defineProperty(BackgroundMaterial.prototype, "imageProcessingConfiguration", {
  100922. /**
  100923. * Gets the image processing configuration used either in this material.
  100924. */
  100925. get: function () {
  100926. return this._imageProcessingConfiguration;
  100927. },
  100928. /**
  100929. * Sets the Default image processing configuration used either in the this material.
  100930. *
  100931. * If sets to null, the scene one is in use.
  100932. */
  100933. set: function (value) {
  100934. this._attachImageProcessingConfiguration(value);
  100935. // Ensure the effect will be rebuilt.
  100936. this._markAllSubMeshesAsTexturesDirty();
  100937. },
  100938. enumerable: true,
  100939. configurable: true
  100940. });
  100941. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurvesEnabled", {
  100942. /**
  100943. * Gets wether the color curves effect is enabled.
  100944. */
  100945. get: function () {
  100946. return this.imageProcessingConfiguration.colorCurvesEnabled;
  100947. },
  100948. /**
  100949. * Sets wether the color curves effect is enabled.
  100950. */
  100951. set: function (value) {
  100952. this.imageProcessingConfiguration.colorCurvesEnabled = value;
  100953. },
  100954. enumerable: true,
  100955. configurable: true
  100956. });
  100957. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingEnabled", {
  100958. /**
  100959. * Gets wether the color grading effect is enabled.
  100960. */
  100961. get: function () {
  100962. return this.imageProcessingConfiguration.colorGradingEnabled;
  100963. },
  100964. /**
  100965. * Gets wether the color grading effect is enabled.
  100966. */
  100967. set: function (value) {
  100968. this.imageProcessingConfiguration.colorGradingEnabled = value;
  100969. },
  100970. enumerable: true,
  100971. configurable: true
  100972. });
  100973. Object.defineProperty(BackgroundMaterial.prototype, "cameraToneMappingEnabled", {
  100974. /**
  100975. * Gets wether tonemapping is enabled or not.
  100976. */
  100977. get: function () {
  100978. return this._imageProcessingConfiguration.toneMappingEnabled;
  100979. },
  100980. /**
  100981. * Sets wether tonemapping is enabled or not
  100982. */
  100983. set: function (value) {
  100984. this._imageProcessingConfiguration.toneMappingEnabled = value;
  100985. },
  100986. enumerable: true,
  100987. configurable: true
  100988. });
  100989. ;
  100990. ;
  100991. Object.defineProperty(BackgroundMaterial.prototype, "cameraExposure", {
  100992. /**
  100993. * The camera exposure used on this material.
  100994. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  100995. * This corresponds to a photographic exposure.
  100996. */
  100997. get: function () {
  100998. return this._imageProcessingConfiguration.exposure;
  100999. },
  101000. /**
  101001. * The camera exposure used on this material.
  101002. * This property is here and not in the camera to allow controlling exposure without full screen post process.
  101003. * This corresponds to a photographic exposure.
  101004. */
  101005. set: function (value) {
  101006. this._imageProcessingConfiguration.exposure = value;
  101007. },
  101008. enumerable: true,
  101009. configurable: true
  101010. });
  101011. ;
  101012. ;
  101013. Object.defineProperty(BackgroundMaterial.prototype, "cameraContrast", {
  101014. /**
  101015. * Gets The camera contrast used on this material.
  101016. */
  101017. get: function () {
  101018. return this._imageProcessingConfiguration.contrast;
  101019. },
  101020. /**
  101021. * Sets The camera contrast used on this material.
  101022. */
  101023. set: function (value) {
  101024. this._imageProcessingConfiguration.contrast = value;
  101025. },
  101026. enumerable: true,
  101027. configurable: true
  101028. });
  101029. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorGradingTexture", {
  101030. /**
  101031. * Gets the Color Grading 2D Lookup Texture.
  101032. */
  101033. get: function () {
  101034. return this._imageProcessingConfiguration.colorGradingTexture;
  101035. },
  101036. /**
  101037. * Sets the Color Grading 2D Lookup Texture.
  101038. */
  101039. set: function (value) {
  101040. this.imageProcessingConfiguration.colorGradingTexture = value;
  101041. },
  101042. enumerable: true,
  101043. configurable: true
  101044. });
  101045. Object.defineProperty(BackgroundMaterial.prototype, "cameraColorCurves", {
  101046. /**
  101047. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101048. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101049. * 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;
  101050. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101051. */
  101052. get: function () {
  101053. return this.imageProcessingConfiguration.colorCurves;
  101054. },
  101055. /**
  101056. * The color grading curves provide additional color adjustmnent that is applied after any color grading transform (3D LUT).
  101057. * They allow basic adjustment of saturation and small exposure adjustments, along with color filter tinting to provide white balance adjustment or more stylistic effects.
  101058. * 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;
  101059. * corresponding to low luminance, medium luminance, and high luminance areas respectively.
  101060. */
  101061. set: function (value) {
  101062. this.imageProcessingConfiguration.colorCurves = value;
  101063. },
  101064. enumerable: true,
  101065. configurable: true
  101066. });
  101067. /**
  101068. * The entire material has been created in order to prevent overdraw.
  101069. * @returns false
  101070. */
  101071. BackgroundMaterial.prototype.needAlphaTesting = function () {
  101072. return true;
  101073. };
  101074. /**
  101075. * The entire material has been created in order to prevent overdraw.
  101076. * @returns true if blending is enable
  101077. */
  101078. BackgroundMaterial.prototype.needAlphaBlending = function () {
  101079. return ((this.alpha < 0) || (this._diffuseTexture != null && this._diffuseTexture.hasAlpha));
  101080. };
  101081. /**
  101082. * Checks wether the material is ready to be rendered for a given mesh.
  101083. * @param mesh The mesh to render
  101084. * @param subMesh The submesh to check against
  101085. * @param useInstances Specify wether or not the material is used with instances
  101086. * @returns true if all the dependencies are ready (Textures, Effects...)
  101087. */
  101088. BackgroundMaterial.prototype.isReadyForSubMesh = function (mesh, subMesh, useInstances) {
  101089. var _this = this;
  101090. if (useInstances === void 0) { useInstances = false; }
  101091. if (subMesh.effect && this.isFrozen) {
  101092. if (this._wasPreviouslyReady) {
  101093. return true;
  101094. }
  101095. }
  101096. if (!subMesh._materialDefines) {
  101097. subMesh._materialDefines = new BackgroundMaterialDefines();
  101098. }
  101099. var scene = this.getScene();
  101100. var defines = subMesh._materialDefines;
  101101. if (!this.checkReadyOnEveryCall && subMesh.effect) {
  101102. if (defines._renderId === scene.getRenderId()) {
  101103. return true;
  101104. }
  101105. }
  101106. var engine = scene.getEngine();
  101107. // Lights
  101108. BABYLON.MaterialHelper.PrepareDefinesForLights(scene, mesh, defines, false, this._maxSimultaneousLights);
  101109. defines._needNormals = true;
  101110. // Textures
  101111. if (defines._areTexturesDirty) {
  101112. defines._needUVs = false;
  101113. if (scene.texturesEnabled) {
  101114. if (scene.getEngine().getCaps().textureLOD) {
  101115. defines.TEXTURELODSUPPORT = true;
  101116. }
  101117. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101118. if (!this._diffuseTexture.isReadyOrNotBlocking()) {
  101119. return false;
  101120. }
  101121. BABYLON.MaterialHelper.PrepareDefinesForMergedUV(this._diffuseTexture, defines, "DIFFUSE");
  101122. defines.DIFFUSEHASALPHA = this._diffuseTexture.hasAlpha;
  101123. defines.GAMMADIFFUSE = this._diffuseTexture.gammaSpace;
  101124. defines.OPACITYFRESNEL = this._opacityFresnel;
  101125. }
  101126. else {
  101127. defines.DIFFUSE = false;
  101128. defines.DIFFUSEHASALPHA = false;
  101129. defines.GAMMADIFFUSE = false;
  101130. defines.OPACITYFRESNEL = false;
  101131. }
  101132. var reflectionTexture = this._reflectionTexture;
  101133. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101134. if (!reflectionTexture.isReadyOrNotBlocking()) {
  101135. return false;
  101136. }
  101137. defines.REFLECTION = true;
  101138. defines.GAMMAREFLECTION = reflectionTexture.gammaSpace;
  101139. defines.RGBDREFLECTION = reflectionTexture.isRGBD;
  101140. defines.REFLECTIONBLUR = this._reflectionBlur > 0;
  101141. defines.REFLECTIONMAP_OPPOSITEZ = this.getScene().useRightHandedSystem ? !reflectionTexture.invertZ : reflectionTexture.invertZ;
  101142. defines.LODINREFLECTIONALPHA = reflectionTexture.lodLevelInAlpha;
  101143. defines.EQUIRECTANGULAR_RELFECTION_FOV = this.useEquirectangularFOV;
  101144. defines.REFLECTIONBGR = this.switchToBGR;
  101145. if (reflectionTexture.coordinatesMode === BABYLON.Texture.INVCUBIC_MODE) {
  101146. defines.INVERTCUBICMAP = true;
  101147. }
  101148. defines.REFLECTIONMAP_3D = reflectionTexture.isCube;
  101149. switch (reflectionTexture.coordinatesMode) {
  101150. case BABYLON.Texture.EXPLICIT_MODE:
  101151. defines.REFLECTIONMAP_EXPLICIT = true;
  101152. break;
  101153. case BABYLON.Texture.PLANAR_MODE:
  101154. defines.REFLECTIONMAP_PLANAR = true;
  101155. break;
  101156. case BABYLON.Texture.PROJECTION_MODE:
  101157. defines.REFLECTIONMAP_PROJECTION = true;
  101158. break;
  101159. case BABYLON.Texture.SKYBOX_MODE:
  101160. defines.REFLECTIONMAP_SKYBOX = true;
  101161. break;
  101162. case BABYLON.Texture.SPHERICAL_MODE:
  101163. defines.REFLECTIONMAP_SPHERICAL = true;
  101164. break;
  101165. case BABYLON.Texture.EQUIRECTANGULAR_MODE:
  101166. defines.REFLECTIONMAP_EQUIRECTANGULAR = true;
  101167. break;
  101168. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MODE:
  101169. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = true;
  101170. break;
  101171. case BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE:
  101172. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = true;
  101173. break;
  101174. case BABYLON.Texture.CUBIC_MODE:
  101175. case BABYLON.Texture.INVCUBIC_MODE:
  101176. default:
  101177. defines.REFLECTIONMAP_CUBIC = true;
  101178. break;
  101179. }
  101180. if (this.reflectionFresnel) {
  101181. defines.REFLECTIONFRESNEL = true;
  101182. defines.REFLECTIONFALLOFF = this.reflectionFalloffDistance > 0;
  101183. this._reflectionControls.x = this.reflectionAmount;
  101184. this._reflectionControls.y = this.reflectionReflectance0;
  101185. this._reflectionControls.z = this.reflectionReflectance90;
  101186. this._reflectionControls.w = 1 / this.reflectionFalloffDistance;
  101187. }
  101188. else {
  101189. defines.REFLECTIONFRESNEL = false;
  101190. defines.REFLECTIONFALLOFF = false;
  101191. }
  101192. }
  101193. else {
  101194. defines.REFLECTION = false;
  101195. defines.REFLECTIONFRESNEL = false;
  101196. defines.REFLECTIONFALLOFF = false;
  101197. defines.REFLECTIONBLUR = false;
  101198. defines.REFLECTIONMAP_3D = false;
  101199. defines.REFLECTIONMAP_SPHERICAL = false;
  101200. defines.REFLECTIONMAP_PLANAR = false;
  101201. defines.REFLECTIONMAP_CUBIC = false;
  101202. defines.REFLECTIONMAP_PROJECTION = false;
  101203. defines.REFLECTIONMAP_SKYBOX = false;
  101204. defines.REFLECTIONMAP_EXPLICIT = false;
  101205. defines.REFLECTIONMAP_EQUIRECTANGULAR = false;
  101206. defines.REFLECTIONMAP_EQUIRECTANGULAR_FIXED = false;
  101207. defines.REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED = false;
  101208. defines.INVERTCUBICMAP = false;
  101209. defines.REFLECTIONMAP_OPPOSITEZ = false;
  101210. defines.LODINREFLECTIONALPHA = false;
  101211. defines.GAMMAREFLECTION = false;
  101212. defines.RGBDREFLECTION = false;
  101213. }
  101214. }
  101215. defines.PREMULTIPLYALPHA = (this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED || this.alphaMode === BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF);
  101216. defines.USERGBCOLOR = this._useRGBColor;
  101217. defines.NOISE = this._enableNoise;
  101218. }
  101219. if (defines._areLightsDirty) {
  101220. defines.USEHIGHLIGHTANDSHADOWCOLORS = !this._useRGBColor && (this._primaryColorShadowLevel !== 0 || this._primaryColorHighlightLevel !== 0);
  101221. }
  101222. if (defines._areImageProcessingDirty && this._imageProcessingConfiguration) {
  101223. if (!this._imageProcessingConfiguration.isReady()) {
  101224. return false;
  101225. }
  101226. this._imageProcessingConfiguration.prepareDefines(defines);
  101227. }
  101228. // Misc.
  101229. BABYLON.MaterialHelper.PrepareDefinesForMisc(mesh, scene, false, this.pointsCloud, this.fogEnabled, this._shouldTurnAlphaTestOn(mesh), defines);
  101230. // Values that need to be evaluated on every frame
  101231. BABYLON.MaterialHelper.PrepareDefinesForFrameBoundValues(scene, engine, defines, useInstances);
  101232. // Attribs
  101233. if (BABYLON.MaterialHelper.PrepareDefinesForAttributes(mesh, defines, false, true, false)) {
  101234. if (mesh) {
  101235. if (!scene.getEngine().getCaps().standardDerivatives && !mesh.isVerticesDataPresent(BABYLON.VertexBuffer.NormalKind)) {
  101236. mesh.createNormals(true);
  101237. BABYLON.Tools.Warn("BackgroundMaterial: Normals have been created for the mesh: " + mesh.name);
  101238. }
  101239. }
  101240. }
  101241. // Get correct effect
  101242. if (defines.isDirty) {
  101243. defines.markAsProcessed();
  101244. scene.resetCachedMaterial();
  101245. // Fallbacks
  101246. var fallbacks = new BABYLON.EffectFallbacks();
  101247. if (defines.FOG) {
  101248. fallbacks.addFallback(0, "FOG");
  101249. }
  101250. if (defines.POINTSIZE) {
  101251. fallbacks.addFallback(1, "POINTSIZE");
  101252. }
  101253. BABYLON.MaterialHelper.HandleFallbacksForShadows(defines, fallbacks, this._maxSimultaneousLights);
  101254. if (defines.NUM_BONE_INFLUENCERS > 0) {
  101255. fallbacks.addCPUSkinningFallback(0, mesh);
  101256. }
  101257. //Attributes
  101258. var attribs = [BABYLON.VertexBuffer.PositionKind];
  101259. if (defines.NORMAL) {
  101260. attribs.push(BABYLON.VertexBuffer.NormalKind);
  101261. }
  101262. if (defines.UV1) {
  101263. attribs.push(BABYLON.VertexBuffer.UVKind);
  101264. }
  101265. if (defines.UV2) {
  101266. attribs.push(BABYLON.VertexBuffer.UV2Kind);
  101267. }
  101268. BABYLON.MaterialHelper.PrepareAttributesForBones(attribs, mesh, defines, fallbacks);
  101269. BABYLON.MaterialHelper.PrepareAttributesForInstances(attribs, defines);
  101270. var uniforms = ["world", "view", "viewProjection", "vEyePosition", "vLightsType",
  101271. "vFogInfos", "vFogColor", "pointSize",
  101272. "vClipPlane", "mBones",
  101273. "vPrimaryColor", "vPrimaryColorShadow",
  101274. "vReflectionInfos", "reflectionMatrix", "vReflectionMicrosurfaceInfos", "fFovMultiplier",
  101275. "shadowLevel", "alpha",
  101276. "vBackgroundCenter", "vReflectionControl",
  101277. "vDiffuseInfos", "diffuseMatrix",
  101278. ];
  101279. var samplers = ["diffuseSampler", "reflectionSampler", "reflectionSamplerLow", "reflectionSamplerHigh"];
  101280. var uniformBuffers = ["Material", "Scene"];
  101281. if (BABYLON.ImageProcessingConfiguration) {
  101282. BABYLON.ImageProcessingConfiguration.PrepareUniforms(uniforms, defines);
  101283. BABYLON.ImageProcessingConfiguration.PrepareSamplers(samplers, defines);
  101284. }
  101285. BABYLON.MaterialHelper.PrepareUniformsAndSamplersList({
  101286. uniformsNames: uniforms,
  101287. uniformBuffersNames: uniformBuffers,
  101288. samplers: samplers,
  101289. defines: defines,
  101290. maxSimultaneousLights: this._maxSimultaneousLights
  101291. });
  101292. var onCompiled = function (effect) {
  101293. if (_this.onCompiled) {
  101294. _this.onCompiled(effect);
  101295. }
  101296. _this.bindSceneUniformBuffer(effect, scene.getSceneUniformBuffer());
  101297. };
  101298. var join = defines.toString();
  101299. subMesh.setEffect(scene.getEngine().createEffect("background", {
  101300. attributes: attribs,
  101301. uniformsNames: uniforms,
  101302. uniformBuffersNames: uniformBuffers,
  101303. samplers: samplers,
  101304. defines: join,
  101305. fallbacks: fallbacks,
  101306. onCompiled: onCompiled,
  101307. onError: this.onError,
  101308. indexParameters: { maxSimultaneousLights: this._maxSimultaneousLights }
  101309. }, engine), defines);
  101310. this.buildUniformLayout();
  101311. }
  101312. if (!subMesh.effect || !subMesh.effect.isReady()) {
  101313. return false;
  101314. }
  101315. defines._renderId = scene.getRenderId();
  101316. this._wasPreviouslyReady = true;
  101317. return true;
  101318. };
  101319. /**
  101320. * Compute the primary color according to the chosen perceptual color.
  101321. */
  101322. BackgroundMaterial.prototype._computePrimaryColorFromPerceptualColor = function () {
  101323. if (!this.__perceptualColor) {
  101324. return;
  101325. }
  101326. this._primaryColor.copyFrom(this.__perceptualColor);
  101327. // Revert gamma space.
  101328. this._primaryColor.toLinearSpaceToRef(this._primaryColor);
  101329. // Revert image processing configuration.
  101330. if (this._imageProcessingConfiguration) {
  101331. // Revert Exposure.
  101332. this._primaryColor.scaleToRef(1 / this._imageProcessingConfiguration.exposure, this._primaryColor);
  101333. }
  101334. this._computePrimaryColors();
  101335. };
  101336. /**
  101337. * Compute the highlights and shadow colors according to their chosen levels.
  101338. */
  101339. BackgroundMaterial.prototype._computePrimaryColors = function () {
  101340. if (this._primaryColorShadowLevel === 0 && this._primaryColorHighlightLevel === 0) {
  101341. return;
  101342. }
  101343. // Find the highlight color based on the configuration.
  101344. this._primaryColor.scaleToRef(this._primaryColorShadowLevel, this._primaryShadowColor);
  101345. this._primaryColor.subtractToRef(this._primaryShadowColor, this._primaryShadowColor);
  101346. // Find the shadow color based on the configuration.
  101347. this._white.subtractToRef(this._primaryColor, this._primaryHighlightColor);
  101348. this._primaryHighlightColor.scaleToRef(this._primaryColorHighlightLevel, this._primaryHighlightColor);
  101349. this._primaryColor.addToRef(this._primaryHighlightColor, this._primaryHighlightColor);
  101350. };
  101351. /**
  101352. * Build the uniform buffer used in the material.
  101353. */
  101354. BackgroundMaterial.prototype.buildUniformLayout = function () {
  101355. // Order is important !
  101356. this._uniformBuffer.addUniform("vPrimaryColor", 4);
  101357. this._uniformBuffer.addUniform("vPrimaryColorShadow", 4);
  101358. this._uniformBuffer.addUniform("vDiffuseInfos", 2);
  101359. this._uniformBuffer.addUniform("vReflectionInfos", 2);
  101360. this._uniformBuffer.addUniform("diffuseMatrix", 16);
  101361. this._uniformBuffer.addUniform("reflectionMatrix", 16);
  101362. this._uniformBuffer.addUniform("vReflectionMicrosurfaceInfos", 3);
  101363. this._uniformBuffer.addUniform("fFovMultiplier", 1);
  101364. this._uniformBuffer.addUniform("pointSize", 1);
  101365. this._uniformBuffer.addUniform("shadowLevel", 1);
  101366. this._uniformBuffer.addUniform("alpha", 1);
  101367. this._uniformBuffer.addUniform("vBackgroundCenter", 3);
  101368. this._uniformBuffer.addUniform("vReflectionControl", 4);
  101369. this._uniformBuffer.create();
  101370. };
  101371. /**
  101372. * Unbind the material.
  101373. */
  101374. BackgroundMaterial.prototype.unbind = function () {
  101375. if (this._diffuseTexture && this._diffuseTexture.isRenderTarget) {
  101376. this._uniformBuffer.setTexture("diffuseSampler", null);
  101377. }
  101378. if (this._reflectionTexture && this._reflectionTexture.isRenderTarget) {
  101379. this._uniformBuffer.setTexture("reflectionSampler", null);
  101380. }
  101381. _super.prototype.unbind.call(this);
  101382. };
  101383. /**
  101384. * Bind only the world matrix to the material.
  101385. * @param world The world matrix to bind.
  101386. */
  101387. BackgroundMaterial.prototype.bindOnlyWorldMatrix = function (world) {
  101388. this._activeEffect.setMatrix("world", world);
  101389. };
  101390. /**
  101391. * Bind the material for a dedicated submeh (every used meshes will be considered opaque).
  101392. * @param world The world matrix to bind.
  101393. * @param subMesh The submesh to bind for.
  101394. */
  101395. BackgroundMaterial.prototype.bindForSubMesh = function (world, mesh, subMesh) {
  101396. var scene = this.getScene();
  101397. var defines = subMesh._materialDefines;
  101398. if (!defines) {
  101399. return;
  101400. }
  101401. var effect = subMesh.effect;
  101402. if (!effect) {
  101403. return;
  101404. }
  101405. this._activeEffect = effect;
  101406. // Matrices
  101407. this.bindOnlyWorldMatrix(world);
  101408. // Bones
  101409. BABYLON.MaterialHelper.BindBonesParameters(mesh, this._activeEffect);
  101410. var mustRebind = this._mustRebind(scene, effect, mesh.visibility);
  101411. if (mustRebind) {
  101412. this._uniformBuffer.bindToEffect(effect, "Material");
  101413. this.bindViewProjection(effect);
  101414. var reflectionTexture = this._reflectionTexture;
  101415. if (!this._uniformBuffer.useUbo || !this.isFrozen || !this._uniformBuffer.isSync) {
  101416. // Texture uniforms
  101417. if (scene.texturesEnabled) {
  101418. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101419. this._uniformBuffer.updateFloat2("vDiffuseInfos", this._diffuseTexture.coordinatesIndex, this._diffuseTexture.level);
  101420. BABYLON.MaterialHelper.BindTextureMatrix(this._diffuseTexture, this._uniformBuffer, "diffuse");
  101421. }
  101422. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101423. this._uniformBuffer.updateMatrix("reflectionMatrix", reflectionTexture.getReflectionTextureMatrix());
  101424. this._uniformBuffer.updateFloat2("vReflectionInfos", reflectionTexture.level, this._reflectionBlur);
  101425. this._uniformBuffer.updateFloat3("vReflectionMicrosurfaceInfos", reflectionTexture.getSize().width, reflectionTexture.lodGenerationScale, reflectionTexture.lodGenerationOffset);
  101426. }
  101427. }
  101428. if (this.shadowLevel > 0) {
  101429. this._uniformBuffer.updateFloat("shadowLevel", this.shadowLevel);
  101430. }
  101431. this._uniformBuffer.updateFloat("alpha", this.alpha);
  101432. // Point size
  101433. if (this.pointsCloud) {
  101434. this._uniformBuffer.updateFloat("pointSize", this.pointSize);
  101435. }
  101436. if (defines.USEHIGHLIGHTANDSHADOWCOLORS) {
  101437. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryHighlightColor, 1.0);
  101438. this._uniformBuffer.updateColor4("vPrimaryColorShadow", this._primaryShadowColor, 1.0);
  101439. }
  101440. else {
  101441. this._uniformBuffer.updateColor4("vPrimaryColor", this._primaryColor, 1.0);
  101442. }
  101443. }
  101444. this._uniformBuffer.updateFloat("fFovMultiplier", this._fovMultiplier);
  101445. // Textures
  101446. if (scene.texturesEnabled) {
  101447. if (this._diffuseTexture && BABYLON.StandardMaterial.DiffuseTextureEnabled) {
  101448. this._uniformBuffer.setTexture("diffuseSampler", this._diffuseTexture);
  101449. }
  101450. if (reflectionTexture && BABYLON.StandardMaterial.ReflectionTextureEnabled) {
  101451. if (defines.REFLECTIONBLUR && defines.TEXTURELODSUPPORT) {
  101452. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101453. }
  101454. else if (!defines.REFLECTIONBLUR) {
  101455. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture);
  101456. }
  101457. else {
  101458. this._uniformBuffer.setTexture("reflectionSampler", reflectionTexture._lodTextureMid || reflectionTexture);
  101459. this._uniformBuffer.setTexture("reflectionSamplerLow", reflectionTexture._lodTextureLow || reflectionTexture);
  101460. this._uniformBuffer.setTexture("reflectionSamplerHigh", reflectionTexture._lodTextureHigh || reflectionTexture);
  101461. }
  101462. if (defines.REFLECTIONFRESNEL) {
  101463. this._uniformBuffer.updateFloat3("vBackgroundCenter", this.sceneCenter.x, this.sceneCenter.y, this.sceneCenter.z);
  101464. this._uniformBuffer.updateFloat4("vReflectionControl", this._reflectionControls.x, this._reflectionControls.y, this._reflectionControls.z, this._reflectionControls.w);
  101465. }
  101466. }
  101467. }
  101468. // Clip plane
  101469. BABYLON.MaterialHelper.BindClipPlane(this._activeEffect, scene);
  101470. BABYLON.MaterialHelper.BindEyePosition(effect, scene);
  101471. }
  101472. if (mustRebind || !this.isFrozen) {
  101473. if (scene.lightsEnabled) {
  101474. BABYLON.MaterialHelper.BindLights(scene, mesh, this._activeEffect, defines, this._maxSimultaneousLights, false);
  101475. }
  101476. // View
  101477. this.bindView(effect);
  101478. // Fog
  101479. BABYLON.MaterialHelper.BindFogParameters(scene, mesh, this._activeEffect);
  101480. // image processing
  101481. if (this._imageProcessingConfiguration) {
  101482. this._imageProcessingConfiguration.bind(this._activeEffect);
  101483. }
  101484. }
  101485. this._uniformBuffer.update();
  101486. this._afterBind(mesh, this._activeEffect);
  101487. };
  101488. /**
  101489. * Dispose the material.
  101490. * @param forceDisposeEffect Force disposal of the associated effect.
  101491. * @param forceDisposeTextures Force disposal of the associated textures.
  101492. */
  101493. BackgroundMaterial.prototype.dispose = function (forceDisposeEffect, forceDisposeTextures) {
  101494. if (forceDisposeEffect === void 0) { forceDisposeEffect = false; }
  101495. if (forceDisposeTextures === void 0) { forceDisposeTextures = false; }
  101496. if (forceDisposeTextures) {
  101497. if (this.diffuseTexture) {
  101498. this.diffuseTexture.dispose();
  101499. }
  101500. if (this.reflectionTexture) {
  101501. this.reflectionTexture.dispose();
  101502. }
  101503. }
  101504. this._renderTargets.dispose();
  101505. if (this._imageProcessingConfiguration && this._imageProcessingObserver) {
  101506. this._imageProcessingConfiguration.onUpdateParameters.remove(this._imageProcessingObserver);
  101507. }
  101508. _super.prototype.dispose.call(this, forceDisposeEffect);
  101509. };
  101510. /**
  101511. * Clones the material.
  101512. * @param name The cloned name.
  101513. * @returns The cloned material.
  101514. */
  101515. BackgroundMaterial.prototype.clone = function (name) {
  101516. var _this = this;
  101517. return BABYLON.SerializationHelper.Clone(function () { return new BackgroundMaterial(name, _this.getScene()); }, this);
  101518. };
  101519. /**
  101520. * Serializes the current material to its JSON representation.
  101521. * @returns The JSON representation.
  101522. */
  101523. BackgroundMaterial.prototype.serialize = function () {
  101524. var serializationObject = BABYLON.SerializationHelper.Serialize(this);
  101525. serializationObject.customType = "BABYLON.BackgroundMaterial";
  101526. return serializationObject;
  101527. };
  101528. /**
  101529. * Gets the class name of the material
  101530. * @returns "BackgroundMaterial"
  101531. */
  101532. BackgroundMaterial.prototype.getClassName = function () {
  101533. return "BackgroundMaterial";
  101534. };
  101535. /**
  101536. * Parse a JSON input to create back a background material.
  101537. * @param source The JSON data to parse
  101538. * @param scene The scene to create the parsed material in
  101539. * @param rootUrl The root url of the assets the material depends upon
  101540. * @returns the instantiated BackgroundMaterial.
  101541. */
  101542. BackgroundMaterial.Parse = function (source, scene, rootUrl) {
  101543. return BABYLON.SerializationHelper.Parse(function () { return new BackgroundMaterial(source.name, scene); }, source, scene, rootUrl);
  101544. };
  101545. /**
  101546. * Standard reflectance value at parallel view angle.
  101547. */
  101548. BackgroundMaterial.StandardReflectance0 = 0.05;
  101549. /**
  101550. * Standard reflectance value at grazing angle.
  101551. */
  101552. BackgroundMaterial.StandardReflectance90 = 0.5;
  101553. __decorate([
  101554. BABYLON.serializeAsColor3()
  101555. ], BackgroundMaterial.prototype, "_primaryColor", void 0);
  101556. __decorate([
  101557. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101558. ], BackgroundMaterial.prototype, "primaryColor", void 0);
  101559. __decorate([
  101560. BABYLON.serializeAsColor3()
  101561. ], BackgroundMaterial.prototype, "__perceptualColor", void 0);
  101562. __decorate([
  101563. BABYLON.serialize()
  101564. ], BackgroundMaterial.prototype, "_primaryColorShadowLevel", void 0);
  101565. __decorate([
  101566. BABYLON.serialize()
  101567. ], BackgroundMaterial.prototype, "_primaryColorHighlightLevel", void 0);
  101568. __decorate([
  101569. BABYLON.expandToProperty("_markAllSubMeshesAsLightsDirty")
  101570. ], BackgroundMaterial.prototype, "primaryColorHighlightLevel", null);
  101571. __decorate([
  101572. BABYLON.serializeAsTexture()
  101573. ], BackgroundMaterial.prototype, "_reflectionTexture", void 0);
  101574. __decorate([
  101575. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101576. ], BackgroundMaterial.prototype, "reflectionTexture", void 0);
  101577. __decorate([
  101578. BABYLON.serialize()
  101579. ], BackgroundMaterial.prototype, "_reflectionBlur", void 0);
  101580. __decorate([
  101581. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101582. ], BackgroundMaterial.prototype, "reflectionBlur", void 0);
  101583. __decorate([
  101584. BABYLON.serializeAsTexture()
  101585. ], BackgroundMaterial.prototype, "_diffuseTexture", void 0);
  101586. __decorate([
  101587. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101588. ], BackgroundMaterial.prototype, "diffuseTexture", void 0);
  101589. __decorate([
  101590. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101591. ], BackgroundMaterial.prototype, "shadowLights", void 0);
  101592. __decorate([
  101593. BABYLON.serialize()
  101594. ], BackgroundMaterial.prototype, "_shadowLevel", void 0);
  101595. __decorate([
  101596. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101597. ], BackgroundMaterial.prototype, "shadowLevel", void 0);
  101598. __decorate([
  101599. BABYLON.serializeAsVector3()
  101600. ], BackgroundMaterial.prototype, "_sceneCenter", void 0);
  101601. __decorate([
  101602. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101603. ], BackgroundMaterial.prototype, "sceneCenter", void 0);
  101604. __decorate([
  101605. BABYLON.serialize()
  101606. ], BackgroundMaterial.prototype, "_opacityFresnel", void 0);
  101607. __decorate([
  101608. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101609. ], BackgroundMaterial.prototype, "opacityFresnel", void 0);
  101610. __decorate([
  101611. BABYLON.serialize()
  101612. ], BackgroundMaterial.prototype, "_reflectionFresnel", void 0);
  101613. __decorate([
  101614. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101615. ], BackgroundMaterial.prototype, "reflectionFresnel", void 0);
  101616. __decorate([
  101617. BABYLON.serialize()
  101618. ], BackgroundMaterial.prototype, "_reflectionFalloffDistance", void 0);
  101619. __decorate([
  101620. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101621. ], BackgroundMaterial.prototype, "reflectionFalloffDistance", void 0);
  101622. __decorate([
  101623. BABYLON.serialize()
  101624. ], BackgroundMaterial.prototype, "_reflectionAmount", void 0);
  101625. __decorate([
  101626. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101627. ], BackgroundMaterial.prototype, "reflectionAmount", void 0);
  101628. __decorate([
  101629. BABYLON.serialize()
  101630. ], BackgroundMaterial.prototype, "_reflectionReflectance0", void 0);
  101631. __decorate([
  101632. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101633. ], BackgroundMaterial.prototype, "reflectionReflectance0", void 0);
  101634. __decorate([
  101635. BABYLON.serialize()
  101636. ], BackgroundMaterial.prototype, "_reflectionReflectance90", void 0);
  101637. __decorate([
  101638. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101639. ], BackgroundMaterial.prototype, "reflectionReflectance90", void 0);
  101640. __decorate([
  101641. BABYLON.serialize()
  101642. ], BackgroundMaterial.prototype, "_useRGBColor", void 0);
  101643. __decorate([
  101644. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101645. ], BackgroundMaterial.prototype, "useRGBColor", void 0);
  101646. __decorate([
  101647. BABYLON.serialize()
  101648. ], BackgroundMaterial.prototype, "_enableNoise", void 0);
  101649. __decorate([
  101650. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101651. ], BackgroundMaterial.prototype, "enableNoise", void 0);
  101652. __decorate([
  101653. BABYLON.serialize()
  101654. ], BackgroundMaterial.prototype, "_maxSimultaneousLights", void 0);
  101655. __decorate([
  101656. BABYLON.expandToProperty("_markAllSubMeshesAsTexturesDirty")
  101657. ], BackgroundMaterial.prototype, "maxSimultaneousLights", void 0);
  101658. __decorate([
  101659. BABYLON.serializeAsImageProcessingConfiguration()
  101660. ], BackgroundMaterial.prototype, "_imageProcessingConfiguration", void 0);
  101661. return BackgroundMaterial;
  101662. }(BABYLON.PushMaterial));
  101663. BABYLON.BackgroundMaterial = BackgroundMaterial;
  101664. })(BABYLON || (BABYLON = {}));
  101665. //# sourceMappingURL=babylon.backgroundMaterial.js.map
  101666. var __assign = (this && this.__assign) || Object.assign || function(t) {
  101667. for (var s, i = 1, n = arguments.length; i < n; i++) {
  101668. s = arguments[i];
  101669. for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
  101670. t[p] = s[p];
  101671. }
  101672. return t;
  101673. };
  101674. var BABYLON;
  101675. (function (BABYLON) {
  101676. /**
  101677. * The Environment helper class can be used to add a fully featuread none expensive background to your scene.
  101678. * It includes by default a skybox and a ground relying on the BackgroundMaterial.
  101679. * It also helps with the default setup of your imageProcessing configuration.
  101680. */
  101681. var EnvironmentHelper = /** @class */ (function () {
  101682. /**
  101683. * constructor
  101684. * @param options
  101685. * @param scene The scene to add the material to
  101686. */
  101687. function EnvironmentHelper(options, scene) {
  101688. var _this = this;
  101689. this._errorHandler = function (message, exception) {
  101690. _this.onErrorObservable.notifyObservers({ message: message, exception: exception });
  101691. };
  101692. this._options = __assign({}, EnvironmentHelper._getDefaultOptions(), options);
  101693. this._scene = scene;
  101694. this.onErrorObservable = new BABYLON.Observable();
  101695. this._setupBackground();
  101696. this._setupImageProcessing();
  101697. }
  101698. /**
  101699. * Creates the default options for the helper.
  101700. */
  101701. EnvironmentHelper._getDefaultOptions = function () {
  101702. return {
  101703. createGround: true,
  101704. groundSize: 15,
  101705. groundTexture: this._groundTextureCDNUrl,
  101706. groundColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101707. groundOpacity: 0.9,
  101708. enableGroundShadow: true,
  101709. groundShadowLevel: 0.5,
  101710. enableGroundMirror: false,
  101711. groundMirrorSizeRatio: 0.3,
  101712. groundMirrorBlurKernel: 64,
  101713. groundMirrorAmount: 1,
  101714. groundMirrorFresnelWeight: 1,
  101715. groundMirrorFallOffDistance: 0,
  101716. groundMirrorTextureType: BABYLON.Engine.TEXTURETYPE_UNSIGNED_INT,
  101717. groundYBias: 0.00001,
  101718. createSkybox: true,
  101719. skyboxSize: 20,
  101720. skyboxTexture: this._skyboxTextureCDNUrl,
  101721. skyboxColor: new BABYLON.Color3(0.2, 0.2, 0.3).toLinearSpace().scale(3),
  101722. backgroundYRotation: 0,
  101723. sizeAuto: true,
  101724. rootPosition: BABYLON.Vector3.Zero(),
  101725. setupImageProcessing: true,
  101726. environmentTexture: this._environmentTextureCDNUrl,
  101727. cameraExposure: 0.8,
  101728. cameraContrast: 1.2,
  101729. toneMappingEnabled: true,
  101730. };
  101731. };
  101732. Object.defineProperty(EnvironmentHelper.prototype, "rootMesh", {
  101733. /**
  101734. * Gets the root mesh created by the helper.
  101735. */
  101736. get: function () {
  101737. return this._rootMesh;
  101738. },
  101739. enumerable: true,
  101740. configurable: true
  101741. });
  101742. Object.defineProperty(EnvironmentHelper.prototype, "skybox", {
  101743. /**
  101744. * Gets the skybox created by the helper.
  101745. */
  101746. get: function () {
  101747. return this._skybox;
  101748. },
  101749. enumerable: true,
  101750. configurable: true
  101751. });
  101752. Object.defineProperty(EnvironmentHelper.prototype, "skyboxTexture", {
  101753. /**
  101754. * Gets the skybox texture created by the helper.
  101755. */
  101756. get: function () {
  101757. return this._skyboxTexture;
  101758. },
  101759. enumerable: true,
  101760. configurable: true
  101761. });
  101762. Object.defineProperty(EnvironmentHelper.prototype, "skyboxMaterial", {
  101763. /**
  101764. * Gets the skybox material created by the helper.
  101765. */
  101766. get: function () {
  101767. return this._skyboxMaterial;
  101768. },
  101769. enumerable: true,
  101770. configurable: true
  101771. });
  101772. Object.defineProperty(EnvironmentHelper.prototype, "ground", {
  101773. /**
  101774. * Gets the ground mesh created by the helper.
  101775. */
  101776. get: function () {
  101777. return this._ground;
  101778. },
  101779. enumerable: true,
  101780. configurable: true
  101781. });
  101782. Object.defineProperty(EnvironmentHelper.prototype, "groundTexture", {
  101783. /**
  101784. * Gets the ground texture created by the helper.
  101785. */
  101786. get: function () {
  101787. return this._groundTexture;
  101788. },
  101789. enumerable: true,
  101790. configurable: true
  101791. });
  101792. Object.defineProperty(EnvironmentHelper.prototype, "groundMirror", {
  101793. /**
  101794. * Gets the ground mirror created by the helper.
  101795. */
  101796. get: function () {
  101797. return this._groundMirror;
  101798. },
  101799. enumerable: true,
  101800. configurable: true
  101801. });
  101802. Object.defineProperty(EnvironmentHelper.prototype, "groundMirrorRenderList", {
  101803. /**
  101804. * Gets the ground mirror render list to helps pushing the meshes
  101805. * you wish in the ground reflection.
  101806. */
  101807. get: function () {
  101808. if (this._groundMirror) {
  101809. return this._groundMirror.renderList;
  101810. }
  101811. return null;
  101812. },
  101813. enumerable: true,
  101814. configurable: true
  101815. });
  101816. Object.defineProperty(EnvironmentHelper.prototype, "groundMaterial", {
  101817. /**
  101818. * Gets the ground material created by the helper.
  101819. */
  101820. get: function () {
  101821. return this._groundMaterial;
  101822. },
  101823. enumerable: true,
  101824. configurable: true
  101825. });
  101826. /**
  101827. * Updates the background according to the new options
  101828. * @param options
  101829. */
  101830. EnvironmentHelper.prototype.updateOptions = function (options) {
  101831. var newOptions = __assign({}, this._options, options);
  101832. if (this._ground && !newOptions.createGround) {
  101833. this._ground.dispose();
  101834. this._ground = null;
  101835. }
  101836. if (this._groundMaterial && !newOptions.createGround) {
  101837. this._groundMaterial.dispose();
  101838. this._groundMaterial = null;
  101839. }
  101840. if (this._groundTexture) {
  101841. if (this._options.groundTexture != newOptions.groundTexture) {
  101842. this._groundTexture.dispose();
  101843. this._groundTexture = null;
  101844. }
  101845. }
  101846. if (this._skybox && !newOptions.createSkybox) {
  101847. this._skybox.dispose();
  101848. this._skybox = null;
  101849. }
  101850. if (this._skyboxMaterial && !newOptions.createSkybox) {
  101851. this._skyboxMaterial.dispose();
  101852. this._skyboxMaterial = null;
  101853. }
  101854. if (this._skyboxTexture) {
  101855. if (this._options.skyboxTexture != newOptions.skyboxTexture) {
  101856. this._skyboxTexture.dispose();
  101857. this._skyboxTexture = null;
  101858. }
  101859. }
  101860. if (this._groundMirror && !newOptions.enableGroundMirror) {
  101861. this._groundMirror.dispose();
  101862. this._groundMirror = null;
  101863. }
  101864. if (this._scene.environmentTexture) {
  101865. if (this._options.environmentTexture != newOptions.environmentTexture) {
  101866. this._scene.environmentTexture.dispose();
  101867. }
  101868. }
  101869. this._options = newOptions;
  101870. this._setupBackground();
  101871. this._setupImageProcessing();
  101872. };
  101873. /**
  101874. * Sets the primary color of all the available elements.
  101875. * @param color the main color to affect to the ground and the background
  101876. */
  101877. EnvironmentHelper.prototype.setMainColor = function (color) {
  101878. if (this.groundMaterial) {
  101879. this.groundMaterial.primaryColor = color;
  101880. }
  101881. if (this.skyboxMaterial) {
  101882. this.skyboxMaterial.primaryColor = color;
  101883. }
  101884. if (this.groundMirror) {
  101885. this.groundMirror.clearColor = new BABYLON.Color4(color.r, color.g, color.b, 1.0);
  101886. }
  101887. };
  101888. /**
  101889. * Setup the image processing according to the specified options.
  101890. */
  101891. EnvironmentHelper.prototype._setupImageProcessing = function () {
  101892. if (this._options.setupImageProcessing) {
  101893. this._scene.imageProcessingConfiguration.contrast = this._options.cameraContrast;
  101894. this._scene.imageProcessingConfiguration.exposure = this._options.cameraExposure;
  101895. this._scene.imageProcessingConfiguration.toneMappingEnabled = this._options.toneMappingEnabled;
  101896. this._setupEnvironmentTexture();
  101897. }
  101898. };
  101899. /**
  101900. * Setup the environment texture according to the specified options.
  101901. */
  101902. EnvironmentHelper.prototype._setupEnvironmentTexture = function () {
  101903. if (this._scene.environmentTexture) {
  101904. return;
  101905. }
  101906. if (this._options.environmentTexture instanceof BABYLON.BaseTexture) {
  101907. this._scene.environmentTexture = this._options.environmentTexture;
  101908. return;
  101909. }
  101910. var environmentTexture = BABYLON.CubeTexture.CreateFromPrefilteredData(this._options.environmentTexture, this._scene);
  101911. this._scene.environmentTexture = environmentTexture;
  101912. };
  101913. /**
  101914. * Setup the background according to the specified options.
  101915. */
  101916. EnvironmentHelper.prototype._setupBackground = function () {
  101917. if (!this._rootMesh) {
  101918. this._rootMesh = new BABYLON.Mesh("BackgroundHelper", this._scene);
  101919. }
  101920. this._rootMesh.rotation.y = this._options.backgroundYRotation;
  101921. var sceneSize = this._getSceneSize();
  101922. if (this._options.createGround) {
  101923. this._setupGround(sceneSize);
  101924. this._setupGroundMaterial();
  101925. this._setupGroundDiffuseTexture();
  101926. if (this._options.enableGroundMirror) {
  101927. this._setupGroundMirrorTexture(sceneSize);
  101928. }
  101929. this._setupMirrorInGroundMaterial();
  101930. }
  101931. if (this._options.createSkybox) {
  101932. this._setupSkybox(sceneSize);
  101933. this._setupSkyboxMaterial();
  101934. this._setupSkyboxReflectionTexture();
  101935. }
  101936. this._rootMesh.position.x = sceneSize.rootPosition.x;
  101937. this._rootMesh.position.z = sceneSize.rootPosition.z;
  101938. this._rootMesh.position.y = sceneSize.rootPosition.y;
  101939. };
  101940. /**
  101941. * Get the scene sizes according to the setup.
  101942. */
  101943. EnvironmentHelper.prototype._getSceneSize = function () {
  101944. var _this = this;
  101945. var groundSize = this._options.groundSize;
  101946. var skyboxSize = this._options.skyboxSize;
  101947. var rootPosition = this._options.rootPosition;
  101948. if (!this._scene.meshes || this._scene.meshes.length === 1) { // 1 only means the root of the helper.
  101949. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101950. }
  101951. var sceneExtends = this._scene.getWorldExtends(function (mesh) {
  101952. return (mesh !== _this._ground && mesh !== _this._rootMesh && mesh !== _this._skybox);
  101953. });
  101954. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  101955. if (this._options.sizeAuto) {
  101956. if (this._scene.activeCamera instanceof BABYLON.ArcRotateCamera &&
  101957. this._scene.activeCamera.upperRadiusLimit) {
  101958. groundSize = this._scene.activeCamera.upperRadiusLimit * 2;
  101959. skyboxSize = groundSize;
  101960. }
  101961. var sceneDiagonalLenght = sceneDiagonal.length();
  101962. if (sceneDiagonalLenght > groundSize) {
  101963. groundSize = sceneDiagonalLenght * 2;
  101964. skyboxSize = groundSize;
  101965. }
  101966. // 10 % bigger.
  101967. groundSize *= 1.1;
  101968. skyboxSize *= 1.5;
  101969. rootPosition = sceneExtends.min.add(sceneDiagonal.scale(0.5));
  101970. rootPosition.y = sceneExtends.min.y - this._options.groundYBias;
  101971. }
  101972. return { groundSize: groundSize, skyboxSize: skyboxSize, rootPosition: rootPosition };
  101973. };
  101974. /**
  101975. * Setup the ground according to the specified options.
  101976. */
  101977. EnvironmentHelper.prototype._setupGround = function (sceneSize) {
  101978. var _this = this;
  101979. if (!this._ground || this._ground.isDisposed()) {
  101980. this._ground = BABYLON.Mesh.CreatePlane("BackgroundPlane", sceneSize.groundSize, this._scene);
  101981. this._ground.rotation.x = Math.PI / 2; // Face up by default.
  101982. this._ground.parent = this._rootMesh;
  101983. this._ground.onDisposeObservable.add(function () { _this._ground = null; });
  101984. }
  101985. this._ground.receiveShadows = this._options.enableGroundShadow;
  101986. };
  101987. /**
  101988. * Setup the ground material according to the specified options.
  101989. */
  101990. EnvironmentHelper.prototype._setupGroundMaterial = function () {
  101991. if (!this._groundMaterial) {
  101992. this._groundMaterial = new BABYLON.BackgroundMaterial("BackgroundPlaneMaterial", this._scene);
  101993. }
  101994. this._groundMaterial.alpha = this._options.groundOpacity;
  101995. this._groundMaterial.alphaMode = BABYLON.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  101996. this._groundMaterial.shadowLevel = this._options.groundShadowLevel;
  101997. this._groundMaterial.primaryColor = this._options.groundColor;
  101998. this._groundMaterial.useRGBColor = false;
  101999. this._groundMaterial.enableNoise = true;
  102000. if (this._ground) {
  102001. this._ground.material = this._groundMaterial;
  102002. }
  102003. };
  102004. /**
  102005. * Setup the ground diffuse texture according to the specified options.
  102006. */
  102007. EnvironmentHelper.prototype._setupGroundDiffuseTexture = function () {
  102008. if (!this._groundMaterial) {
  102009. return;
  102010. }
  102011. if (this._groundTexture) {
  102012. return;
  102013. }
  102014. if (this._options.groundTexture instanceof BABYLON.BaseTexture) {
  102015. this._groundMaterial.diffuseTexture = this._options.groundTexture;
  102016. return;
  102017. }
  102018. var diffuseTexture = new BABYLON.Texture(this._options.groundTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102019. diffuseTexture.gammaSpace = false;
  102020. diffuseTexture.hasAlpha = true;
  102021. this._groundMaterial.diffuseTexture = diffuseTexture;
  102022. };
  102023. /**
  102024. * Setup the ground mirror texture according to the specified options.
  102025. */
  102026. EnvironmentHelper.prototype._setupGroundMirrorTexture = function (sceneSize) {
  102027. var wrapping = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102028. if (!this._groundMirror) {
  102029. this._groundMirror = new BABYLON.MirrorTexture("BackgroundPlaneMirrorTexture", { ratio: this._options.groundMirrorSizeRatio }, this._scene, false, this._options.groundMirrorTextureType, BABYLON.Texture.BILINEAR_SAMPLINGMODE, true);
  102030. this._groundMirror.mirrorPlane = new BABYLON.Plane(0, -1, 0, sceneSize.rootPosition.y);
  102031. this._groundMirror.anisotropicFilteringLevel = 1;
  102032. this._groundMirror.wrapU = wrapping;
  102033. this._groundMirror.wrapV = wrapping;
  102034. this._groundMirror.gammaSpace = false;
  102035. if (this._groundMirror.renderList) {
  102036. for (var i = 0; i < this._scene.meshes.length; i++) {
  102037. var mesh = this._scene.meshes[i];
  102038. if (mesh !== this._ground &&
  102039. mesh !== this._skybox &&
  102040. mesh !== this._rootMesh) {
  102041. this._groundMirror.renderList.push(mesh);
  102042. }
  102043. }
  102044. }
  102045. }
  102046. this._groundMirror.clearColor = new BABYLON.Color4(this._options.groundColor.r, this._options.groundColor.g, this._options.groundColor.b, 1);
  102047. this._groundMirror.adaptiveBlurKernel = this._options.groundMirrorBlurKernel;
  102048. };
  102049. /**
  102050. * Setup the ground to receive the mirror texture.
  102051. */
  102052. EnvironmentHelper.prototype._setupMirrorInGroundMaterial = function () {
  102053. if (this._groundMaterial) {
  102054. this._groundMaterial.reflectionTexture = this._groundMirror;
  102055. this._groundMaterial.reflectionFresnel = true;
  102056. this._groundMaterial.reflectionAmount = this._options.groundMirrorAmount;
  102057. this._groundMaterial.reflectionStandardFresnelWeight = this._options.groundMirrorFresnelWeight;
  102058. this._groundMaterial.reflectionFalloffDistance = this._options.groundMirrorFallOffDistance;
  102059. }
  102060. };
  102061. /**
  102062. * Setup the skybox according to the specified options.
  102063. */
  102064. EnvironmentHelper.prototype._setupSkybox = function (sceneSize) {
  102065. var _this = this;
  102066. if (!this._skybox || this._skybox.isDisposed()) {
  102067. this._skybox = BABYLON.Mesh.CreateBox("BackgroundSkybox", sceneSize.skyboxSize, this._scene, undefined, BABYLON.Mesh.BACKSIDE);
  102068. this._skybox.onDisposeObservable.add(function () { _this._skybox = null; });
  102069. }
  102070. this._skybox.parent = this._rootMesh;
  102071. };
  102072. /**
  102073. * Setup the skybox material according to the specified options.
  102074. */
  102075. EnvironmentHelper.prototype._setupSkyboxMaterial = function () {
  102076. if (!this._skybox) {
  102077. return;
  102078. }
  102079. if (!this._skyboxMaterial) {
  102080. this._skyboxMaterial = new BABYLON.BackgroundMaterial("BackgroundSkyboxMaterial", this._scene);
  102081. }
  102082. this._skyboxMaterial.useRGBColor = false;
  102083. this._skyboxMaterial.primaryColor = this._options.skyboxColor;
  102084. this._skyboxMaterial.enableNoise = true;
  102085. this._skybox.material = this._skyboxMaterial;
  102086. };
  102087. /**
  102088. * Setup the skybox reflection texture according to the specified options.
  102089. */
  102090. EnvironmentHelper.prototype._setupSkyboxReflectionTexture = function () {
  102091. if (!this._skyboxMaterial) {
  102092. return;
  102093. }
  102094. if (this._skyboxTexture) {
  102095. return;
  102096. }
  102097. if (this._options.skyboxTexture instanceof BABYLON.BaseTexture) {
  102098. this._skyboxMaterial.reflectionTexture = this._options.skyboxTexture;
  102099. return;
  102100. }
  102101. this._skyboxTexture = new BABYLON.CubeTexture(this._options.skyboxTexture, this._scene, undefined, undefined, undefined, undefined, this._errorHandler);
  102102. this._skyboxTexture.coordinatesMode = BABYLON.Texture.SKYBOX_MODE;
  102103. this._skyboxTexture.gammaSpace = false;
  102104. this._skyboxMaterial.reflectionTexture = this._skyboxTexture;
  102105. };
  102106. /**
  102107. * Dispose all the elements created by the Helper.
  102108. */
  102109. EnvironmentHelper.prototype.dispose = function () {
  102110. if (this._groundMaterial) {
  102111. this._groundMaterial.dispose(true, true);
  102112. }
  102113. if (this._skyboxMaterial) {
  102114. this._skyboxMaterial.dispose(true, true);
  102115. }
  102116. this._rootMesh.dispose(false);
  102117. };
  102118. /**
  102119. * Default ground texture URL.
  102120. */
  102121. EnvironmentHelper._groundTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundGround.png";
  102122. /**
  102123. * Default skybox texture URL.
  102124. */
  102125. EnvironmentHelper._skyboxTextureCDNUrl = "https://assets.babylonjs.com/environments/backgroundSkybox.dds";
  102126. /**
  102127. * Default environment texture URL.
  102128. */
  102129. EnvironmentHelper._environmentTextureCDNUrl = "https://assets.babylonjs.com/environments/environmentSpecular.env";
  102130. return EnvironmentHelper;
  102131. }());
  102132. BABYLON.EnvironmentHelper = EnvironmentHelper;
  102133. })(BABYLON || (BABYLON = {}));
  102134. //# sourceMappingURL=babylon.environmentHelper.js.map
  102135. var BABYLON;
  102136. (function (BABYLON) {
  102137. /** Internal class used to store shapes for emitters */
  102138. var ParticleSystemSetEmitterCreationOptions = /** @class */ (function () {
  102139. function ParticleSystemSetEmitterCreationOptions() {
  102140. }
  102141. return ParticleSystemSetEmitterCreationOptions;
  102142. }());
  102143. /**
  102144. * Represents a set of particle systems working together to create a specific effect
  102145. */
  102146. var ParticleSystemSet = /** @class */ (function () {
  102147. function ParticleSystemSet() {
  102148. /**
  102149. * Gets the particle system list
  102150. */
  102151. this.systems = new Array();
  102152. }
  102153. Object.defineProperty(ParticleSystemSet.prototype, "emitterNode", {
  102154. /**
  102155. * Gets the emitter node used with this set
  102156. */
  102157. get: function () {
  102158. return this._emitterNode;
  102159. },
  102160. enumerable: true,
  102161. configurable: true
  102162. });
  102163. /**
  102164. * Creates a new emitter mesh as a sphere
  102165. * @param options defines the options used to create the sphere
  102166. * @param renderingGroupId defines the renderingGroupId to use for the sphere
  102167. * @param scene defines the hosting scene
  102168. */
  102169. ParticleSystemSet.prototype.setEmitterAsSphere = function (options, renderingGroupId, scene) {
  102170. if (this._emitterNode) {
  102171. this._emitterNode.dispose();
  102172. }
  102173. this._emitterCreationOptions = {
  102174. kind: "Sphere",
  102175. options: options,
  102176. renderingGroupId: renderingGroupId
  102177. };
  102178. var emitterMesh = BABYLON.MeshBuilder.CreateSphere("emitterSphere", { diameter: options.diameter, segments: options.segments }, scene);
  102179. emitterMesh.renderingGroupId = renderingGroupId;
  102180. var material = new BABYLON.StandardMaterial("emitterSphereMaterial", scene);
  102181. material.emissiveColor = options.color;
  102182. emitterMesh.material = material;
  102183. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102184. var system = _a[_i];
  102185. system.emitter = emitterMesh;
  102186. }
  102187. this._emitterNode = emitterMesh;
  102188. };
  102189. /**
  102190. * Starts all particle systems of the set
  102191. * @param emitter defines an optional mesh to use as emitter for the particle systems
  102192. */
  102193. ParticleSystemSet.prototype.start = function (emitter) {
  102194. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102195. var system = _a[_i];
  102196. if (emitter) {
  102197. system.emitter = emitter;
  102198. }
  102199. system.start();
  102200. }
  102201. };
  102202. /**
  102203. * Release all associated resources
  102204. */
  102205. ParticleSystemSet.prototype.dispose = function () {
  102206. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102207. var system = _a[_i];
  102208. system.dispose();
  102209. }
  102210. this.systems = [];
  102211. if (this._emitterNode) {
  102212. this._emitterNode.dispose();
  102213. this._emitterNode = null;
  102214. }
  102215. };
  102216. /**
  102217. * Serialize the set into a JSON compatible object
  102218. * @returns a JSON compatible representation of the set
  102219. */
  102220. ParticleSystemSet.prototype.serialize = function () {
  102221. var result = {};
  102222. result.systems = [];
  102223. for (var _i = 0, _a = this.systems; _i < _a.length; _i++) {
  102224. var system = _a[_i];
  102225. result.systems.push(system.serialize());
  102226. }
  102227. if (this._emitterNode) {
  102228. result.emitter = this._emitterCreationOptions;
  102229. }
  102230. return result;
  102231. };
  102232. /**
  102233. * Parse a new ParticleSystemSet from a serialized source
  102234. * @param data defines a JSON compatible representation of the set
  102235. * @param scene defines the hosting scene
  102236. * @param gpu defines if we want GPU particles or CPU particles
  102237. * @returns a new ParticleSystemSet
  102238. */
  102239. ParticleSystemSet.Parse = function (data, scene, gpu) {
  102240. if (gpu === void 0) { gpu = false; }
  102241. var result = new ParticleSystemSet();
  102242. var rootUrl = BABYLON.ParticleHelper.BaseAssetsUrl + "/textures/";
  102243. for (var _i = 0, _a = data.systems; _i < _a.length; _i++) {
  102244. var system = _a[_i];
  102245. result.systems.push(gpu ? BABYLON.GPUParticleSystem.Parse(system, scene, rootUrl) : BABYLON.ParticleSystem.Parse(system, scene, rootUrl));
  102246. }
  102247. if (data.emitter) {
  102248. var options = data.emitter.options;
  102249. switch (data.emitter.kind) {
  102250. case "Sphere":
  102251. result.setEmitterAsSphere({
  102252. diameter: options.diameter,
  102253. segments: options.segments,
  102254. color: BABYLON.Color3.FromArray(options.color)
  102255. }, data.emitter.renderingGroupId, scene);
  102256. break;
  102257. }
  102258. }
  102259. return result;
  102260. };
  102261. return ParticleSystemSet;
  102262. }());
  102263. BABYLON.ParticleSystemSet = ParticleSystemSet;
  102264. })(BABYLON || (BABYLON = {}));
  102265. //# sourceMappingURL=babylon.particleSystemSet.js.map
  102266. var BABYLON;
  102267. (function (BABYLON) {
  102268. /**
  102269. * This class is made for on one-liner static method to help creating particle system set.
  102270. */
  102271. var ParticleHelper = /** @class */ (function () {
  102272. function ParticleHelper() {
  102273. }
  102274. /**
  102275. * This is the main static method (one-liner) of this helper to create different particle systems
  102276. * @param type This string represents the type to the particle system to create
  102277. * @param scene The scene where the particle system should live
  102278. * @param gpu If the system will use gpu
  102279. * @returns the ParticleSystemSet created
  102280. */
  102281. ParticleHelper.CreateAsync = function (type, scene, gpu) {
  102282. if (scene === void 0) { scene = BABYLON.Engine.LastCreatedScene; }
  102283. if (gpu === void 0) { gpu = false; }
  102284. return new Promise(function (resolve, reject) {
  102285. if (!scene) {
  102286. scene = BABYLON.Engine.LastCreatedScene;
  102287. ;
  102288. }
  102289. if (gpu && !BABYLON.GPUParticleSystem.IsSupported) {
  102290. return reject("Particle system with GPU is not supported.");
  102291. }
  102292. BABYLON.Tools.LoadFile(ParticleHelper.BaseAssetsUrl + "/systems/" + type + ".json", function (data, response) {
  102293. var newData = JSON.parse(data.toString());
  102294. return resolve(BABYLON.ParticleSystemSet.Parse(newData, scene, gpu));
  102295. }, undefined, undefined, undefined, function (req, exception) {
  102296. return reject("An error occured while the creation of your particle system. Check if your type '" + type + "' exists.");
  102297. });
  102298. });
  102299. };
  102300. /**
  102301. * Static function used to export a particle system to a ParticleSystemSet variable.
  102302. * Please note that the emitter shape is not exported
  102303. * @param system defines the particle systems to export
  102304. */
  102305. ParticleHelper.ExportSet = function (systems) {
  102306. var set = new BABYLON.ParticleSystemSet();
  102307. for (var _i = 0, systems_1 = systems; _i < systems_1.length; _i++) {
  102308. var system = systems_1[_i];
  102309. set.systems.push(system);
  102310. }
  102311. return set;
  102312. };
  102313. /**
  102314. * Gets or sets base Assets URL
  102315. */
  102316. ParticleHelper.BaseAssetsUrl = "https://assets.babylonjs.com/particles";
  102317. return ParticleHelper;
  102318. }());
  102319. BABYLON.ParticleHelper = ParticleHelper;
  102320. })(BABYLON || (BABYLON = {}));
  102321. //# sourceMappingURL=babylon.particleHelper.js.map
  102322. var BABYLON;
  102323. (function (BABYLON) {
  102324. /**
  102325. * Display a 360 degree video on an approximately spherical surface, useful for VR applications or skyboxes.
  102326. * As a subclass of Node, this allow parenting to the camera or multiple videos with different locations in the scene.
  102327. * This class achieves its effect with a VideoTexture and a correctly configured BackgroundMaterial on an inverted sphere.
  102328. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102329. */
  102330. var VideoDome = /** @class */ (function (_super) {
  102331. __extends(VideoDome, _super);
  102332. /**
  102333. * Create an instance of this class and pass through the parameters to the relevant classes, VideoTexture, StandardMaterial, and Mesh.
  102334. * @param name Element's name, child elements will append suffixes for their own names.
  102335. * @param urlsOrVideo defines the url(s) or the video element to use
  102336. * @param options An object containing optional or exposed sub element properties
  102337. */
  102338. function VideoDome(name, urlsOrVideo, options, scene) {
  102339. var _this = _super.call(this, name, scene) || this;
  102340. _this._useDirectMapping = false;
  102341. // set defaults and manage values
  102342. name = name || "videoDome";
  102343. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102344. options.clickToPlay = Boolean(options.clickToPlay);
  102345. options.autoPlay = options.autoPlay === undefined ? true : Boolean(options.autoPlay);
  102346. options.loop = options.loop === undefined ? true : Boolean(options.loop);
  102347. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102348. if (options.useDirectMapping === undefined) {
  102349. _this._useDirectMapping = true;
  102350. }
  102351. else {
  102352. _this._useDirectMapping = options.useDirectMapping;
  102353. }
  102354. // create
  102355. var tempOptions = { loop: options.loop, autoPlay: options.autoPlay, autoUpdateTexture: true, poster: options.poster };
  102356. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102357. var texture = _this._videoTexture = new BABYLON.VideoTexture(name + "_texture", urlsOrVideo, scene, false, _this._useDirectMapping, BABYLON.Texture.TRILINEAR_SAMPLINGMODE, tempOptions);
  102358. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102359. // configure material
  102360. material.useEquirectangularFOV = true;
  102361. material.fovMultiplier = 1.0;
  102362. material.opacityFresnel = false;
  102363. if (_this._useDirectMapping) {
  102364. texture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102365. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102366. material.diffuseTexture = texture;
  102367. }
  102368. else {
  102369. texture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102370. texture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102371. material.reflectionTexture = texture;
  102372. }
  102373. // configure mesh
  102374. _this._mesh.material = material;
  102375. _this._mesh.parent = _this;
  102376. // optional configuration
  102377. if (options.clickToPlay) {
  102378. scene.onPointerUp = function () {
  102379. _this._videoTexture.video.play();
  102380. };
  102381. }
  102382. return _this;
  102383. }
  102384. Object.defineProperty(VideoDome.prototype, "videoTexture", {
  102385. /**
  102386. * Gets the video texture being displayed on the sphere
  102387. */
  102388. get: function () {
  102389. return this._videoTexture;
  102390. },
  102391. enumerable: true,
  102392. configurable: true
  102393. });
  102394. Object.defineProperty(VideoDome.prototype, "fovMultiplier", {
  102395. /**
  102396. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102397. * Also see the options.resolution property.
  102398. */
  102399. get: function () {
  102400. return this._material.fovMultiplier;
  102401. },
  102402. set: function (value) {
  102403. this._material.fovMultiplier = value;
  102404. },
  102405. enumerable: true,
  102406. configurable: true
  102407. });
  102408. /**
  102409. * Releases resources associated with this node.
  102410. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102411. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102412. */
  102413. VideoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102414. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102415. this._videoTexture.dispose();
  102416. this._mesh.dispose();
  102417. this._material.dispose();
  102418. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102419. };
  102420. return VideoDome;
  102421. }(BABYLON.Node));
  102422. BABYLON.VideoDome = VideoDome;
  102423. })(BABYLON || (BABYLON = {}));
  102424. //# sourceMappingURL=babylon.videoDome.js.map
  102425. var BABYLON;
  102426. (function (BABYLON) {
  102427. /**
  102428. * Display a 360 degree photo on an approximately spherical surface, useful for VR applications or skyboxes.
  102429. * As a subclass of Node, this allow parenting to the camera with different locations in the scene.
  102430. * This class achieves its effect with a Texture and a correctly configured BackgroundMaterial on an inverted sphere.
  102431. * Potential additions to this helper include zoom and and non-infinite distance rendering effects.
  102432. */
  102433. var PhotoDome = /** @class */ (function (_super) {
  102434. __extends(PhotoDome, _super);
  102435. /**
  102436. * Create an instance of this class and pass through the parameters to the relevant classes, Texture, StandardMaterial, and Mesh.
  102437. * @param name Element's name, child elements will append suffixes for their own names.
  102438. * @param urlsOfPhoto define the url of the photo to display
  102439. * @param options An object containing optional or exposed sub element properties
  102440. */
  102441. function PhotoDome(name, urlOfPhoto, options, scene) {
  102442. var _this = _super.call(this, name, scene) || this;
  102443. _this._useDirectMapping = false;
  102444. // set defaults and manage values
  102445. name = name || "photoDome";
  102446. options.resolution = (Math.abs(options.resolution) | 0) || 32;
  102447. options.size = Math.abs(options.size) || (scene.activeCamera ? scene.activeCamera.maxZ * 0.48 : 1000);
  102448. if (options.useDirectMapping === undefined) {
  102449. _this._useDirectMapping = true;
  102450. }
  102451. else {
  102452. _this._useDirectMapping = options.useDirectMapping;
  102453. }
  102454. // create
  102455. var material = _this._material = new BABYLON.BackgroundMaterial(name + "_material", scene);
  102456. _this._mesh = BABYLON.Mesh.CreateSphere(name + "_mesh", options.resolution, options.size, scene, false, BABYLON.Mesh.BACKSIDE);
  102457. // configure material
  102458. material.opacityFresnel = false;
  102459. material.useEquirectangularFOV = true;
  102460. material.fovMultiplier = 1.0;
  102461. _this.photoTexture = new BABYLON.Texture(urlOfPhoto, scene, true, !_this._useDirectMapping);
  102462. // configure mesh
  102463. _this._mesh.material = material;
  102464. _this._mesh.parent = _this;
  102465. return _this;
  102466. }
  102467. Object.defineProperty(PhotoDome.prototype, "photoTexture", {
  102468. /**
  102469. * Gets or sets the texture being displayed on the sphere
  102470. */
  102471. get: function () {
  102472. return this._photoTexture;
  102473. },
  102474. set: function (value) {
  102475. if (this._photoTexture === value) {
  102476. return;
  102477. }
  102478. this._photoTexture = value;
  102479. if (this._useDirectMapping) {
  102480. this._photoTexture.wrapU = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102481. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102482. this._material.diffuseTexture = this._photoTexture;
  102483. }
  102484. else {
  102485. this._photoTexture.coordinatesMode = BABYLON.Texture.FIXED_EQUIRECTANGULAR_MIRRORED_MODE; // matches orientation
  102486. this._photoTexture.wrapV = BABYLON.Texture.CLAMP_ADDRESSMODE;
  102487. this._material.reflectionTexture = this._photoTexture;
  102488. }
  102489. },
  102490. enumerable: true,
  102491. configurable: true
  102492. });
  102493. Object.defineProperty(PhotoDome.prototype, "fovMultiplier", {
  102494. /**
  102495. * The current fov(field of view) multiplier, 0.0 - 2.0. Defaults to 1.0. Lower values "zoom in" and higher values "zoom out".
  102496. * Also see the options.resolution property.
  102497. */
  102498. get: function () {
  102499. return this._material.fovMultiplier;
  102500. },
  102501. set: function (value) {
  102502. this._material.fovMultiplier = value;
  102503. },
  102504. enumerable: true,
  102505. configurable: true
  102506. });
  102507. /**
  102508. * Releases resources associated with this node.
  102509. * @param doNotRecurse Set to true to not recurse into each children (recurse into each children by default)
  102510. * @param disposeMaterialAndTextures Set to true to also dispose referenced materials and textures (false by default)
  102511. */
  102512. PhotoDome.prototype.dispose = function (doNotRecurse, disposeMaterialAndTextures) {
  102513. if (disposeMaterialAndTextures === void 0) { disposeMaterialAndTextures = false; }
  102514. this._photoTexture.dispose();
  102515. this._mesh.dispose();
  102516. this._material.dispose();
  102517. _super.prototype.dispose.call(this, doNotRecurse, disposeMaterialAndTextures);
  102518. };
  102519. return PhotoDome;
  102520. }(BABYLON.Node));
  102521. BABYLON.PhotoDome = PhotoDome;
  102522. })(BABYLON || (BABYLON = {}));
  102523. //# sourceMappingURL=babylon.photoDome.js.map
  102524. BABYLON.Effect.ShadersStore={"defaultVertexShader":"#include<__decl__defaultVertex>\n\n#define CUSTOM_VERTEX_BEGIN\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nvarying vec2 vSpecularUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\n#define CUSTOM_VERTEX_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_VERTEX_MAIN_BEGIN\nvec3 positionUpdated=position;\n#ifdef NORMAL \nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#define CUSTOM_VERTEX_UPDATE_POSITION\n#define CUSTOM_VERTEX_UPDATE_NORMAL\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif\n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM) && SPECULARDIRECTUV == 0\nif (vSpecularInfos.x == 0.)\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvSpecularUV=vec2(specularMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#include<bumpVertex>\n#include<clipPlaneVertex>\n#include<fogVertex>\n#include<shadowsVertex>[0..maxSimultaneousLights]\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n#include<pointCloudVertex>\n#include<logDepthVertex>\n#define CUSTOM_VERTEX_MAIN_END\n}\n","defaultPixelShader":"#include<__decl__defaultFragment>\n#if defined(BUMP) || !defined(NORMAL)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#define CUSTOM_FRAGMENT_BEGIN\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\n\n#define RECIPROCAL_PI2 0.15915494\nuniform vec3 vEyePosition;\nuniform vec3 vAmbientColor;\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2;\n#endif\n\n#include<helperFunctions>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY \n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\nuniform samplerCube refractionCubeSampler;\n#else\nuniform sampler2D refraction2DSampler;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\n#if SPECULARDIRECTUV == 1\n#define vSpecularUV vMainUV1\n#elif SPECULARDIRECTUV == 2\n#define vSpecularUV vMainUV2\n#else\nvarying vec2 vSpecularUV;\n#endif\nuniform sampler2D specularSampler;\n#endif\n#ifdef ALPHATEST\nuniform float alphaCutOff;\n#endif\n\n#include<fresnelFunction>\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\nuniform samplerCube reflectionCubeSampler;\n#else\nuniform sampler2D reflection2DSampler;\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#include<imageProcessingDeclaration>\n#include<imageProcessingFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n#include<fogFragmentDeclaration>\n#define CUSTOM_FRAGMENT_DEFINITIONS\nvoid main(void) {\n#define CUSTOM_FRAGMENT_MAIN_BEGIN\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\nvec4 baseColor=vec4(1.,1.,1.,1.);\nvec3 diffuseColor=vDiffuseColor.rgb;\n\nfloat alpha=vDiffuseColor.a;\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(-cross(dFdx(vPositionW),dFdy(vPositionW)));\n#endif\n#include<bumpFragment>\n#ifdef TWOSIDEDLIGHTING\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n#ifdef DIFFUSE\nbaseColor=texture2D(diffuseSampler,vDiffuseUV+uvOffset);\n#ifdef ALPHATEST\nif (baseColor.a<alphaCutOff)\ndiscard;\n#endif\n#ifdef ALPHAFROMDIFFUSE\nalpha*=baseColor.a;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_ALPHA\nbaseColor.rgb*=vDiffuseInfos.y;\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nbaseColor.rgb*=vColor.rgb;\n#endif\n#define CUSTOM_FRAGMENT_UPDATE_DIFFUSE\n\nvec3 baseAmbientColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nbaseAmbientColor=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_LIGHTS\n\n#ifdef SPECULARTERM\nfloat glossiness=vSpecularColor.a;\nvec3 specularColor=vSpecularColor.rgb;\n#ifdef SPECULAR\nvec4 specularMapColor=texture2D(specularSampler,vSpecularUV+uvOffset);\nspecularColor=specularMapColor.rgb;\n#ifdef GLOSSINESS\nglossiness=glossiness*specularMapColor.a;\n#endif\n#endif\n#else\nfloat glossiness=0.;\n#endif\n\nvec3 diffuseBase=vec3(0.,0.,0.);\nlightingInfo info;\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\nfloat shadow=1.;\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb*vLightmapInfos.y;\n#endif\n#include<lightFragment>[0..maxSimultaneousLights]\n\nvec3 refractionColor=vec3(0.,0.,0.);\n#ifdef REFRACTION\nvec3 refractionVector=normalize(refract(-viewDirectionW,normalW,vRefractionInfos.y));\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nif (dot(refractionVector,viewDirectionW)<1.0) {\nrefractionColor=textureCube(refractionCubeSampler,refractionVector).rgb;\n}\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\nrefractionColor=texture2D(refraction2DSampler,refractionCoords).rgb;\n#endif\n#ifdef IS_REFRACTION_LINEAR\nrefractionColor=toGammaSpace(refractionColor);\n#endif\nrefractionColor*=vRefractionInfos.x;\n#endif\n\nvec3 reflectionColor=vec3(0.,0.,0.);\n#ifdef REFLECTION\nvec3 vReflectionUVW=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_3D\n#ifdef ROUGHNESS\nfloat bias=vReflectionInfos.y;\n#ifdef SPECULARTERM\n#ifdef SPECULAR\n#ifdef GLOSSINESS\nbias*=(1.0-specularMapColor.a);\n#endif\n#endif\n#endif\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW,bias).rgb;\n#else\nreflectionColor=textureCube(reflectionCubeSampler,vReflectionUVW).rgb;\n#endif\n#else\nvec2 coords=vReflectionUVW.xy;\n#ifdef REFLECTIONMAP_PROJECTION\ncoords/=vReflectionUVW.z;\n#endif\ncoords.y=1.0-coords.y;\nreflectionColor=texture2D(reflection2DSampler,coords).rgb;\n#endif\n#ifdef IS_REFLECTION_LINEAR\nreflectionColor=toGammaSpace(reflectionColor);\n#endif\nreflectionColor*=vReflectionInfos.x;\n#ifdef REFLECTIONFRESNEL\nfloat reflectionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,reflectionRightColor.a,reflectionLeftColor.a);\n#ifdef REFLECTIONFRESNELFROMSPECULAR\n#ifdef SPECULARTERM\nreflectionColor*=specularColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#else\nreflectionColor*=reflectionLeftColor.rgb*(1.0-reflectionFresnelTerm)+reflectionFresnelTerm*reflectionRightColor.rgb;\n#endif\n#endif\n#endif\n#ifdef REFRACTIONFRESNEL\nfloat refractionFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,refractionRightColor.a,refractionLeftColor.a);\nrefractionColor*=refractionLeftColor.rgb*(1.0-refractionFresnelTerm)+refractionFresnelTerm*refractionRightColor.rgb;\n#endif\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nopacityMap.rgb=opacityMap.rgb*vec3(0.3,0.59,0.11);\nalpha*=(opacityMap.x+opacityMap.y+opacityMap.z)* vOpacityInfos.y;\n#else\nalpha*=opacityMap.a*vOpacityInfos.y;\n#endif\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#ifdef OPACITYFRESNEL\nfloat opacityFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,opacityParts.z,opacityParts.w);\nalpha+=opacityParts.x*(1.0-opacityFresnelTerm)+opacityFresnelTerm*opacityParts.y;\n#endif\n\nvec3 emissiveColor=vEmissiveColor;\n#ifdef EMISSIVE\nemissiveColor+=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb*vEmissiveInfos.y;\n#endif\n#ifdef EMISSIVEFRESNEL\nfloat emissiveFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,emissiveRightColor.a,emissiveLeftColor.a);\nemissiveColor*=emissiveLeftColor.rgb*(1.0-emissiveFresnelTerm)+emissiveFresnelTerm*emissiveRightColor.rgb;\n#endif\n\n#ifdef DIFFUSEFRESNEL\nfloat diffuseFresnelTerm=computeFresnelTerm(viewDirectionW,normalW,diffuseRightColor.a,diffuseLeftColor.a);\ndiffuseBase*=diffuseLeftColor.rgb*(1.0-diffuseFresnelTerm)+diffuseFresnelTerm*diffuseRightColor.rgb;\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\n#ifdef LINKEMISSIVEWITHDIFFUSE\nvec3 finalDiffuse=clamp((diffuseBase+emissiveColor)*diffuseColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#else\nvec3 finalDiffuse=clamp(diffuseBase*diffuseColor+emissiveColor+vAmbientColor,0.0,1.0)*baseColor.rgb;\n#endif\n#endif\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase*specularColor;\n#ifdef SPECULAROVERALPHA\nalpha=clamp(alpha+dot(finalSpecular,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n#else\nvec3 finalSpecular=vec3(0.0);\n#endif\n#ifdef REFLECTIONOVERALPHA\nalpha=clamp(alpha+dot(reflectionColor,vec3(0.3,0.59,0.11)),0.,1.);\n#endif\n\n#ifdef EMISSIVEASILLUMINATION\nvec4 color=vec4(clamp(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+emissiveColor+refractionColor,0.0,1.0),alpha);\n#else\nvec4 color=vec4(finalDiffuse*baseAmbientColor+finalSpecular+reflectionColor+refractionColor,alpha);\n#endif\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\ncolor.rgb*=lightmapColor;\n#else\ncolor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FOG\ncolor.rgb=max(color.rgb,0.);\n#include<logDepthFragment>\n#include<fogFragment>\n\n\n#ifdef IMAGEPROCESSINGPOSTPROCESS\ncolor.rgb=toLinearSpace(color.rgb);\n#else\n#ifdef IMAGEPROCESSING\ncolor.rgb=toLinearSpace(color.rgb);\ncolor=applyImageProcessing(color);\n#endif\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#define CUSTOM_FRAGMENT_BEFORE_FRAGCOLOR\ngl_FragColor=color;\n}\n","pbrVertexShader":"precision highp float;\n#include<__decl__pbrVertex>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#ifdef TANGENT\nattribute vec4 tangent;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif \n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<helperFunctions>\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#if defined(ALBEDO) && ALBEDODIRECTUV == 0\nvarying vec2 vAlbedoUV;\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0\nvarying vec2 vAmbientUV;\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0\nvarying vec2 vOpacityUV;\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0\nvarying vec2 vEmissiveUV;\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0\nvarying vec2 vLightmapUV;\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0\nvarying vec2 vReflectivityUV;\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0\nvarying vec2 vBumpUV;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#include<harmonicsFunctions>\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n#include<bumpVertexDeclaration>\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\nvec3 positionUpdated=position;\n#ifdef NORMAL\nvec3 normalUpdated=normal;\n#endif\n#ifdef TANGENT\nvec4 tangentUpdated=tangent;\n#endif\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=positionUpdated;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(positionUpdated,1.0);\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normalUpdated);\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvec3 reflectionVector=vec3(reflectionMatrix*vec4(vNormalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\nvEnvironmentIrradiance=environmentIrradianceJones(reflectionVector);\n#endif\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(positionUpdated,0.0)));\n#endif\n\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif \n#if defined(ALBEDO) && ALBEDODIRECTUV == 0 \nif (vAlbedoInfos.x == 0.)\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAlbedoUV=vec2(albedoMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(AMBIENT) && AMBIENTDIRECTUV == 0 \nif (vAmbientInfos.x == 0.)\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvAmbientUV=vec2(ambientMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(OPACITY) && OPACITYDIRECTUV == 0 \nif (vOpacityInfos.x == 0.)\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvOpacityUV=vec2(opacityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(EMISSIVE) && EMISSIVEDIRECTUV == 0 \nif (vEmissiveInfos.x == 0.)\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvEmissiveUV=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(LIGHTMAP) && LIGHTMAPDIRECTUV == 0 \nif (vLightmapInfos.x == 0.)\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvLightmapUV=vec2(lightmapMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(REFLECTIVITY) && REFLECTIVITYDIRECTUV == 0 \nif (vReflectivityInfos.x == 0.)\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvReflectivityUV=vec2(reflectivityMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(MICROSURFACEMAP) && MICROSURFACEMAPDIRECTUV == 0 \nif (vMicroSurfaceSamplerInfos.x == 0.)\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvMicroSurfaceSamplerUV=vec2(microSurfaceSamplerMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n#if defined(BUMP) && BUMPDIRECTUV == 0 \nif (vBumpInfos.x == 0.)\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvBumpUV=vec2(bumpMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<bumpVertex>\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n\n#include<logDepthVertex>\n}","pbrPixelShader":"#if defined(BUMP) || !defined(NORMAL) || defined(FORCENORMALFORWARD) || defined(SPECULARAA)\n#extension GL_OES_standard_derivatives : enable\n#endif\n#ifdef LODBASEDMICROSFURACE\n#extension GL_EXT_shader_texture_lod : enable\n#endif\n#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nprecision highp float;\n#include<__decl__pbrFragment>\nuniform vec4 vEyePosition;\nuniform vec3 vAmbientColor;\nuniform vec4 vCameraInfos;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2;\n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#if defined(USESPHERICALFROMREFLECTIONMAP) && defined(USESPHERICALINVERTEX)\nvarying vec3 vEnvironmentIrradiance;\n#endif\n#endif\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n\n#ifdef ALBEDO\n#if ALBEDODIRECTUV == 1\n#define vAlbedoUV vMainUV1\n#elif ALBEDODIRECTUV == 2\n#define vAlbedoUV vMainUV2\n#else\nvarying vec2 vAlbedoUV;\n#endif\nuniform sampler2D albedoSampler;\n#endif\n#ifdef AMBIENT\n#if AMBIENTDIRECTUV == 1\n#define vAmbientUV vMainUV1\n#elif AMBIENTDIRECTUV == 2\n#define vAmbientUV vMainUV2\n#else\nvarying vec2 vAmbientUV;\n#endif\nuniform sampler2D ambientSampler;\n#endif\n#ifdef OPACITY\n#if OPACITYDIRECTUV == 1\n#define vOpacityUV vMainUV1\n#elif OPACITYDIRECTUV == 2\n#define vOpacityUV vMainUV2\n#else\nvarying vec2 vOpacityUV;\n#endif\nuniform sampler2D opacitySampler;\n#endif\n#ifdef EMISSIVE\n#if EMISSIVEDIRECTUV == 1\n#define vEmissiveUV vMainUV1\n#elif EMISSIVEDIRECTUV == 2\n#define vEmissiveUV vMainUV2\n#else\nvarying vec2 vEmissiveUV;\n#endif\nuniform sampler2D emissiveSampler;\n#endif\n#ifdef LIGHTMAP\n#if LIGHTMAPDIRECTUV == 1\n#define vLightmapUV vMainUV1\n#elif LIGHTMAPDIRECTUV == 2\n#define vLightmapUV vMainUV2\n#else\nvarying vec2 vLightmapUV;\n#endif\nuniform sampler2D lightmapSampler;\n#endif\n#ifdef REFLECTIVITY\n#if REFLECTIVITYDIRECTUV == 1\n#define vReflectivityUV vMainUV1\n#elif REFLECTIVITYDIRECTUV == 2\n#define vReflectivityUV vMainUV2\n#else\nvarying vec2 vReflectivityUV;\n#endif\nuniform sampler2D reflectivitySampler;\n#endif\n#ifdef MICROSURFACEMAP\n#if MICROSURFACEMAPDIRECTUV == 1\n#define vMicroSurfaceSamplerUV vMainUV1\n#elif MICROSURFACEMAPDIRECTUV == 2\n#define vMicroSurfaceSamplerUV vMainUV2\n#else\nvarying vec2 vMicroSurfaceSamplerUV;\n#endif\nuniform sampler2D microSurfaceSampler;\n#endif\n\n#ifdef REFRACTION\n#ifdef REFRACTIONMAP_3D\n#define sampleRefraction(s,c) textureCube(s,c)\nuniform samplerCube refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#else\n#define sampleRefraction(s,c) texture2D(s,c)\nuniform sampler2D refractionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleRefractionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube refractionSamplerLow;\nuniform samplerCube refractionSamplerHigh;\n#endif\n#endif\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef LODBASEDMICROSFURACE\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n#ifdef ENVIRONMENTBRDF\nuniform sampler2D environmentBrdfSampler;\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\n\n#include<shadowsFragmentFunctions>\n#include<pbrFunctions>\n#include<harmonicsFunctions>\n#include<pbrLightFunctions>\n#include<bumpFragmentFunctions>\n#include<clipPlaneFragmentDeclaration>\n#include<logDepthDeclaration>\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\n#include<clipPlaneFragment>\n\n\nvec3 viewDirectionW=normalize(vEyePosition.xyz-vPositionW);\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#endif\n#include<bumpFragment>\n#ifdef SPECULARAA\nvec3 nDfdx=dFdx(normalW.xyz);\nvec3 nDfdy=dFdy(normalW.xyz);\nfloat slopeSquare=max(dot(nDfdx,nDfdx),dot(nDfdy,nDfdy));\n\nfloat geometricRoughnessFactor=pow(clamp(slopeSquare ,0.,1.),0.333);\n\nfloat geometricAlphaGFactor=sqrt(slopeSquare);\n#else\nfloat geometricRoughnessFactor=0.;\n#endif\n#if defined(FORCENORMALFORWARD) && defined(NORMAL)\nvec3 faceNormal=normalize(cross(dFdx(vPositionW),dFdy(vPositionW)))*vEyePosition.w;\n#if defined(TWOSIDEDLIGHTING)\nfaceNormal=gl_FrontFacing ? faceNormal : -faceNormal;\n#endif\nnormalW*=sign(dot(normalW,faceNormal));\n#endif\n#if defined(TWOSIDEDLIGHTING) && defined(NORMAL)\nnormalW=gl_FrontFacing ? normalW : -normalW;\n#endif\n\n\nvec3 surfaceAlbedo=vAlbedoColor.rgb;\n\nfloat alpha=vAlbedoColor.a;\n#ifdef ALBEDO\nvec4 albedoTexture=texture2D(albedoSampler,vAlbedoUV+uvOffset);\n#if defined(ALPHAFROMALBEDO) || defined(ALPHATEST)\nalpha*=albedoTexture.a;\n#endif\nsurfaceAlbedo*=toLinearSpace(albedoTexture.rgb);\nsurfaceAlbedo*=vAlbedoInfos.y;\n#endif\n\n#ifdef OPACITY\nvec4 opacityMap=texture2D(opacitySampler,vOpacityUV+uvOffset);\n#ifdef OPACITYRGB\nalpha=getLuminance(opacityMap.rgb);\n#else\nalpha*=opacityMap.a;\n#endif\nalpha*=vOpacityInfos.y;\n#endif\n#ifdef VERTEXALPHA\nalpha*=vColor.a;\n#endif\n#if !defined(LINKREFRACTIONTOTRANSPARENCY) && !defined(ALPHAFRESNEL)\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#include<depthPrePass>\n#ifdef VERTEXCOLOR\nsurfaceAlbedo*=vColor.rgb;\n#endif\n\nvec3 ambientOcclusionColor=vec3(1.,1.,1.);\n#ifdef AMBIENT\nvec3 ambientOcclusionColorMap=texture2D(ambientSampler,vAmbientUV+uvOffset).rgb*vAmbientInfos.y;\n#ifdef AMBIENTINGRAYSCALE\nambientOcclusionColorMap=vec3(ambientOcclusionColorMap.r,ambientOcclusionColorMap.r,ambientOcclusionColorMap.r);\n#endif\nambientOcclusionColor=mix(ambientOcclusionColor,ambientOcclusionColorMap,vAmbientInfos.z);\n#endif\n#ifdef UNLIT\nvec3 diffuseBase=vec3(1.,1.,1.);\n#else\n\nfloat microSurface=vReflectivityColor.a;\nvec3 surfaceReflectivityColor=vReflectivityColor.rgb;\n#ifdef METALLICWORKFLOW\nvec2 metallicRoughness=surfaceReflectivityColor.rg;\n#ifdef REFLECTIVITY\nvec4 surfaceMetallicColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\n#ifdef AOSTOREINMETALMAPRED\nvec3 aoStoreInMetalMap=vec3(surfaceMetallicColorMap.r,surfaceMetallicColorMap.r,surfaceMetallicColorMap.r);\nambientOcclusionColor=mix(ambientOcclusionColor,aoStoreInMetalMap,vReflectivityInfos.z);\n#endif\n#ifdef METALLNESSSTOREINMETALMAPBLUE\nmetallicRoughness.r*=surfaceMetallicColorMap.b;\n#else\nmetallicRoughness.r*=surfaceMetallicColorMap.r;\n#endif\n#ifdef ROUGHNESSSTOREINMETALMAPALPHA\nmetallicRoughness.g*=surfaceMetallicColorMap.a;\n#else\n#ifdef ROUGHNESSSTOREINMETALMAPGREEN\nmetallicRoughness.g*=surfaceMetallicColorMap.g;\n#endif\n#endif\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmetallicRoughness.g*=microSurfaceTexel.r;\n#endif\n\nmicroSurface=1.0-metallicRoughness.g;\n\nvec3 baseColor=surfaceAlbedo;\n\n\nconst vec3 DefaultSpecularReflectanceDielectric=vec3(0.04,0.04,0.04);\n\nsurfaceAlbedo=mix(baseColor.rgb*(1.0-DefaultSpecularReflectanceDielectric.r),vec3(0.,0.,0.),metallicRoughness.r);\n\nsurfaceReflectivityColor=mix(DefaultSpecularReflectanceDielectric,baseColor,metallicRoughness.r);\n#else\n#ifdef REFLECTIVITY\nvec4 surfaceReflectivityColorMap=texture2D(reflectivitySampler,vReflectivityUV+uvOffset);\nsurfaceReflectivityColor*=toLinearSpace(surfaceReflectivityColorMap.rgb);\nsurfaceReflectivityColor*=vReflectivityInfos.y;\n#ifdef MICROSURFACEFROMREFLECTIVITYMAP\nmicroSurface*=surfaceReflectivityColorMap.a;\nmicroSurface*=vReflectivityInfos.z;\n#else\n#ifdef MICROSURFACEAUTOMATIC\nmicroSurface*=computeDefaultMicroSurface(microSurface,surfaceReflectivityColor);\n#endif\n#ifdef MICROSURFACEMAP\nvec4 microSurfaceTexel=texture2D(microSurfaceSampler,vMicroSurfaceSamplerUV+uvOffset)*vMicroSurfaceSamplerInfos.y;\nmicroSurface*=microSurfaceTexel.r;\n#endif\n#endif\n#endif\n#endif\n\nmicroSurface=clamp(microSurface,0.,1.);\n\nfloat roughness=1.-microSurface;\n\n#ifdef ALPHAFRESNEL\n#if defined(ALPHATEST) || defined(ALPHABLEND)\n\n\n\nfloat opacityPerceptual=alpha;\n#ifdef LINEARALPHAFRESNEL\nfloat opacity0=opacityPerceptual;\n#else\nfloat opacity0=opacityPerceptual*opacityPerceptual;\n#endif\nfloat opacity90=fresnelGrazingReflectance(opacity0);\nvec3 normalForward=faceforward(normalW,-viewDirectionW,normalW);\n\nalpha=fresnelSchlickEnvironmentGGX(clamp(dot(viewDirectionW,normalForward),0.0,1.0),vec3(opacity0),vec3(opacity90),sqrt(microSurface)).x;\n#ifdef ALPHATEST\nif (alpha<ALPHATESTVALUE)\ndiscard;\n#ifndef ALPHABLEND\n\nalpha=1.0;\n#endif\n#endif\n#endif\n#endif\n\n\nfloat NdotVUnclamped=dot(normalW,viewDirectionW);\nfloat NdotV=clamp(NdotVUnclamped,0.,1.)+0.00001;\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\n#ifdef SPECULARAA\n\n\nalphaG+=(0.75*geometricAlphaGFactor);\n#endif\n\n#ifdef REFRACTION\nvec4 environmentRefraction=vec4(0.,0.,0.,0.);\nvec3 refractionVector=refract(-viewDirectionW,normalW,vRefractionInfos.y);\n#ifdef REFRACTIONMAP_OPPOSITEZ\nrefractionVector.z*=-1.0;\n#endif\n\n#ifdef REFRACTIONMAP_3D\nrefractionVector.y=refractionVector.y*vRefractionInfos.w;\nvec3 refractionCoords=refractionVector;\nrefractionCoords=vec3(refractionMatrix*vec4(refractionCoords,0));\n#else\nvec3 vRefractionUVW=vec3(refractionMatrix*(view*vec4(vPositionW+refractionVector*vRefractionInfos.z,1.0)));\nvec2 refractionCoords=vRefractionUVW.xy/vRefractionUVW.z;\nrefractionCoords.y=1.0-refractionCoords.y;\n#endif\n#ifdef LODINREFRACTIONALPHA\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat refractionLOD=getLodFromAlphaG(vRefractionMicrosurfaceInfos.x,alphaG,1.0);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nrefractionLOD=refractionLOD*vRefractionMicrosurfaceInfos.y+vRefractionMicrosurfaceInfos.z;\n#ifdef LODINREFRACTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticRefractionLOD=UNPACK_LOD(sampleRefraction(refractionSampler,refractionCoords).a);\nfloat requestedRefractionLOD=max(automaticRefractionLOD,refractionLOD);\n#else\nfloat requestedRefractionLOD=refractionLOD;\n#endif\nenvironmentRefraction=sampleRefractionLod(refractionSampler,refractionCoords,requestedRefractionLOD);\n#else\nfloat lodRefractionNormalized=clamp(refractionLOD/log2(vRefractionMicrosurfaceInfos.x),0.,1.);\nfloat lodRefractionNormalizedDoubled=lodRefractionNormalized*2.0;\nvec4 environmentRefractionMid=sampleRefraction(refractionSampler,refractionCoords);\nif(lodRefractionNormalizedDoubled<1.0){\nenvironmentRefraction=mix(\nsampleRefraction(refractionSamplerHigh,refractionCoords),\nenvironmentRefractionMid,\nlodRefractionNormalizedDoubled\n);\n}else{\nenvironmentRefraction=mix(\nenvironmentRefractionMid,\nsampleRefraction(refractionSamplerLow,refractionCoords),\nlodRefractionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef GAMMAREFRACTION\nenvironmentRefraction.rgb=fromRGBD(environmentRefraction);\n#endif\n#ifdef RGBDREFRACTION\nenvironmentRefraction.rgb=toLinearSpace(environmentRefraction.rgb);\n#endif\n\nenvironmentRefraction.rgb*=vRefractionInfos.x;\n#endif\n\n#ifdef REFLECTION\nvec4 environmentRadiance=vec4(0.,0.,0.,0.);\nvec3 environmentIrradiance=vec3(0.,0.,0.);\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#if defined(LODINREFLECTIONALPHA) && !defined(REFLECTIONMAP_SKYBOX)\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,NdotVUnclamped);\n#else\nfloat reflectionLOD=getLodFromAlphaG(vReflectionMicrosurfaceInfos.x,alphaG,1.);\n#endif\n#ifdef LODBASEDMICROSFURACE\n\nreflectionLOD=reflectionLOD*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\n#ifdef LODINREFLECTIONALPHA\n\n\n\n\n\n\n\n\n\nfloat automaticReflectionLOD=UNPACK_LOD(sampleReflection(reflectionSampler,reflectionCoords).a);\nfloat requestedReflectionLOD=max(automaticReflectionLOD,reflectionLOD);\n#else\nfloat requestedReflectionLOD=reflectionLOD;\n#endif\nenvironmentRadiance=sampleReflectionLod(reflectionSampler,reflectionCoords,requestedReflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD/log2(vReflectionMicrosurfaceInfos.x),0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 environmentSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nenvironmentRadiance=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nenvironmentSpecularMid,\nlodReflectionNormalizedDoubled\n);\n}else{\nenvironmentRadiance=mix(\nenvironmentSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#ifdef RGBDREFLECTION\nenvironmentRadiance.rgb=fromRGBD(environmentRadiance);\n#endif\n#ifdef GAMMAREFLECTION\nenvironmentRadiance.rgb=toLinearSpace(environmentRadiance.rgb);\n#endif\n\n#ifdef USESPHERICALFROMREFLECTIONMAP\n#if defined(NORMAL) && defined(USESPHERICALINVERTEX)\nenvironmentIrradiance=vEnvironmentIrradiance;\n#else\nvec3 irradianceVector=vec3(reflectionMatrix*vec4(normalW,0)).xyz;\n#ifdef REFLECTIONMAP_OPPOSITEZ\nirradianceVector.z*=-1.0;\n#endif\nenvironmentIrradiance=environmentIrradianceJones(irradianceVector);\n#endif\n#endif\n\nenvironmentRadiance.rgb*=vReflectionInfos.x;\nenvironmentRadiance.rgb*=vReflectionColor.rgb;\nenvironmentIrradiance*=vReflectionColor.rgb;\n#endif\n\n\n\nfloat reflectance=max(max(surfaceReflectivityColor.r,surfaceReflectivityColor.g),surfaceReflectivityColor.b);\nfloat reflectance90=fresnelGrazingReflectance(reflectance);\nvec3 specularEnvironmentR0=surfaceReflectivityColor.rgb;\nvec3 specularEnvironmentR90=vec3(1.0,1.0,1.0)*reflectance90;\n\nvec3 diffuseBase=vec3(0.,0.,0.);\n#ifdef SPECULARTERM\nvec3 specularBase=vec3(0.,0.,0.);\n#endif\n#ifdef LIGHTMAP\nvec3 lightmapColor=texture2D(lightmapSampler,vLightmapUV+uvOffset).rgb;\n#ifdef GAMMALIGHTMAP\nlightmapColor=toLinearSpace(lightmapColor);\n#endif\nlightmapColor*=vLightmapInfos.y;\n#endif\nlightingInfo info;\nfloat shadow=1.; \nfloat NdotL=-1.;\n#include<lightFragment>[0..maxSimultaneousLights]\n\n#if defined(ENVIRONMENTBRDF) && !defined(REFLECTIONMAP_SKYBOX)\n\nvec2 brdfSamplerUV=vec2(NdotV,roughness);\n\nvec4 environmentBrdf=texture2D(environmentBrdfSampler,brdfSamplerUV);\nvec3 specularEnvironmentReflectance=specularEnvironmentR0*environmentBrdf.x+environmentBrdf.y;\n#ifdef RADIANCEOCCLUSION\n#ifdef AMBIENTINGRAYSCALE\nfloat ambientMonochrome=ambientOcclusionColor.r;\n#else\nfloat ambientMonochrome=getLuminance(ambientOcclusionColor);\n#endif\nfloat seo=environmentRadianceOcclusion(ambientMonochrome,NdotVUnclamped);\nspecularEnvironmentReflectance*=seo;\n#endif\n#ifdef HORIZONOCCLUSION\n#ifdef BUMP\n#ifdef REFLECTIONMAP_3D\nfloat eho=environmentHorizonOcclusion(-viewDirectionW,normalW);\nspecularEnvironmentReflectance*=eho;\n#endif\n#endif\n#endif\n#else\n\nvec3 specularEnvironmentReflectance=fresnelSchlickEnvironmentGGX(NdotV,specularEnvironmentR0,specularEnvironmentR90,sqrt(microSurface));\n#endif\n\n#ifdef REFRACTION\nvec3 refractance=vec3(0.0,0.0,0.0);\nvec3 transmission=vec3(1.0,1.0,1.0);\n#ifdef LINKREFRACTIONTOTRANSPARENCY\n\ntransmission*=(1.0-alpha);\n\n\nvec3 mixedAlbedo=surfaceAlbedo;\nfloat maxChannel=max(max(mixedAlbedo.r,mixedAlbedo.g),mixedAlbedo.b);\nvec3 tint=clamp(maxChannel*mixedAlbedo,0.0,1.0);\n\nsurfaceAlbedo*=alpha;\n\nenvironmentIrradiance*=alpha;\n\nenvironmentRefraction.rgb*=tint;\n\nalpha=1.0;\n#endif\n\nvec3 bounceSpecularEnvironmentReflectance=(2.0*specularEnvironmentReflectance)/(1.0+specularEnvironmentReflectance);\nspecularEnvironmentReflectance=mix(bounceSpecularEnvironmentReflectance,specularEnvironmentReflectance,alpha);\n\ntransmission*=1.0-specularEnvironmentReflectance;\n\nrefractance=transmission;\n#endif\n\n\n\n\nsurfaceAlbedo.rgb=(1.-reflectance)*surfaceAlbedo.rgb;\n\n#ifdef REFLECTION\nvec3 finalIrradiance=environmentIrradiance;\nfinalIrradiance*=surfaceAlbedo.rgb;\n#endif\n\n#ifdef SPECULARTERM\nvec3 finalSpecular=specularBase;\nfinalSpecular=max(finalSpecular,0.0);\n\nvec3 finalSpecularScaled=finalSpecular*vLightingIntensity.x*vLightingIntensity.w;\n#endif\n\n#ifdef REFLECTION\nvec3 finalRadiance=environmentRadiance.rgb;\nfinalRadiance*=specularEnvironmentReflectance;\n\nvec3 finalRadianceScaled=finalRadiance*vLightingIntensity.z;\n#endif\n\n#ifdef REFRACTION\nvec3 finalRefraction=environmentRefraction.rgb;\nfinalRefraction*=refractance;\n#endif\n\n#ifdef ALPHABLEND\nfloat luminanceOverAlpha=0.0;\n#if defined(REFLECTION) && defined(RADIANCEOVERALPHA)\nluminanceOverAlpha+=getLuminance(finalRadianceScaled);\n#endif\n#if defined(SPECULARTERM) && defined(SPECULAROVERALPHA)\nluminanceOverAlpha+=getLuminance(finalSpecularScaled);\n#endif\n#if defined(RADIANCEOVERALPHA) || defined(SPECULAROVERALPHA)\nalpha=clamp(alpha+luminanceOverAlpha*luminanceOverAlpha,0.,1.);\n#endif\n#endif\n#endif\n\nvec3 finalDiffuse=diffuseBase;\nfinalDiffuse.rgb+=vAmbientColor;\nfinalDiffuse*=surfaceAlbedo.rgb;\nfinalDiffuse=max(finalDiffuse,0.0);\n\nvec3 finalEmissive=vEmissiveColor;\n#ifdef EMISSIVE\nvec3 emissiveColorTex=texture2D(emissiveSampler,vEmissiveUV+uvOffset).rgb;\nfinalEmissive*=toLinearSpace(emissiveColorTex.rgb);\nfinalEmissive*=vEmissiveInfos.y;\n#endif\n\n\n\nvec4 finalColor=vec4(\nfinalDiffuse*ambientOcclusionColor*vLightingIntensity.x +\n#ifndef UNLIT\n#ifdef REFLECTION\nfinalIrradiance*ambientOcclusionColor*vLightingIntensity.z +\n#endif\n#ifdef SPECULARTERM\n\n\nfinalSpecularScaled +\n#endif\n#ifdef REFLECTION\n\n\nfinalRadianceScaled +\n#endif\n#ifdef REFRACTION\nfinalRefraction*vLightingIntensity.z +\n#endif\n#endif\nfinalEmissive*vLightingIntensity.y,\nalpha);\n\n#ifdef LIGHTMAP\n#ifndef LIGHTMAPEXCLUDED\n#ifdef USELIGHTMAPASSHADOWMAP\nfinalColor.rgb*=lightmapColor;\n#else\nfinalColor.rgb+=lightmapColor;\n#endif\n#endif\n#endif\n\nfinalColor=max(finalColor,0.0);\n#include<logDepthFragment>\n#include<fogFragment>(color,finalColor)\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\nfinalColor.rgb=clamp(finalColor.rgb,0.,30.0);\n#else\n\nfinalColor=applyImageProcessing(finalColor);\n#endif\n#ifdef PREMULTIPLYALPHA\n\nfinalColor.rgb*=finalColor.a;\n#endif\ngl_FragColor=finalColor;\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n}","rgbdEncodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=toRGBD(texture2D(textureSampler,vUV).rgb);\n}","rgbdDecodePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<helperFunctions>\nvoid main(void) \n{\ngl_FragColor=vec4(fromRGBD(texture2D(textureSampler,vUV)),1.0);\n}","spritesVertexShader":"\nattribute vec4 position;\nattribute vec4 options;\nattribute vec4 cellInfo;\nattribute vec4 color;\n\nuniform vec2 textureInfos;\nuniform mat4 view;\nuniform mat4 projection;\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#include<fogVertexDeclaration>\nvoid main(void) { \nvec3 viewPos=(view*vec4(position.xyz,1.0)).xyz; \nvec2 cornerPos;\nfloat angle=position.w;\nvec2 size=vec2(options.x,options.y);\nvec2 offset=options.zw;\nvec2 uvScale=textureInfos.xy;\ncornerPos=vec2(offset.x-0.5,offset.y-0.5)*size;\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\n\nviewPos+=rotatedCorner;\ngl_Position=projection*vec4(viewPos,1.0); \n\nvColor=color;\n\nvec2 uvOffset=vec2(abs(offset.x-cellInfo.x),1.0-abs(offset.y-cellInfo.y));\nvUV=(uvOffset+cellInfo.zw)*uvScale;\n\n#ifdef FOG\nvFogDistance=viewPos;\n#endif\n}","spritesPixelShader":"uniform bool alphaTest;\nvarying vec4 vColor;\n\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n\n#include<fogFragmentDeclaration>\nvoid main(void) {\nvec4 color=texture2D(diffuseSampler,vUV);\nif (alphaTest) \n{\nif (color.a<0.95)\ndiscard;\n}\ncolor*=vColor;\n#include<fogFragment>\ngl_FragColor=color;\n}","particlesVertexShader":"\nattribute vec3 position;\nattribute vec4 color;\nattribute float angle;\nattribute vec2 size;\n#ifdef ANIMATESHEET \nattribute float cellIndex;\n#endif\n#ifndef BILLBOARD \nattribute vec3 direction;\n#endif\nattribute vec2 offset;\n\nuniform mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n#ifdef ANIMATESHEET \nuniform vec3 particlesInfos; \n#endif\n\nvarying vec2 vUV;\nvarying vec4 vColor;\n#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nuniform mat4 invView;\nvarying float fClipDistance;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner; \n}\nvoid main(void) { \nvec2 cornerPos;\ncornerPos=(vec2(offset.x-0.5,offset.y-0.5)-translationPivot)*size+translationPivot;\n#ifdef BILLBOARD \n\nvec3 rotatedCorner;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner);\nvec3 viewPos=(view*vec4(worldPos,1.0)).xyz; \n#else\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.y=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.z=0.;\nvec3 viewPos=(view*vec4(position,1.0)).xyz+rotatedCorner; \n#endif\n\ngl_Position=projection*vec4(viewPos,1.0); \n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle)-cornerPos.y*sin(angle);\nrotatedCorner.z=cornerPos.x*sin(angle)+cornerPos.y*cos(angle);\nrotatedCorner.y=0.;\nvec3 yaxis=normalize(direction);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\ngl_Position=projection*view*vec4(worldPos,1.0); \n#endif \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 mat4 view;\nuniform mat4 projection;\nuniform vec2 translationPivot;\n\nin vec3 position;\nin float age;\nin float life;\nin vec3 size;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\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\n#ifdef COLORGRADIENTS\nuniform sampler2D colorGradientSampler;\n#else\nuniform vec4 colorDead;\nin vec4 color;\n#endif\n#ifdef ANIMATESHEET\nuniform vec3 sheetInfos;\n#endif\n#ifdef BILLBOARD\nuniform vec3 eyePosition; \n#endif\nvec3 rotate(vec3 yaxis,vec3 rotatedCorner) {\nvec3 xaxis=normalize(cross(vec3(0.,1.0,0.),yaxis));\nvec3 zaxis=normalize(cross(yaxis,xaxis));\nvec3 row0=vec3(xaxis.x,xaxis.y,xaxis.z);\nvec3 row1=vec3(yaxis.x,yaxis.y,yaxis.z);\nvec3 row2=vec3(zaxis.x,zaxis.y,zaxis.z);\nmat3 rotMatrix=mat3(row0,row1,row2);\nvec3 alignedCorner=rotMatrix*rotatedCorner;\nreturn position+alignedCorner;\n}\nvoid main() {\n#ifdef ANIMATESHEET\nfloat rowOffset=floor(cellIndex/sheetInfos.z);\nfloat columnOffset=cellIndex-rowOffset*sheetInfos.z;\nvec2 uvScale=sheetInfos.xy;\nvec2 uvOffset=vec2(uv.x ,1.0-uv.y);\nvUV=(uvOffset+vec2(columnOffset,rowOffset))*uvScale;\n#else \nvUV=uv;\n#endif\nfloat ratio=age/life;\n#ifdef COLORGRADIENTS\nvColor=texture(colorGradientSampler,vec2(ratio,0));\n#else\nvColor=color*vec4(1.0-ratio)+colorDead*vec4(ratio);\n#endif\nvec2 cornerPos=(offset-translationPivot)*size.yz*size.x+translationPivot;\n#ifdef BILLBOARD\nvec4 rotatedCorner;\nrotatedCorner.w=0.;\n#ifdef BILLBOARDY \nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.y=0.;\nvec3 yaxis=position-eyePosition;\nyaxis.y=0.;\nvec3 worldPos=rotate(normalize(yaxis),rotatedCorner.xyz);\nvec4 viewPosition=(view*vec4(worldPos,1.0)); \n#else\n\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nrotatedCorner.z=0.;\n\nvec4 viewPosition=view*vec4(position,1.0)+rotatedCorner;\n#endif\n#else\n\nvec3 rotatedCorner;\nrotatedCorner.x=cornerPos.x*cos(angle.x)-cornerPos.y*sin(angle.x);\nrotatedCorner.y=0.;\nrotatedCorner.z=cornerPos.x*sin(angle.x)+cornerPos.y*cos(angle.x);\nvec3 yaxis=normalize(initialDirection);\nvec3 worldPos=rotate(yaxis,rotatedCorner);\n\nvec4 viewPosition=view*vec4(worldPos,1.0); \n#endif\ngl_Position=projection*viewPosition;\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 mat4 emitterWM;\nuniform vec2 lifeTime;\nuniform vec2 emitPower;\nuniform vec2 sizeRange;\nuniform vec4 scaleRange;\n#ifndef COLORGRADIENTS\nuniform vec4 color1;\nuniform vec4 color2;\n#endif\nuniform vec3 gravity;\nuniform sampler2D randomSampler;\nuniform sampler2D randomSampler2;\nuniform vec4 angleRange;\n#ifdef BOXEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\nuniform vec3 minEmitBox;\nuniform vec3 maxEmitBox;\n#endif\n#ifdef SPHEREEMITTER\nuniform float radius;\nuniform float radiusRange;\n#ifdef DIRECTEDSPHEREEMITTER\nuniform vec3 direction1;\nuniform vec3 direction2;\n#else\nuniform float directionRandomizer;\n#endif\n#endif\n#ifdef CONEEMITTER\nuniform vec2 radius;\nuniform float coneAngle;\nuniform vec2 height;\nuniform float directionRandomizer;\n#endif\n\nin vec3 position;\nin float age;\nin float life;\nin vec4 seed;\nin vec3 size;\n#ifndef COLORGRADIENTS\nin vec4 color;\n#endif\nin vec3 direction;\n#ifndef BILLBOARD\nin vec3 initialDirection;\n#endif\nin vec2 angle;\n#ifdef ANIMATESHEET\nin float cellIndex;\n#endif\n\nout vec3 outPosition;\nout float outAge;\nout float outLife;\nout vec4 outSeed;\nout vec3 outSize;\n#ifndef COLORGRADIENTS\nout vec4 outColor;\n#endif\nout vec3 outDirection;\n#ifndef BILLBOARD\nout vec3 outInitialDirection;\n#endif\nout vec2 outAngle;\n#ifdef ANIMATESHEET\nout float outCellIndex;\n#endif\n#ifdef SIZEGRADIENTS\nuniform sampler2D sizeGradientSampler;\n#endif \n#ifdef ANIMATESHEET\nuniform vec3 cellInfos;\n#endif\nvec3 getRandomVec3(float offset) {\nreturn texture(randomSampler2,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;\n#ifndef COLORGRADIENTS \noutColor=vec4(0.,0.,0.,0.);\n#endif\noutSize=vec3(0.,0.,0.);\n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif \noutDirection=direction;\noutAngle=angle;\n#ifdef ANIMATESHEET \noutCellIndex=cellIndex;\n#endif\nreturn;\n}\nvec3 position;\nvec3 direction;\n\nvec4 randoms=getRandomVec4(seed.x);\n\noutAge=0.0;\noutLife=lifeTime.x+(lifeTime.y-lifeTime.x)*randoms.r;\n\noutSeed=seed;\n\n#ifdef SIZEGRADIENTS \noutSize.x=texture(sizeGradientSampler,vec2(0,0)).r;\n#else\noutSize.x=sizeRange.x+(sizeRange.y-sizeRange.x)*randoms.g;\n#endif\noutSize.y=scaleRange.x+(scaleRange.y-scaleRange.x)*randoms.b;\noutSize.z=scaleRange.z+(scaleRange.w-scaleRange.z)*randoms.a; \n#ifndef COLORGRADIENTS\n\noutColor=color1+(color2-color1)*randoms.b;\n#endif\n\noutAngle.y=angleRange.x+(angleRange.y-angleRange.x)*randoms.a;\noutAngle.x=angleRange.z+(angleRange.w-angleRange.z)*randoms.r;\n\n#ifdef BOXEMITTER\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\nposition=minEmitBox+(maxEmitBox-minEmitBox)*randoms2;\ndirection=direction1+(direction2-direction1)*randoms3;\n#elif defined(SPHEREEMITTER)\nvec3 randoms2=getRandomVec3(seed.y);\nvec3 randoms3=getRandomVec3(seed.z);\n\nfloat phi=2.0*PI*randoms2.x;\nfloat theta=acos(2.0*randoms2.y-1.0);\nfloat randX=cos(phi)*sin(theta);\nfloat randY=cos(theta);\nfloat randZ=sin(phi)*sin(theta);\nposition=(radius-(radius*radiusRange*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(seed.y);\nfloat s=2.0*PI*randoms2.x;\nfloat h=randoms2.y*height.y;\n\nh=1.-h*h;\nfloat lRadius=radius.x-radius.x*randoms2.z*radius.y;\nlRadius=lRadius*h;\nfloat randX=lRadius*sin(s);\nfloat randZ=lRadius*cos(s);\nfloat randY=h*height.x;\nposition=vec3(randX,randY,randZ); \n\nif (abs(cos(coneAngle)) == 1.0) {\ndirection=vec3(0.,1.0,0.);\n} else {\nvec3 randoms3=getRandomVec3(seed.z);\ndirection=position+directionRandomizer*randoms3;\n}\n#else \n\nposition=vec3(0.,0.,0.);\n\ndirection=2.0*(getRandomVec3(seed.w)-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;\nvec3 initial=(emitterWM*vec4(direction,0.)).xyz;\noutDirection=initial*power;\n#ifndef BILLBOARD \noutInitialDirection=initial;\n#endif\n#ifdef ANIMATESHEET \noutCellIndex=cellInfos.x;\n#endif\n} else { \noutPosition=position+direction*timeDelta;\noutAge=age+timeDelta;\noutLife=life;\noutSeed=seed;\n#ifndef COLORGRADIENTS \noutColor=color;\n#endif\n#ifdef SIZEGRADIENTS\noutSize.x=texture(sizeGradientSampler,vec2(age/life,0)).r;\noutSize.yz=size.yz;\n#else\noutSize=size;\n#endif \n#ifndef BILLBOARD \noutInitialDirection=initialDirection;\n#endif\noutDirection=direction+gravity*timeDelta;\noutAngle=vec2(angle.x+angle.y*timeDelta,angle.y);\n#ifdef ANIMATESHEET \nfloat dist=cellInfos.y-cellInfos.x;\nfloat ratio=clamp(mod(outAge*cellInfos.z,life)/life,0.,1.0);\noutCellIndex=float(int(cellInfos.x+ratio*dist));\n#endif\n}\n}","gpuUpdateParticlesPixelShader":"#version 300 es\nvoid main() {\ndiscard;\n}\n","colorVertexShader":"\nattribute vec3 position;\n#ifdef VERTEXCOLOR\nattribute vec4 color;\n#endif\n#include<bonesDeclaration>\n\nuniform mat4 viewProjection;\nuniform mat4 world;\n\n#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#endif\nvoid main(void) {\nmat4 finalWorld=world;\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#ifdef VERTEXCOLOR\n\nvColor=color;\n#endif\n}","colorPixelShader":"#ifdef VERTEXCOLOR\nvarying vec4 vColor;\n#else\nuniform vec4 color;\n#endif\nvoid main(void) {\n#ifdef VERTEXCOLOR\ngl_FragColor=vColor;\n#else\ngl_FragColor=color;\n#endif\n}","postprocessVertexShader":"\nattribute vec2 position;\nuniform vec2 scale;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd)*scale;\ngl_Position=vec4(position,0.0,1.0);\n}","passPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\n}","shadowMapVertexShader":"\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\nuniform vec3 lightData;\n#endif\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\n#include<helperFunctions>\nuniform mat4 viewProjection;\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 worldPos=finalWorld*vec4(positionUpdated,1.0);\n\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvec3 worldNor=normalize(normalWorld*normal);\n#ifdef DIRECTIONINLIGHTDATA\nvec3 worldLightDir=normalize(-lightData.xyz);\n#else\nvec3 directionToLight=lightData.xyz-worldPos.xyz;\nvec3 worldLightDir=normalize(directionToLight);\n#endif\nfloat ndl=dot(worldNor,worldLightDir);\nfloat sinNL=sqrt(1.0-ndl*ndl);\nfloat normalBias=biasAndScale.y*sinNL;\nworldPos.xyz-=worldNor*normalBias;\n#endif\n\ngl_Position=viewProjection*worldPos;\n#ifdef DEPTHTEXTURE\n\ngl_Position.z+=biasAndScale.x*gl_Position.w;\n#endif\n\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y))+biasAndScale.x;\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","shadowMapPixelShader":"#ifndef FLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvarying float vDepthMetric;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nuniform vec3 biasAndScale;\nuniform vec2 depthValues;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\nfloat depth=vDepthMetric;\n#ifdef ESM\ndepth=clamp(exp(-min(87.,biasAndScale.z*depth)),0.,1.);\n#endif\n#ifdef FLOAT\ngl_FragColor=vec4(depth,1.0,1.0,1.0);\n#else\ngl_FragColor=pack(depth);\n#endif\n}","depthBoxBlurPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nvoid main(void)\n{\nvec4 colorDepth=vec4(0.0);\nfor (int x=-OFFSET; x<=OFFSET; x++)\nfor (int y=-OFFSET; y<=OFFSET; y++)\ncolorDepth+=texture2D(textureSampler,vUV+vec2(x,y)/screenSize);\ngl_FragColor=(colorDepth/float((OFFSET*2+1)*(OFFSET*2+1)));\n}","proceduralVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vPosition;\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvPosition=position;\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","depthVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nuniform vec2 depthValues;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvDepthMetric=((gl_Position.z+depthValues.x)/(depthValues.y));\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","depthPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\nvarying float vDepthMetric;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(vDepthMetric,vDepthMetric*vDepthMetric,0.0,1.0);\n}","ssaoPixelShader":"\nuniform sampler2D textureSampler;\nvarying vec2 vUV;\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float radius;\nuniform float area;\nuniform float fallOff;\nuniform float base;\nvec3 normalFromDepth(float depth,vec2 coords)\n{\nvec2 offset1=vec2(0.0,radius);\nvec2 offset2=vec2(radius,0.0);\nfloat depth1=texture2D(textureSampler,coords+offset1).r;\nfloat depth2=texture2D(textureSampler,coords+offset2).r;\nvec3 p1=vec3(offset1,depth1-depth);\nvec3 p2=vec3(offset2,depth2-depth);\nvec3 normal=cross(p1,p2);\nnormal.z=-normal.z;\nreturn normalize(normal);\n}\nvoid main()\n{\nvec3 random=normalize(texture2D(randomSampler,vUV*randTextureTiles).rgb);\nfloat depth=texture2D(textureSampler,vUV).r;\nvec3 position=vec3(vUV,depth);\nvec3 normal=normalFromDepth(depth,vUV);\nfloat radiusDepth=radius/depth;\nfloat occlusion=0.0;\nvec3 ray;\nvec3 hemiRay;\nfloat occlusionDepth;\nfloat difference;\nfor (int i=0; i<SAMPLES; i++)\n{\nray=radiusDepth*reflect(sampleSphere[i],random);\nhemiRay=position+sign(dot(ray,normal))*ray;\nocclusionDepth=texture2D(textureSampler,clamp(hemiRay.xy,vec2(0.001,0.001),vec2(0.999,0.999))).r;\ndifference=depth-occlusionDepth;\nocclusion+=step(fallOff,difference)*(1.0-smoothstep(fallOff,area,difference));\n}\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor.r=result;\ngl_FragColor.g=result;\ngl_FragColor.b=result;\ngl_FragColor.a=1.0;\n}\n#endif\n","ssao2PixelShader":"\nprecision highp float;\nuniform sampler2D textureSampler;\nuniform float near;\nuniform float far;\nuniform float radius;\nvarying vec2 vUV;\nfloat perspectiveDepthToViewZ( const in float invClipZ,const in float near,const in float far ) {\nreturn ( near*far )/( ( far-near )*invClipZ-far );\n}\nfloat viewZToPerspectiveDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( near*far/viewZ+far)/( far-near );\n}\nfloat viewZToOrthographicDepth( const in float viewZ,const in float near,const in float far ) {\nreturn ( viewZ+near )/( near-far );\n}\n#ifdef SSAO\nuniform sampler2D randomSampler;\nuniform sampler2D normalSampler;\nuniform float randTextureTiles;\nuniform float samplesFactor;\nuniform vec3 sampleSphere[SAMPLES];\nuniform float totalStrength;\nuniform float base;\nuniform float xViewport;\nuniform float yViewport;\nuniform float maxZ;\nuniform float minZAspect;\nuniform vec2 texelSize;\nuniform mat4 projection;\nvoid main()\n{\nvec3 random=texture2D(randomSampler,vUV*randTextureTiles).rgb;\nfloat depth=texture2D(textureSampler,vUV).r;\nfloat depthSign=depth/abs(depth);\ndepth=depth*depthSign;\nvec3 normal=texture2D(normalSampler,vUV).rgb; \nfloat occlusion=0.0;\nfloat correctedRadius=min(radius,minZAspect*depth/near);\nvec3 vViewRay=vec3((vUV.x*2.0-1.0)*xViewport,(vUV.y*2.0-1.0)*yViewport,depthSign);\nvec3 origin=vViewRay*depth;\nvec3 rvec=random*2.0-1.0;\nrvec.z=0.0;\nvec3 tangent=normalize(rvec-normal*dot(rvec,normal));\nvec3 bitangent=cross(normal,tangent);\nmat3 tbn=mat3(tangent,bitangent,normal);\nfloat difference;\nif (depth>maxZ) {\ngl_FragColor=vec4(1.0,1.0,1.0,1.0);\nreturn;\n}\nfor (int i=0; i<SAMPLES; ++i) {\n\nvec3 samplePosition=tbn*sampleSphere[i];\nsamplePosition=samplePosition*correctedRadius+origin;\n\nvec4 offset=vec4(samplePosition,1.0);\noffset=projection*offset;\noffset.xyz/=offset.w;\noffset.xy=offset.xy*0.5+0.5;\nif (offset.x<0.0 || offset.y<0.0 || offset.x>1.0 || offset.y>1.0) {\ncontinue;\n}\n\nfloat sampleDepth=abs(texture2D(textureSampler,offset.xy).r);\n\nfloat rangeCheck=abs(depth-sampleDepth)<correctedRadius ? 1.0 : 0.0;\ndifference=depthSign*samplePosition.z-sampleDepth;\n\nocclusion+=(difference>=1e-5 ? 1.0 : 0.0)*rangeCheck;\n}\n\nfloat ao=1.0-totalStrength*occlusion*samplesFactor;\nfloat result=clamp(ao+base,0.0,1.0);\ngl_FragColor=vec4(vec3(result),1.0);\n}\n#endif\n#ifdef BILATERAL_BLUR\nuniform sampler2D depthSampler;\nuniform float outSize;\nuniform float samplerOffsets[SAMPLES];\nvec4 blur9(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.3846153846)*direction;\nvec2 off2=vec2(3.2307692308)*direction;\ncolor+=texture2D(image,uv)*0.2270270270;\ncolor+=texture2D(image,uv+(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv-(off1/resolution))*0.3162162162;\ncolor+=texture2D(image,uv+(off2/resolution))*0.0702702703;\ncolor+=texture2D(image,uv-(off2/resolution))*0.0702702703;\nreturn color;\n}\nvec4 blur13(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\ncolor+=texture2D(image,uv)*0.1964825501511404;\ncolor+=texture2D(image,uv+(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv-(off1/resolution))*0.2969069646728344;\ncolor+=texture2D(image,uv+(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv-(off2/resolution))*0.09447039785044732;\ncolor+=texture2D(image,uv+(off3/resolution))*0.010381362401148057;\ncolor+=texture2D(image,uv-(off3/resolution))*0.010381362401148057;\nreturn color;\n}\nvec4 blur13Bilateral(sampler2D image,vec2 uv,float resolution,vec2 direction) {\nvec4 color=vec4(0.0);\nvec2 off1=vec2(1.411764705882353)*direction;\nvec2 off2=vec2(3.2941176470588234)*direction;\nvec2 off3=vec2(5.176470588235294)*direction;\nfloat compareDepth=abs(texture2D(depthSampler,uv).r);\nfloat sampleDepth;\nfloat weight;\nfloat weightSum=30.0;\ncolor+=texture2D(image,uv)*30.0;\nsampleDepth=abs(texture2D(depthSampler,uv+(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off1/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off1/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off2/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off2/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv+(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv+(off3/resolution))*weight;\nsampleDepth=abs(texture2D(depthSampler,uv-(off3/resolution)).r);\nweight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30.0);\nweightSum+=weight;\ncolor+=texture2D(image,uv-(off3/resolution))*weight;\nreturn color/weightSum;\n}\nvoid main()\n{\n#if EXPENSIVE\nfloat compareDepth=abs(texture2D(depthSampler,vUV).r);\nfloat texelsize=1.0/outSize;\nfloat result=0.0;\nfloat weightSum=0.0;\nfor (int i=0; i<SAMPLES; ++i)\n{\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\nvec2 sampleOffset=vec2(texelsize*samplerOffsets[i],0.0);\n#else\nvec2 direction=vec2(0.0,1.0);\nvec2 sampleOffset=vec2(0.0,texelsize*samplerOffsets[i]);\n#endif\nvec2 samplePos=vUV+sampleOffset;\nfloat sampleDepth=abs(texture2D(depthSampler,samplePos).r);\nfloat weight=clamp(1.0/( 0.003+abs(compareDepth-sampleDepth)),0.0,30000.0);\nresult+=texture2D(textureSampler,samplePos).r*weight;\nweightSum+=weight;\n}\nresult/=weightSum;\ngl_FragColor.rgb=vec3(result);\ngl_FragColor.a=1.0;\n#else\nvec4 color;\n#ifdef BILATERAL_BLUR_H\nvec2 direction=vec2(1.0,0.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#else\nvec2 direction=vec2(0.0,1.0);\ncolor=blur13Bilateral(textureSampler,vUV,outSize,direction);\n#endif\ngl_FragColor.rgb=vec3(color.r);\ngl_FragColor.a=1.0;\n#endif\n}\n#endif\n","ssaoCombinePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D originalColor;\nuniform vec4 viewport;\nvarying vec2 vUV;\nvoid main(void) {\nvec4 ssaoColor=texture2D(textureSampler,viewport.xy+vUV*viewport.zw);\nvec4 sceneColor=texture2D(originalColor,vUV);\ngl_FragColor=sceneColor*ssaoColor;\n}\n","lensHighlightsPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float gain;\nuniform float threshold;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\n\nvec4 highlightColor(vec4 color) {\nvec4 highlight=color;\nfloat luminance=dot(highlight.rgb,vec3(0.2125,0.7154,0.0721));\nfloat lum_threshold;\nif (threshold>1.0) { lum_threshold=0.94+0.01*threshold; }\nelse { lum_threshold=0.5+0.44*threshold; }\nluminance=clamp((luminance-lum_threshold)*(1.0/(1.0-lum_threshold)),0.0,1.0);\nhighlight*=luminance*gain;\nhighlight.a=1.0;\nreturn highlight;\n}\nvoid main(void)\n{\nvec4 original=texture2D(textureSampler,vUV);\n\nif (gain == -1.0) {\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\nreturn;\n}\nfloat w=2.0/screen_width;\nfloat h=2.0/screen_height;\nfloat weight=1.0;\n\nvec4 blurred=vec4(0.0,0.0,0.0,0.0);\n#ifdef PENTAGON\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.84*w,0.43*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.48*w,-1.29*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.61*w,1.51*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.55*w,-0.74*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.71*w,-0.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.94*w,1.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.40*w,-1.87*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.62*w,1.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.09*w,0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.46*w,-1.71*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.08*w,2.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.85*w,-1.89*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.89*w,0.16*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.29*w,1.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.40*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.54*w,2.26*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.60*w,-0.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.31*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.83*w,2.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.12*w,-2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.60*w,1.11*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.99*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.50*w,-2.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.85*w,3.33*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.94*w,-1.92*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.27*w,-0.53*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.95*w,2.48*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.23*w,-3.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.17*w,2.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.97*w,-0.04*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.25*w,-2.00*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.31*w,3.08*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.94*w,-2.59*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.37*w,0.64*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.13*w,1.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.03*w,-3.65*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.60*w,3.17*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.14*w,-1.19*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.00*w,-1.19*h)));\n#else\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.85*w,0.36*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.52*w,-1.14*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.46*w,1.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.46*w,-0.83*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.79*w,-0.42*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.11*w,1.62*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.29*w,-2.07*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.69*w,1.39*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.28*w,0.12*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.65*w,-1.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.08*w,2.44*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.63*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.55*w,0.31*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.13*w,1.52*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.56*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.38*w,2.34*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.64*w,-0.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.53*w,-1.21*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.06*w,2.63*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.00*w,-2.69*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.59*w,1.32*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.82*w,0.78*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.57*w,-2.50*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(0.54*w,2.93*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.39*w,-1.81*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,-0.28*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.04*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.02*w,-3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.09*w,2.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-3.07*w,-0.25*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.44*w,-1.90*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-0.52*w,3.05*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-1.68*w,-2.61*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(3.01*w,0.79*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.76*w,1.46*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.05*w,-2.94*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(1.21*w,2.88*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(-2.84*w,-1.30*h)));\nblurred+=highlightColor(texture2D(textureSampler,vUV+vec2(2.98*w,-0.96*h)));\n#endif\nblurred/=39.0;\ngl_FragColor=blurred;\n\n}","depthOfFieldPixelShader":"\n\n\n\n\nuniform sampler2D textureSampler;\nuniform sampler2D highlightsSampler;\nuniform sampler2D depthSampler;\nuniform sampler2D grainSampler;\n\nuniform float grain_amount;\nuniform bool blur_noise;\nuniform float screen_width;\nuniform float screen_height;\nuniform float distortion;\nuniform bool dof_enabled;\n\nuniform float screen_distance; \nuniform float aperture;\nuniform float darken;\nuniform float edge_blur;\nuniform bool highlights;\n\nuniform float near;\nuniform float far;\n\nvarying vec2 vUV;\n\n#define PI 3.14159265\n#define TWOPI 6.28318530\n#define inverse_focal_length 0.1 \n\nvec2 centered_screen_pos;\nvec2 distorted_coords;\nfloat radius2;\nfloat radius;\n\nvec2 rand(vec2 co)\n{\nfloat noise1=(fract(sin(dot(co,vec2(12.9898,78.233)))*43758.5453));\nfloat noise2=(fract(sin(dot(co,vec2(12.9898,78.233)*2.0))*43758.5453));\nreturn clamp(vec2(noise1,noise2),0.0,1.0);\n}\n\nvec2 getDistortedCoords(vec2 coords) {\nif (distortion == 0.0) { return coords; }\nvec2 direction=1.0*normalize(centered_screen_pos);\nvec2 dist_coords=vec2(0.5,0.5);\ndist_coords.x=0.5+direction.x*radius2*1.0;\ndist_coords.y=0.5+direction.y*radius2*1.0;\nfloat dist_amount=clamp(distortion*0.23,0.0,1.0);\ndist_coords=mix(coords,dist_coords,dist_amount);\nreturn dist_coords;\n}\n\nfloat sampleScreen(inout vec4 color,const in vec2 offset,const in float weight) {\n\nvec2 coords=distorted_coords;\nfloat angle=rand(coords*100.0).x*TWOPI;\ncoords+=vec2(offset.x*cos(angle)-offset.y*sin(angle),offset.x*sin(angle)+offset.y*cos(angle));\ncolor+=texture2D(textureSampler,coords)*weight;\nreturn weight;\n}\n\nfloat getBlurLevel(float size) {\nreturn min(3.0,ceil(size/1.0));\n}\n\nvec4 getBlurColor(float size) {\nvec4 col=texture2D(textureSampler,distorted_coords);\nif (size == 0.0) { return col; }\n\n\nfloat blur_level=getBlurLevel(size);\nfloat w=(size/screen_width);\nfloat h=(size/screen_height);\nfloat total_weight=1.0;\nvec2 sample_coords;\ntotal_weight+=sampleScreen(col,vec2(-0.50*w,0.24*h),0.93);\ntotal_weight+=sampleScreen(col,vec2(0.30*w,-0.75*h),0.90);\ntotal_weight+=sampleScreen(col,vec2(0.36*w,0.96*h),0.87);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,-0.55*h),0.85);\ntotal_weight+=sampleScreen(col,vec2(1.33*w,-0.37*h),0.83);\ntotal_weight+=sampleScreen(col,vec2(-0.82*w,1.31*h),0.80);\ntotal_weight+=sampleScreen(col,vec2(-0.31*w,-1.67*h),0.78);\ntotal_weight+=sampleScreen(col,vec2(1.47*w,1.11*h),0.76);\ntotal_weight+=sampleScreen(col,vec2(-1.97*w,0.19*h),0.74);\ntotal_weight+=sampleScreen(col,vec2(1.42*w,-1.57*h),0.72);\nif (blur_level>1.0) {\ntotal_weight+=sampleScreen(col,vec2(0.01*w,2.25*h),0.70);\ntotal_weight+=sampleScreen(col,vec2(-1.62*w,-1.74*h),0.67);\ntotal_weight+=sampleScreen(col,vec2(2.49*w,0.20*h),0.65);\ntotal_weight+=sampleScreen(col,vec2(-2.07*w,1.61*h),0.63);\ntotal_weight+=sampleScreen(col,vec2(0.46*w,-2.70*h),0.61);\ntotal_weight+=sampleScreen(col,vec2(1.55*w,2.40*h),0.59);\ntotal_weight+=sampleScreen(col,vec2(-2.88*w,-0.75*h),0.56);\ntotal_weight+=sampleScreen(col,vec2(2.73*w,-1.44*h),0.54);\ntotal_weight+=sampleScreen(col,vec2(-1.08*w,3.02*h),0.52);\ntotal_weight+=sampleScreen(col,vec2(-1.28*w,-3.05*h),0.49);\n}\nif (blur_level>2.0) {\ntotal_weight+=sampleScreen(col,vec2(3.11*w,1.43*h),0.46);\ntotal_weight+=sampleScreen(col,vec2(-3.36*w,1.08*h),0.44);\ntotal_weight+=sampleScreen(col,vec2(1.80*w,-3.16*h),0.41);\ntotal_weight+=sampleScreen(col,vec2(0.83*w,3.65*h),0.38);\ntotal_weight+=sampleScreen(col,vec2(-3.16*w,-2.19*h),0.34);\ntotal_weight+=sampleScreen(col,vec2(3.92*w,-0.53*h),0.31);\ntotal_weight+=sampleScreen(col,vec2(-2.59*w,3.12*h),0.26);\ntotal_weight+=sampleScreen(col,vec2(-0.20*w,-4.15*h),0.22);\ntotal_weight+=sampleScreen(col,vec2(3.02*w,3.00*h),0.15);\n}\ncol/=total_weight; \n\nif (darken>0.0) {\ncol.rgb*=clamp(0.3,1.0,1.05-size*0.5*darken);\n}\n\n\n\n\nreturn col;\n}\nvoid main(void)\n{\n\ncentered_screen_pos=vec2(vUV.x-0.5,vUV.y-0.5);\nradius2=centered_screen_pos.x*centered_screen_pos.x+centered_screen_pos.y*centered_screen_pos.y;\nradius=sqrt(radius2);\ndistorted_coords=getDistortedCoords(vUV); \nvec2 texels_coords=vec2(vUV.x*screen_width,vUV.y*screen_height); \nfloat depth=texture2D(depthSampler,distorted_coords).r; \nfloat distance=near+(far-near)*depth; \nvec4 color=texture2D(textureSampler,vUV); \n\n\nfloat coc=abs(aperture*(screen_distance*(inverse_focal_length-1.0/distance)-1.0));\n\nif (dof_enabled == false || coc<0.07) { coc=0.0; }\n\nfloat edge_blur_amount=0.0;\nif (edge_blur>0.0) {\nedge_blur_amount=clamp((radius*2.0-1.0+0.15*edge_blur)*1.5,0.0,1.0)*1.3;\n}\n\nfloat blur_amount=max(edge_blur_amount,coc);\n\nif (blur_amount == 0.0) {\ngl_FragColor=texture2D(textureSampler,distorted_coords);\n}\nelse {\n\ngl_FragColor=getBlurColor(blur_amount*1.7);\n\nif (highlights) {\ngl_FragColor.rgb+=clamp(coc,0.0,1.0)*texture2D(highlightsSampler,distorted_coords).rgb;\n}\nif (blur_noise) {\n\nvec2 noise=rand(distorted_coords)*0.01*blur_amount;\nvec2 blurred_coord=vec2(distorted_coords.x+noise.x,distorted_coords.y+noise.y);\ngl_FragColor=0.04*texture2D(textureSampler,blurred_coord)+0.96*gl_FragColor;\n}\n}\n\nif (grain_amount>0.0) {\nvec4 grain_color=texture2D(grainSampler,texels_coords*0.003);\ngl_FragColor.rgb+=(-0.5+grain_color.rgb)*0.30*grain_amount;\n}\n}\n","standardPixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\n#if defined(PASS_POST_PROCESS)\nvoid main(void)\n{\nvec4 color=texture2D(textureSampler,vUV);\ngl_FragColor=color;\n}\n#endif\n#if defined(DOWN_SAMPLE_X4)\nuniform vec2 dsOffsets[16];\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+dsOffsets[0]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[1]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[2]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[3]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[4]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[5]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[6]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[7]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[8]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[9]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[10]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[11]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[12]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[13]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[14]);\naverage+=texture2D(textureSampler,vUV+dsOffsets[15]);\naverage/=16.0;\ngl_FragColor=average;\n}\n#endif\n#if defined(BRIGHT_PASS)\nuniform vec2 dsOffsets[4];\nuniform float brightThreshold;\nvoid main(void)\n{\nvec4 average=vec4(0.0,0.0,0.0,0.0);\naverage=texture2D(textureSampler,vUV+vec2(dsOffsets[0].x,dsOffsets[0].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[1].x,dsOffsets[1].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[2].x,dsOffsets[2].y));\naverage+=texture2D(textureSampler,vUV+vec2(dsOffsets[3].x,dsOffsets[3].y));\naverage*=0.25;\nfloat luminance=length(average.rgb);\nif (luminance<brightThreshold) {\naverage=vec4(0.0,0.0,0.0,1.0);\n}\ngl_FragColor=average;\n}\n#endif\n#if defined(TEXTURE_ADDER)\nuniform sampler2D otherSampler;\nuniform sampler2D lensSampler;\nuniform float exposure;\nvoid main(void)\n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\ncolour*=exposure;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\ncolour+=colour*texture2D(lensSampler,vUV).rgb;\nvec4 finalColor=vec4(colour.rgb,1.0)+texture2D(otherSampler,vUV);\ngl_FragColor=finalColor;\n}\n#endif\n#if defined(VLS)\n#define PI 3.1415926535897932384626433832795\nuniform mat4 shadowViewProjection;\nuniform mat4 lightWorld;\nuniform vec3 cameraPosition;\nuniform vec3 sunDirection;\nuniform vec3 sunColor;\nuniform vec2 depthValues;\nuniform float scatteringCoefficient;\nuniform float scatteringPower;\nuniform sampler2D shadowMapSampler;\nuniform sampler2D positionSampler;\nfloat computeScattering(float lightDotView)\n{\nfloat result=1.0-scatteringCoefficient*scatteringCoefficient;\nresult/=(4.0*PI*pow(1.0+scatteringCoefficient*scatteringCoefficient-(2.0*scatteringCoefficient)*lightDotView,1.5));\nreturn result;\n}\nvoid main(void)\n{\n\nvec3 worldPos=texture2D(positionSampler,vUV).rgb;\nvec3 startPosition=cameraPosition;\nvec3 rayVector=worldPos-startPosition;\nfloat rayLength=length(rayVector);\nvec3 rayDirection=rayVector/rayLength;\nfloat stepLength=rayLength/NB_STEPS;\nvec3 stepL=rayDirection*stepLength;\nvec3 currentPosition=startPosition;\nvec3 accumFog=vec3(0.0);\nfor (int i=0; i<int(NB_STEPS); i++)\n{\nvec4 worldInShadowCameraSpace=shadowViewProjection*vec4(currentPosition,1.0);\nfloat depthMetric=(worldInShadowCameraSpace.z+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depthMetric,0.0,1.0);\nworldInShadowCameraSpace.xyz/=worldInShadowCameraSpace.w;\nworldInShadowCameraSpace.xyz=0.5*worldInShadowCameraSpace.xyz+vec3(0.5);\nfloat shadowMapValue=texture2D(shadowMapSampler,worldInShadowCameraSpace.xy).r;\nif (shadowMapValue>shadowPixelDepth)\naccumFog+=sunColor*computeScattering(dot(rayDirection,sunDirection));\ncurrentPosition+=stepL;\n}\naccumFog/=NB_STEPS;\nvec3 color=accumFog*scatteringPower;\ngl_FragColor=vec4(color*exp(color) ,1.0);\n}\n#endif\n#if defined(VLSMERGE)\nuniform sampler2D originalSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(originalSampler,vUV)+texture2D(textureSampler,vUV);\n}\n#endif\n#if defined(LUMINANCE)\nuniform vec2 lumOffsets[4];\nvoid main()\n{\nfloat average=0.0;\nvec4 color=vec4(0.0);\nfloat maximum=-1e20;\nvec3 weight=vec3(0.299,0.587,0.114);\nfor (int i=0; i<4; i++)\n{\ncolor=texture2D(textureSampler,vUV+ lumOffsets[i]);\n\nfloat GreyValue=dot(color.rgb,vec3(0.33,0.33,0.33));\n\n#ifdef WEIGHTED_AVERAGE\nfloat GreyValue=dot(color.rgb,weight);\n#endif\n#ifdef BRIGHTNESS\nfloat GreyValue=max(color.r,max(color.g,color.b));\n#endif\n#ifdef HSL_COMPONENT\nfloat GreyValue=0.5*(max(color.r,max(color.g,color.b))+min(color.r,min(color.g,color.b)));\n#endif\n#ifdef MAGNITUDE\nfloat GreyValue=length(color.rgb);\n#endif\nmaximum=max(maximum,GreyValue);\naverage+=(0.25*log(1e-5+GreyValue));\n}\naverage=exp(average);\ngl_FragColor=vec4(average,maximum,0.0,1.0);\n}\n#endif\n#if defined(LUMINANCE_DOWN_SAMPLE)\nuniform vec2 dsOffsets[9];\nuniform float halfDestPixelSize;\n#ifdef FINAL_DOWN_SAMPLER\nvec4 pack(float value) {\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(value*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\n#endif\nvoid main()\n{\nvec4 color=vec4(0.0);\nfloat average=0.0;\nfor (int i=0; i<9; i++)\n{\ncolor=texture2D(textureSampler,vUV+vec2(halfDestPixelSize,halfDestPixelSize)+dsOffsets[i]);\naverage+=color.r;\n}\naverage/=9.0;\n#ifdef FINAL_DOWN_SAMPLER\ngl_FragColor=pack(average);\n#else\ngl_FragColor=vec4(average,average,0.0,1.0);\n#endif\n}\n#endif\n#if defined(HDR)\nuniform sampler2D textureAdderSampler;\nuniform float averageLuminance;\nvoid main()\n{\nvec4 color=texture2D(textureAdderSampler,vUV);\nvec4 adjustedColor=color/averageLuminance;\ncolor=adjustedColor;\ncolor.a=1.0;\ngl_FragColor=color;\n}\n#endif\n#if defined(LENS_FLARE)\n#define GHOSTS 3\nuniform sampler2D lensColorSampler;\nuniform float strength;\nuniform float ghostDispersal;\nuniform float haloWidth;\nuniform vec2 resolution;\nuniform float distortionStrength;\nfloat hash(vec2 p)\n{\nfloat h=dot(p,vec2(127.1,311.7));\nreturn -1.0+2.0*fract(sin(h)*43758.5453123);\n}\nfloat noise(in vec2 p)\n{\nvec2 i=floor(p);\nvec2 f=fract(p);\nvec2 u=f*f*(3.0-2.0*f);\nreturn mix(mix(hash(i+vec2(0.0,0.0)),\nhash(i+vec2(1.0,0.0)),u.x),\nmix(hash(i+vec2(0.0,1.0)),\nhash(i+vec2(1.0,1.0)),u.x),u.y);\n}\nfloat fbm(vec2 p)\n{\nfloat f=0.0;\nf+=0.5000*noise(p); p*=2.02;\nf+=0.2500*noise(p); p*=2.03;\nf+=0.1250*noise(p); p*=2.01;\nf+=0.0625*noise(p); p*=2.04;\nf/=0.9375;\nreturn f;\n}\nvec3 pattern(vec2 uv)\n{\nvec2 p=-1.0+2.0*uv;\nfloat p2=dot(p,p);\nfloat f=fbm(vec2(15.0*p2))/2.0;\nfloat r=0.2+0.6*sin(12.5*length(uv-vec2(0.5)));\nfloat g=0.2+0.6*sin(20.5*length(uv-vec2(0.5)));\nfloat b=0.2+0.6*sin(17.2*length(uv-vec2(0.5)));\nreturn (1.0-f)*vec3(r,g,b);\n}\nfloat luminance(vec3 color)\n{\nreturn dot(color.rgb,vec3(0.2126,0.7152,0.0722));\n}\nvec4 textureDistorted(sampler2D tex,vec2 texcoord,vec2 direction,vec3 distortion)\n{\nreturn vec4(\ntexture2D(tex,texcoord+direction*distortion.r).r,\ntexture2D(tex,texcoord+direction*distortion.g).g,\ntexture2D(tex,texcoord+direction*distortion.b).b,\n1.0\n);\n}\nvoid main(void)\n{\nvec2 uv=-vUV+vec2(1.0);\nvec2 ghostDir=(vec2(0.5)-uv)*ghostDispersal;\nvec2 texelSize=1.0/resolution;\nvec3 distortion=vec3(-texelSize.x*distortionStrength,0.0,texelSize.x*distortionStrength);\nvec4 result=vec4(0.0);\nfloat ghostIndice=1.0;\nfor (int i=0; i<GHOSTS; ++i)\n{\nvec2 offset=fract(uv+ghostDir*ghostIndice);\nfloat weight=length(vec2(0.5)-offset)/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,offset,normalize(ghostDir),distortion)*weight*strength;\nghostIndice+=1.0;\n}\nvec2 haloVec=normalize(ghostDir)*haloWidth;\nfloat weight=length(vec2(0.5)-fract(uv+haloVec))/length(vec2(0.5));\nweight=pow(1.0-weight,10.0);\nresult+=textureDistorted(textureSampler,fract(uv+haloVec),normalize(ghostDir),distortion)*weight*strength;\nresult*=texture2D(lensColorSampler,vec2(length(vec2(0.5)-uv)/length(vec2(0.5))));\ngl_FragColor=result;\n}\n#endif\n#if defined(LENS_FLARE_COMPOSE)\nuniform sampler2D otherSampler;\nuniform sampler2D lensDirtSampler;\nuniform sampler2D lensStarSampler;\nuniform mat4 lensStarMatrix;\nvoid main(void)\n{\nvec2 lensFlareCoords=(lensStarMatrix*vec4(vUV,1.0,1.0)).xy;\nvec4 lensMod=texture2D(lensDirtSampler,vUV);\nlensMod+=texture2D(lensStarSampler,vUV);\nvec4 result=texture2D(textureSampler,vUV)*lensMod;\ngl_FragColor=texture2D(otherSampler,vUV)+result;\n}\n#endif\n#if defined(DEPTH_OF_FIELD)\nuniform sampler2D otherSampler;\nuniform sampler2D depthSampler;\nuniform float distance;\nvoid main(void)\n{\nvec4 sharp=texture2D(otherSampler,vUV);\nvec4 blur=texture2D(textureSampler,vUV);\nfloat dist=clamp(texture2D(depthSampler,vUV).r*distance,0.0,1.0);\nfloat factor=0.0;\nif (dist<0.05)\nfactor=1.0;\nelse if (dist<0.1)\nfactor=20.0*(0.1-dist);\nelse if (dist<0.5)\nfactor=0.0;\nelse\nfactor=2.0*(dist-0.5);\nfactor=clamp(factor,0.0,0.90);\ngl_FragColor=mix(sharp,blur,factor);\n}\n#endif\n#if defined(MOTION_BLUR)\nuniform mat4 inverseViewProjection;\nuniform mat4 prevViewProjection;\nuniform vec2 screenSize;\nuniform float motionScale;\nuniform float motionStrength;\nuniform sampler2D depthSampler;\nvoid main(void)\n{\nvec2 texelSize=1.0/screenSize;\nfloat depth=texture2D(depthSampler,vUV).r;\nvec4 cpos=vec4(vUV*2.0-1.0,depth,1.0);\ncpos=cpos*inverseViewProjection;\nvec4 ppos=cpos*prevViewProjection;\nppos.xyz/=ppos.w;\nppos.xy=ppos.xy*0.5+0.5;\nvec2 velocity=(ppos.xy-vUV)*motionScale*motionStrength;\nfloat speed=length(velocity/texelSize);\nint nSamples=int(clamp(speed,1.0,MAX_MOTION_SAMPLES));\nvec4 result=texture2D(textureSampler,vUV);\nfor (int i=1; i<int(MAX_MOTION_SAMPLES); ++i) {\nif (i>=nSamples)\nbreak;\nvec2 offset1=vUV+velocity*(float(i)/float(nSamples-1)-0.5);\nresult+=texture2D(textureSampler,offset1);\n}\ngl_FragColor=result/float(nSamples);\n}\n#endif\n","fxaaVertexShader":"\nattribute vec2 position;\nuniform vec2 texelSize;\n\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=(position*madd+madd);\nsampleCoordS=vUV+vec2( 0.0,1.0)*texelSize;\nsampleCoordE=vUV+vec2( 1.0,0.0)*texelSize;\nsampleCoordN=vUV+vec2( 0.0,-1.0)*texelSize;\nsampleCoordW=vUV+vec2(-1.0,0.0)*texelSize;\nsampleCoordNW=vUV+vec2(-1.0,-1.0)*texelSize;\nsampleCoordSE=vUV+vec2( 1.0,1.0)*texelSize;\nsampleCoordNE=vUV+vec2( 1.0,-1.0)*texelSize;\nsampleCoordSW=vUV+vec2(-1.0,1.0)*texelSize;\ngl_Position=vec4(position,0.0,1.0);\n}","fxaaPixelShader":"uniform sampler2D textureSampler;\nuniform vec2 texelSize;\nvarying vec2 vUV;\nvarying vec2 sampleCoordS;\nvarying vec2 sampleCoordE;\nvarying vec2 sampleCoordN;\nvarying vec2 sampleCoordW;\nvarying vec2 sampleCoordNW;\nvarying vec2 sampleCoordSE;\nvarying vec2 sampleCoordNE;\nvarying vec2 sampleCoordSW;\nconst float fxaaQualitySubpix=1.0;\nconst float fxaaQualityEdgeThreshold=0.166;\nconst float fxaaQualityEdgeThresholdMin=0.0833;\nconst vec3 kLumaCoefficients=vec3(0.2126,0.7152,0.0722);\n#define FxaaLuma(rgba) dot(rgba.rgb,kLumaCoefficients)\nvoid main(){\nvec2 posM;\nposM.x=vUV.x;\nposM.y=vUV.y;\nvec4 rgbyM=texture2D(textureSampler,vUV,0.0);\nfloat lumaM=FxaaLuma(rgbyM);\nfloat lumaS=FxaaLuma(texture2D(textureSampler,sampleCoordS,0.0));\nfloat lumaE=FxaaLuma(texture2D(textureSampler,sampleCoordE,0.0));\nfloat lumaN=FxaaLuma(texture2D(textureSampler,sampleCoordN,0.0));\nfloat lumaW=FxaaLuma(texture2D(textureSampler,sampleCoordW,0.0));\nfloat maxSM=max(lumaS,lumaM);\nfloat minSM=min(lumaS,lumaM);\nfloat maxESM=max(lumaE,maxSM);\nfloat minESM=min(lumaE,minSM);\nfloat maxWN=max(lumaN,lumaW);\nfloat minWN=min(lumaN,lumaW);\nfloat rangeMax=max(maxWN,maxESM);\nfloat rangeMin=min(minWN,minESM);\nfloat rangeMaxScaled=rangeMax*fxaaQualityEdgeThreshold;\nfloat range=rangeMax-rangeMin;\nfloat rangeMaxClamped=max(fxaaQualityEdgeThresholdMin,rangeMaxScaled);\n#ifndef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\nreturn;\n}\n#endif\nfloat lumaNW=FxaaLuma(texture2D(textureSampler,sampleCoordNW,0.0));\nfloat lumaSE=FxaaLuma(texture2D(textureSampler,sampleCoordSE,0.0));\nfloat lumaNE=FxaaLuma(texture2D(textureSampler,sampleCoordNE,0.0));\nfloat lumaSW=FxaaLuma(texture2D(textureSampler,sampleCoordSW,0.0));\nfloat lumaNS=lumaN+lumaS;\nfloat lumaWE=lumaW+lumaE;\nfloat subpixRcpRange=1.0/range;\nfloat subpixNSWE=lumaNS+lumaWE;\nfloat edgeHorz1=(-2.0*lumaM)+lumaNS;\nfloat edgeVert1=(-2.0*lumaM)+lumaWE;\nfloat lumaNESE=lumaNE+lumaSE;\nfloat lumaNWNE=lumaNW+lumaNE;\nfloat edgeHorz2=(-2.0*lumaE)+lumaNESE;\nfloat edgeVert2=(-2.0*lumaN)+lumaNWNE;\nfloat lumaNWSW=lumaNW+lumaSW;\nfloat lumaSWSE=lumaSW+lumaSE;\nfloat edgeHorz4=(abs(edgeHorz1)*2.0)+abs(edgeHorz2);\nfloat edgeVert4=(abs(edgeVert1)*2.0)+abs(edgeVert2);\nfloat edgeHorz3=(-2.0*lumaW)+lumaNWSW;\nfloat edgeVert3=(-2.0*lumaS)+lumaSWSE;\nfloat edgeHorz=abs(edgeHorz3)+edgeHorz4;\nfloat edgeVert=abs(edgeVert3)+edgeVert4;\nfloat subpixNWSWNESE=lumaNWSW+lumaNESE;\nfloat lengthSign=texelSize.x;\nbool horzSpan=edgeHorz>=edgeVert;\nfloat subpixA=subpixNSWE*2.0+subpixNWSWNESE;\nif (!horzSpan)\n{\nlumaN=lumaW;\n}\nif (!horzSpan) \n{\nlumaS=lumaE;\n}\nif (horzSpan) \n{\nlengthSign=texelSize.y;\n}\nfloat subpixB=(subpixA*(1.0/12.0))-lumaM;\nfloat gradientN=lumaN-lumaM;\nfloat gradientS=lumaS-lumaM;\nfloat lumaNN=lumaN+lumaM;\nfloat lumaSS=lumaS+lumaM;\nbool pairN=abs(gradientN)>=abs(gradientS);\nfloat gradient=max(abs(gradientN),abs(gradientS));\nif (pairN)\n{\nlengthSign=-lengthSign;\n}\nfloat subpixC=clamp(abs(subpixB)*subpixRcpRange,0.0,1.0);\nvec2 posB;\nposB.x=posM.x;\nposB.y=posM.y;\nvec2 offNP;\noffNP.x=(!horzSpan) ? 0.0 : texelSize.x;\noffNP.y=(horzSpan) ? 0.0 : texelSize.y;\nif (!horzSpan) \n{\nposB.x+=lengthSign*0.5;\n}\nif (horzSpan)\n{\nposB.y+=lengthSign*0.5;\n}\nvec2 posN;\nposN.x=posB.x-offNP.x*1.5;\nposN.y=posB.y-offNP.y*1.5;\nvec2 posP;\nposP.x=posB.x+offNP.x*1.5;\nposP.y=posB.y+offNP.y*1.5;\nfloat subpixD=((-2.0)*subpixC)+3.0;\nfloat lumaEndN=FxaaLuma(texture2D(textureSampler,posN,0.0));\nfloat subpixE=subpixC*subpixC;\nfloat lumaEndP=FxaaLuma(texture2D(textureSampler,posP,0.0));\nif (!pairN) \n{\nlumaNN=lumaSS;\n}\nfloat gradientScaled=gradient*1.0/4.0;\nfloat lumaMM=lumaM-lumaNN*0.5;\nfloat subpixF=subpixD*subpixE;\nbool lumaMLTZero=lumaMM<0.0;\nlumaEndN-=lumaNN*0.5;\nlumaEndP-=lumaNN*0.5;\nbool doneN=abs(lumaEndN)>=gradientScaled;\nbool doneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) \n{\nposN.x-=offNP.x*3.0;\n}\nif (!doneN) \n{\nposN.y-=offNP.y*3.0;\n}\nbool doneNP=(!doneN) || (!doneP);\nif (!doneP) \n{\nposP.x+=offNP.x*3.0;\n}\nif (!doneP)\n{\nposP.y+=offNP.y*3.0;\n}\nif (doneNP)\n{\nif (!doneN) lumaEndN=FxaaLuma(texture2D(textureSampler,posN.xy,0.0));\nif (!doneP) lumaEndP=FxaaLuma(texture2D(textureSampler,posP.xy,0.0));\nif (!doneN) lumaEndN=lumaEndN-lumaNN*0.5;\nif (!doneP) lumaEndP=lumaEndP-lumaNN*0.5;\ndoneN=abs(lumaEndN)>=gradientScaled;\ndoneP=abs(lumaEndP)>=gradientScaled;\nif (!doneN) posN.x-=offNP.x*12.0;\nif (!doneN) posN.y-=offNP.y*12.0;\ndoneNP=(!doneN) || (!doneP);\nif (!doneP) posP.x+=offNP.x*12.0;\nif (!doneP) posP.y+=offNP.y*12.0;\n}\nfloat dstN=posM.x-posN.x;\nfloat dstP=posP.x-posM.x;\nif (!horzSpan)\n{\ndstN=posM.y-posN.y;\n}\nif (!horzSpan) \n{\ndstP=posP.y-posM.y;\n}\nbool goodSpanN=(lumaEndN<0.0) != lumaMLTZero;\nfloat spanLength=(dstP+dstN);\nbool goodSpanP=(lumaEndP<0.0) != lumaMLTZero;\nfloat spanLengthRcp=1.0/spanLength;\nbool directionN=dstN<dstP;\nfloat dst=min(dstN,dstP);\nbool goodSpan=directionN ? goodSpanN : goodSpanP;\nfloat subpixG=subpixF*subpixF;\nfloat pixelOffset=(dst*(-spanLengthRcp))+0.5;\nfloat subpixH=subpixG*fxaaQualitySubpix;\nfloat pixelOffsetGood=goodSpan ? pixelOffset : 0.0;\nfloat pixelOffsetSubpix=max(pixelOffsetGood,subpixH);\nif (!horzSpan)\n{\nposM.x+=pixelOffsetSubpix*lengthSign;\n}\nif (horzSpan)\n{\nposM.y+=pixelOffsetSubpix*lengthSign;\n}\n#ifdef MALI\nif(range<rangeMaxClamped) \n{\ngl_FragColor=rgbyM;\n}\nelse\n{\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n}\n#else\ngl_FragColor=texture2D(textureSampler,posM,0.0);\n#endif\n}","chromaticAberrationPixelShader":"\nuniform sampler2D textureSampler; \n\nuniform float chromatic_aberration;\nuniform float radialIntensity;\nuniform vec2 direction;\nuniform vec2 centerPosition;\nuniform float screen_width;\nuniform float screen_height;\n\nvarying vec2 vUV;\nvoid main(void)\n{\nvec2 centered_screen_pos=vec2(vUV.x-centerPosition.x,vUV.y-centerPosition.y);\nvec2 directionOfEffect=direction;\nif(directionOfEffect.x == 0. && directionOfEffect.y == 0.){\ndirectionOfEffect=normalize(centered_screen_pos);\n}\nfloat radius2=centered_screen_pos.x*centered_screen_pos.x\n+centered_screen_pos.y*centered_screen_pos.y;\nfloat radius=sqrt(radius2);\nvec4 original=texture2D(textureSampler,vUV);\n\nvec3 ref_indices=vec3(-0.3,0.0,0.3);\nfloat ref_shiftX=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.x/screen_width;\nfloat ref_shiftY=chromatic_aberration*pow(radius,radialIntensity)*directionOfEffect.y/screen_height;\n\nvec2 ref_coords_r=vec2(vUV.x+ref_indices.r*ref_shiftX,vUV.y+ref_indices.r*ref_shiftY*0.5);\nvec2 ref_coords_g=vec2(vUV.x+ref_indices.g*ref_shiftX,vUV.y+ref_indices.g*ref_shiftY*0.5);\nvec2 ref_coords_b=vec2(vUV.x+ref_indices.b*ref_shiftX,vUV.y+ref_indices.b*ref_shiftY*0.5);\noriginal.r=texture2D(textureSampler,ref_coords_r).r;\noriginal.g=texture2D(textureSampler,ref_coords_g).g;\noriginal.b=texture2D(textureSampler,ref_coords_b).b;\noriginal.a=clamp(texture2D(textureSampler,ref_coords_r).a+texture2D(textureSampler,ref_coords_g).a+texture2D(textureSampler,ref_coords_b).a,0.,1.);\ngl_FragColor=original;\n}","grainPixelShader":"#include<helperFunctions>\n\nuniform sampler2D textureSampler; \n\nuniform float intensity;\nuniform float animatedSeed;\n\nvarying vec2 vUV;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec2 seed=vUV*(animatedSeed);\nfloat grain=dither(seed,intensity);\n\nfloat lum=getLuminance(gl_FragColor.rgb);\nfloat grainAmount=(cos(-PI+(lum*PI*2.))+1.)/2.;\ngl_FragColor.rgb+=grain*grainAmount;\ngl_FragColor.rgb=max(gl_FragColor.rgb,0.0);\n}","sharpenPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform vec2 sharpnessAmounts;\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 color=texture2D(textureSampler,vUV);\nvec4 edgeDetection=texture2D(textureSampler,vUV+onePixel*vec2(0,-1)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0)) +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1)) -\ncolor*4.0;\ngl_FragColor=max(vec4(color.rgb*sharpnessAmounts.y,color.a)-(sharpnessAmounts.x*vec4(edgeDetection.rgb,0)),0.);\n}","kernelBlurVertexShader":"\nattribute vec2 position;\n\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nsampleCenter=(position*madd+madd);\n#include<kernelBlurVertex>[0..varyingCount]\ngl_Position=vec4(position,0.0,1.0);\n}","kernelBlurPixelShader":"\nuniform sampler2D textureSampler;\nuniform vec2 delta;\n\nvarying vec2 sampleCenter;\n#ifdef DOF\nuniform sampler2D circleOfConfusionSampler;\nuniform vec2 cameraMinMaxZ;\nfloat sampleDistance(const in vec2 offset) {\nfloat depth=texture2D(circleOfConfusionSampler,offset).g; \nreturn cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth; \n}\nfloat sampleCoC(const in vec2 offset) {\nfloat coc=texture2D(circleOfConfusionSampler,offset).r; \nreturn coc; \n}\n#endif\n#include<kernelBlurVaryingDeclaration>[0..varyingCount]\n#ifdef PACKEDFLOAT\nvec4 pack(float depth)\n{\nconst vec4 bit_shift=vec4(255.0*255.0*255.0,255.0*255.0,255.0,1.0);\nconst vec4 bit_mask=vec4(0.0,1.0/255.0,1.0/255.0,1.0/255.0);\nvec4 res=fract(depth*bit_shift);\nres-=res.xxyz*bit_mask;\nreturn res;\n}\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nvoid main(void)\n{\nfloat computedWeight=0.0;\n#ifdef PACKEDFLOAT \nfloat blend=0.;\n#else\nvec4 blend=vec4(0.);\n#endif\n#ifdef DOF\nfloat sumOfWeights=CENTER_WEIGHT; \nfloat factor=0.0;\n\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter))*CENTER_WEIGHT;\n#else\nblend+=texture2D(textureSampler,sampleCenter)*CENTER_WEIGHT;\n#endif\n#endif\n#include<kernelBlurFragment>[0..varyingCount]\n#include<kernelBlurFragment2>[0..depCount]\n#ifdef PACKEDFLOAT\ngl_FragColor=pack(blend);\n#else\ngl_FragColor=blend;\n#endif\n#ifdef DOF\ngl_FragColor/=sumOfWeights;\n#endif\n}","depthOfFieldMergePixelShader":"uniform sampler2D textureSampler;\nvarying vec2 vUV;\nuniform sampler2D circleOfConfusionSampler;\nuniform sampler2D blurStep0;\n#if BLUR_LEVEL>0\nuniform sampler2D blurStep1;\n#endif\n#if BLUR_LEVEL>1\nuniform sampler2D blurStep2;\n#endif\nvoid main(void)\n{\nfloat coc=texture2D(circleOfConfusionSampler,vUV).r;\n#if BLUR_LEVEL == 0\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred0=texture2D(blurStep0,vUV);\ngl_FragColor=mix(original,blurred0,coc);\n#endif\n#if BLUR_LEVEL == 1\nif(coc<0.5){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(original,blurred1,coc/0.5);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV); \nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.5)/0.5);\n}\n#endif\n#if BLUR_LEVEL == 2\nif(coc<0.33){\nvec4 original=texture2D(textureSampler,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(original,blurred2,coc/0.33);\n}else if(coc<0.66){\nvec4 blurred1=texture2D(blurStep1,vUV);\nvec4 blurred2=texture2D(blurStep2,vUV);\ngl_FragColor=mix(blurred2,blurred1,(coc-0.33)/0.33);\n}else{\nvec4 blurred0=texture2D(blurStep0,vUV);\nvec4 blurred1=texture2D(blurStep1,vUV);\ngl_FragColor=mix(blurred1,blurred0,(coc-0.66)/0.34);\n}\n#endif\n}\n","circleOfConfusionPixelShader":"\nuniform sampler2D depthSampler;\n\nvarying vec2 vUV;\n\nuniform vec2 cameraMinMaxZ;\n\nuniform float focusDistance;\nuniform float cocPrecalculation;\nvoid main(void)\n{\nfloat depth=texture2D(depthSampler,vUV).r;\nfloat pixelDistance=(cameraMinMaxZ.x+(cameraMinMaxZ.y-cameraMinMaxZ.x)*depth)*1000.0; \nfloat coc=abs(cocPrecalculation* ((focusDistance-pixelDistance)/pixelDistance));\ncoc=clamp(coc,0.0,1.0);\ngl_FragColor=vec4(coc,depth,coc,1.0);\n}\n","bloomMergePixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D bloomBlur;\nvarying vec2 vUV;\nuniform float bloomWeight;\nvoid main(void)\n{\ngl_FragColor=texture2D(textureSampler,vUV);\nvec3 blurred=texture2D(bloomBlur,vUV).rgb;\ngl_FragColor.rgb=gl_FragColor.rgb+(blurred.rgb*bloomWeight); \n}\n","extractHighlightsPixelShader":"#include<helperFunctions>\n\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float threshold;\nuniform float exposure;\nvoid main(void) \n{\ngl_FragColor=texture2D(textureSampler,vUV);\nfloat luma=getLuminance(gl_FragColor.rgb*exposure);\ngl_FragColor.rgb=step(threshold,luma)*gl_FragColor.rgb;\n}","geometryVertexShader":"precision highp float;\nprecision highp int;\n#include<bonesDeclaration>\n#include<instancesDeclaration>\nattribute vec3 position;\nattribute vec3 normal;\n#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nvarying vec2 uv;\n#endif\n#ifdef UV2\nvarying vec2 uv2;\n#endif\n#endif\n\nuniform mat4 viewProjection;\nuniform mat4 view;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\nvoid main(void)\n{\n#include<instancesVertex>\n#include<bonesVertex>\nvec4 pos=vec4(finalWorld*vec4(position,1.0));\nvNormalV=normalize(vec3((view*finalWorld)*vec4(normal,0.0)));\nvViewPos=view*pos;\n#ifdef POSITION\nvPosition=pos.xyz/pos.w;\n#endif\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#if defined(ALPHATEST) || defined(BASIC_RENDER)\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","geometryPixelShader":"#extension GL_EXT_draw_buffers : require\nprecision highp float;\nprecision highp int;\nvarying vec3 vNormalV;\nvarying vec4 vViewPos;\n#ifdef POSITION\nvarying vec3 vPosition;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef POSITION\n#include<mrtFragmentDeclaration>[3]\n#else\n#include<mrtFragmentDeclaration>[2]\n#endif\nvoid main() {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\ngl_FragData[0]=vec4(vViewPos.z/vViewPos.w,0.0,0.0,1.0);\n\ngl_FragData[1]=vec4(normalize(vNormalV),1.0);\n\n#ifdef POSITION\ngl_FragData[2]=vec4(vPosition,1.0);\n#endif\n}","refractionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D refractionSampler;\n\nuniform vec3 baseColor;\nuniform float depth;\nuniform float colorLevel;\nvoid main() {\nfloat ref=1.0-texture2D(refractionSampler,vUV).r;\nvec2 uv=vUV-vec2(0.5);\nvec2 offset=uv*depth*ref;\nvec3 sourceColor=texture2D(textureSampler,vUV-offset).rgb;\ngl_FragColor=vec4(sourceColor+sourceColor*ref*colorLevel,1.0);\n}","blackAndWhitePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform float degree;\nvoid main(void) \n{\nvec3 color=texture2D(textureSampler,vUV).rgb;\nfloat luminance=dot(color,vec3(0.3,0.59,0.11)); \nvec3 blackAndWhite=vec3(luminance,luminance,luminance);\ngl_FragColor=vec4(color-((color-blackAndWhite)*degree),1.0);\n}","convolutionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 screenSize;\nuniform float kernel[9];\nvoid main(void)\n{\nvec2 onePixel=vec2(1.0,1.0)/screenSize;\nvec4 colorSum =\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,-1))*kernel[0] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,-1))*kernel[1] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,-1))*kernel[2] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,0))*kernel[3] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,0))*kernel[4] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,0))*kernel[5] +\ntexture2D(textureSampler,vUV+onePixel*vec2(-1,1))*kernel[6] +\ntexture2D(textureSampler,vUV+onePixel*vec2(0,1))*kernel[7] +\ntexture2D(textureSampler,vUV+onePixel*vec2(1,1))*kernel[8];\nfloat kernelWeight =\nkernel[0] +\nkernel[1] +\nkernel[2] +\nkernel[3] +\nkernel[4] +\nkernel[5] +\nkernel[6] +\nkernel[7] +\nkernel[8];\nif (kernelWeight<=0.0) {\nkernelWeight=1.0;\n}\ngl_FragColor=vec4((colorSum/kernelWeight).rgb,1);\n}","filterPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform mat4 kernelMatrix;\nvoid main(void)\n{\nvec3 baseColor=texture2D(textureSampler,vUV).rgb;\nvec3 updatedColor=(kernelMatrix*vec4(baseColor,1.0)).rgb;\ngl_FragColor=vec4(updatedColor,1.0);\n}","volumetricLightScatteringPixelShader":"uniform sampler2D textureSampler;\nuniform sampler2D lightScatteringSampler;\nuniform float decay;\nuniform float exposure;\nuniform float weight;\nuniform float density;\nuniform vec2 meshPositionOnScreen;\nvarying vec2 vUV;\nvoid main(void) {\nvec2 tc=vUV;\nvec2 deltaTexCoord=(tc-meshPositionOnScreen.xy);\ndeltaTexCoord*=1.0/float(NUM_SAMPLES)*density;\nfloat illuminationDecay=1.0;\nvec4 color=texture2D(lightScatteringSampler,tc)*0.4;\nfor(int i=0; i<NUM_SAMPLES; i++) {\ntc-=deltaTexCoord;\nvec4 dataSample=texture2D(lightScatteringSampler,tc)*0.4;\ndataSample*=illuminationDecay*weight;\ncolor+=dataSample;\nilluminationDecay*=decay;\n}\nvec4 realColor=texture2D(textureSampler,vUV);\ngl_FragColor=((vec4((vec3(color.r,color.g,color.b)*exposure),1))+(realColor*(1.5-0.4)));\n}\n","volumetricLightScatteringPassPixelShader":"#if defined(ALPHATEST) || defined(NEED_UV)\nvarying vec2 vUV;\n#endif\n#if defined(ALPHATEST)\nuniform sampler2D diffuseSampler;\n#endif\nvoid main(void)\n{\n#if defined(ALPHATEST)\nvec4 diffuseColor=texture2D(diffuseSampler,vUV);\nif (diffuseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=vec4(0.0,0.0,0.0,1.0);\n}\n","colorCorrectionPixelShader":"\nuniform sampler2D textureSampler; \nuniform sampler2D colorTable; \n\nvarying vec2 vUV;\n\nconst float SLICE_COUNT=16.0; \n\nvec4 sampleAs3DTexture(sampler2D textureSampler,vec3 uv,float width) {\nfloat sliceSize=1.0/width; \nfloat slicePixelSize=sliceSize/width; \nfloat sliceInnerSize=slicePixelSize*(width-1.0); \nfloat zSlice0=min(floor(uv.z*width),width-1.0);\nfloat zSlice1=min(zSlice0+1.0,width-1.0);\nfloat xOffset=slicePixelSize*0.5+uv.x*sliceInnerSize;\nfloat s0=xOffset+(zSlice0*sliceSize);\nfloat s1=xOffset+(zSlice1*sliceSize);\nvec4 slice0Color=texture2D(textureSampler,vec2(s0,uv.y));\nvec4 slice1Color=texture2D(textureSampler,vec2(s1,uv.y));\nfloat zOffset=mod(uv.z*width,1.0);\nvec4 result=mix(slice0Color,slice1Color,zOffset);\nreturn result;\n}\nvoid main(void)\n{\nvec4 screen_color=texture2D(textureSampler,vUV);\ngl_FragColor=sampleAs3DTexture(colorTable,screen_color.rgb,SLICE_COUNT);\n}","tonemapPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform float _ExposureAdjustment;\n#if defined(HABLE_TONEMAPPING)\nconst float A=0.15;\nconst float B=0.50;\nconst float C=0.10;\nconst float D=0.20;\nconst float E=0.02;\nconst float F=0.30;\nconst float W=11.2;\n#endif\nfloat Luminance(vec3 c)\n{\nreturn dot(c,vec3(0.22,0.707,0.071));\n}\nvoid main(void) \n{\nvec3 colour=texture2D(textureSampler,vUV).rgb;\n#if defined(REINHARD_TONEMAPPING)\nfloat lum=Luminance(colour.rgb); \nfloat lumTm=lum*_ExposureAdjustment;\nfloat scale=lumTm/(1.0+lumTm); \ncolour*=scale/lum;\n#elif defined(HABLE_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nconst float ExposureBias=2.0;\nvec3 x=ExposureBias*colour;\nvec3 curr=((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F;\nx=vec3(W,W,W);\nvec3 whiteScale=1.0/(((x*(A*x+C*B)+D*E)/(x*(A*x+B)+D*F))-E/F);\ncolour=curr*whiteScale;\n#elif defined(OPTIMIZED_HEJIDAWSON_TONEMAPPING)\ncolour*=_ExposureAdjustment;\nvec3 X=max(vec3(0.0,0.0,0.0),colour-0.004);\nvec3 retColor=(X*(6.2*X+0.5))/(X*(6.2*X+1.7)+0.06);\ncolour=retColor*retColor;\n#elif defined(PHOTOGRAPHIC_TONEMAPPING)\ncolour=vec3(1.0,1.0,1.0)-exp2(-_ExposureAdjustment*colour);\n#endif\ngl_FragColor=vec4(colour.rgb,1.0);\n}","displayPassPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D passSampler;\nvoid main(void)\n{\ngl_FragColor=texture2D(passSampler,vUV);\n}","highlightsPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nconst vec3 RGBLuminanceCoefficients=vec3(0.2126,0.7152,0.0722);\nvoid main(void) \n{\nvec4 tex=texture2D(textureSampler,vUV);\nvec3 c=tex.rgb;\nfloat luma=dot(c.rgb,RGBLuminanceCoefficients);\n\n\ngl_FragColor=vec4(pow(c,vec3(25.0-luma*15.0)),tex.a); \n}","imageProcessingPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#include<imageProcessingDeclaration>\n#include<helperFunctions>\n#include<imageProcessingFunctions>\nvoid main(void)\n{\nvec4 result=texture2D(textureSampler,vUV);\n#ifdef IMAGEPROCESSING\n#ifndef FROMLINEARSPACE\n\nresult.rgb=toLinearSpace(result.rgb);\n#endif\nresult=applyImageProcessing(result);\n#else\n\n#ifdef FROMLINEARSPACE\nresult=applyImageProcessing(result);\n#endif\n#endif\ngl_FragColor=result;\n}","lensFlareVertexShader":"\nattribute vec2 position;\n\nuniform mat4 viewportMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvUV=position*madd+madd;\ngl_Position=viewportMatrix*vec4(position,0.0,1.0);\n}","lensFlarePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\ngl_FragColor=baseColor*color;\n}","anaglyphPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform sampler2D leftSampler;\nvoid main(void)\n{\nvec4 leftFrag=texture2D(leftSampler,vUV);\nleftFrag=vec4(1.0,leftFrag.g,leftFrag.b,1.0);\nvec4 rightFrag=texture2D(textureSampler,vUV);\nrightFrag=vec4(rightFrag.r,1.0,1.0,1.0);\ngl_FragColor=vec4(rightFrag.rgb*leftFrag.rgb,1.0);\n}","stereoscopicInterlacePixelShader":"const vec3 TWO=vec3(2.0,2.0,2.0);\nvarying vec2 vUV;\nuniform sampler2D camASampler;\nuniform sampler2D textureSampler;\nuniform vec2 stepSize;\nvoid main(void)\n{\nbool useCamB;\nvec2 texCoord1;\nvec2 texCoord2;\nvec3 frag1;\nvec3 frag2;\n#ifdef IS_STEREOSCOPIC_HORIZ\nuseCamB=vUV.x>0.5;\ntexCoord1=vec2(useCamB ? (vUV.x-0.5)*2.0 : vUV.x*2.0,vUV.y);\ntexCoord2=vec2(texCoord1.x+stepSize.x,vUV.y);\n#else\nuseCamB=vUV.y>0.5;\ntexCoord1=vec2(vUV.x,useCamB ? (vUV.y-0.5)*2.0 : vUV.y*2.0);\ntexCoord2=vec2(vUV.x,texCoord1.y+stepSize.y);\n#endif\n\nif (useCamB){\nfrag1=texture2D(textureSampler,texCoord1).rgb;\nfrag2=texture2D(textureSampler,texCoord2).rgb;\n}else{\nfrag1=texture2D(camASampler ,texCoord1).rgb;\nfrag2=texture2D(camASampler ,texCoord2).rgb;\n}\ngl_FragColor=vec4((frag1+frag2)/TWO,1.0);\n}","vrDistortionCorrectionPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\nuniform vec2 LensCenter;\nuniform vec2 Scale;\nuniform vec2 ScaleIn;\nuniform vec4 HmdWarpParam;\nvec2 HmdWarp(vec2 in01) {\nvec2 theta=(in01-LensCenter)*ScaleIn; \nfloat rSq=theta.x*theta.x+theta.y*theta.y;\nvec2 rvector=theta*(HmdWarpParam.x+HmdWarpParam.y*rSq+HmdWarpParam.z*rSq*rSq+HmdWarpParam.w*rSq*rSq*rSq);\nreturn LensCenter+Scale*rvector;\n}\nvoid main(void)\n{\nvec2 tc=HmdWarp(vUV);\nif (tc.x <0.0 || tc.x>1.0 || tc.y<0.0 || tc.y>1.0)\ngl_FragColor=vec4(0.0,0.0,0.0,0.0);\nelse{\ngl_FragColor=texture2D(textureSampler,tc);\n}\n}","glowBlurPostProcessPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec2 screenSize;\nuniform vec2 direction;\nuniform float blurWidth;\n\nfloat getLuminance(vec3 color)\n{\nreturn dot(color,vec3(0.2126,0.7152,0.0722));\n}\nvoid main(void)\n{\nfloat weights[7];\nweights[0]=0.05;\nweights[1]=0.1;\nweights[2]=0.2;\nweights[3]=0.3;\nweights[4]=0.2;\nweights[5]=0.1;\nweights[6]=0.05;\nvec2 texelSize=vec2(1.0/screenSize.x,1.0/screenSize.y);\nvec2 texelStep=texelSize*direction*blurWidth;\nvec2 start=vUV-3.0*texelStep;\nvec4 baseColor=vec4(0.,0.,0.,0.);\nvec2 texelOffset=vec2(0.,0.);\nfor (int i=0; i<7; i++)\n{\n\nvec4 texel=texture2D(textureSampler,start+texelOffset);\nbaseColor.a+=texel.a*weights[i];\n\nfloat luminance=getLuminance(baseColor.rgb);\nfloat luminanceTexel=getLuminance(texel.rgb);\nfloat choice=step(luminanceTexel,luminance);\nbaseColor.rgb=choice*baseColor.rgb+(1.0-choice)*texel.rgb;\ntexelOffset+=texelStep;\n}\ngl_FragColor=baseColor;\n}","glowMapGenerationPixelShader":"#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform sampler2D diffuseSampler;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform sampler2D emissiveSampler;\n#endif\nuniform vec4 color;\nvoid main(void)\n{\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUVDiffuse).a<0.4)\ndiscard;\n#endif\n#ifdef EMISSIVE\ngl_FragColor=texture2D(emissiveSampler,vUVEmissive)*color;\n#else\ngl_FragColor=color;\n#endif\n}","glowMapGenerationVertexShader":"\nattribute vec3 position;\n#include<bonesDeclaration>\n#include<morphTargetsVertexGlobalDeclaration>\n#include<morphTargetsVertexDeclaration>[0..maxSimultaneousMorphTargets]\n\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\nvarying vec4 vPosition;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef ALPHATEST\nvarying vec2 vUVDiffuse;\nuniform mat4 diffuseMatrix;\n#endif\n#ifdef EMISSIVE\nvarying vec2 vUVEmissive;\nuniform mat4 emissiveMatrix;\n#endif\nvoid main(void)\n{\nvec3 positionUpdated=position;\n#include<morphTargetsVertex>[0..maxSimultaneousMorphTargets]\n#include<instancesVertex>\n#include<bonesVertex>\n#ifdef CUBEMAP\nvPosition=finalWorld*vec4(positionUpdated,1.0);\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\n#else\nvPosition=viewProjection*finalWorld*vec4(positionUpdated,1.0);\ngl_Position=vPosition;\n#endif\n#ifdef ALPHATEST\n#ifdef DIFFUSEUV1\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef DIFFUSEUV2\nvUVDiffuse=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#ifdef EMISSIVE\n#ifdef EMISSIVEUV1\nvUVEmissive=vec2(emissiveMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef EMISSIVEUV2\nvUVEmissive=vec2(emissiveMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n}","glowMapMergePixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n#ifdef EMISSIVE\nuniform sampler2D textureSampler2;\n#endif\n\nuniform float offset;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef EMISSIVE\nbaseColor+=texture2D(textureSampler2,vUV);\nbaseColor*=offset;\n#else\nbaseColor.a=abs(offset-baseColor.a);\n#ifdef STROKE\nfloat alpha=smoothstep(.0,.1,baseColor.a);\nbaseColor.a=alpha;\nbaseColor.rgb=baseColor.rgb*alpha;\n#endif\n#endif\ngl_FragColor=baseColor;\n}","glowMapMergeVertexShader":"\nattribute vec2 position;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) {\nvUV=position*madd+madd;\ngl_Position=vec4(position,0.0,1.0);\n}","lineVertexShader":"\nattribute vec3 position;\nattribute vec4 normal;\n\nuniform mat4 worldViewProjection;\nuniform float width;\nuniform float aspectRatio;\nvoid main(void) {\nvec4 viewPosition=worldViewProjection*vec4(position,1.0);\nvec4 viewPositionNext=worldViewProjection*vec4(normal.xyz,1.0);\nvec2 currentScreen=viewPosition.xy/viewPosition.w;\nvec2 nextScreen=viewPositionNext.xy/viewPositionNext.w;\ncurrentScreen.x*=aspectRatio;\nnextScreen.x*=aspectRatio;\nvec2 dir=normalize(nextScreen-currentScreen);\nvec2 normalDir=vec2(-dir.y,dir.x);\nnormalDir*=width/2.0;\nnormalDir.x/=aspectRatio;\nvec4 offset=vec4(normalDir*normal.w,0.0,0.0);\ngl_Position=viewPosition+offset;\n}","linePixelShader":"uniform vec4 color;\nvoid main(void) {\ngl_FragColor=color;\n}","outlineVertexShader":"\nattribute vec3 position;\nattribute vec3 normal;\n#include<bonesDeclaration>\n\nuniform float offset;\n#include<instancesDeclaration>\nuniform mat4 viewProjection;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform mat4 diffuseMatrix;\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#endif\n#include<logDepthDeclaration>\nvoid main(void)\n{\nvec3 offsetPosition=position+normal*offset;\n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(offsetPosition,1.0);\n#ifdef ALPHATEST\n#ifdef UV1\nvUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n#endif\n#ifdef UV2\nvUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n#endif\n#endif\n#include<logDepthVertex>\n}\n","outlinePixelShader":"#ifdef LOGARITHMICDEPTH\n#extension GL_EXT_frag_depth : enable\n#endif\nuniform vec4 color;\n#ifdef ALPHATEST\nvarying vec2 vUV;\nuniform sampler2D diffuseSampler;\n#endif\n#include<logDepthDeclaration>\nvoid main(void) {\n#ifdef ALPHATEST\nif (texture2D(diffuseSampler,vUV).a<0.4)\ndiscard;\n#endif\n#include<logDepthFragment>\ngl_FragColor=color;\n}","layerVertexShader":"\nattribute vec2 position;\n\nuniform vec2 scale;\nuniform vec2 offset;\nuniform mat4 textureMatrix;\n\nvarying vec2 vUV;\nconst vec2 madd=vec2(0.5,0.5);\nvoid main(void) { \nvec2 shiftedPosition=position*scale+offset;\nvUV=vec2(textureMatrix*vec4(shiftedPosition*madd+madd,1.0,0.0));\ngl_Position=vec4(shiftedPosition,0.0,1.0);\n}","layerPixelShader":"\nvarying vec2 vUV;\nuniform sampler2D textureSampler;\n\nuniform vec4 color;\nvoid main(void) {\nvec4 baseColor=texture2D(textureSampler,vUV);\n#ifdef ALPHATEST\nif (baseColor.a<0.4)\ndiscard;\n#endif\ngl_FragColor=baseColor*color;\n}","backgroundVertexShader":"precision highp float;\n#include<__decl__backgroundVertex>\n#include<helperFunctions>\n\nattribute vec3 position;\n#ifdef NORMAL\nattribute vec3 normal;\n#endif\n#include<bonesDeclaration>\n\n#include<instancesDeclaration>\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\nvarying vec3 vPositionW;\n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef UV1\nattribute vec2 uv;\n#endif\n#ifdef UV2\nattribute vec2 uv2;\n#endif\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif\n#ifdef MAINUV2\nvarying vec2 vMainUV2; \n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0\nvarying vec2 vDiffuseUV;\n#endif\n#include<clipPlaneVertexDeclaration>\n#include<fogVertexDeclaration>\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\nvoid main(void) {\n#ifdef REFLECTIONMAP_SKYBOX\nvPositionUVW=position;\n#endif \n#include<instancesVertex>\n#include<bonesVertex>\ngl_Position=viewProjection*finalWorld*vec4(position,1.0);\nvec4 worldPos=finalWorld*vec4(position,1.0);\nvPositionW=vec3(worldPos);\n#ifdef NORMAL\nmat3 normalWorld=mat3(finalWorld);\n#ifdef NONUNIFORMSCALING\nnormalWorld=transposeMat3(inverseMat3(normalWorld));\n#endif\nvNormalW=normalize(normalWorld*normal);\n#endif\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvDirectionW=normalize(vec3(finalWorld*vec4(position,0.0)));\n#ifdef EQUIRECTANGULAR_RELFECTION_FOV\nmat3 screenToWorld=inverseMat3(mat3(finalWorld*viewProjection));\nvec3 segment=mix(vDirectionW,screenToWorld*vec3(0.0,0.0,1.0),abs(fFovMultiplier-1.0));\nif (fFovMultiplier<=1.0) {\nvDirectionW=normalize(segment);\n} else {\nvDirectionW=normalize(vDirectionW+(vDirectionW-segment));\n}\n#endif\n#endif\n#ifndef UV1\nvec2 uv=vec2(0.,0.);\n#endif\n#ifndef UV2\nvec2 uv2=vec2(0.,0.);\n#endif\n#ifdef MAINUV1\nvMainUV1=uv;\n#endif \n#ifdef MAINUV2\nvMainUV2=uv2;\n#endif\n#if defined(DIFFUSE) && DIFFUSEDIRECTUV == 0 \nif (vDiffuseInfos.x == 0.)\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv,1.0,0.0));\n}\nelse\n{\nvDiffuseUV=vec2(diffuseMatrix*vec4(uv2,1.0,0.0));\n}\n#endif\n\n#include<clipPlaneVertex>\n\n#include<fogVertex>\n\n#include<shadowsVertex>[0..maxSimultaneousLights]\n\n#ifdef VERTEXCOLOR\nvColor=color;\n#endif\n\n#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif\n}\n","backgroundPixelShader":"#ifdef TEXTURELODSUPPORT\n#extension GL_EXT_shader_texture_lod : enable\n#endif\nprecision highp float;\n#include<__decl__backgroundFragment>\n#define RECIPROCAL_PI2 0.15915494\n\nuniform vec3 vEyePosition;\n\nvarying vec3 vPositionW;\n#ifdef MAINUV1\nvarying vec2 vMainUV1;\n#endif \n#ifdef MAINUV2 \nvarying vec2 vMainUV2; \n#endif \n#ifdef NORMAL\nvarying vec3 vNormalW;\n#endif\n#ifdef DIFFUSE\n#if DIFFUSEDIRECTUV == 1\n#define vDiffuseUV vMainUV1\n#elif DIFFUSEDIRECTUV == 2\n#define vDiffuseUV vMainUV2\n#else\nvarying vec2 vDiffuseUV;\n#endif\nuniform sampler2D diffuseSampler;\n#endif\n\n#ifdef REFLECTION\n#ifdef REFLECTIONMAP_3D\n#define sampleReflection(s,c) textureCube(s,c)\nuniform samplerCube reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) textureCubeLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#else\n#define sampleReflection(s,c) texture2D(s,c)\nuniform sampler2D reflectionSampler;\n#ifdef TEXTURELODSUPPORT\n#define sampleReflectionLod(s,c,l) texture2DLodEXT(s,c,l)\n#else\nuniform samplerCube reflectionSamplerLow;\nuniform samplerCube reflectionSamplerHigh;\n#endif\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nvarying vec3 vPositionUVW;\n#else\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvarying vec3 vDirectionW;\n#endif\n#endif\n#include<reflectionFunction>\n#endif\n\n#ifndef FROMLINEARSPACE\n#define FROMLINEARSPACE;\n#endif\n\n#ifndef SHADOWONLY\n#define SHADOWONLY;\n#endif\n#include<imageProcessingDeclaration>\n\n#include<__decl__lightFragment>[0..maxSimultaneousLights]\n#include<helperFunctions>\n#include<lightsFragmentFunctions>\n#include<shadowsFragmentFunctions>\n#include<imageProcessingFunctions>\n#include<clipPlaneFragmentDeclaration>\n\n#include<fogFragmentDeclaration>\n#ifdef REFLECTIONFRESNEL\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n#endif\nvoid main(void) {\n#include<clipPlaneFragment>\nvec3 viewDirectionW=normalize(vEyePosition-vPositionW);\n\n#ifdef NORMAL\nvec3 normalW=normalize(vNormalW);\n#else\nvec3 normalW=vec3(0.0,1.0,0.0);\n#endif\n\nfloat shadow=1.;\nfloat globalShadow=0.;\nfloat shadowLightCount=0.;\n#include<lightFragment>[0..maxSimultaneousLights]\n#ifdef SHADOWINUSE\nglobalShadow/=shadowLightCount;\n#else\nglobalShadow=1.0;\n#endif\n\nvec4 reflectionColor=vec4(1.,1.,1.,1.);\n#ifdef REFLECTION\nvec3 reflectionVector=computeReflectionCoords(vec4(vPositionW,1.0),normalW);\n#ifdef REFLECTIONMAP_OPPOSITEZ\nreflectionVector.z*=-1.0;\n#endif\n\n#ifdef REFLECTIONMAP_3D\nvec3 reflectionCoords=reflectionVector;\n#else\nvec2 reflectionCoords=reflectionVector.xy;\n#ifdef REFLECTIONMAP_PROJECTION\nreflectionCoords/=reflectionVector.z;\n#endif\nreflectionCoords.y=1.0-reflectionCoords.y;\n#endif\n#ifdef REFLECTIONBLUR\nfloat reflectionLOD=vReflectionInfos.y;\n#ifdef TEXTURELODSUPPORT\n\nreflectionLOD=reflectionLOD*log2(vReflectionMicrosurfaceInfos.x)*vReflectionMicrosurfaceInfos.y+vReflectionMicrosurfaceInfos.z;\nreflectionColor=sampleReflectionLod(reflectionSampler,reflectionCoords,reflectionLOD);\n#else\nfloat lodReflectionNormalized=clamp(reflectionLOD,0.,1.);\nfloat lodReflectionNormalizedDoubled=lodReflectionNormalized*2.0;\nvec4 reflectionSpecularMid=sampleReflection(reflectionSampler,reflectionCoords);\nif(lodReflectionNormalizedDoubled<1.0){\nreflectionColor=mix(\nsampleReflection(reflectionSamplerHigh,reflectionCoords),\nreflectionSpecularMid,\nlodReflectionNormalizedDoubled\n);\n} else {\nreflectionColor=mix(\nreflectionSpecularMid,\nsampleReflection(reflectionSamplerLow,reflectionCoords),\nlodReflectionNormalizedDoubled-1.0\n);\n}\n#endif\n#else\nvec4 reflectionSample=sampleReflection(reflectionSampler,reflectionCoords);\nreflectionColor=reflectionSample;\n#endif\n#ifdef RGBDREFLECTION\nreflectionColor.rgb=fromRGBD(reflectionColor);\n#endif\n#ifdef GAMMAREFLECTION\nreflectionColor.rgb=toLinearSpace(reflectionColor.rgb);\n#endif\n#ifdef REFLECTIONBGR\nreflectionColor.rgb=reflectionColor.bgr;\n#endif\n\nreflectionColor.rgb*=vReflectionInfos.x;\n#endif\n\nvec3 diffuseColor=vec3(1.,1.,1.);\nfloat finalAlpha=alpha;\n#ifdef DIFFUSE\nvec4 diffuseMap=texture2D(diffuseSampler,vDiffuseUV);\n#ifdef GAMMADIFFUSE\ndiffuseMap.rgb=toLinearSpace(diffuseMap.rgb);\n#endif\n\ndiffuseMap.rgb*=vDiffuseInfos.y;\n#ifdef DIFFUSEHASALPHA\nfinalAlpha*=diffuseMap.a;\n#endif\ndiffuseColor=diffuseMap.rgb;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 colorBase=diffuseColor;\n#else\nvec3 colorBase=reflectionColor.rgb*diffuseColor;\n#endif\ncolorBase=max(colorBase,0.0);\n\n#ifdef USERGBCOLOR\nvec3 finalColor=colorBase;\n#else\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nvec3 mainColor=mix(vPrimaryColorShadow.rgb,vPrimaryColor.rgb,colorBase);\n#else\nvec3 mainColor=vPrimaryColor.rgb;\n#endif\nvec3 finalColor=colorBase*mainColor;\n#endif\n\n#ifdef REFLECTIONFRESNEL\nvec3 reflectionAmount=vReflectionControl.xxx;\nvec3 reflectionReflectance0=vReflectionControl.yyy;\nvec3 reflectionReflectance90=vReflectionControl.zzz;\nfloat VdotN=dot(normalize(vEyePosition),normalW);\nvec3 planarReflectionFresnel=fresnelSchlickEnvironmentGGX(clamp(VdotN,0.0,1.0),reflectionReflectance0,reflectionReflectance90,1.0);\nreflectionAmount*=planarReflectionFresnel;\n#ifdef REFLECTIONFALLOFF\nfloat reflectionDistanceFalloff=1.0-clamp(length(vPositionW.xyz-vBackgroundCenter)*vReflectionControl.w,0.0,1.0);\nreflectionDistanceFalloff*=reflectionDistanceFalloff;\nreflectionAmount*=reflectionDistanceFalloff;\n#endif\nfinalColor=mix(finalColor,reflectionColor.rgb,clamp(reflectionAmount,0.,1.));\n#endif\n#ifdef OPACITYFRESNEL\nfloat viewAngleToFloor=dot(normalW,normalize(vEyePosition-vBackgroundCenter));\n\nconst float startAngle=0.1;\nfloat fadeFactor=clamp(viewAngleToFloor/startAngle,0.0,1.0);\nfinalAlpha*=fadeFactor*fadeFactor;\n#endif\n\n#ifdef SHADOWINUSE\nfinalColor=mix(finalColor*shadowLevel,finalColor,globalShadow);\n#endif\n\nvec4 color=vec4(finalColor,finalAlpha);\n#include<fogFragment>\n#ifdef IMAGEPROCESSINGPOSTPROCESS\n\n\ncolor.rgb=clamp(color.rgb,0.,30.0);\n#else\n\ncolor=applyImageProcessing(color);\n#endif\n#ifdef PREMULTIPLYALPHA\n\ncolor.rgb*=color.a;\n#endif\n#ifdef NOISE\ncolor.rgb+=dither(vPositionW.xy,0.5);\ncolor=max(color,0.0);\n#endif\ngl_FragColor=color;\n}\n"};
  102525. BABYLON.Effect.IncludesShadersStore={"depthPrePass":"#ifdef DEPTHPREPASS\ngl_FragColor=vec4(0.,0.,0.,1.0);\nreturn;\n#endif","bonesDeclaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nattribute vec4 matricesIndices;\nattribute vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nattribute vec4 matricesIndicesExtra;\nattribute vec4 matricesWeightsExtra;\n#endif\n#endif","instancesDeclaration":"#ifdef INSTANCES\nattribute vec4 world0;\nattribute vec4 world1;\nattribute vec4 world2;\nattribute vec4 world3;\n#else\nuniform mat4 world;\n#endif","pointCloudVertexDeclaration":"#ifdef POINTSIZE\nuniform float pointSize;\n#endif","bumpVertexDeclaration":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#endif\n","clipPlaneVertexDeclaration":"#ifdef CLIPPLANE\nuniform vec4 vClipPlane;\nvarying float fClipDistance;\n#endif","fogVertexDeclaration":"#ifdef FOG\nvarying vec3 vFogDistance;\n#endif","morphTargetsVertexGlobalDeclaration":"#ifdef MORPHTARGETS\nuniform float morphTargetInfluences[NUM_MORPH_INFLUENCERS];\n#endif","morphTargetsVertexDeclaration":"#ifdef MORPHTARGETS\nattribute vec3 position{X};\n#ifdef MORPHTARGETS_NORMAL\nattribute vec3 normal{X};\n#endif\n#ifdef MORPHTARGETS_TANGENT\nattribute vec3 tangent{X};\n#endif\n#endif","logDepthDeclaration":"#ifdef LOGARITHMICDEPTH\nuniform float logarithmicDepthConstant;\nvarying float vFragmentDepth;\n#endif","morphTargetsVertex":"#ifdef MORPHTARGETS\npositionUpdated+=(position{X}-position)*morphTargetInfluences[{X}];\n#ifdef MORPHTARGETS_NORMAL\nnormalUpdated+=(normal{X}-normal)*morphTargetInfluences[{X}];\n#endif\n#ifdef MORPHTARGETS_TANGENT\ntangentUpdated.xyz+=(tangent{X}-tangent.xyz)*morphTargetInfluences[{X}];\n#endif\n#endif","instancesVertex":"#ifdef INSTANCES\nmat4 finalWorld=mat4(world0,world1,world2,world3);\n#else\nmat4 finalWorld=world;\n#endif","bonesVertex":"#if NUM_BONE_INFLUENCERS>0\nmat4 influence;\ninfluence=mBones[int(matricesIndices[0])]*matricesWeights[0];\n#if NUM_BONE_INFLUENCERS>1\ninfluence+=mBones[int(matricesIndices[1])]*matricesWeights[1];\n#endif \n#if NUM_BONE_INFLUENCERS>2\ninfluence+=mBones[int(matricesIndices[2])]*matricesWeights[2];\n#endif \n#if NUM_BONE_INFLUENCERS>3\ninfluence+=mBones[int(matricesIndices[3])]*matricesWeights[3];\n#endif \n#if NUM_BONE_INFLUENCERS>4\ninfluence+=mBones[int(matricesIndicesExtra[0])]*matricesWeightsExtra[0];\n#endif \n#if NUM_BONE_INFLUENCERS>5\ninfluence+=mBones[int(matricesIndicesExtra[1])]*matricesWeightsExtra[1];\n#endif \n#if NUM_BONE_INFLUENCERS>6\ninfluence+=mBones[int(matricesIndicesExtra[2])]*matricesWeightsExtra[2];\n#endif \n#if NUM_BONE_INFLUENCERS>7\ninfluence+=mBones[int(matricesIndicesExtra[3])]*matricesWeightsExtra[3];\n#endif \nfinalWorld=finalWorld*influence;\n#endif","bumpVertex":"#if defined(BUMP) || defined(PARALLAX)\n#if defined(TANGENT) && defined(NORMAL)\nvec3 tbnNormal=normalize(normalUpdated);\nvec3 tbnTangent=normalize(tangentUpdated.xyz);\nvec3 tbnBitangent=cross(tbnNormal,tbnTangent)*tangentUpdated.w;\nvTBN=mat3(finalWorld)*mat3(tbnTangent,tbnBitangent,tbnNormal);\n#endif\n#endif","clipPlaneVertex":"#ifdef CLIPPLANE\nfClipDistance=dot(worldPos,vClipPlane);\n#endif","fogVertex":"#ifdef FOG\nvFogDistance=(view*worldPos).xyz;\n#endif","shadowsVertex":"#ifdef SHADOWS\n#if defined(SHADOW{X}) && !defined(SHADOWCUBE{X})\nvPositionFromLight{X}=lightMatrix{X}*worldPos;\nvDepthMetric{X}=((vPositionFromLight{X}.z+light{X}.depthValues.x)/(light{X}.depthValues.y));\n#endif\n#endif","pointCloudVertex":"#ifdef POINTSIZE\ngl_PointSize=pointSize;\n#endif","logDepthVertex":"#ifdef LOGARITHMICDEPTH\nvFragmentDepth=1.0+gl_Position.w;\ngl_Position.z=log2(max(0.000001,vFragmentDepth))*logarithmicDepthConstant;\n#endif","helperFunctions":"const float PI=3.1415926535897932384626433832795;\nconst float LinearEncodePowerApprox=2.2;\nconst float GammaEncodePowerApprox=1.0/LinearEncodePowerApprox;\nconst vec3 LuminanceEncodeApprox=vec3(0.2126,0.7152,0.0722);\nmat3 transposeMat3(mat3 inMatrix) {\nvec3 i0=inMatrix[0];\nvec3 i1=inMatrix[1];\nvec3 i2=inMatrix[2];\nmat3 outMatrix=mat3(\nvec3(i0.x,i1.x,i2.x),\nvec3(i0.y,i1.y,i2.y),\nvec3(i0.z,i1.z,i2.z)\n);\nreturn outMatrix;\n}\n\nmat3 inverseMat3(mat3 inMatrix) {\nfloat a00=inMatrix[0][0],a01=inMatrix[0][1],a02=inMatrix[0][2];\nfloat a10=inMatrix[1][0],a11=inMatrix[1][1],a12=inMatrix[1][2];\nfloat a20=inMatrix[2][0],a21=inMatrix[2][1],a22=inMatrix[2][2];\nfloat b01=a22*a11-a12*a21;\nfloat b11=-a22*a10+a12*a20;\nfloat b21=a21*a10-a11*a20;\nfloat det=a00*b01+a01*b11+a02*b21;\nreturn mat3(b01,(-a22*a01+a02*a21),(a12*a01-a02*a11),\nb11,(a22*a00-a02*a20),(-a12*a00+a02*a10),\nb21,(-a21*a00+a01*a20),(a11*a00-a01*a10))/det;\n}\nfloat computeFallOff(float value,vec2 clipSpace,float frustumEdgeFalloff)\n{\nfloat mask=smoothstep(1.0-frustumEdgeFalloff,1.0,clamp(dot(clipSpace,clipSpace),0.,1.));\nreturn mix(value,1.0,mask);\n}\nvec3 applyEaseInOut(vec3 x){\nreturn x*x*(3.0-2.0*x);\n}\nvec3 toLinearSpace(vec3 color)\n{\nreturn pow(color,vec3(LinearEncodePowerApprox));\n}\nvec3 toGammaSpace(vec3 color)\n{\nreturn pow(color,vec3(GammaEncodePowerApprox));\n}\nfloat square(float value)\n{\nreturn value*value;\n}\nfloat getLuminance(vec3 color)\n{\nreturn clamp(dot(color,LuminanceEncodeApprox),0.,1.);\n}\n\nfloat getRand(vec2 seed) {\nreturn fract(sin(dot(seed.xy ,vec2(12.9898,78.233)))*43758.5453);\n}\nfloat dither(vec2 seed,float varianceAmount) {\nfloat rand=getRand(seed);\nfloat dither=mix(-varianceAmount/255.0,varianceAmount/255.0,rand);\nreturn dither;\n}\n\nconst float rgbdMaxRange=255.0;\nvec4 toRGBD(vec3 color) {\nfloat maxRGB=max(0.0000001,max(color.r,max(color.g,color.b)));\nfloat D=max(rgbdMaxRange/maxRGB,1.);\nD=clamp(floor(D)/255.0,0.,1.);\n\nvec3 rgb=color.rgb*D;\n\nrgb=toGammaSpace(rgb);\nreturn vec4(rgb,D); \n}\nvec3 fromRGBD(vec4 rgbd) {\n\nrgbd.rgb=toLinearSpace(rgbd.rgb);\n\nreturn rgbd.rgb/rgbd.a;\n}","lightFragmentDeclaration":"#ifdef LIGHT{X}\nuniform vec4 vLightData{X};\nuniform vec4 vLightDiffuse{X};\n#ifdef SPECULARTERM\nuniform vec3 vLightSpecular{X};\n#else\nvec3 vLightSpecular{X}=vec3(0.);\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X};\n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\nuniform vec4 shadowsInfo{X};\nuniform vec2 depthValues{X};\n#endif\n#ifdef SPOTLIGHT{X}\nuniform vec4 vLightDirection{X};\n#endif\n#ifdef HEMILIGHT{X}\nuniform vec3 vLightGround{X};\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#endif","lightsFragmentFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n#ifdef NDOTL\nfloat ndl;\n#endif\n};\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 lightVectorW;\nfloat attenuation=1.0;\nif (lightData.w == 0.)\n{\nvec3 direction=lightData.xyz-vPositionW;\nattenuation=max(0.,1.0-length(direction)/range);\nlightVectorW=normalize(direction);\n}\nelse\n{\nlightVectorW=normalize(-lightData.xyz);\n}\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float range,float glossiness) {\nlightingInfo result;\nvec3 direction=lightData.xyz-vPositionW;\nvec3 lightVectorW=normalize(direction);\nfloat attenuation=max(0.,1.0-length(direction)/range);\n\nfloat cosAngle=max(0.,dot(lightDirection.xyz,-lightVectorW));\nif (cosAngle>=lightDirection.w)\n{\ncosAngle=max(0.,pow(cosAngle,lightData.w));\nattenuation*=cosAngle;\n\nfloat ndl=max(0.,dot(vNormal,lightVectorW));\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=ndl*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightVectorW);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor*attenuation;\n#endif\nreturn result;\n}\nresult.diffuse=vec3(0.);\n#ifdef SPECULARTERM\nresult.specular=vec3(0.);\n#endif\n#ifdef NDOTL\nresult.ndl=0.;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float glossiness) {\nlightingInfo result;\n\nfloat ndl=dot(vNormal,lightData.xyz)*0.5+0.5;\n#ifdef NDOTL\nresult.ndl=ndl;\n#endif\nresult.diffuse=mix(groundColor,diffuseColor,ndl);\n#ifdef SPECULARTERM\n\nvec3 angleW=normalize(viewDirectionW+lightData.xyz);\nfloat specComp=max(0.,dot(vNormal,angleW));\nspecComp=pow(specComp,max(1.,glossiness));\nresult.specular=specComp*specularColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn textureColor;\n}","lightUboDeclaration":"#ifdef LIGHT{X}\nuniform Light{X}\n{\nvec4 vLightData;\nvec4 vLightDiffuse;\nvec3 vLightSpecular;\n#ifdef SPOTLIGHT{X}\nvec4 vLightDirection;\n#endif\n#ifdef HEMILIGHT{X}\nvec3 vLightGround;\n#endif\nvec4 shadowsInfo;\nvec2 depthValues;\n} light{X};\n#ifdef PROJECTEDLIGHTTEXTURE{X}\nuniform mat4 textureProjectionMatrix{X};\nuniform sampler2D projectionLightSampler{X};\n#endif\n#ifdef SHADOW{X}\n#if defined(SHADOWCUBE{X})\nuniform samplerCube shadowSampler{X}; \n#else\nvarying vec4 vPositionFromLight{X};\nvarying float vDepthMetric{X};\n#if defined(SHADOWPCSS{X})\nuniform highp sampler2DShadow shadowSampler{X};\nuniform highp sampler2D depthSampler{X};\n#elif defined(SHADOWPCF{X})\nuniform highp sampler2DShadow shadowSampler{X};\n#else\nuniform sampler2D shadowSampler{X};\n#endif\nuniform mat4 lightMatrix{X};\n#endif\n#endif\n#endif","defaultVertexDeclaration":"\nuniform mat4 viewProjection;\nuniform mat4 view;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\nuniform mat4 specularMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n","defaultFragmentDeclaration":"uniform vec4 vDiffuseColor;\n#ifdef SPECULARTERM\nuniform vec4 vSpecularColor;\n#endif\nuniform vec3 vEmissiveColor;\n\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef AMBIENT\nuniform vec2 vAmbientInfos;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\n#ifndef REFRACTIONMAP_3D\nuniform mat4 refractionMatrix;\n#endif\n#ifdef REFRACTIONFRESNEL\nuniform vec4 refractionLeftColor;\nuniform vec4 refractionRightColor;\n#endif\n#endif\n#if defined(SPECULAR) && defined(SPECULARTERM)\nuniform vec2 vSpecularInfos;\n#endif\n#ifdef DIFFUSEFRESNEL\nuniform vec4 diffuseLeftColor;\nuniform vec4 diffuseRightColor;\n#endif\n#ifdef OPACITYFRESNEL\nuniform vec4 opacityParts;\n#endif\n#ifdef EMISSIVEFRESNEL\nuniform vec4 emissiveLeftColor;\nuniform vec4 emissiveRightColor;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\n#ifdef REFLECTIONMAP_SKYBOX\n#else\n#if defined(REFLECTIONMAP_PLANAR) || defined(REFLECTIONMAP_CUBIC) || defined(REFLECTIONMAP_PROJECTION)\nuniform mat4 reflectionMatrix;\n#endif\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 reflectionLeftColor;\nuniform vec4 reflectionRightColor;\n#endif\n#endif","defaultUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nvec4 diffuseLeftColor;\nvec4 diffuseRightColor;\nvec4 opacityParts;\nvec4 reflectionLeftColor;\nvec4 reflectionRightColor;\nvec4 refractionLeftColor;\nvec4 refractionRightColor;\nvec4 emissiveLeftColor; \nvec4 emissiveRightColor;\nvec2 vDiffuseInfos;\nvec2 vAmbientInfos;\nvec2 vOpacityInfos;\nvec2 vReflectionInfos;\nvec3 vReflectionPosition;\nvec3 vReflectionSize;\nvec2 vEmissiveInfos;\nvec2 vLightmapInfos;\nvec2 vSpecularInfos;\nvec3 vBumpInfos;\nmat4 diffuseMatrix;\nmat4 ambientMatrix;\nmat4 opacityMatrix;\nmat4 reflectionMatrix;\nmat4 emissiveMatrix;\nmat4 lightmapMatrix;\nmat4 specularMatrix;\nmat4 bumpMatrix; \nvec4 vTangentSpaceParams;\nmat4 refractionMatrix;\nvec4 vRefractionInfos;\nvec4 vSpecularColor;\nvec3 vEmissiveColor;\nvec4 vDiffuseColor;\nfloat pointSize; \n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","shadowsFragmentFunctions":"#ifdef SHADOWS\n#ifndef SHADOWFLOAT\nfloat unpack(vec4 color)\n{\nconst vec4 bit_shift=vec4(1.0/(255.0*255.0*255.0),1.0/(255.0*255.0),1.0/255.0,1.0);\nreturn dot(color,bit_shift);\n}\n#endif\nfloat computeShadowCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadow=textureCube(shadowSampler,directionToLight).x;\n#endif\nif (depth>shadow)\n{\nreturn darkness;\n}\nreturn 1.0;\n}\nfloat computeShadowWithPoissonSamplingCube(vec3 lightPosition,samplerCube shadowSampler,float mapSize,float darkness,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\ndepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\nfloat visibility=1.;\nvec3 poissonDisk[4];\npoissonDisk[0]=vec3(-1.0,1.0,-1.0);\npoissonDisk[1]=vec3(1.0,-1.0,-1.0);\npoissonDisk[2]=vec3(-1.0,-1.0,-1.0);\npoissonDisk[3]=vec3(1.0,-1.0,1.0);\n\n#ifndef SHADOWFLOAT\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize))<depth) visibility-=0.25;\nif (unpack(textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize))<depth) visibility-=0.25;\n#else\nif (textureCube(shadowSampler,directionToLight+poissonDisk[0]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[1]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[2]*mapSize).x<depth) visibility-=0.25;\nif (textureCube(shadowSampler,directionToLight+poissonDisk[3]*mapSize).x<depth) visibility-=0.25;\n#endif\nreturn min(1.0,visibility+darkness);\n}\nfloat computeShadowWithESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness); \nreturn esm;\n}\nfloat computeShadowWithCloseESMCube(vec3 lightPosition,samplerCube shadowSampler,float darkness,float depthScale,vec2 depthValues)\n{\nvec3 directionToLight=vPositionW-lightPosition;\nfloat depth=length(directionToLight);\ndepth=(depth+depthValues.x)/(depthValues.y);\nfloat shadowPixelDepth=clamp(depth,0.,1.0);\ndirectionToLight=normalize(directionToLight);\ndirectionToLight.y=-directionToLight.y;\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(textureCube(shadowSampler,directionToLight));\n#else\nfloat shadowMapSample=textureCube(shadowSampler,directionToLight).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn esm;\n}\nfloat computeShadow(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadow=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadow=texture2D(shadowSampler,uv).x;\n#endif\nif (shadowPixelDepth>shadow)\n{\nreturn computeFallOff(darkness,clipSpace.xy,frustumEdgeFalloff);\n}\nreturn 1.;\n}\nfloat computeShadowWithPoissonSampling(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float mapSize,float darkness,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\nfloat visibility=1.;\nvec2 poissonDisk[4];\npoissonDisk[0]=vec2(-0.94201624,-0.39906216);\npoissonDisk[1]=vec2(0.94558609,-0.76890725);\npoissonDisk[2]=vec2(-0.094184101,-0.92938870);\npoissonDisk[3]=vec2(0.34495938,0.29387760);\n\n#ifndef SHADOWFLOAT\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[0]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[1]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[2]*mapSize))<shadowPixelDepth) visibility-=0.25;\nif (unpack(texture2D(shadowSampler,uv+poissonDisk[3]*mapSize))<shadowPixelDepth) visibility-=0.25;\n#else\nif (texture2D(shadowSampler,uv+poissonDisk[0]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[1]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[2]*mapSize).x<shadowPixelDepth) visibility-=0.25;\nif (texture2D(shadowSampler,uv+poissonDisk[3]*mapSize).x<shadowPixelDepth) visibility-=0.25;\n#endif\nreturn computeFallOff(min(1.0,visibility+darkness),clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0);\n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=1.0-clamp(exp(min(87.,depthScale*shadowPixelDepth))*shadowMapSample,0.,1.-darkness);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithCloseESM(vec4 vPositionFromLight,float depthMetric,sampler2D shadowSampler,float darkness,float depthScale,float frustumEdgeFalloff)\n{\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec2 uv=0.5*clipSpace.xy+vec2(0.5);\nif (uv.x<0. || uv.x>1.0 || uv.y<0. || uv.y>1.0)\n{\nreturn 1.0;\n}\nfloat shadowPixelDepth=clamp(depthMetric,0.,1.0); \n#ifndef SHADOWFLOAT\nfloat shadowMapSample=unpack(texture2D(shadowSampler,uv));\n#else\nfloat shadowMapSample=texture2D(shadowSampler,uv).x;\n#endif\nfloat esm=clamp(exp(min(87.,-depthScale*(shadowPixelDepth-shadowMapSample))),darkness,1.);\nreturn computeFallOff(esm,clipSpace.xy,frustumEdgeFalloff);\n}\n#ifdef WEBGL2\n\nfloat computeShadowWithPCF1(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat shadow=texture2D(shadowSampler,uvDepth);\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF3(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\n\n\nvec2 uvw0=3.-2.*st;\nvec2 uvw1=1.+2.*st;\nvec2 u=vec2((2.-st.x)/uvw0.x-1.,st.x/uvw1.x+1.)*shadowMapSizeAndInverse.y;\nvec2 v=vec2((2.-st.y)/uvw0.y-1.,st.y/uvw1.y+1.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow=shadow/16.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\n\n\n\nfloat computeShadowWithPCF5(vec4 vPositionFromLight,float depthMetric,sampler2DShadow shadowSampler,vec2 shadowMapSizeAndInverse,float darkness,float frustumEdgeFalloff)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nvec2 uv=uvDepth.xy*shadowMapSizeAndInverse.x; \nuv+=0.5; \nvec2 st=fract(uv); \nvec2 base_uv=floor(uv)-0.5; \nbase_uv*=shadowMapSizeAndInverse.y; \n\n\nvec2 uvw0=4.-3.*st;\nvec2 uvw1=vec2(7.);\nvec2 uvw2=1.+3.*st;\nvec3 u=vec3((3.-2.*st.x)/uvw0.x-2.,(3.+st.x)/uvw1.x,st.x/uvw2.x+2.)*shadowMapSizeAndInverse.y;\nvec3 v=vec3((3.-2.*st.y)/uvw0.y-2.,(3.+st.y)/uvw1.y,st.y/uvw2.y+2.)*shadowMapSizeAndInverse.y;\nfloat shadow=0.;\nshadow+=uvw0.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[0]),uvDepth.z));\nshadow+=uvw1.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[0]),uvDepth.z));\nshadow+=uvw2.x*uvw0.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[0]),uvDepth.z));\nshadow+=uvw0.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[1]),uvDepth.z));\nshadow+=uvw1.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[1]),uvDepth.z));\nshadow+=uvw2.x*uvw1.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[1]),uvDepth.z));\nshadow+=uvw0.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[0],v[2]),uvDepth.z));\nshadow+=uvw1.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[1],v[2]),uvDepth.z));\nshadow+=uvw2.x*uvw2.y*texture2D(shadowSampler,vec3(base_uv.xy+vec2(u[2],v[2]),uvDepth.z));\nshadow=shadow/144.;\nshadow=mix(darkness,1.,shadow);\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nconst vec3 PoissonSamplers32[64]=vec3[64](\nvec3(0.06407013,0.05409927,0.),\nvec3(0.7366577,0.5789394,0.),\nvec3(-0.6270542,-0.5320278,0.),\nvec3(-0.4096107,0.8411095,0.),\nvec3(0.6849564,-0.4990818,0.),\nvec3(-0.874181,-0.04579735,0.),\nvec3(0.9989998,0.0009880066,0.),\nvec3(-0.004920578,-0.9151649,0.),\nvec3(0.1805763,0.9747483,0.),\nvec3(-0.2138451,0.2635818,0.),\nvec3(0.109845,0.3884785,0.),\nvec3(0.06876755,-0.3581074,0.),\nvec3(0.374073,-0.7661266,0.),\nvec3(0.3079132,-0.1216763,0.),\nvec3(-0.3794335,-0.8271583,0.),\nvec3(-0.203878,-0.07715034,0.),\nvec3(0.5912697,0.1469799,0.),\nvec3(-0.88069,0.3031784,0.),\nvec3(0.5040108,0.8283722,0.),\nvec3(-0.5844124,0.5494877,0.),\nvec3(0.6017799,-0.1726654,0.),\nvec3(-0.5554981,0.1559997,0.),\nvec3(-0.3016369,-0.3900928,0.),\nvec3(-0.5550632,-0.1723762,0.),\nvec3(0.925029,0.2995041,0.),\nvec3(-0.2473137,0.5538505,0.),\nvec3(0.9183037,-0.2862392,0.),\nvec3(0.2469421,0.6718712,0.),\nvec3(0.3916397,-0.4328209,0.),\nvec3(-0.03576927,-0.6220032,0.),\nvec3(-0.04661255,0.7995201,0.),\nvec3(0.4402924,0.3640312,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.),\nvec3(0.,0.,0.)\n);\nconst vec3 PoissonSamplers64[64]=vec3[64](\nvec3(-0.613392,0.617481,0.),\nvec3(0.170019,-0.040254,0.),\nvec3(-0.299417,0.791925,0.),\nvec3(0.645680,0.493210,0.),\nvec3(-0.651784,0.717887,0.),\nvec3(0.421003,0.027070,0.),\nvec3(-0.817194,-0.271096,0.),\nvec3(-0.705374,-0.668203,0.),\nvec3(0.977050,-0.108615,0.),\nvec3(0.063326,0.142369,0.),\nvec3(0.203528,0.214331,0.),\nvec3(-0.667531,0.326090,0.),\nvec3(-0.098422,-0.295755,0.),\nvec3(-0.885922,0.215369,0.),\nvec3(0.566637,0.605213,0.),\nvec3(0.039766,-0.396100,0.),\nvec3(0.751946,0.453352,0.),\nvec3(0.078707,-0.715323,0.),\nvec3(-0.075838,-0.529344,0.),\nvec3(0.724479,-0.580798,0.),\nvec3(0.222999,-0.215125,0.),\nvec3(-0.467574,-0.405438,0.),\nvec3(-0.248268,-0.814753,0.),\nvec3(0.354411,-0.887570,0.),\nvec3(0.175817,0.382366,0.),\nvec3(0.487472,-0.063082,0.),\nvec3(-0.084078,0.898312,0.),\nvec3(0.488876,-0.783441,0.),\nvec3(0.470016,0.217933,0.),\nvec3(-0.696890,-0.549791,0.),\nvec3(-0.149693,0.605762,0.),\nvec3(0.034211,0.979980,0.),\nvec3(0.503098,-0.308878,0.),\nvec3(-0.016205,-0.872921,0.),\nvec3(0.385784,-0.393902,0.),\nvec3(-0.146886,-0.859249,0.),\nvec3(0.643361,0.164098,0.),\nvec3(0.634388,-0.049471,0.),\nvec3(-0.688894,0.007843,0.),\nvec3(0.464034,-0.188818,0.),\nvec3(-0.440840,0.137486,0.),\nvec3(0.364483,0.511704,0.),\nvec3(0.034028,0.325968,0.),\nvec3(0.099094,-0.308023,0.),\nvec3(0.693960,-0.366253,0.),\nvec3(0.678884,-0.204688,0.),\nvec3(0.001801,0.780328,0.),\nvec3(0.145177,-0.898984,0.),\nvec3(0.062655,-0.611866,0.),\nvec3(0.315226,-0.604297,0.),\nvec3(-0.780145,0.486251,0.),\nvec3(-0.371868,0.882138,0.),\nvec3(0.200476,0.494430,0.),\nvec3(-0.494552,-0.711051,0.),\nvec3(0.612476,0.705252,0.),\nvec3(-0.578845,-0.768792,0.),\nvec3(-0.772454,-0.090976,0.),\nvec3(0.504440,0.372295,0.),\nvec3(0.155736,0.065157,0.),\nvec3(0.391522,0.849605,0.),\nvec3(-0.620106,-0.328104,0.),\nvec3(0.789239,-0.419965,0.),\nvec3(-0.545396,0.538133,0.),\nvec3(-0.178564,-0.596057,0.)\n);\n\n\n\n\n\nfloat computeShadowWithPCSS(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff,int searchTapCount,int pcfTapCount,vec3[64] poissonSamplers)\n{\nif (depthMetric>1.0 || depthMetric<0.0) {\nreturn 1.0;\n}\nvec3 clipSpace=vPositionFromLight.xyz/vPositionFromLight.w;\nvec3 uvDepth=vec3(0.5*clipSpace.xyz+vec3(0.5));\nfloat blockerDepth=0.0;\nfloat sumBlockerDepth=0.0;\nfloat numBlocker=0.0;\nfor (int i=0; i<searchTapCount; i ++) {\nblockerDepth=texture(depthSampler,uvDepth.xy+(lightSizeUV*shadowMapSizeInverse*PoissonSamplers32[i].xy)).r;\nif (blockerDepth<depthMetric) {\nsumBlockerDepth+=blockerDepth;\nnumBlocker++;\n}\n}\nif (numBlocker<1.0) {\nreturn 1.0;\n}\nfloat avgBlockerDepth=sumBlockerDepth/numBlocker;\n\nfloat AAOffset=shadowMapSizeInverse*10.;\n\n\nfloat penumbraRatio=((depthMetric-avgBlockerDepth)+AAOffset);\nfloat filterRadius=penumbraRatio*lightSizeUV*shadowMapSizeInverse;\nfloat random=getRand(vPositionFromLight.xy);\nfloat rotationAngle=random*3.1415926;\nvec2 rotationVector=vec2(cos(rotationAngle),sin(rotationAngle));\nfloat shadow=0.;\nfor (int i=0; i<pcfTapCount; i++) {\nvec3 offset=poissonSamplers[i];\n\noffset=vec3(offset.x*rotationVector.x-offset.y*rotationVector.y,offset.y*rotationVector.x+offset.x*rotationVector.y,0.);\nshadow+=texture2D(shadowSampler,uvDepth+offset*filterRadius);\n}\nshadow/=float(pcfTapCount);\n\nshadow=mix(shadow,1.,depthMetric-avgBlockerDepth);\n\nshadow=mix(darkness,1.,shadow);\n\nreturn computeFallOff(shadow,clipSpace.xy,frustumEdgeFalloff);\n}\nfloat computeShadowWithPCSS16(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,16,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS32(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,16,32,PoissonSamplers32);\n}\nfloat computeShadowWithPCSS64(vec4 vPositionFromLight,float depthMetric,sampler2D depthSampler,sampler2DShadow shadowSampler,float shadowMapSizeInverse,float lightSizeUV,float darkness,float frustumEdgeFalloff)\n{\nreturn computeShadowWithPCSS(vPositionFromLight,depthMetric,depthSampler,shadowSampler,shadowMapSizeInverse,lightSizeUV,darkness,frustumEdgeFalloff,32,64,PoissonSamplers64);\n}\n#endif\n#endif\n","fresnelFunction":"#ifdef FRESNEL\nfloat computeFresnelTerm(vec3 viewDirection,vec3 worldNormal,float bias,float power)\n{\nfloat fresnelTerm=pow(bias+abs(dot(viewDirection,worldNormal)),power);\nreturn clamp(fresnelTerm,0.,1.);\n}\n#endif","reflectionFunction":"#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\nvec3 parallaxCorrectNormal( vec3 vertexPos,vec3 origVec,vec3 cubeSize,vec3 cubePos ) {\n\nvec3 invOrigVec=vec3(1.0,1.0,1.0)/origVec;\nvec3 halfSize=cubeSize*0.5;\nvec3 intersecAtMaxPlane=(cubePos+halfSize-vertexPos)*invOrigVec;\nvec3 intersecAtMinPlane=(cubePos-halfSize-vertexPos)*invOrigVec;\n\nvec3 largestIntersec=max(intersecAtMaxPlane,intersecAtMinPlane);\n\nfloat distance=min(min(largestIntersec.x,largestIntersec.y),largestIntersec.z);\n\nvec3 intersectPositionWS=vertexPos+origVec*distance;\n\nreturn intersectPositionWS-cubePos;\n}\n#endif\nvec3 computeReflectionCoords(vec4 worldPos,vec3 worldNormal)\n{\n#if defined(REFLECTIONMAP_EQUIRECTANGULAR_FIXED) || defined(REFLECTIONMAP_MIRROREDEQUIRECTANGULAR_FIXED)\nvec3 direction=normalize(vDirectionW);\nfloat lon=atan(direction.z,direction.x);\nfloat lat=acos(direction.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \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=normalize(reflect(cameraToVertex,worldNormal));\nfloat lon=atan(r.z,r.x);\nfloat lat=acos(r.y);\nvec2 sphereCoords=vec2(lon,lat)*RECIPROCAL_PI2*2.0;\nfloat s=sphereCoords.x*0.5+0.5;\nfloat t=sphereCoords.y; \nreturn vec3(s,t,0);\n#endif\n#ifdef REFLECTIONMAP_SPHERICAL\nvec3 viewDir=normalize(vec3(view*worldPos));\nvec3 viewNormal=normalize(vec3(view*vec4(worldNormal,0.0)));\nvec3 r=reflect(viewDir,viewNormal);\nr.z=r.z-1.0;\nfloat m=2.0*length(r);\nreturn vec3(r.x/m+0.5,1.0-r.y/m-0.5,0);\n#endif\n#ifdef REFLECTIONMAP_PLANAR\nvec3 viewDir=worldPos.xyz-vEyePosition.xyz;\nvec3 coords=normalize(reflect(viewDir,worldNormal));\nreturn vec3(reflectionMatrix*vec4(coords,1));\n#endif\n#ifdef REFLECTIONMAP_CUBIC\nvec3 viewDir=normalize(worldPos.xyz-vEyePosition.xyz);\n\nvec3 coords=reflect(viewDir,worldNormal);\n#ifdef USE_LOCAL_REFLECTIONMAP_CUBIC\ncoords=parallaxCorrectNormal(worldPos.xyz,coords,vReflectionSize,vReflectionPosition);\n#endif\ncoords=vec3(reflectionMatrix*vec4(coords,0));\n#ifdef INVERTCUBICMAP\ncoords.y*=-1.0;\n#endif\nreturn coords;\n#endif\n#ifdef REFLECTIONMAP_PROJECTION\nreturn vec3(reflectionMatrix*(view*worldPos));\n#endif\n#ifdef REFLECTIONMAP_SKYBOX\nreturn vPositionUVW;\n#endif\n#ifdef REFLECTIONMAP_EXPLICIT\nreturn vec3(0,0,0);\n#endif\n}","imageProcessingDeclaration":"#ifdef EXPOSURE\nuniform float exposureLinear;\n#endif\n#ifdef CONTRAST\nuniform float contrast;\n#endif\n#ifdef VIGNETTE\nuniform vec2 vInverseScreenSize;\nuniform vec4 vignetteSettings1;\nuniform vec4 vignetteSettings2;\n#endif\n#ifdef COLORCURVES\nuniform vec4 vCameraColorCurveNegative;\nuniform vec4 vCameraColorCurveNeutral;\nuniform vec4 vCameraColorCurvePositive;\n#endif\n#ifdef COLORGRADING\n#ifdef COLORGRADING3D\nuniform highp sampler3D txColorTransform;\n#else\nuniform sampler2D txColorTransform;\n#endif\nuniform vec4 colorTransformSettings;\n#endif","imageProcessingFunctions":"#if defined(COLORGRADING) && !defined(COLORGRADING3D)\n\nvec3 sampleTexture3D(sampler2D colorTransform,vec3 color,vec2 sampler3dSetting)\n{\nfloat sliceSize=2.0*sampler3dSetting.x; \n#ifdef SAMPLER3DGREENDEPTH\nfloat sliceContinuous=(color.g-sampler3dSetting.x)*sampler3dSetting.y;\n#else\nfloat sliceContinuous=(color.b-sampler3dSetting.x)*sampler3dSetting.y;\n#endif\nfloat sliceInteger=floor(sliceContinuous);\n\n\nfloat sliceFraction=sliceContinuous-sliceInteger;\n#ifdef SAMPLER3DGREENDEPTH\nvec2 sliceUV=color.rb;\n#else\nvec2 sliceUV=color.rg;\n#endif\nsliceUV.x*=sliceSize;\nsliceUV.x+=sliceInteger*sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice0Color=texture2D(colorTransform,sliceUV);\nsliceUV.x+=sliceSize;\nsliceUV=clamp(sliceUV,0.,1.);\nvec4 slice1Color=texture2D(colorTransform,sliceUV);\nvec3 result=mix(slice0Color.rgb,slice1Color.rgb,sliceFraction);\n#ifdef SAMPLER3DBGRMAP\ncolor.rgb=result.rgb;\n#else\ncolor.rgb=result.bgr;\n#endif\nreturn color;\n}\n#endif\nvec4 applyImageProcessing(vec4 result) {\n#ifdef EXPOSURE\nresult.rgb*=exposureLinear;\n#endif\n#ifdef VIGNETTE\n\nvec2 viewportXY=gl_FragCoord.xy*vInverseScreenSize;\nviewportXY=viewportXY*2.0-1.0;\nvec3 vignetteXY1=vec3(viewportXY*vignetteSettings1.xy+vignetteSettings1.zw,1.0);\nfloat vignetteTerm=dot(vignetteXY1,vignetteXY1);\nfloat vignette=pow(vignetteTerm,vignetteSettings2.w);\n\nvec3 vignetteColor=vignetteSettings2.rgb;\n#ifdef VIGNETTEBLENDMODEMULTIPLY\nvec3 vignetteColorMultiplier=mix(vignetteColor,vec3(1,1,1),vignette);\nresult.rgb*=vignetteColorMultiplier;\n#endif\n#ifdef VIGNETTEBLENDMODEOPAQUE\nresult.rgb=mix(vignetteColor,result.rgb,vignette);\n#endif\n#endif\n#ifdef TONEMAPPING\nconst float tonemappingCalibration=1.590579;\nresult.rgb=1.0-exp2(-tonemappingCalibration*result.rgb);\n#endif\n\nresult.rgb=toGammaSpace(result.rgb);\nresult.rgb=clamp(result.rgb,0.0,1.0);\n#ifdef CONTRAST\n\nvec3 resultHighContrast=applyEaseInOut(result.rgb);\nif (contrast<1.0) {\n\nresult.rgb=mix(vec3(0.5,0.5,0.5),result.rgb,contrast);\n} else {\n\nresult.rgb=mix(result.rgb,resultHighContrast,contrast-1.0);\n}\n#endif\n\n#ifdef COLORGRADING\nvec3 colorTransformInput=result.rgb*colorTransformSettings.xxx+colorTransformSettings.yyy;\n#ifdef COLORGRADING3D\nvec3 colorTransformOutput=texture(txColorTransform,colorTransformInput).rgb;\n#else\nvec3 colorTransformOutput=sampleTexture3D(txColorTransform,colorTransformInput,colorTransformSettings.yz).rgb;\n#endif\nresult.rgb=mix(result.rgb,colorTransformOutput,colorTransformSettings.www);\n#endif\n#ifdef COLORCURVES\n\nfloat luma=getLuminance(result.rgb);\nvec2 curveMix=clamp(vec2(luma*3.0-1.5,luma*-3.0+1.5),vec2(0.0),vec2(1.0));\nvec4 colorCurve=vCameraColorCurveNeutral+curveMix.x*vCameraColorCurvePositive-curveMix.y*vCameraColorCurveNegative;\nresult.rgb*=colorCurve.rgb;\nresult.rgb=mix(vec3(luma),result.rgb,colorCurve.a);\n#endif\nreturn result;\n}","bumpFragmentFunctions":"#ifdef BUMP\n#if BUMPDIRECTUV == 1\n#define vBumpUV vMainUV1\n#elif BUMPDIRECTUV == 2\n#define vBumpUV vMainUV2\n#else\nvarying vec2 vBumpUV;\n#endif\nuniform sampler2D bumpSampler;\n#if defined(TANGENT) && defined(NORMAL) \nvarying mat3 vTBN;\n#endif\n#ifdef OBJECTSPACE_NORMALMAP\nuniform mat4 normalMatrix;\n#endif\n\nmat3 cotangent_frame(vec3 normal,vec3 p,vec2 uv)\n{\n\nuv=gl_FrontFacing ? uv : -uv;\n\nvec3 dp1=dFdx(p);\nvec3 dp2=dFdy(p);\nvec2 duv1=dFdx(uv);\nvec2 duv2=dFdy(uv);\n\nvec3 dp2perp=cross(dp2,normal);\nvec3 dp1perp=cross(normal,dp1);\nvec3 tangent=dp2perp*duv1.x+dp1perp*duv2.x;\nvec3 bitangent=dp2perp*duv1.y+dp1perp*duv2.y;\n\ntangent*=vTangentSpaceParams.x;\nbitangent*=vTangentSpaceParams.y;\n\nfloat invmax=inversesqrt(max(dot(tangent,tangent),dot(bitangent,bitangent)));\nreturn mat3(tangent*invmax,bitangent*invmax,normal);\n}\nvec3 perturbNormal(mat3 cotangentFrame,vec2 uv)\n{\nvec3 map=texture2D(bumpSampler,uv).xyz;\nmap=map*2.0-1.0;\n#ifdef NORMALXYSCALE\nmap=normalize(map*vec3(vBumpInfos.y,vBumpInfos.y,1.0));\n#endif\nreturn normalize(cotangentFrame*map);\n}\n#ifdef PARALLAX\nconst float minSamples=4.;\nconst float maxSamples=15.;\nconst int iMaxSamples=15;\n\nvec2 parallaxOcclusion(vec3 vViewDirCoT,vec3 vNormalCoT,vec2 texCoord,float parallaxScale) {\nfloat parallaxLimit=length(vViewDirCoT.xy)/vViewDirCoT.z;\nparallaxLimit*=parallaxScale;\nvec2 vOffsetDir=normalize(vViewDirCoT.xy);\nvec2 vMaxOffset=vOffsetDir*parallaxLimit;\nfloat numSamples=maxSamples+(dot(vViewDirCoT,vNormalCoT)*(minSamples-maxSamples));\nfloat stepSize=1.0/numSamples;\n\nfloat currRayHeight=1.0;\nvec2 vCurrOffset=vec2(0,0);\nvec2 vLastOffset=vec2(0,0);\nfloat lastSampledHeight=1.0;\nfloat currSampledHeight=1.0;\nfor (int i=0; i<iMaxSamples; i++)\n{\ncurrSampledHeight=texture2D(bumpSampler,vBumpUV+vCurrOffset).w;\n\nif (currSampledHeight>currRayHeight)\n{\nfloat delta1=currSampledHeight-currRayHeight;\nfloat delta2=(currRayHeight+stepSize)-lastSampledHeight;\nfloat ratio=delta1/(delta1+delta2);\nvCurrOffset=(ratio)* vLastOffset+(1.0-ratio)*vCurrOffset;\n\nbreak;\n}\nelse\n{\ncurrRayHeight-=stepSize;\nvLastOffset=vCurrOffset;\nvCurrOffset+=stepSize*vMaxOffset;\nlastSampledHeight=currSampledHeight;\n}\n}\nreturn vCurrOffset;\n}\nvec2 parallaxOffset(vec3 viewDir,float heightScale)\n{\n\nfloat height=texture2D(bumpSampler,vBumpUV).w;\nvec2 texCoordOffset=heightScale*viewDir.xy*height;\nreturn -texCoordOffset;\n}\n#endif\n#endif","clipPlaneFragmentDeclaration":"#ifdef CLIPPLANE\nvarying float fClipDistance;\n#endif","fogFragmentDeclaration":"#ifdef FOG\n#define FOGMODE_NONE 0.\n#define FOGMODE_EXP 1.\n#define FOGMODE_EXP2 2.\n#define FOGMODE_LINEAR 3.\n#define E 2.71828\nuniform vec4 vFogInfos;\nuniform vec3 vFogColor;\nvarying vec3 vFogDistance;\nfloat CalcFogFactor()\n{\nfloat fogCoeff=1.0;\nfloat fogStart=vFogInfos.y;\nfloat fogEnd=vFogInfos.z;\nfloat fogDensity=vFogInfos.w;\nfloat fogDistance=length(vFogDistance);\nif (FOGMODE_LINEAR == vFogInfos.x)\n{\nfogCoeff=(fogEnd-fogDistance)/(fogEnd-fogStart);\n}\nelse if (FOGMODE_EXP == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDensity);\n}\nelse if (FOGMODE_EXP2 == vFogInfos.x)\n{\nfogCoeff=1.0/pow(E,fogDistance*fogDistance*fogDensity*fogDensity);\n}\nreturn clamp(fogCoeff,0.0,1.0);\n}\n#endif","clipPlaneFragment":"#ifdef CLIPPLANE\nif (fClipDistance>0.0)\n{\ndiscard;\n}\n#endif","bumpFragment":"vec2 uvOffset=vec2(0.0,0.0);\n#if defined(BUMP) || defined(PARALLAX)\n#ifdef NORMALXYSCALE\nfloat normalScale=1.0;\n#else \nfloat normalScale=vBumpInfos.y;\n#endif\n#if defined(TANGENT) && defined(NORMAL)\nmat3 TBN=vTBN;\n#else\nmat3 TBN=cotangent_frame(normalW*normalScale,vPositionW,vBumpUV);\n#endif\n#endif\n#ifdef PARALLAX\nmat3 invTBN=transposeMat3(TBN);\n#ifdef PARALLAXOCCLUSION\nuvOffset=parallaxOcclusion(invTBN*-viewDirectionW,invTBN*normalW,vBumpUV,vBumpInfos.z);\n#else\nuvOffset=parallaxOffset(invTBN*viewDirectionW,vBumpInfos.z);\n#endif\n#endif\n#ifdef BUMP\n#ifdef OBJECTSPACE_NORMALMAP\nnormalW=normalize(texture2D(bumpSampler,vBumpUV).xyz*2.0-1.0);\nnormalW=normalize(mat3(normalMatrix)*normalW); \n#else\nnormalW=perturbNormal(TBN,vBumpUV+uvOffset);\n#endif\n#endif","lightFragment":"#ifdef LIGHT{X}\n#if defined(SHADOWONLY) || (defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X}) && defined(LIGHTMAPNOSPECULAR{X}))\n\n#else\n#ifdef PBR\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,roughness,NdotV,specularEnvironmentR0,specularEnvironmentR90,geometricRoughnessFactor,NdotL);\n#endif\n#else\n#ifdef SPOTLIGHT{X}\ninfo=computeSpotLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDirection,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#ifdef HEMILIGHT{X}\ninfo=computeHemisphericLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightGround,glossiness);\n#endif\n#if defined(POINTLIGHT{X}) || defined(DIRLIGHT{X})\ninfo=computeLighting(viewDirectionW,normalW,light{X}.vLightData,light{X}.vLightDiffuse.rgb,light{X}.vLightSpecular,light{X}.vLightDiffuse.a,glossiness);\n#endif\n#endif\n#ifdef PROJECTEDLIGHTTEXTURE{X}\ninfo.diffuse*=computeProjectionTextureDiffuseLighting(projectionLightSampler{X},textureProjectionMatrix{X});\n#endif\n#endif\n#ifdef SHADOW{X}\n#ifdef SHADOWCLOSEESM{X}\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithCloseESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithCloseESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWESM{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithESMCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.depthValues);\n#else\nshadow=computeShadowWithESM(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.z,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPOISSON{X})\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowWithPoissonSamplingCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadowWithPoissonSampling(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCF{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCF1(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCF3(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCF5(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.yz,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#elif defined(SHADOWPCSS{X})\n#if defined(SHADOWLOWQUALITY{X})\nshadow=computeShadowWithPCSS16(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#elif defined(SHADOWMEDIUMQUALITY{X})\nshadow=computeShadowWithPCSS32(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#else\nshadow=computeShadowWithPCSS64(vPositionFromLight{X},vDepthMetric{X},depthSampler{X},shadowSampler{X},light{X}.shadowsInfo.y,light{X}.shadowsInfo.z,light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#else\n#if defined(SHADOWCUBE{X})\nshadow=computeShadowCube(light{X}.vLightData.xyz,shadowSampler{X},light{X}.shadowsInfo.x,light{X}.depthValues);\n#else\nshadow=computeShadow(vPositionFromLight{X},vDepthMetric{X},shadowSampler{X},light{X}.shadowsInfo.x,light{X}.shadowsInfo.w);\n#endif\n#endif\n#ifdef SHADOWONLY\n#ifndef SHADOWINUSE\n#define SHADOWINUSE\n#endif\nglobalShadow+=shadow;\nshadowLightCount+=1.0;\n#endif\n#else\nshadow=1.;\n#endif\n#ifndef SHADOWONLY\n#ifdef CUSTOMUSERLIGHTING\ndiffuseBase+=computeCustomDiffuseLighting(info,diffuseBase,shadow);\n#ifdef SPECULARTERM\nspecularBase+=computeCustomSpecularLighting(info,specularBase,shadow);\n#endif\n#elif defined(LIGHTMAP) && defined(LIGHTMAPEXCLUDED{X})\ndiffuseBase+=lightmapColor*shadow;\n#ifdef SPECULARTERM\n#ifndef LIGHTMAPNOSPECULAR{X}\nspecularBase+=info.specular*shadow*lightmapColor;\n#endif\n#endif\n#else\ndiffuseBase+=info.diffuse*shadow;\n#ifdef SPECULARTERM\nspecularBase+=info.specular*shadow;\n#endif\n#endif\n#endif\n#endif","logDepthFragment":"#ifdef LOGARITHMICDEPTH\ngl_FragDepthEXT=log2(vFragmentDepth)*logarithmicDepthConstant*0.5;\n#endif","fogFragment":"#ifdef FOG\nfloat fog=CalcFogFactor();\ncolor.rgb=fog*color.rgb+(1.0-fog)*vFogColor;\n#endif","pbrVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\n#ifdef ALBEDO\nuniform mat4 albedoMatrix;\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform mat4 ambientMatrix;\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef OPACITY\nuniform mat4 opacityMatrix;\nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\nuniform mat4 emissiveMatrix;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\nuniform mat4 lightmapMatrix;\n#endif\n#ifdef REFLECTIVITY \nuniform vec3 vReflectivityInfos;\nuniform mat4 reflectivityMatrix;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform mat4 microSurfaceSamplerMatrix;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform mat4 bumpMatrix;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n","pbrFragmentDeclaration":"uniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\n\nuniform vec4 vLightingIntensity;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\n\n#ifdef ALBEDO\nuniform vec2 vAlbedoInfos;\n#endif\n#ifdef AMBIENT\nuniform vec3 vAmbientInfos;\n#endif\n#ifdef BUMP\nuniform vec3 vBumpInfos;\nuniform vec2 vTangentSpaceParams;\n#endif\n#ifdef OPACITY \nuniform vec2 vOpacityInfos;\n#endif\n#ifdef EMISSIVE\nuniform vec2 vEmissiveInfos;\n#endif\n#ifdef LIGHTMAP\nuniform vec2 vLightmapInfos;\n#endif\n#ifdef REFLECTIVITY\nuniform vec3 vReflectivityInfos;\n#endif\n#ifdef MICROSURFACEMAP\nuniform vec2 vMicroSurfaceSamplerInfos;\n#endif\n\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif\n\n#ifdef REFRACTION\nuniform vec4 vRefractionInfos;\nuniform mat4 refractionMatrix;\nuniform vec3 vRefractionMicrosurfaceInfos;\n#endif\n\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#if defined(USE_LOCAL_REFLECTIONMAP_CUBIC) && defined(REFLECTIONMAP_CUBIC)\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \n#endif\n#endif","pbrUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec2 vAlbedoInfos;\nuniform vec3 vAmbientInfos;\nuniform vec2 vOpacityInfos;\nuniform vec2 vEmissiveInfos;\nuniform vec2 vLightmapInfos;\nuniform vec3 vReflectivityInfos;\nuniform vec2 vMicroSurfaceSamplerInfos;\nuniform vec4 vRefractionInfos;\nuniform vec2 vReflectionInfos;\nuniform vec3 vReflectionPosition;\nuniform vec3 vReflectionSize; \nuniform vec3 vBumpInfos;\nuniform mat4 albedoMatrix;\nuniform mat4 ambientMatrix;\nuniform mat4 opacityMatrix;\nuniform mat4 emissiveMatrix;\nuniform mat4 lightmapMatrix;\nuniform mat4 reflectivityMatrix;\nuniform mat4 microSurfaceSamplerMatrix;\nuniform mat4 bumpMatrix;\nuniform vec2 vTangentSpaceParams;\nuniform mat4 refractionMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionColor;\nuniform vec4 vAlbedoColor;\nuniform vec4 vLightingIntensity;\nuniform vec3 vRefractionMicrosurfaceInfos;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform vec4 vReflectivityColor;\nuniform vec3 vEmissiveColor;\nuniform float pointSize;\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};","pbrFunctions":"\n#define RECIPROCAL_PI2 0.15915494\n#define FRESNEL_MAXIMUM_ON_ROUGH 0.25\n\nconst float kRougnhessToAlphaScale=0.1;\nconst float kRougnhessToAlphaOffset=0.29248125;\nfloat convertRoughnessToAverageSlope(float roughness)\n{\n\nconst float kMinimumVariance=0.0005;\nfloat alphaG=square(roughness)+kMinimumVariance;\nreturn alphaG;\n}\n\nfloat smithVisibilityG1_TrowbridgeReitzGGX(float dot,float alphaG)\n{\nfloat tanSquared=(1.0-dot*dot)/(dot*dot);\nreturn 2.0/(1.0+sqrt(1.0+alphaG*alphaG*tanSquared));\n}\nfloat smithVisibilityG_TrowbridgeReitzGGX_Walter(float NdotL,float NdotV,float alphaG)\n{\nreturn smithVisibilityG1_TrowbridgeReitzGGX(NdotL,alphaG)*smithVisibilityG1_TrowbridgeReitzGGX(NdotV,alphaG);\n}\n\n\nfloat normalDistributionFunction_TrowbridgeReitzGGX(float NdotH,float alphaG)\n{\n\n\n\nfloat a2=square(alphaG);\nfloat d=NdotH*NdotH*(a2-1.0)+1.0;\nreturn a2/(PI*d*d);\n}\nvec3 fresnelSchlickGGX(float VdotH,vec3 reflectance0,vec3 reflectance90)\n{\nreturn reflectance0+(reflectance90-reflectance0)*pow(clamp(1.0-VdotH,0.,1.),5.0);\n}\nvec3 fresnelSchlickEnvironmentGGX(float VdotN,vec3 reflectance0,vec3 reflectance90,float smoothness)\n{\n\nfloat weight=mix(FRESNEL_MAXIMUM_ON_ROUGH,1.0,smoothness);\nreturn reflectance0+weight*(reflectance90-reflectance0)*pow(clamp(1.0-VdotN,0.,1.),5.0);\n}\n\nvec3 computeSpecularTerm(float NdotH,float NdotL,float NdotV,float VdotH,float roughness,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor)\n{\nroughness=max(roughness,geometricRoughnessFactor);\nfloat alphaG=convertRoughnessToAverageSlope(roughness);\nfloat distribution=normalDistributionFunction_TrowbridgeReitzGGX(NdotH,alphaG);\nfloat visibility=smithVisibilityG_TrowbridgeReitzGGX_Walter(NdotL,NdotV,alphaG);\nvisibility/=(4.0*NdotL*NdotV); \nfloat specTerm=max(0.,visibility*distribution)*NdotL;\nvec3 fresnel=fresnelSchlickGGX(VdotH,reflectance0,reflectance90);\nreturn fresnel*specTerm;\n}\nfloat computeDiffuseTerm(float NdotL,float NdotV,float VdotH,float roughness)\n{\n\n\nfloat diffuseFresnelNV=pow(clamp(1.0-NdotL,0.000001,1.),5.0);\nfloat diffuseFresnelNL=pow(clamp(1.0-NdotV,0.000001,1.),5.0);\nfloat diffuseFresnel90=0.5+2.0*VdotH*VdotH*roughness;\nfloat fresnel =\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNL) *\n(1.0+(diffuseFresnel90-1.0)*diffuseFresnelNV);\nreturn fresnel*NdotL/PI;\n}\nfloat adjustRoughnessFromLightProperties(float roughness,float lightRadius,float lightDistance)\n{\n#ifdef USEPHYSICALLIGHTFALLOFF\n\nfloat lightRoughness=lightRadius/lightDistance;\n\nfloat totalRoughness=clamp(lightRoughness+roughness,0.,1.);\nreturn totalRoughness;\n#else\nreturn roughness;\n#endif\n}\nfloat computeDefaultMicroSurface(float microSurface,vec3 reflectivityColor)\n{\nconst float kReflectivityNoAlphaWorkflow_SmoothnessMax=0.95;\nfloat reflectivityLuminance=getLuminance(reflectivityColor);\nfloat reflectivityLuma=sqrt(reflectivityLuminance);\nmicroSurface=reflectivityLuma*kReflectivityNoAlphaWorkflow_SmoothnessMax;\nreturn microSurface;\n}\n\n\nfloat fresnelGrazingReflectance(float reflectance0) {\nfloat reflectance90=clamp(reflectance0*25.0,0.0,1.0);\nreturn reflectance90;\n}\n\n\n#define UNPACK_LOD(x) (1.0-x)*255.0\nfloat getLodFromAlphaG(float cubeMapDimensionPixels,float alphaG,float NdotV) {\nfloat microsurfaceAverageSlope=alphaG;\n\n\n\n\n\n\nmicrosurfaceAverageSlope*=sqrt(abs(NdotV));\nfloat microsurfaceAverageSlopeTexels=microsurfaceAverageSlope*cubeMapDimensionPixels;\nfloat lod=log2(microsurfaceAverageSlopeTexels);\nreturn lod;\n}\nfloat environmentRadianceOcclusion(float ambientOcclusion,float NdotVUnclamped) {\n\n\nfloat temp=NdotVUnclamped+ambientOcclusion;\nreturn clamp(square(temp)-1.0+ambientOcclusion,0.0,1.0);\n}\nfloat environmentHorizonOcclusion(vec3 view,vec3 normal) {\n\nvec3 reflection=reflect(view,normal);\nfloat temp=clamp( 1.0+1.1*dot(reflection,normal),0.0,1.0);\nreturn square(temp);\n}","harmonicsFunctions":"#ifdef USESPHERICALFROMREFLECTIONMAP\nuniform vec3 vSphericalX;\nuniform vec3 vSphericalY;\nuniform vec3 vSphericalZ;\nuniform vec3 vSphericalXX_ZZ;\nuniform vec3 vSphericalYY_ZZ;\nuniform vec3 vSphericalZZ;\nuniform vec3 vSphericalXY;\nuniform vec3 vSphericalYZ;\nuniform vec3 vSphericalZX;\nvec3 quaternionVectorRotation_ScaledSqrtTwo(vec4 Q,vec3 V){\nvec3 T=cross(Q.xyz,V);\nT+=Q.www*V;\nreturn cross(Q.xyz,T)+V;\n}\nvec3 environmentIrradianceJones(vec3 normal)\n{\n\n\n\n\n\n\n\n\n\nfloat Nx=normal.x;\nfloat Ny=normal.y;\nfloat Nz=normal.z;\nvec3 C1=vSphericalZZ.rgb;\nvec3 Cx=vSphericalX.rgb;\nvec3 Cy=vSphericalY.rgb;\nvec3 Cz=vSphericalZ.rgb;\nvec3 Cxx_zz=vSphericalXX_ZZ.rgb;\nvec3 Cyy_zz=vSphericalYY_ZZ.rgb;\nvec3 Cxy=vSphericalXY.rgb;\nvec3 Cyz=vSphericalYZ.rgb;\nvec3 Czx=vSphericalZX.rgb;\nvec3 a1=Cyy_zz*Ny+Cy;\nvec3 a2=Cyz*Nz+a1;\nvec3 b1=Czx*Nz+Cx;\nvec3 b2=Cxy*Ny+b1;\nvec3 b3=Cxx_zz*Nx+b2;\nvec3 t1=Cz*Nz+C1;\nvec3 t2=a2*Ny+t1;\nvec3 t3=b3*Nx+t2;\nreturn t3;\n}\n#endif","pbrLightFunctions":"\nstruct lightingInfo\n{\nvec3 diffuse;\n#ifdef SPECULARTERM\nvec3 specular;\n#endif\n};\nfloat computeDistanceLightFalloff(vec3 lightOffset,float lightDistanceSquared,float range)\n{ \n#ifdef USEPHYSICALLIGHTFALLOFF\nfloat lightDistanceFalloff=1.0/((lightDistanceSquared+0.001));\n#else\nfloat lightDistanceFalloff=max(0.,1.0-length(lightOffset)/range);\n#endif\nreturn lightDistanceFalloff;\n}\nfloat computeDirectionalLightFalloff(vec3 lightDirection,vec3 directionToLightCenterW,float cosHalfAngle,float exponent)\n{\nfloat falloff=0.0;\n#ifdef USEPHYSICALLIGHTFALLOFF\nconst float kMinusLog2ConeAngleIntensityRatio=6.64385618977; \n\n\n\n\n\nfloat concentrationKappa=kMinusLog2ConeAngleIntensityRatio/(1.0-cosHalfAngle);\n\n\nvec4 lightDirectionSpreadSG=vec4(-lightDirection*concentrationKappa,-concentrationKappa);\nfalloff=exp2(dot(vec4(directionToLightCenterW,1.0),lightDirectionSpreadSG));\n#else\nfloat cosAngle=max(0.000000000000001,dot(-lightDirection,directionToLightCenterW));\nif (cosAngle>=cosHalfAngle)\n{\nfalloff=max(0.,pow(cosAngle,exponent));\n}\n#endif\nreturn falloff;\n}\nlightingInfo computeLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightDirection;\nfloat attenuation=1.0;\nfloat lightDistance;\n\nif (lightData.w == 0.)\n{\nvec3 lightOffset=lightData.xyz-vPositionW;\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nattenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\nlightDistance=sqrt(lightDistanceSquared);\nlightDirection=normalize(lightOffset);\n}\n\nelse\n{\nlightDistance=length(-lightData.xyz);\nlightDirection=normalize(-lightData.xyz);\n}\n\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+lightDirection);\nNdotL=clamp(dot(vNormal,lightDirection),0.00000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeSpotLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec4 lightDirection,vec3 diffuseColor,vec3 specularColor,float rangeRadius,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\nvec3 lightOffset=lightData.xyz-vPositionW;\nvec3 directionToLightCenterW=normalize(lightOffset);\n\nfloat lightDistanceSquared=dot(lightOffset,lightOffset);\nfloat attenuation=computeDistanceLightFalloff(lightOffset,lightDistanceSquared,rangeRadius);\n\nfloat directionalAttenuation=computeDirectionalLightFalloff(lightDirection.xyz,directionToLightCenterW,lightDirection.w,lightData.w);\nattenuation*=directionalAttenuation;\n\nfloat lightDistance=sqrt(lightDistanceSquared);\nroughness=adjustRoughnessFromLightProperties(roughness,rangeRadius,lightDistance);\n\nvec3 H=normalize(viewDirectionW+directionToLightCenterW);\nNdotL=clamp(dot(vNormal,directionToLightCenterW),0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nfloat diffuseTerm=computeDiffuseTerm(NdotL,NdotV,VdotH,roughness);\nresult.diffuse=diffuseTerm*diffuseColor*attenuation;\n#ifdef SPECULARTERM\n\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor*attenuation;\n#endif\nreturn result;\n}\nlightingInfo computeHemisphericLighting(vec3 viewDirectionW,vec3 vNormal,vec4 lightData,vec3 diffuseColor,vec3 specularColor,vec3 groundColor,float roughness,float NdotV,vec3 reflectance0,vec3 reflectance90,float geometricRoughnessFactor,out float NdotL) {\nlightingInfo result;\n\n\n\nNdotL=dot(vNormal,lightData.xyz)*0.5+0.5;\nresult.diffuse=mix(groundColor,diffuseColor,NdotL);\n#ifdef SPECULARTERM\n\nvec3 lightVectorW=normalize(lightData.xyz);\nvec3 H=normalize(viewDirectionW+lightVectorW);\nfloat NdotH=clamp(dot(vNormal,H),0.000000000001,1.0);\nNdotL=clamp(NdotL,0.000000000001,1.0);\nfloat VdotH=clamp(dot(viewDirectionW,H),0.0,1.0);\nvec3 specTerm=computeSpecularTerm(NdotH,NdotL,NdotV,VdotH,roughness,reflectance0,reflectance90,geometricRoughnessFactor);\nresult.specular=specTerm*diffuseColor;\n#endif\nreturn result;\n}\nvec3 computeProjectionTextureDiffuseLighting(sampler2D projectionLightSampler,mat4 textureProjectionMatrix){\nvec4 strq=textureProjectionMatrix*vec4(vPositionW,1.0);\nstrq/=strq.w;\nvec3 textureColor=texture2D(projectionLightSampler,strq.xy).rgb;\nreturn toLinearSpace(textureColor);\n}","kernelBlurFragment":"#ifdef DOF\nfactor=sampleCoC(sampleCoord{X}); \ncomputedWeight=KERNEL_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCoord{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCoord{X})*computedWeight;\n#endif","kernelBlurFragment2":"#ifdef DOF\nfactor=sampleCoC(sampleCenter+delta*KERNEL_DEP_OFFSET{X});\ncomputedWeight=KERNEL_DEP_WEIGHT{X}*factor;\nsumOfWeights+=computedWeight;\n#else\ncomputedWeight=KERNEL_DEP_WEIGHT{X};\n#endif\n#ifdef PACKEDFLOAT\nblend+=unpack(texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X}))*computedWeight;\n#else\nblend+=texture2D(textureSampler,sampleCenter+delta*KERNEL_DEP_OFFSET{X})*computedWeight;\n#endif","kernelBlurVaryingDeclaration":"varying vec2 sampleCoord{X};","kernelBlurVertex":"sampleCoord{X}=sampleCenter+delta*KERNEL_OFFSET{X};","mrtFragmentDeclaration":"#if __VERSION__>=200\nlayout(location=0) out vec4 glFragData[{X}];\n#endif\n","bones300Declaration":"#if NUM_BONE_INFLUENCERS>0\nuniform mat4 mBones[BonesPerMesh];\nin vec4 matricesIndices;\nin vec4 matricesWeights;\n#if NUM_BONE_INFLUENCERS>4\nin vec4 matricesIndicesExtra;\nin vec4 matricesWeightsExtra;\n#endif\n#endif","instances300Declaration":"#ifdef INSTANCES\nin vec4 world0;\nin vec4 world1;\nin vec4 world2;\nin vec4 world3;\n#else\nuniform mat4 world;\n#endif","backgroundVertexDeclaration":"uniform mat4 view;\nuniform mat4 viewProjection;\nuniform float shadowLevel;\n#ifdef DIFFUSE\nuniform mat4 diffuseMatrix;\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\n#endif\n#ifdef POINTSIZE\nuniform float pointSize;\n#endif","backgroundFragmentDeclaration":" uniform vec4 vPrimaryColor;\n#ifdef USEHIGHLIGHTANDSHADOWCOLORS\nuniform vec4 vPrimaryColorShadow;\n#endif\nuniform float shadowLevel;\nuniform float alpha;\n#ifdef DIFFUSE\nuniform vec2 vDiffuseInfos;\n#endif\n#ifdef REFLECTION\nuniform vec2 vReflectionInfos;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\n#endif\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n#if defined(REFLECTIONMAP_SPHERICAL) || defined(REFLECTIONMAP_PROJECTION) || defined(REFRACTION)\nuniform mat4 view;\n#endif","backgroundUboDeclaration":"layout(std140,column_major) uniform;\nuniform Material\n{\nuniform vec4 vPrimaryColor;\nuniform vec4 vPrimaryColorShadow;\nuniform vec2 vDiffuseInfos;\nuniform vec2 vReflectionInfos;\nuniform mat4 diffuseMatrix;\nuniform mat4 reflectionMatrix;\nuniform vec3 vReflectionMicrosurfaceInfos;\nuniform float fFovMultiplier;\nuniform float pointSize;\nuniform float shadowLevel;\nuniform float alpha;\n#if defined(REFLECTIONFRESNEL) || defined(OPACITYFRESNEL)\nuniform vec3 vBackgroundCenter;\n#endif\n#ifdef REFLECTIONFRESNEL\nuniform vec4 vReflectionControl;\n#endif\n};\nuniform Scene {\nmat4 viewProjection;\nmat4 view;\n};"};
  102526. var globalObject = (typeof global !== 'undefined') ? global : ((typeof window !== 'undefined') ? window : this);
  102527. globalObject["BABYLON"] = BABYLON;
  102528. //backwards compatibility
  102529. if(typeof earcut !== 'undefined') {
  102530. globalObject["Earcut"] = {
  102531. earcut: earcut
  102532. };
  102533. }
  102534. return BABYLON;
  102535. });
  102536. /* WEBPACK VAR INJECTION */}.call(exports, __webpack_require__(18)))
  102537. /***/ }),
  102538. /* 1 */
  102539. /***/ (function(module, exports, __webpack_require__) {
  102540. "use strict";
  102541. Object.defineProperty(exports, "__esModule", { value: true });
  102542. var deepmerge = __webpack_require__(22);
  102543. var expDm = deepmerge['default'];
  102544. exports.deepmerge = expDm;
  102545. /**
  102546. * Is the provided string a URL?
  102547. *
  102548. * @param urlToCheck the url to inspect
  102549. */
  102550. function isUrl(urlToCheck) {
  102551. if (urlToCheck.indexOf('http') === 0 || urlToCheck.indexOf('/') === 0 || urlToCheck.indexOf('./') === 0 || urlToCheck.indexOf('../') === 0) {
  102552. return true;
  102553. }
  102554. return false;
  102555. }
  102556. exports.isUrl = isUrl;
  102557. /**
  102558. * Convert a string from kebab-case to camelCase
  102559. * @param s string to convert
  102560. */
  102561. function kebabToCamel(s) {
  102562. return s.replace(/(\-\w)/g, function (m) { return m[1].toUpperCase(); });
  102563. }
  102564. exports.kebabToCamel = kebabToCamel;
  102565. //https://gist.github.com/youssman/745578062609e8acac9f
  102566. /**
  102567. * Convert a string from camelCase to kebab-case
  102568. * @param str string to convert
  102569. */
  102570. function camelToKebab(str) {
  102571. return !str ? null : str.replace(/([A-Z])/g, function (g) { return '-' + g[0].toLowerCase(); });
  102572. }
  102573. exports.camelToKebab = camelToKebab;
  102574. /**
  102575. * This will extend an object with configuration values.
  102576. * What it practically does it take the keys from the configuration and set them on the object.
  102577. * I the configuration is a tree, it will traverse into the tree.
  102578. * @param object the object to extend
  102579. * @param config the configuration object that will extend the object
  102580. */
  102581. function extendClassWithConfig(object, config) {
  102582. if (!config)
  102583. return;
  102584. Object.keys(config).forEach(function (key) {
  102585. if (key in object && typeof object[key] !== 'function') {
  102586. // if (typeof object[key] === 'function') return;
  102587. // if it is an object, iterate internally until reaching basic types
  102588. if (typeof object[key] === 'object') {
  102589. extendClassWithConfig(object[key], config[key]);
  102590. }
  102591. else {
  102592. if (config[key] !== undefined) {
  102593. object[key] = config[key];
  102594. }
  102595. }
  102596. }
  102597. });
  102598. }
  102599. exports.extendClassWithConfig = extendClassWithConfig;
  102600. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvaGVscGVyL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQXVDO0FBRXZDLElBQUksS0FBSyxHQUFHLFNBQV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NQUFXO0lBQzFELElBQUksQ0FBQyxNQUFNO1FBQUUsT0FBTztJQUNwQixNQUFNLENBQUMsSUFBSSxDQUFDLE1BQU0sQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDM0IsSUFBSSxHQUFHLElBQUksTUFBTSxJQUFJLE9BQU8sTUFBTSxDQUFDLEdBQUcsQ0FBQyxLQUFLLFVBQVUsRUFBRTtZQUNwRCxpREFBaUQ7WUFDakQsb0VBQW9FO1lBQ3BFLElBQUksT0FBTyxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssUUFBUSxFQUFFO2dCQUNqQyxxQkFBcUIsQ0FBQyxNQUFNLENBQUMsR0FBRyxDQUFDLEVBQUUsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDLENBQUM7YUFDbkQ7aUJBQU07Z0JBQ0gsSUFBSSxNQUFNLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO29CQUMzQixNQUFNLENBQUMsR0FBRyxDQUFDLEdBQUcsTUFBTSxDQUFDLEdBQUcsQ0FBQyxDQUFDO2lCQUM3QjthQUNKO1NBQ0o7SUFDTCxDQUFDLENBQUMsQ0FBQztBQUNQLENBQUM7QUFmRCxzREFlQyJ9
  102601. /***/ }),
  102602. /* 2 */
  102603. /***/ (function(module, exports, __webpack_require__) {
  102604. "use strict";
  102605. function __export(m) {
  102606. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  102607. }
  102608. Object.defineProperty(exports, "__esModule", { value: true });
  102609. __export(__webpack_require__(32));
  102610. __export(__webpack_require__(34));
  102611. __export(__webpack_require__(40));
  102612. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvYXNzZXRzL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7O0FBQUEsNEJBQXVCO0FBQ3ZCLDJCQUFzQjtBQUN0QixpQ0FBNEIifQ==
  102613. /***/ }),
  102614. /* 3 */
  102615. /***/ (function(module, exports, __webpack_require__) {
  102616. "use strict";
  102617. Object.defineProperty(exports, "__esModule", { value: true });
  102618. var babylonjs_1 = __webpack_require__(0);
  102619. var _1 = __webpack_require__(1);
  102620. /**
  102621. * This is a simple HTML mapper.
  102622. * This mapper parses a single HTML element and returns the configuration from its attributes.
  102623. * it parses numbers and boolean values to the corresponding variable types.
  102624. * The following HTML element:
  102625. * <div test="1" random-flag="true" a.string.object="test"> will result in the following configuration:
  102626. *
  102627. * {
  102628. * test: 1, //a number!
  102629. * randomFlag: boolean, //camelCase and boolean
  102630. * a: {
  102631. * string: {
  102632. * object: "test" //dot-separated object levels
  102633. * }
  102634. * }
  102635. * }
  102636. */
  102637. var HTMLMapper = /** @class */ (function () {
  102638. function HTMLMapper() {
  102639. }
  102640. /**
  102641. * Map a specific element and get configuration from it
  102642. * @param element the HTML element to analyze.
  102643. */
  102644. HTMLMapper.prototype.map = function (element) {
  102645. var config = {};
  102646. var _loop_1 = function (attrIdx) {
  102647. var attr = element.attributes.item(attrIdx);
  102648. if (!attr) {
  102649. return "continue";
  102650. }
  102651. // map "object.property" to the right configuration place.
  102652. var split = attr.nodeName.split('.');
  102653. split.reduce(function (currentConfig, key, idx) {
  102654. //convert html-style to json-style
  102655. var camelKey = _1.kebabToCamel(key);
  102656. if (idx === split.length - 1) {
  102657. var val = attr.nodeValue; // firefox warns nodeValue is deprecated, but I found no sign of it anywhere.
  102658. if (val === "true") {
  102659. val = true;
  102660. }
  102661. else if (val === "false") {
  102662. val = false;
  102663. }
  102664. else if (val === "undefined") {
  102665. val = undefined;
  102666. }
  102667. else if (val === "null") {
  102668. val = null;
  102669. }
  102670. else {
  102671. var isnum = !isNaN(parseFloat(val)) && isFinite(val); ///^\d+$/.test(val);
  102672. if (isnum) {
  102673. var number = parseFloat(val);
  102674. if (!isNaN(number)) {
  102675. val = number;
  102676. }
  102677. }
  102678. }
  102679. currentConfig[camelKey] = val;
  102680. }
  102681. else {
  102682. currentConfig[camelKey] = currentConfig[camelKey] || {};
  102683. }
  102684. return currentConfig[camelKey];
  102685. }, config);
  102686. };
  102687. for (var attrIdx = 0; attrIdx < element.attributes.length; ++attrIdx) {
  102688. _loop_1(attrIdx);
  102689. }
  102690. return config;
  102691. };
  102692. return HTMLMapper;
  102693. }());
  102694. /**
  102695. * A simple string-to-JSON mapper.
  102696. * This is the main mapper, used to analyze downloaded JSON-Configuration or JSON payload
  102697. */
  102698. var JSONMapper = /** @class */ (function () {
  102699. function JSONMapper() {
  102700. }
  102701. JSONMapper.prototype.map = function (rawSource) {
  102702. return JSON.parse(rawSource);
  102703. };
  102704. return JSONMapper;
  102705. }());
  102706. /**
  102707. * The DOM Mapper will traverse an entire DOM Tree and will load the configuration from the
  102708. * DOM elements and attributes.
  102709. */
  102710. var DOMMapper = /** @class */ (function () {
  102711. function DOMMapper() {
  102712. }
  102713. /**
  102714. * The mapping function that will convert HTML data to a viewer configuration object
  102715. * @param baseElement the baseElement from which to start traversing
  102716. * @returns a ViewerCOnfiguration object from the provided HTML Element
  102717. */
  102718. DOMMapper.prototype.map = function (baseElement) {
  102719. var htmlMapper = new HTMLMapper();
  102720. var config = htmlMapper.map(baseElement);
  102721. var traverseChildren = function (element, partConfig) {
  102722. var children = element.children;
  102723. if (children.length) {
  102724. for (var i = 0; i < children.length; ++i) {
  102725. var item = children.item(i);
  102726. // use the HTML Mapper to read configuration from a single element
  102727. var configMapped = htmlMapper.map(item);
  102728. var key = _1.kebabToCamel(item.nodeName.toLowerCase());
  102729. if (item.attributes.getNamedItem('array') && item.attributes.getNamedItem('array').nodeValue === 'true') {
  102730. partConfig[key] = [];
  102731. }
  102732. else {
  102733. if (element.attributes.getNamedItem('array') && element.attributes.getNamedItem('array').nodeValue === 'true') {
  102734. partConfig.push(configMapped);
  102735. }
  102736. else if (partConfig[key]) {
  102737. //exists already! probably an array
  102738. element.setAttribute('array', 'true');
  102739. var oldItem = partConfig[key];
  102740. partConfig = [oldItem, configMapped];
  102741. }
  102742. else {
  102743. partConfig[key] = configMapped;
  102744. }
  102745. }
  102746. traverseChildren(item, partConfig[key] || configMapped);
  102747. }
  102748. }
  102749. return partConfig;
  102750. };
  102751. traverseChildren(baseElement, config);
  102752. return config;
  102753. };
  102754. return DOMMapper;
  102755. }());
  102756. /**
  102757. * The MapperManager manages the different implemented mappers.
  102758. * It allows the user to register new mappers as well and use them to parse their own configuration data
  102759. */
  102760. var MapperManager = /** @class */ (function () {
  102761. function MapperManager() {
  102762. this._mappers = {
  102763. "html": new HTMLMapper(),
  102764. "json": new JSONMapper(),
  102765. "dom": new DOMMapper()
  102766. };
  102767. }
  102768. /**
  102769. * Get a specific configuration mapper.
  102770. *
  102771. * @param type the name of the mapper to load
  102772. */
  102773. MapperManager.prototype.getMapper = function (type) {
  102774. if (!this._mappers[type]) {
  102775. babylonjs_1.Tools.Error("No mapper defined for " + type);
  102776. }
  102777. return this._mappers[type];
  102778. };
  102779. /**
  102780. * Use this functio to register your own configuration mapper.
  102781. * After a mapper is registered, it can be used to parse the specific type fo configuration to the standard ViewerConfiguration.
  102782. * @param type the name of the mapper. This will be used to define the configuration type and/or to get the mapper
  102783. * @param mapper The implemented mapper
  102784. */
  102785. MapperManager.prototype.registerMapper = function (type, mapper) {
  102786. this._mappers[type] = mapper;
  102787. };
  102788. /**
  102789. * Dispose the mapper manager and all of its mappers.
  102790. */
  102791. MapperManager.prototype.dispose = function () {
  102792. this._mappers = {};
  102793. };
  102794. /**
  102795. * The default mapper is the JSON mapper.
  102796. */
  102797. MapperManager.DefaultMapper = 'json';
  102798. return MapperManager;
  102799. }());
  102800. exports.MapperManager = MapperManager;
  102801. /**
  102802. * mapperManager is a singleton of the type MapperManager.
  102803. * The mapperManager can be disposed directly with calling mapperManager.dispose()
  102804. * or indirectly with using BabylonViewer.disposeAll()
  102805. */
  102806. exports.mapperManager = new Mapper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. Object.defineProperty(exports, "__esModule", { value: true });
  102813. var babylonjs_1 = __webpack_require__(0);
  102814. var ViewerGlobals = /** @class */ (function () {
  102815. function ViewerGlobals() {
  102816. this.disableInit = false;
  102817. this.disableWebGL2Support = false;
  102818. }
  102819. Object.defineProperty(ViewerGlobals.prototype, "version", {
  102820. get: function () {
  102821. return babylonjs_1.Engine.Version;
  102822. },
  102823. enumerable: true,
  102824. configurable: true
  102825. });
  102826. return ViewerGlobals;
  102827. }());
  102828. exports.ViewerGlobals = ViewerGlobals;
  102829. exports.viewerGlobals = new ViewerGlobals();
  102830. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2xvYmFscy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2dsb2JhbHMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBbUM7QUFFbkM7SUFBQTtRQUVXLGdCQUFXLEdBQVksS0FBSyxDQUFDO1FBQzdCLHlCQUFvQixHQUFZLEtBQUssQ0FBQztJQU1qRCxDQUFDO0lBSkcsc0JBQVcsa0NBQU87YUFBbEI7WUFDSSxPQUFPLGtCQUFNLENBQUMsT0FBTyxDQUFDO1FBQzFCLENBQUM7OztPQUFBO0lBRUwsb0JBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHNDQUFhO0FBV2YsUUFBQSxhQUFhLEdBQWtCLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  102831. /***/ }),
  102832. /* 5 */
  102833. /***/ (function(module, exports, __webpack_require__) {
  102834. "use strict";
  102835. Object.defineProperty(exports, "__esModule", { value: true });
  102836. var babylonjs_1 = __webpack_require__(0);
  102837. var modelAnimation_1 = __webpack_require__(24);
  102838. var _1 = __webpack_require__(1);
  102839. /**
  102840. * The current state of the model
  102841. */
  102842. var ModelState;
  102843. (function (ModelState) {
  102844. ModelState[ModelState["INIT"] = 0] = "INIT";
  102845. ModelState[ModelState["LOADING"] = 1] = "LOADING";
  102846. ModelState[ModelState["LOADED"] = 2] = "LOADED";
  102847. ModelState[ModelState["ENTRY"] = 3] = "ENTRY";
  102848. ModelState[ModelState["ENTRYDONE"] = 4] = "ENTRYDONE";
  102849. ModelState[ModelState["COMPLETE"] = 5] = "COMPLETE";
  102850. ModelState[ModelState["CANCELED"] = 6] = "CANCELED";
  102851. ModelState[ModelState["ERROR"] = 7] = "ERROR";
  102852. })(ModelState = exports.ModelState || (exports.ModelState = {}));
  102853. /**
  102854. * The viewer model is a container for all assets representing a sngle loaded model.
  102855. */
  102856. var ViewerModel = /** @class */ (function () {
  102857. function ViewerModel(_observablesManager, modelConfiguration, _configurationContainer) {
  102858. var _this = this;
  102859. this._observablesManager = _observablesManager;
  102860. this._configurationContainer = _configurationContainer;
  102861. /**
  102862. * the list of meshes that are a part of this model
  102863. */
  102864. this._meshes = [];
  102865. /**
  102866. * ParticleSystems connected to this model
  102867. */
  102868. this.particleSystems = [];
  102869. /**
  102870. * Skeletons defined in this model
  102871. */
  102872. this.skeletons = [];
  102873. this._loaderDone = false;
  102874. this._animatables = [];
  102875. this._frameRate = 60;
  102876. this._shadowsRenderedAfterLoad = false;
  102877. this.onLoadedObservable = new babylonjs_1.Observable();
  102878. this.onLoadErrorObservable = new babylonjs_1.Observable();
  102879. this.onLoadProgressObservable = new babylonjs_1.Observable();
  102880. this.onCompleteObservable = new babylonjs_1.Observable();
  102881. this.onAfterConfigure = new babylonjs_1.Observable();
  102882. this.state = ModelState.INIT;
  102883. var scene = this._configurationContainer && this._configurationContainer.scene;
  102884. this.rootMesh = new babylonjs_1.AbstractMesh("modelRootMesh", scene);
  102885. this._pivotMesh = new babylonjs_1.AbstractMesh("pivotMesh", scene);
  102886. this._pivotMesh.parent = this.rootMesh;
  102887. // rotate 180, gltf fun
  102888. this._pivotMesh.rotation.y += Math.PI;
  102889. this._scaleTransition = new babylonjs_1.Animation("scaleAnimation", "scaling", this._frameRate, babylonjs_1.Animation.ANIMATIONTYPE_VECTOR3, babylonjs_1.Animation.ANIMATIONLOOPMODE_CONSTANT);
  102890. this._animations = [];
  102891. //create a copy of the configuration to make sure it doesn't change even after it is changed in the viewer
  102892. this._modelConfiguration = _1.deepmerge((this._configurationContainer && this._configurationContainer.configuration.model) || {}, modelConfiguration);
  102893. if (this._observablesManager) {
  102894. this._observablesManager.onModelAddedObservable.notifyObservers(this);
  102895. }
  102896. if (this._modelConfiguration.entryAnimation) {
  102897. this.rootMesh.setEnabled(false);
  102898. }
  102899. this.onLoadedObservable.add(function () {
  102900. _this.updateConfiguration(_this._modelConfiguration);
  102901. if (_this._observablesManager) {
  102902. _this._observablesManager.onModelLoadedObservable.notifyObservers(_this);
  102903. }
  102904. _this._initAnimations();
  102905. });
  102906. this.onCompleteObservable.add(function () {
  102907. _this.state = ModelState.COMPLETE;
  102908. });
  102909. }
  102910. Object.defineProperty(ViewerModel.prototype, "shadowsRenderedAfterLoad", {
  102911. get: function () {
  102912. return this._shadowsRenderedAfterLoad;
  102913. },
  102914. set: function (rendered) {
  102915. if (!rendered) {
  102916. throw new Error("can only be enabled");
  102917. }
  102918. else {
  102919. this._shadowsRenderedAfterLoad = rendered;
  102920. }
  102921. },
  102922. enumerable: true,
  102923. configurable: true
  102924. });
  102925. ViewerModel.prototype.getViewerId = function () {
  102926. return this._configurationContainer && this._configurationContainer.viewerId;
  102927. };
  102928. Object.defineProperty(ViewerModel.prototype, "enabled", {
  102929. /**
  102930. * Is this model enabled?
  102931. */
  102932. get: function () {
  102933. return this.rootMesh.isEnabled();
  102934. },
  102935. /**
  102936. * Set whether this model is enabled or not.
  102937. */
  102938. set: function (enable) {
  102939. this.rootMesh.setEnabled(enable);
  102940. },
  102941. enumerable: true,
  102942. configurable: true
  102943. });
  102944. Object.defineProperty(ViewerModel.prototype, "loaderDone", {
  102945. set: function (done) {
  102946. this._loaderDone = done;
  102947. this._checkCompleteState();
  102948. },
  102949. enumerable: true,
  102950. configurable: true
  102951. });
  102952. ViewerModel.prototype._checkCompleteState = function () {
  102953. if (this._loaderDone && (this.state === ModelState.ENTRYDONE)) {
  102954. this._modelComplete();
  102955. }
  102956. };
  102957. /**
  102958. * Add a mesh to this model.
  102959. * Any mesh that has no parent will be provided with the root mesh as its new parent.
  102960. *
  102961. * @param mesh the new mesh to add
  102962. * @param triggerLoaded should this mesh trigger the onLoaded observable. Used when adding meshes manually.
  102963. */
  102964. ViewerModel.prototype.addMesh = function (mesh, triggerLoaded) {
  102965. if (!mesh.parent) {
  102966. mesh.parent = this._pivotMesh;
  102967. }
  102968. mesh.receiveShadows = !!this.configuration.receiveShadows;
  102969. this._meshes.push(mesh);
  102970. if (triggerLoaded) {
  102971. return this.onLoadedObservable.notifyObserversWithPromise(this);
  102972. }
  102973. };
  102974. Object.defineProperty(ViewerModel.prototype, "meshes", {
  102975. /**
  102976. * get the list of meshes (excluding the root mesh)
  102977. */
  102978. get: function () {
  102979. return this._meshes;
  102980. },
  102981. enumerable: true,
  102982. configurable: true
  102983. });
  102984. Object.defineProperty(ViewerModel.prototype, "configuration", {
  102985. /**
  102986. * Get the model's configuration
  102987. */
  102988. get: function () {
  102989. return this._modelConfiguration;
  102990. },
  102991. /**
  102992. * (Re-)set the model's entire configuration
  102993. * @param newConfiguration the new configuration to replace the new one
  102994. */
  102995. set: function (newConfiguration) {
  102996. this._modelConfiguration = newConfiguration;
  102997. this._configureModel();
  102998. },
  102999. enumerable: true,
  103000. configurable: true
  103001. });
  103002. /**
  103003. * Update the current configuration with new values.
  103004. * Configuration will not be overwritten, but merged with the new configuration.
  103005. * Priority is to the new configuration
  103006. * @param newConfiguration the configuration to be merged into the current configuration;
  103007. */
  103008. ViewerModel.prototype.updateConfiguration = function (newConfiguration) {
  103009. this._modelConfiguration = _1.deepmerge(this._modelConfiguration, newConfiguration);
  103010. this._configureModel();
  103011. };
  103012. ViewerModel.prototype._initAnimations = function () {
  103013. var _this = this;
  103014. // check if this is not a gltf loader and init the animations
  103015. if (this.skeletons.length) {
  103016. this.skeletons.forEach(function (skeleton, idx) {
  103017. var ag = new babylonjs_1.AnimationGroup("animation-" + idx, _this._configurationContainer && _this._configurationContainer.scene);
  103018. var add = false;
  103019. skeleton.getAnimatables().forEach(function (a) {
  103020. if (a.animations[0]) {
  103021. ag.addTargetedAnimation(a.animations[0], a);
  103022. add = true;
  103023. }
  103024. });
  103025. if (add) {
  103026. _this.addAnimationGroup(ag);
  103027. }
  103028. });
  103029. }
  103030. var completeCallback = function () {
  103031. };
  103032. if (this._modelConfiguration.animation) {
  103033. if (this._modelConfiguration.animation.playOnce) {
  103034. this._animations.forEach(function (a) {
  103035. a.playMode = 0 /* ONCE */;
  103036. });
  103037. }
  103038. if (this._modelConfiguration.animation.autoStart && this._animations.length) {
  103039. var animationName_1 = this._modelConfiguration.animation.autoStart === true ?
  103040. this._animations[0].name : this._modelConfiguration.animation.autoStart;
  103041. completeCallback = function () {
  103042. _this.playAnimation(animationName_1);
  103043. };
  103044. }
  103045. }
  103046. this._enterScene(completeCallback);
  103047. };
  103048. /**
  103049. * Animates the model from the current position to the default position
  103050. * @param completeCallback A function to call when the animation has completed
  103051. */
  103052. ViewerModel.prototype._enterScene = function (completeCallback) {
  103053. var _this = this;
  103054. var scene = this.rootMesh.getScene();
  103055. var previousValue = scene.animationPropertiesOverride.enableBlending;
  103056. var callback = function () {
  103057. _this.state = ModelState.ENTRYDONE;
  103058. scene.animationPropertiesOverride.enableBlending = previousValue;
  103059. _this._checkCompleteState();
  103060. if (completeCallback)
  103061. completeCallback();
  103062. };
  103063. if (!this._entryAnimation) {
  103064. callback();
  103065. return;
  103066. }
  103067. this.rootMesh.setEnabled(true);
  103068. // disable blending for the sake of the entry animation;
  103069. scene.animationPropertiesOverride.enableBlending = false;
  103070. this._applyAnimation(this._entryAnimation, true, callback);
  103071. };
  103072. /**
  103073. * Animates the model from the current position to the exit-screen position
  103074. * @param completeCallback A function to call when the animation has completed
  103075. */
  103076. ViewerModel.prototype._exitScene = function (completeCallback) {
  103077. if (!this._exitAnimation) {
  103078. completeCallback();
  103079. return;
  103080. }
  103081. this._applyAnimation(this._exitAnimation, false, completeCallback);
  103082. };
  103083. ViewerModel.prototype._modelComplete = function () {
  103084. var _this = this;
  103085. //reapply material defines to be sure:
  103086. var meshes = this._pivotMesh.getChildMeshes(false);
  103087. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  103088. _this._applyModelMaterialConfiguration(mesh.material);
  103089. });
  103090. this.state = ModelState.COMPLETE;
  103091. this.onCompleteObservable.notifyObservers(this);
  103092. };
  103093. /**
  103094. * Add a new animation group to this model.
  103095. * @param animationGroup the new animation group to be added
  103096. */
  103097. ViewerModel.prototype.addAnimationGroup = function (animationGroup) {
  103098. this._animations.push(new modelAnimation_1.GroupModelAnimation(animationGroup));
  103099. };
  103100. /**
  103101. * Get the ModelAnimation array
  103102. */
  103103. ViewerModel.prototype.getAnimations = function () {
  103104. return this._animations;
  103105. };
  103106. /**
  103107. * Get the animations' names. Using the names you can play a specific animation.
  103108. */
  103109. ViewerModel.prototype.getAnimationNames = function () {
  103110. return this._animations.map(function (a) { return a.name; });
  103111. };
  103112. /**
  103113. * Get an animation by the provided name. Used mainly when playing n animation.
  103114. * @param name the name of the animation to find
  103115. */
  103116. ViewerModel.prototype._getAnimationByName = function (name) {
  103117. // can't use .find, noe available on IE
  103118. var filtered = this._animations.filter(function (a) { return a.name === name; });
  103119. // what the next line means - if two animations have the same name, they will not be returned!
  103120. if (filtered.length === 1) {
  103121. return filtered[0];
  103122. }
  103123. else {
  103124. return null;
  103125. }
  103126. };
  103127. /**
  103128. * Choose an initialized animation using its name and start playing it
  103129. * @param name the name of the animation to play
  103130. * @returns The model aniamtion to be played.
  103131. */
  103132. ViewerModel.prototype.playAnimation = function (name) {
  103133. var animation = this.setCurrentAnimationByName(name);
  103134. if (animation) {
  103135. animation.start();
  103136. }
  103137. return animation;
  103138. };
  103139. ViewerModel.prototype.setCurrentAnimationByName = function (name) {
  103140. var animation = this._getAnimationByName(name);
  103141. if (animation) {
  103142. if (this.currentAnimation && this.currentAnimation.state !== 3 /* STOPPED */) {
  103143. this.currentAnimation.stop();
  103144. }
  103145. this.currentAnimation = animation;
  103146. return animation;
  103147. }
  103148. else {
  103149. throw new Error("animation not found - " + name);
  103150. }
  103151. };
  103152. ViewerModel.prototype._configureModel = function () {
  103153. var _this = this;
  103154. // this can be changed to the meshes that have rootMesh a parent without breaking anything.
  103155. var meshesWithNoParent = [this.rootMesh]; //this._meshes.filter(m => m.parent === this.rootMesh);
  103156. var updateMeshesWithNoParent = function (variable, value, param) {
  103157. meshesWithNoParent.forEach(function (mesh) {
  103158. if (param) {
  103159. mesh[variable][param] = value;
  103160. }
  103161. else {
  103162. mesh[variable] = value;
  103163. }
  103164. });
  103165. };
  103166. var updateXYZ = function (variable, configValues) {
  103167. if (configValues.x !== undefined) {
  103168. updateMeshesWithNoParent(variable, configValues.x, 'x');
  103169. }
  103170. if (configValues.y !== undefined) {
  103171. updateMeshesWithNoParent(variable, configValues.y, 'y');
  103172. }
  103173. if (configValues.z !== undefined) {
  103174. updateMeshesWithNoParent(variable, configValues.z, 'z');
  103175. }
  103176. if (configValues.w !== undefined) {
  103177. updateMeshesWithNoParent(variable, configValues.w, 'w');
  103178. }
  103179. };
  103180. if (this._modelConfiguration.normalize) {
  103181. var center = false;
  103182. var unitSize = false;
  103183. var parentIndex = void 0;
  103184. if (this._modelConfiguration.normalize === true) {
  103185. center = true;
  103186. unitSize = true;
  103187. }
  103188. else {
  103189. center = !!this._modelConfiguration.normalize.center;
  103190. unitSize = !!this._modelConfiguration.normalize.unitSize;
  103191. parentIndex = this._modelConfiguration.normalize.parentIndex;
  103192. }
  103193. var meshesToNormalize = [];
  103194. if (parentIndex !== undefined) {
  103195. meshesToNormalize.push(this._meshes[parentIndex]);
  103196. }
  103197. else {
  103198. meshesToNormalize = this._pivotMesh.getChildMeshes(true).length === 1 ? [this._pivotMesh] : meshesWithNoParent;
  103199. }
  103200. if (unitSize) {
  103201. meshesToNormalize.forEach(function (mesh) {
  103202. mesh.normalizeToUnitCube(true);
  103203. mesh.computeWorldMatrix(true);
  103204. });
  103205. }
  103206. if (center) {
  103207. meshesToNormalize.forEach(function (mesh) {
  103208. var boundingInfo = mesh.getHierarchyBoundingVectors(true);
  103209. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  103210. var halfSizeVec = sizeVec.scale(0.5);
  103211. var center = boundingInfo.min.add(halfSizeVec);
  103212. mesh.position = center.scale(-1);
  103213. mesh.position.y += halfSizeVec.y;
  103214. // Recompute Info.
  103215. mesh.computeWorldMatrix(true);
  103216. });
  103217. }
  103218. }
  103219. else {
  103220. // if centered, should be done here
  103221. }
  103222. // position?
  103223. if (this._modelConfiguration.position) {
  103224. updateXYZ('position', this._modelConfiguration.position);
  103225. }
  103226. if (this._modelConfiguration.rotation) {
  103227. //quaternion?
  103228. if (this._modelConfiguration.rotation.w) {
  103229. meshesWithNoParent.forEach(function (mesh) {
  103230. if (!mesh.rotationQuaternion) {
  103231. mesh.rotationQuaternion = new babylonjs_1.Quaternion();
  103232. }
  103233. });
  103234. updateXYZ('rotationQuaternion', this._modelConfiguration.rotation);
  103235. }
  103236. else {
  103237. updateXYZ('rotation', this._modelConfiguration.rotation);
  103238. }
  103239. }
  103240. if (this._modelConfiguration.rotationOffsetAxis) {
  103241. var rotationAxis_1 = new babylonjs_1.Vector3(0, 0, 0).copyFrom(this._modelConfiguration.rotationOffsetAxis);
  103242. meshesWithNoParent.forEach(function (m) {
  103243. if (_this._modelConfiguration.rotationOffsetAngle) {
  103244. m.rotate(rotationAxis_1, _this._modelConfiguration.rotationOffsetAngle);
  103245. }
  103246. });
  103247. }
  103248. if (this._modelConfiguration.scaling) {
  103249. updateXYZ('scaling', this._modelConfiguration.scaling);
  103250. }
  103251. if (this._modelConfiguration.castShadow) {
  103252. this._meshes.forEach(function (mesh) {
  103253. babylonjs_1.Tags.AddTagsTo(mesh, 'castShadow');
  103254. });
  103255. }
  103256. var meshes = this._pivotMesh.getChildMeshes(false);
  103257. meshes.filter(function (m) { return m.material; }).forEach(function (mesh) {
  103258. _this._applyModelMaterialConfiguration(mesh.material);
  103259. });
  103260. if (this._modelConfiguration.entryAnimation) {
  103261. this._entryAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.entryAnimation);
  103262. }
  103263. if (this._modelConfiguration.exitAnimation) {
  103264. this._exitAnimation = this._modelAnimationConfigurationToObject(this._modelConfiguration.exitAnimation);
  103265. }
  103266. this.onAfterConfigure.notifyObservers(this);
  103267. };
  103268. ViewerModel.prototype._modelAnimationConfigurationToObject = function (animConfig) {
  103269. var anim = {
  103270. time: 0.5
  103271. };
  103272. if (animConfig.scaling) {
  103273. anim.scaling = babylonjs_1.Vector3.Zero();
  103274. }
  103275. if (animConfig.easingFunction !== undefined) {
  103276. anim.easingFunction = animConfig.easingFunction;
  103277. }
  103278. if (animConfig.easingMode !== undefined) {
  103279. anim.easingMode = animConfig.easingMode;
  103280. }
  103281. _1.extendClassWithConfig(anim, animConfig);
  103282. return anim;
  103283. };
  103284. /**
  103285. * Apply a material configuration to a material
  103286. * @param material Material to apply configuration to
  103287. */
  103288. ViewerModel.prototype._applyModelMaterialConfiguration = function (material) {
  103289. if (!this._modelConfiguration.material)
  103290. return;
  103291. _1.extendClassWithConfig(material, this._modelConfiguration.material);
  103292. if (material instanceof babylonjs_1.PBRMaterial) {
  103293. if (this._modelConfiguration.material.directIntensity !== undefined) {
  103294. material.directIntensity = this._modelConfiguration.material.directIntensity;
  103295. }
  103296. if (this._modelConfiguration.material.emissiveIntensity !== undefined) {
  103297. material.emissiveIntensity = this._modelConfiguration.material.emissiveIntensity;
  103298. }
  103299. if (this._modelConfiguration.material.environmentIntensity !== undefined) {
  103300. material.environmentIntensity = this._modelConfiguration.material.environmentIntensity;
  103301. }
  103302. if (this._modelConfiguration.material.directEnabled !== undefined) {
  103303. material.disableLighting = !this._modelConfiguration.material.directEnabled;
  103304. }
  103305. if (this._configurationContainer && this._configurationContainer.reflectionColor) {
  103306. material.reflectionColor = this._configurationContainer.reflectionColor;
  103307. }
  103308. }
  103309. else if (material instanceof babylonjs_1.MultiMaterial) {
  103310. for (var i = 0; i < material.subMaterials.length; i++) {
  103311. var subMaterial = material.subMaterials[i];
  103312. if (subMaterial) {
  103313. this._applyModelMaterialConfiguration(subMaterial);
  103314. }
  103315. }
  103316. }
  103317. };
  103318. /**
  103319. * Start entry/exit animation given an animation configuration
  103320. * @param animationConfiguration Entry/Exit animation configuration
  103321. * @param isEntry Pass true if the animation is an entry animation
  103322. * @param completeCallback Callback to execute when the animation completes
  103323. */
  103324. ViewerModel.prototype._applyAnimation = function (animationConfiguration, isEntry, completeCallback) {
  103325. var animations = [];
  103326. //scale
  103327. if (animationConfiguration.scaling) {
  103328. var scaleStart = isEntry ? animationConfiguration.scaling : new babylonjs_1.Vector3(1, 1, 1);
  103329. var scaleEnd = isEntry ? new babylonjs_1.Vector3(1, 1, 1) : animationConfiguration.scaling;
  103330. if (!scaleStart.equals(scaleEnd)) {
  103331. this.rootMesh.scaling = scaleStart;
  103332. this._setLinearKeys(this._scaleTransition, this.rootMesh.scaling, scaleEnd, animationConfiguration.time);
  103333. animations.push(this._scaleTransition);
  103334. }
  103335. }
  103336. //Start the animation(s)
  103337. this.transitionTo(animations, animationConfiguration.time, this._createEasingFunction(animationConfiguration.easingFunction), animationConfiguration.easingMode, function () { if (completeCallback)
  103338. completeCallback(); });
  103339. };
  103340. /**
  103341. * Begin @animations with the specified @easingFunction
  103342. * @param animations The BABYLON Animations to begin
  103343. * @param duration of transition, in seconds
  103344. * @param easingFunction An easing function to apply
  103345. * @param easingMode A easing mode to apply to the easingFunction
  103346. * @param onAnimationEnd Call back trigger at the end of the animation.
  103347. */
  103348. ViewerModel.prototype.transitionTo = function (animations, duration, easingFunction, easingMode, onAnimationEnd) {
  103349. if (easingMode === void 0) { easingMode = BABYLON.EasingFunction.EASINGMODE_EASEINOUT; }
  103350. if (easingFunction) {
  103351. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  103352. var animation = animations_1[_i];
  103353. easingFunction.setEasingMode(easingMode);
  103354. animation.setEasingFunction(easingFunction);
  103355. }
  103356. }
  103357. //Stop any current animations before starting the new one - merging not yet supported.
  103358. this.stopAllAnimations();
  103359. this.rootMesh.animations = animations;
  103360. if (this.rootMesh.getScene().beginAnimation) {
  103361. var animatable = this.rootMesh.getScene().beginAnimation(this.rootMesh, 0, this._frameRate * duration, false, 1, function () {
  103362. if (onAnimationEnd) {
  103363. onAnimationEnd();
  103364. }
  103365. });
  103366. this._animatables.push(animatable);
  103367. }
  103368. };
  103369. /**
  103370. * Sets key values on an Animation from first to last frame.
  103371. * @param animation The Babylon animation object to set keys on
  103372. * @param startValue The value of the first key
  103373. * @param endValue The value of the last key
  103374. * @param duration The duration of the animation, used to determine the end frame
  103375. */
  103376. ViewerModel.prototype._setLinearKeys = function (animation, startValue, endValue, duration) {
  103377. animation.setKeys([
  103378. {
  103379. frame: 0,
  103380. value: startValue
  103381. },
  103382. {
  103383. frame: this._frameRate * duration,
  103384. value: endValue
  103385. }
  103386. ]);
  103387. };
  103388. /**
  103389. * Creates and returns a Babylon easing funtion object based on a string representing the Easing function
  103390. * @param easingFunctionID The enum of the easing funtion to create
  103391. * @return The newly created Babylon easing function object
  103392. */
  103393. ViewerModel.prototype._createEasingFunction = function (easingFunctionID) {
  103394. var easingFunction;
  103395. switch (easingFunctionID) {
  103396. case 1 /* CircleEase */:
  103397. easingFunction = new babylonjs_1.CircleEase();
  103398. break;
  103399. case 2 /* BackEase */:
  103400. easingFunction = new babylonjs_1.BackEase(0.3);
  103401. break;
  103402. case 3 /* BounceEase */:
  103403. easingFunction = new babylonjs_1.BounceEase();
  103404. break;
  103405. case 4 /* CubicEase */:
  103406. easingFunction = new babylonjs_1.CubicEase();
  103407. break;
  103408. case 5 /* ElasticEase */:
  103409. easingFunction = new babylonjs_1.ElasticEase();
  103410. break;
  103411. case 6 /* ExponentialEase */:
  103412. easingFunction = new babylonjs_1.ExponentialEase();
  103413. break;
  103414. case 7 /* PowerEase */:
  103415. easingFunction = new babylonjs_1.PowerEase();
  103416. break;
  103417. case 8 /* QuadraticEase */:
  103418. easingFunction = new babylonjs_1.QuadraticEase();
  103419. break;
  103420. case 9 /* QuarticEase */:
  103421. easingFunction = new babylonjs_1.QuarticEase();
  103422. break;
  103423. case 10 /* QuinticEase */:
  103424. easingFunction = new babylonjs_1.QuinticEase();
  103425. break;
  103426. case 11 /* SineEase */:
  103427. easingFunction = new babylonjs_1.SineEase();
  103428. break;
  103429. default:
  103430. babylonjs_1.Tools.Log("No ease function found");
  103431. break;
  103432. }
  103433. return easingFunction;
  103434. };
  103435. /**
  103436. * Stops and removes all animations that have been applied to the model
  103437. */
  103438. ViewerModel.prototype.stopAllAnimations = function () {
  103439. if (this.rootMesh) {
  103440. this.rootMesh.animations = [];
  103441. }
  103442. if (this.currentAnimation) {
  103443. this.currentAnimation.stop();
  103444. }
  103445. while (this._animatables.length) {
  103446. this._animatables[0].onAnimationEnd = null;
  103447. this._animatables[0].stop();
  103448. this._animatables.shift();
  103449. }
  103450. };
  103451. /**
  103452. * Will remove this model from the viewer (but NOT dispose it).
  103453. */
  103454. ViewerModel.prototype.remove = function () {
  103455. this.stopAllAnimations();
  103456. // hide it
  103457. this.rootMesh.isVisible = false;
  103458. if (this._observablesManager) {
  103459. this._observablesManager.onModelRemovedObservable.notifyObservers(this);
  103460. }
  103461. };
  103462. /**
  103463. * Dispose this model, including all of its associated assets.
  103464. */
  103465. ViewerModel.prototype.dispose = function () {
  103466. this.remove();
  103467. this.onAfterConfigure.clear();
  103468. this.onLoadedObservable.clear();
  103469. this.onLoadErrorObservable.clear();
  103470. this.onLoadProgressObservable.clear();
  103471. if (this.loader && this.loader.name === "gltf") {
  103472. this.loader.dispose();
  103473. }
  103474. this.particleSystems.forEach(function (ps) { return ps.dispose(); });
  103475. this.particleSystems.length = 0;
  103476. this.skeletons.forEach(function (s) { return s.dispose(); });
  103477. this.skeletons.length = 0;
  103478. this._animations.forEach(function (ag) { return ag.dispose(); });
  103479. this._animations.length = 0;
  103480. this.rootMesh.dispose(false, true);
  103481. };
  103482. return ViewerModel;
  103483. }());
  103484. exports.ViewerModel = ViewerModel;
  103485. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTW9kZWwuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvdmlld2VyTW9kZWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBc2Q7QUFJdGQsbURBQXdKO0FBRXhKLCtCQUE4RDtBQUs5RDs7R0FFRztBQUNILElBQVksVUFTWDtBQVRELFdBQVksVUFBVTtJQUNsQiwyQ0FBSSxDQUFBO0lBQ0osaURBQU8sQ0FBQTtJQUNQLCtDQUFNLENBQUE7SUFDTiw2Q0FBSyxDQUFBO0lBQ0wscURBQVMsQ0FBQTtJQUNULG1EQUFRLENBQUE7SUFDUixtREFBUSxDQUFBO0lBQ1IsNkNBQUssQ0FBQTtBQUNULENBQUMsRUFUVyxVQUFVLEdBQVYsa0JBQVUsS0FBVixrQkFBVSxRQVNyQjtBQUVEOztHQUVHO0FBQ0g7SUErRUkscUJBQW9CLG1CQUF1QyxFQUFFLGtCQUF1QyxFQUFVLHVCQUFnRDtRQUE5SixpQkFzQ0M7UUF0Q21CLHdCQUFtQixHQUFuQixtQkFBbUIsQ0FBb0I7UUFBbUQsNEJBQXVCLEdBQXZCLHVCQUF1QixDQUF5QjtRQXZFOUo7O1dBRUc7UUFDSyxZQUFPLEdBQXdCLEVBQUUsQ0FBQztRQVExQzs7V0FFRztRQUNJLG9CQUFlLEdBQTBCLEVBQUUsQ0FBQztRQUNuRDs7V0FFRztRQUNJLGNBQVMsR0FBb0IsRUFBRSxDQUFDO1FBMkMvQixnQkFBVyxHQUF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U8sRUFBRSxFQUFYLENBQVcsQ0FBQyxDQUFDO1FBQ3pDLElBQUksQ0FBQyxTQUFTLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUMxQixJQUFJLENBQUMsV0FBVyxDQUFDLE9BQU8sQ0FBQyxVQUFBLEVBQUUsSUFBSSxPQUFBLEVBQUUsQ0FBQyxPQUFPLEVBQUUsRUFBWixDQUFZLENBQUMsQ0FBQztRQUM3QyxJQUFJLENBQUMsV0FBVyxDQUFDLE1BQU0sR0FBRyxDQUFDLENBQUM7UUFDNUIsSUFBSSxDQUFDLFFBQVEsQ0FBQyxPQUFPLENBQUMsS0FBSyxFQUFFLElBQUksQ0FBQyxDQUFDO0lBQ3ZDLENBQUM7SUFDTCxrQkFBQztBQUFELENBQUMsQUFsdUJELElBa3VCQztBQWx1Qlksa0NBQVcifQ==
  103486. /***/ }),
  103487. /* 6 */
  103488. /***/ (function(module, exports, __webpack_require__) {
  103489. "use strict";
  103490. Object.defineProperty(exports, "__esModule", { value: true });
  103491. var babylonjs_1 = __webpack_require__(0);
  103492. /**
  103493. * Receives Telemetry events and raises events to the API
  103494. */
  103495. var TelemetryManager = /** @class */ (function () {
  103496. function TelemetryManager() {
  103497. this.onEventBroadcastedObservable = new babylonjs_1.Observable();
  103498. this._event = this._eventEnabled;
  103499. }
  103500. Object.defineProperty(TelemetryManager.prototype, "broadcast", {
  103501. /**
  103502. * Receives a telemetry event
  103503. * @param event The name of the Telemetry event
  103504. * @param details An additional value, or an object containing a list of property/value pairs
  103505. */
  103506. get: function () {
  103507. return this._event;
  103508. },
  103509. enumerable: true,
  103510. configurable: true
  103511. });
  103512. /**
  103513. * Log a Telemetry event for errors raised on the WebGL context.
  103514. * @param engine The Babylon engine with the WebGL context.
  103515. */
  103516. TelemetryManager.prototype.flushWebGLErrors = function (engine, viewerId) {
  103517. if (!engine) {
  103518. return;
  103519. }
  103520. var logErrors = true;
  103521. while (logErrors) {
  103522. var gl = engine._gl;
  103523. if (gl && gl.getError) {
  103524. var error = gl.getError();
  103525. if (error === gl.NO_ERROR) {
  103526. logErrors = false;
  103527. }
  103528. else {
  103529. this.broadcast("WebGL Error", viewerId, { error: error });
  103530. }
  103531. }
  103532. else {
  103533. logErrors = false;
  103534. }
  103535. }
  103536. };
  103537. Object.defineProperty(TelemetryManager.prototype, "enable", {
  103538. /**
  103539. * Enable or disable telemetry events
  103540. * @param enabled Boolan, true if events are enabled
  103541. */
  103542. set: function (enabled) {
  103543. if (enabled) {
  103544. this._event = this._eventEnabled;
  103545. }
  103546. else {
  103547. this._event = this._eventDisabled;
  103548. }
  103549. },
  103550. enumerable: true,
  103551. configurable: true
  103552. });
  103553. /**
  103554. * Called on event when disabled, typically do nothing here
  103555. */
  103556. TelemetryManager.prototype._eventDisabled = function () {
  103557. // nothing to do
  103558. };
  103559. /**
  103560. * Called on event when enabled
  103561. * @param event - The name of the Telemetry event
  103562. * @param details An additional value, or an object containing a list of property/value pairs
  103563. */
  103564. TelemetryManager.prototype._eventEnabled = function (event, viewerId, details) {
  103565. var telemetryData = {
  103566. viewerId: viewerId,
  103567. event: event,
  103568. session: this.session,
  103569. date: new Date(),
  103570. now: window.performance ? window.performance.now() : Date.now(),
  103571. detail: null
  103572. };
  103573. if (typeof details === "object") {
  103574. for (var attr in details) {
  103575. if (details.hasOwnProperty(attr)) {
  103576. telemetryData[attr] = details[attr];
  103577. }
  103578. }
  103579. }
  103580. else if (details) {
  103581. telemetryData.detail = details;
  103582. }
  103583. this.onEventBroadcastedObservable.notifyObservers(telemetryData);
  103584. };
  103585. Object.defineProperty(TelemetryManager.prototype, "session", {
  103586. /**
  103587. * Returns the current session ID or creates one if it doesn't exixt
  103588. * @return The current session ID
  103589. */
  103590. get: function () {
  103591. if (!this._currentSessionId) {
  103592. //String + Timestamp + Random Integer
  103593. this._currentSessionId = "SESSION_" + Date.now() + Math.floor(Math.random() * 0x10000);
  103594. }
  103595. return this._currentSessionId;
  103596. },
  103597. enumerable: true,
  103598. configurable: true
  103599. });
  103600. /**
  103601. * Disposes the telemetry manager
  103602. */
  103603. TelemetryManager.prototype.dispose = function () {
  103604. this.onEventBroadcastedObservable.clear();
  103605. delete this.onEventBroadcastedObservable;
  103606. };
  103607. return TelemetryManager;
  103608. }());
  103609. exports.TelemetryManager = TelemetryManager;
  103610. exports.telemetryManager = new TelemetryManager();
  103611. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9tYW5hZ2Vycy90ZWxlbWV0cnlNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEsdUNBQStDO0FBYy9DOztHQUVHO0FBQ0g7SUFBQTtRQUVXLGlDQUE0QixHQUE4QixJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUkxRSxXQUFNLEdBQThELElBQUksQ0FBQyxhQUFhLENBQUM7SUFzR25HLENBQUM7SUEvRkcsc0JBQVcsdUNBQVM7UUFMcEI7Ozs7V0FJRzthQUNIO1lBQ0ksT0FBTyxJQUFJLENBQUMsTUFBTSxDQUFDO1FBQ3ZCLENBQUM7OztPQUFBO0lBRUQ7OztPQUdHO0lBQ0ksMkNBQWdCLEdBQXZCLFVBQXdCLE1BQWMsRUFBRSxRQUFpQjtRQUNyRCxJQUFJLENBQUMsTUFBTSxFQUFFO1lBQ1QsT0FBTztTQUNWO1FBQ0QsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDO1FBRXJCLE9BQU8sU0FBUyxFQUFFO1lBQ2QsSUFBSSxFQUFFLEdBQVMsTUFBTyxDQUFDLEdBQUcsQ0FBQztZQUMzQixJQUFJLEVBQUUsSUFBSSxFQUFFLENBQUMsUUFBUSxFQUFFO2dCQUNuQixJQUFJLEtBQUssR0FBRyxFQUFFLENBQUMsUUFBUSxFQUFFLENBQUM7Z0JBQ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csSUFBSSxnQkFBZ0IsRUFBRSxDQUFDIn0=
  103612. /***/ }),
  103613. /* 7 */
  103614. /***/ (function(module, exports, __webpack_require__) {
  103615. "use strict";
  103616. Object.defineProperty(exports, "__esModule", { value: true });
  103617. var babylonjs_1 = __webpack_require__(0);
  103618. /**
  103619. * The viewer manager is the container for all viewers currently registered on this page.
  103620. * It is possible to have more than one viewer on a single page.
  103621. */
  103622. var ViewerManager = /** @class */ (function () {
  103623. function ViewerManager() {
  103624. this._viewers = {};
  103625. this.onViewerAddedObservable = new babylonjs_1.Observable();
  103626. this.onViewerRemovedObservable = new babylonjs_1.Observable();
  103627. }
  103628. /**
  103629. * Adding a new viewer to the viewer manager and start tracking it.
  103630. * @param viewer the viewer to add
  103631. */
  103632. ViewerManager.prototype.addViewer = function (viewer) {
  103633. this._viewers[viewer.getBaseId()] = viewer;
  103634. this._onViewerAdded(viewer);
  103635. };
  103636. /**
  103637. * remove a viewer from the viewer manager
  103638. * @param viewer the viewer to remove
  103639. */
  103640. ViewerManager.prototype.removeViewer = function (viewer) {
  103641. var id = viewer.getBaseId();
  103642. delete this._viewers[id];
  103643. this.onViewerRemovedObservable.notifyObservers(id);
  103644. };
  103645. /**
  103646. * 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)
  103647. * @param id the id of the HTMl element (or the viewer's, if none provided)
  103648. */
  103649. ViewerManager.prototype.getViewerById = function (id) {
  103650. return this._viewers[id];
  103651. };
  103652. /**
  103653. * Get a viewer using a container element
  103654. * @param element the HTML element to search viewers associated with
  103655. */
  103656. ViewerManager.prototype.getViewerByHTMLElement = function (element) {
  103657. for (var id in this._viewers) {
  103658. if (this._viewers[id].containerElement === element) {
  103659. return this.getViewerById(id);
  103660. }
  103661. }
  103662. };
  103663. /**
  103664. * Get a promise that will fullfil when this viewer was initialized.
  103665. * Since viewer initialization and template injection is asynchronous, using the promise will guaranty that
  103666. * you will get the viewer after everything was already configured.
  103667. * @param id the viewer id to find
  103668. */
  103669. ViewerManager.prototype.getViewerPromiseById = function (id) {
  103670. var _this = this;
  103671. return new Promise(function (resolve, reject) {
  103672. var localViewer = _this.getViewerById(id);
  103673. if (localViewer) {
  103674. return resolve(localViewer);
  103675. }
  103676. var viewerFunction = function (viewer) {
  103677. if (viewer.getBaseId() === id) {
  103678. resolve(viewer);
  103679. _this.onViewerAddedObservable.removeCallback(viewerFunction);
  103680. }
  103681. };
  103682. _this.onViewerAddedObservable.add(viewerFunction);
  103683. });
  103684. };
  103685. ViewerManager.prototype._onViewerAdded = function (viewer) {
  103686. this.onViewerAdded && this.onViewerAdded(viewer);
  103687. this.onViewerAddedObservable.notifyObservers(viewer);
  103688. };
  103689. /**
  103690. * dispose the manager and all of its associated viewers
  103691. */
  103692. ViewerManager.prototype.dispose = function () {
  103693. delete this._onViewerAdded;
  103694. for (var id in this._viewers) {
  103695. this._viewers[id].dispose();
  103696. }
  103697. this.onViewerAddedObservable.clear();
  103698. this.onViewerRemovedObservable.clear();
  103699. };
  103700. return ViewerManager;
  103701. }());
  103702. exports.ViewerManager = ViewerManager;
  103703. exports.viewerManager = new ViewerManager();
  103704. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTWFuYWdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvdmlld2VyTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUF1QztBQUd2Qzs7O0dBR0c7QUFDSDtJQWlCSTtRQUNJLElBQUksQ0FBQyxRQUFRLEdBQUcsRUFBRSxDQUFDO1FBQ25CLElBQUksQ0FBQyx1QkFBdUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUNoRCxJQUFJLENBQUMseUJBQXlCLEdBQUcsSUFBSSxzQkFBVSxFQUFFLENBQUM7SUFDdEQsQ0FBQztJQUVEOzs7T0FHRztJQUNJ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Q0wsb0JBQUM7QUFBRCxDQUFDLEFBdEdELElBc0dDO0FBdEdZLHNDQUFhO0FBd0dmLFFBQUEsYUFBYSxHQUFHLElBQUksYUFBYSxFQUFFLENBQUMifQ==
  103705. /***/ }),
  103706. /* 8 */
  103707. /***/ (function(module, exports, __webpack_require__) {
  103708. "use strict";
  103709. var __extends = (this && this.__extends) || (function () {
  103710. var extendStatics = Object.setPrototypeOf ||
  103711. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  103712. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  103713. return function (d, b) {
  103714. extendStatics(d, b);
  103715. function __() { this.constructor = d; }
  103716. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  103717. };
  103718. })();
  103719. Object.defineProperty(exports, "__esModule", { value: true });
  103720. var viewer_1 = __webpack_require__(9);
  103721. var babylonjs_1 = __webpack_require__(0);
  103722. var hdButtonPlugin_1 = __webpack_require__(64);
  103723. /**
  103724. * The Default viewer is the default implementation of the AbstractViewer.
  103725. * It uses the templating system to render a new canvas and controls.
  103726. */
  103727. var DefaultViewer = /** @class */ (function (_super) {
  103728. __extends(DefaultViewer, _super);
  103729. /**
  103730. * Create a new default viewer
  103731. * @param containerElement the element in which the templates will be rendered
  103732. * @param initialConfiguration the initial configuration. Defaults to extending the default configuration
  103733. */
  103734. function DefaultViewer(containerElement, initialConfiguration) {
  103735. if (initialConfiguration === void 0) { initialConfiguration = { extends: 'default' }; }
  103736. var _this = _super.call(this, containerElement, initialConfiguration) || this;
  103737. _this.containerElement = containerElement;
  103738. _this._registeredPlugins = [];
  103739. _this._handlePointerDown = function (event) {
  103740. var pointerDown = event.event;
  103741. if (pointerDown.button !== 0)
  103742. return;
  103743. var element = event.event.target;
  103744. if (!element) {
  103745. return;
  103746. }
  103747. var parentClasses = element.parentElement.classList;
  103748. var elementClasses = element.classList;
  103749. var elementName = "";
  103750. for (var i = 0; i < elementClasses.length; ++i) {
  103751. var className = elementClasses[i];
  103752. if (className.indexOf("-button") !== -1 || className.indexOf("-wrapper") !== -1) {
  103753. elementName = className;
  103754. break;
  103755. }
  103756. }
  103757. switch (elementName) {
  103758. case "speed-button":
  103759. case "types-button":
  103760. if (parentClasses.contains("open")) {
  103761. parentClasses.remove("open");
  103762. }
  103763. else {
  103764. parentClasses.add("open");
  103765. }
  103766. break;
  103767. case "play-pause-button":
  103768. _this._togglePlayPause();
  103769. break;
  103770. case "label-option-button":
  103771. var value = element.dataset["value"];
  103772. var label = element.querySelector("span.animation-label");
  103773. if (label && value) {
  103774. _this._updateAnimationType({ value: value, label: label.innerHTML });
  103775. }
  103776. break;
  103777. case "speed-option-button":
  103778. if (!_this._currentAnimation) {
  103779. return;
  103780. }
  103781. var speed = element.dataset["value"];
  103782. if (speed)
  103783. _this._updateAnimationSpeed(speed);
  103784. break;
  103785. case "progress-wrapper":
  103786. _this._resumePlay = !_this._isAnimationPaused;
  103787. if (_this._resumePlay) {
  103788. _this._togglePlayPause(true);
  103789. }
  103790. break;
  103791. case "fullscreen-button":
  103792. _this.toggleFullscreen();
  103793. break;
  103794. case "vr-button":
  103795. _this.toggleVR();
  103796. break;
  103797. default:
  103798. return;
  103799. }
  103800. };
  103801. /**
  103802. * Plays or Pauses animation
  103803. */
  103804. _this._togglePlayPause = function (noUiUpdate) {
  103805. if (!_this._currentAnimation) {
  103806. return;
  103807. }
  103808. if (_this._isAnimationPaused) {
  103809. _this._currentAnimation.restart();
  103810. }
  103811. else {
  103812. _this._currentAnimation.pause();
  103813. }
  103814. _this._isAnimationPaused = !_this._isAnimationPaused;
  103815. if (noUiUpdate)
  103816. return;
  103817. var navbar = _this.templateManager.getTemplate('navBar');
  103818. if (!navbar)
  103819. return;
  103820. navbar.updateParams({
  103821. paused: _this._isAnimationPaused,
  103822. });
  103823. };
  103824. /**
  103825. * Control progress bar position based on animation current frame
  103826. */
  103827. _this._updateProgressBar = function () {
  103828. var navbar = _this.templateManager.getTemplate('navBar');
  103829. if (!navbar)
  103830. return;
  103831. var progressSlider = navbar.parent.querySelector("input.progress-wrapper");
  103832. if (progressSlider && _this._currentAnimation) {
  103833. var progress = _this._currentAnimation.currentFrame / _this._currentAnimation.frames * 100;
  103834. var currentValue = progressSlider.valueAsNumber;
  103835. if (Math.abs(currentValue - progress) > 0.5) { // Only move if greater than a 1% change
  103836. progressSlider.value = '' + progress;
  103837. }
  103838. if (_this._currentAnimation.state === 1 /* PLAYING */) {
  103839. if (_this.sceneManager.camera.autoRotationBehavior && !_this._oldIdleRotationValue) {
  103840. _this._oldIdleRotationValue = _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed;
  103841. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = 0;
  103842. }
  103843. }
  103844. else {
  103845. if (_this.sceneManager.camera.autoRotationBehavior && _this._oldIdleRotationValue) {
  103846. _this.sceneManager.camera.autoRotationBehavior.idleRotationSpeed = _this._oldIdleRotationValue;
  103847. _this._oldIdleRotationValue = 0;
  103848. }
  103849. }
  103850. }
  103851. };
  103852. /**
  103853. * Update Current Animation Speed
  103854. */
  103855. _this._updateAnimationSpeed = function (speed, paramsObject) {
  103856. var navbar = _this.templateManager.getTemplate('navBar');
  103857. if (!navbar)
  103858. return;
  103859. if (speed && _this._currentAnimation) {
  103860. _this._currentAnimation.speedRatio = parseFloat(speed);
  103861. if (!_this._isAnimationPaused) {
  103862. _this._currentAnimation.restart();
  103863. }
  103864. if (paramsObject) {
  103865. paramsObject.selectedSpeed = speed + "x";
  103866. }
  103867. else {
  103868. navbar.updateParams({
  103869. selectedSpeed: speed + "x",
  103870. });
  103871. }
  103872. }
  103873. };
  103874. /**
  103875. * Update Current Animation Type
  103876. */
  103877. _this._updateAnimationType = function (data, paramsObject) {
  103878. var navbar = _this.templateManager.getTemplate('navBar');
  103879. if (!navbar)
  103880. return;
  103881. if (data) {
  103882. _this._currentAnimation = _this.sceneManager.models[0].setCurrentAnimationByName(data.value);
  103883. }
  103884. if (paramsObject) {
  103885. paramsObject.selectedAnimation = (_this._animationList.indexOf(data.value) + 1);
  103886. paramsObject.selectedAnimationName = data.label;
  103887. }
  103888. else {
  103889. navbar.updateParams({
  103890. selectedAnimation: (_this._animationList.indexOf(data.value) + 1),
  103891. selectedAnimationName: data.label
  103892. });
  103893. }
  103894. _this._updateAnimationSpeed("1.0", paramsObject);
  103895. };
  103896. /**
  103897. * Toggle fullscreen of the entire viewer
  103898. */
  103899. _this.toggleFullscreen = function () {
  103900. var viewerTemplate = _this.templateManager.getTemplate('viewer');
  103901. var viewerElement = viewerTemplate && viewerTemplate.parent;
  103902. var fullscreenElement = _this.fullscreenElement || viewerElement;
  103903. if (fullscreenElement) {
  103904. var currentElement = document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement;
  103905. if (!currentElement) {
  103906. var requestFullScreen = fullscreenElement.requestFullscreen || fullscreenElement.webkitRequestFullscreen || fullscreenElement.msRequestFullscreen || fullscreenElement.mozRequestFullScreen;
  103907. requestFullScreen.call(fullscreenElement);
  103908. if (viewerElement) {
  103909. viewerElement.classList.add("in-fullscreen");
  103910. }
  103911. }
  103912. else {
  103913. var exitFullscreen = document.exitFullscreen || document.webkitExitFullscreen || document.msExitFullscreen || document.mozCancelFullScreen;
  103914. exitFullscreen.call(document);
  103915. if (viewerElement) {
  103916. viewerElement.classList.remove("in-fullscreen");
  103917. }
  103918. }
  103919. }
  103920. };
  103921. _this._onModelLoaded = function (model) {
  103922. _this._configureTemplate(model);
  103923. // with a short timeout, making sure everything is there already.
  103924. var hideLoadingDelay = 20;
  103925. if (_this.configuration.lab && _this.configuration.lab.hideLoadingDelay !== undefined) {
  103926. hideLoadingDelay = _this.configuration.lab.hideLoadingDelay;
  103927. }
  103928. setTimeout(function () {
  103929. _this.sceneManager.scene.executeWhenReady(function () {
  103930. _this.hideLoadingScreen();
  103931. });
  103932. }, hideLoadingDelay);
  103933. return;
  103934. };
  103935. _this.onModelLoadedObservable.add(_this._onModelLoaded);
  103936. _this.onModelRemovedObservable.add(function () {
  103937. _this._configureTemplate();
  103938. });
  103939. _this.onEngineInitObservable.add(function () {
  103940. _this.sceneManager.onLightsConfiguredObservable.add(function (data) {
  103941. _this._configureLights();
  103942. });
  103943. });
  103944. return _this;
  103945. }
  103946. DefaultViewer.prototype.registerTemplatePlugin = function (plugin) {
  103947. var _this = this;
  103948. //validate
  103949. if (!plugin.templateName) {
  103950. throw new Error("No template name provided");
  103951. }
  103952. this._registeredPlugins.push(plugin);
  103953. var template = this.templateManager.getTemplate(plugin.templateName);
  103954. if (!template) {
  103955. throw new Error("Template " + plugin.templateName + " not found");
  103956. }
  103957. if (plugin.addHTMLTemplate) {
  103958. template.onHTMLRendered.add(function (tmpl) {
  103959. plugin.addHTMLTemplate && plugin.addHTMLTemplate(tmpl);
  103960. });
  103961. }
  103962. if (plugin.eventsToAttach) {
  103963. plugin.eventsToAttach.forEach(function (eventName) {
  103964. plugin.onEvent && _this.templateManager.eventManager.registerCallback(plugin.templateName, function (event) {
  103965. if (plugin.onEvent && plugin.interactionPredicate(event)) {
  103966. plugin.onEvent(event);
  103967. }
  103968. }, eventName);
  103969. });
  103970. }
  103971. };
  103972. /**
  103973. * This will be executed when the templates initialize.
  103974. */
  103975. DefaultViewer.prototype._onTemplatesLoaded = function () {
  103976. var _this = this;
  103977. this.showLoadingScreen();
  103978. // navbar
  103979. this._initNavbar();
  103980. // close overlay button
  103981. var template = this.templateManager.getTemplate('overlay');
  103982. if (template) {
  103983. var closeButton = template.parent.querySelector('.close-button');
  103984. if (closeButton) {
  103985. closeButton.addEventListener('pointerdown', function () {
  103986. _this.hideOverlayScreen();
  103987. });
  103988. }
  103989. }
  103990. if (this.configuration.templates && this.configuration.templates.viewer) {
  103991. if (this.configuration.templates.viewer.params && this.configuration.templates.viewer.params.enableDragAndDrop) {
  103992. var filesInput = new babylonjs_1.FilesInput(this.engine, this.sceneManager.scene, function () {
  103993. }, function () {
  103994. }, function () {
  103995. }, function () {
  103996. }, function () {
  103997. }, function (file) {
  103998. _this.loadModel(file);
  103999. }, function () {
  104000. });
  104001. filesInput.monitorElementForDragNDrop(this.templateManager.getCanvas());
  104002. }
  104003. }
  104004. return _super.prototype._onTemplatesLoaded.call(this);
  104005. };
  104006. DefaultViewer.prototype._initNavbar = function () {
  104007. var _this = this;
  104008. var navbar = this.templateManager.getTemplate('navBar');
  104009. if (navbar) {
  104010. this.onFrameRenderedObservable.add(this._updateProgressBar);
  104011. this.templateManager.eventManager.registerCallback('navBar', this._handlePointerDown, 'pointerdown');
  104012. // an example how to trigger the help button. publiclly available
  104013. this.templateManager.eventManager.registerCallback("navBar", function () {
  104014. // do your thing
  104015. }, "pointerdown", ".help-button");
  104016. this.templateManager.eventManager.registerCallback("navBar", function (event) {
  104017. var evt = event.event;
  104018. var element = (evt.target);
  104019. if (!_this._currentAnimation)
  104020. return;
  104021. var gotoFrame = +element.value / 100 * _this._currentAnimation.frames;
  104022. if (isNaN(gotoFrame))
  104023. return;
  104024. _this._currentAnimation.goToFrame(gotoFrame);
  104025. }, "input");
  104026. this.templateManager.eventManager.registerCallback("navBar", function () {
  104027. if (_this._resumePlay) {
  104028. _this._togglePlayPause(true);
  104029. }
  104030. _this._resumePlay = false;
  104031. }, "pointerup", ".progress-wrapper");
  104032. if (window.devicePixelRatio === 1 && navbar.configuration.params && !navbar.configuration.params.hideHdButton) {
  104033. navbar.updateParams({
  104034. hideHdButton: true
  104035. });
  104036. }
  104037. this.registerTemplatePlugin(new hdButtonPlugin_1.HDButtonPlugin(this));
  104038. }
  104039. };
  104040. DefaultViewer.prototype.toggleVR = function () {
  104041. _super.prototype.toggleVR.call(this);
  104042. var viewerTemplate = this.templateManager.getTemplate('viewer');
  104043. var viewerElement = viewerTemplate && viewerTemplate.parent;
  104044. if (viewerElement) {
  104045. if (this._vrToggled) {
  104046. viewerElement.classList.add("in-vr");
  104047. }
  104048. else {
  104049. viewerElement.classList.remove("in-vr");
  104050. }
  104051. }
  104052. };
  104053. /**
  104054. * Preparing the container element to present the viewer
  104055. */
  104056. DefaultViewer.prototype._prepareContainerElement = function () {
  104057. this.containerElement.style.position = 'relative';
  104058. this.containerElement.style.height = '100%';
  104059. this.containerElement.style.display = 'flex';
  104060. };
  104061. /**
  104062. * This function will configure the templates and update them after a model was loaded
  104063. * It is mainly responsible to changing the title and subtitle etc'.
  104064. * @param model the model to be used to configure the templates by
  104065. */
  104066. DefaultViewer.prototype._configureTemplate = function (model) {
  104067. var navbar = this.templateManager.getTemplate('navBar');
  104068. if (!navbar)
  104069. return;
  104070. var newParams = navbar.configuration.params || {};
  104071. if (!model) {
  104072. newParams.animations = null;
  104073. }
  104074. else {
  104075. var animationNames = model.getAnimationNames();
  104076. newParams.animations = animationNames.map(function (a) { return { label: a, value: a }; });
  104077. if (animationNames.length) {
  104078. this._isAnimationPaused = (model.configuration.animation && !model.configuration.animation.autoStart) || !model.configuration.animation;
  104079. this._animationList = animationNames;
  104080. newParams.paused = this._isAnimationPaused;
  104081. var animationIndex = 0;
  104082. if (model.configuration.animation && typeof model.configuration.animation.autoStart === 'string') {
  104083. animationIndex = animationNames.indexOf(model.configuration.animation.autoStart);
  104084. if (animationIndex === -1) {
  104085. animationIndex = 0;
  104086. }
  104087. }
  104088. this._updateAnimationType(newParams.animations[animationIndex], newParams);
  104089. }
  104090. else {
  104091. newParams.animations = null;
  104092. }
  104093. if (model.configuration.thumbnail) {
  104094. newParams.logoImage = model.configuration.thumbnail;
  104095. }
  104096. }
  104097. navbar.updateParams(newParams, false);
  104098. };
  104099. /**
  104100. * This will load a new model to the default viewer
  104101. * overriding the AbstractViewer's loadModel.
  104102. * The scene will automatically be cleared of the old models, if exist.
  104103. * @param model the configuration object (or URL) to load.
  104104. */
  104105. DefaultViewer.prototype.loadModel = function (model) {
  104106. var _this = this;
  104107. if (!model) {
  104108. model = this.configuration.model;
  104109. }
  104110. this.showLoadingScreen();
  104111. return _super.prototype.loadModel.call(this, model, true).catch(function (error) {
  104112. console.log(error);
  104113. _this.hideLoadingScreen();
  104114. _this.showOverlayScreen('error');
  104115. return Promise.reject(error);
  104116. });
  104117. };
  104118. /**
  104119. * Show the overlay and the defined sub-screen.
  104120. * Mainly used for help and errors
  104121. * @param subScreen the name of the subScreen. Those can be defined in the configuration object
  104122. */
  104123. DefaultViewer.prototype.showOverlayScreen = function (subScreen) {
  104124. var _this = this;
  104125. var template = this.templateManager.getTemplate('overlay');
  104126. if (!template)
  104127. return Promise.resolve('Overlay template not found');
  104128. return template.show((function (template) {
  104129. var canvasRect = _this.containerElement.getBoundingClientRect();
  104130. template.parent.style.display = 'flex';
  104131. template.parent.style.width = canvasRect.width + "px";
  104132. template.parent.style.height = canvasRect.height + "px";
  104133. template.parent.style.opacity = "1";
  104134. var subTemplate = _this.templateManager.getTemplate(subScreen);
  104135. if (!subTemplate) {
  104136. return Promise.reject(subScreen + ' template not found');
  104137. }
  104138. return subTemplate.show((function (template) {
  104139. template.parent.style.display = 'flex';
  104140. return Promise.resolve(template);
  104141. }));
  104142. }));
  104143. };
  104144. /**
  104145. * Hide the overlay screen.
  104146. */
  104147. DefaultViewer.prototype.hideOverlayScreen = function () {
  104148. var template = this.templateManager.getTemplate('overlay');
  104149. if (!template)
  104150. return Promise.resolve('Overlay template not found');
  104151. return template.hide((function (template) {
  104152. template.parent.style.opacity = "0";
  104153. var onTransitionEnd = function () {
  104154. template.parent.removeEventListener("transitionend", onTransitionEnd);
  104155. template.parent.style.display = 'none';
  104156. };
  104157. template.parent.addEventListener("transitionend", onTransitionEnd);
  104158. var overlays = template.parent.querySelectorAll('.overlay');
  104159. if (overlays) {
  104160. for (var i = 0; i < overlays.length; ++i) {
  104161. var htmlElement = overlays.item(i);
  104162. htmlElement.style.display = 'none';
  104163. }
  104164. }
  104165. return Promise.resolve(template);
  104166. }));
  104167. };
  104168. /**
  104169. * show the viewer (in case it was hidden)
  104170. *
  104171. * @param visibilityFunction an optional function to execute in order to show the container
  104172. */
  104173. DefaultViewer.prototype.show = function (visibilityFunction) {
  104174. var template = this.templateManager.getTemplate('main');
  104175. //not possible, but yet:
  104176. if (!template)
  104177. return Promise.reject('Main template not found');
  104178. return template.show(visibilityFunction);
  104179. };
  104180. /**
  104181. * hide the viewer (in case it is visible)
  104182. *
  104183. * @param visibilityFunction an optional function to execute in order to hide the container
  104184. */
  104185. DefaultViewer.prototype.hide = function (visibilityFunction) {
  104186. var template = this.templateManager.getTemplate('main');
  104187. //not possible, but yet:
  104188. if (!template)
  104189. return Promise.reject('Main template not found');
  104190. return template.hide(visibilityFunction);
  104191. };
  104192. /**
  104193. * Show the loading screen.
  104194. * The loading screen can be configured using the configuration object
  104195. */
  104196. DefaultViewer.prototype.showLoadingScreen = function () {
  104197. var _this = this;
  104198. var template = this.templateManager.getTemplate('loadingScreen');
  104199. if (!template)
  104200. return Promise.resolve('Loading Screen template not found');
  104201. return template.show((function (template) {
  104202. var canvasRect = _this.containerElement.getBoundingClientRect();
  104203. // var canvasPositioning = window.getComputedStyle(this.containerElement).position;
  104204. template.parent.style.display = 'flex';
  104205. template.parent.style.width = canvasRect.width + "px";
  104206. template.parent.style.height = canvasRect.height + "px";
  104207. template.parent.style.opacity = "1";
  104208. // from the configuration!!!
  104209. var color = "black";
  104210. if (_this.configuration.templates && _this.configuration.templates.loadingScreen) {
  104211. color = (_this.configuration.templates.loadingScreen.params &&
  104212. _this.configuration.templates.loadingScreen.params.backgroundColor) || color;
  104213. }
  104214. template.parent.style.backgroundColor = color;
  104215. return Promise.resolve(template);
  104216. }));
  104217. };
  104218. /**
  104219. * Hide the loading screen
  104220. */
  104221. DefaultViewer.prototype.hideLoadingScreen = function () {
  104222. var template = this.templateManager.getTemplate('loadingScreen');
  104223. if (!template)
  104224. return Promise.resolve('Loading Screen template not found');
  104225. return template.hide((function (template) {
  104226. template.parent.style.opacity = "0";
  104227. var onTransitionEnd = function () {
  104228. template.parent.removeEventListener("transitionend", onTransitionEnd);
  104229. template.parent.style.display = 'none';
  104230. };
  104231. template.parent.addEventListener("transitionend", onTransitionEnd);
  104232. return Promise.resolve(template);
  104233. }));
  104234. };
  104235. DefaultViewer.prototype.dispose = function () {
  104236. this.templateManager.dispose();
  104237. _super.prototype.dispose.call(this);
  104238. };
  104239. DefaultViewer.prototype._onConfigurationLoaded = function (configuration) {
  104240. var _this = this;
  104241. _super.prototype._onConfigurationLoaded.call(this, configuration);
  104242. // initialize the templates
  104243. var templateConfiguration = this.configuration.templates || {};
  104244. this.templateManager.initTemplate(templateConfiguration);
  104245. // when done, execute onTemplatesLoaded()
  104246. this.templateManager.onAllLoaded.add(function () {
  104247. var canvas = _this.templateManager.getCanvas();
  104248. if (canvas) {
  104249. _this._canvas = canvas;
  104250. }
  104251. _this._onTemplateLoaded();
  104252. });
  104253. };
  104254. /**
  104255. * An extension of the light configuration of the abstract viewer.
  104256. * @param lightsConfiguration the light configuration to use
  104257. * @param model the model that will be used to configure the lights (if the lights are model-dependant)
  104258. */
  104259. DefaultViewer.prototype._configureLights = function () {
  104260. var _this = this;
  104261. // labs feature - flashlight
  104262. if (this.configuration.lab && this.configuration.lab.flashlight) {
  104263. var lightTarget_1;
  104264. var angle = 0.5;
  104265. var exponent = Math.PI / 2;
  104266. if (typeof this.configuration.lab.flashlight === "object") {
  104267. exponent = this.configuration.lab.flashlight.exponent || exponent;
  104268. angle = this.configuration.lab.flashlight.angle || angle;
  104269. }
  104270. var flashlight = new babylonjs_1.SpotLight("flashlight", babylonjs_1.Vector3.Zero(), babylonjs_1.Vector3.Zero(), exponent, angle, this.sceneManager.scene);
  104271. if (typeof this.configuration.lab.flashlight === "object") {
  104272. flashlight.intensity = this.configuration.lab.flashlight.intensity || flashlight.intensity;
  104273. if (this.configuration.lab.flashlight.diffuse) {
  104274. flashlight.diffuse.r = this.configuration.lab.flashlight.diffuse.r;
  104275. flashlight.diffuse.g = this.configuration.lab.flashlight.diffuse.g;
  104276. flashlight.diffuse.b = this.configuration.lab.flashlight.diffuse.b;
  104277. }
  104278. if (this.configuration.lab.flashlight.specular) {
  104279. flashlight.specular.r = this.configuration.lab.flashlight.specular.r;
  104280. flashlight.specular.g = this.configuration.lab.flashlight.specular.g;
  104281. flashlight.specular.b = this.configuration.lab.flashlight.specular.b;
  104282. }
  104283. }
  104284. this.sceneManager.scene.constantlyUpdateMeshUnderPointer = true;
  104285. this.sceneManager.scene.onPointerObservable.add(function (eventData) {
  104286. if (eventData.type === 4 && eventData.pickInfo) {
  104287. lightTarget_1 = (eventData.pickInfo.pickedPoint);
  104288. }
  104289. else {
  104290. lightTarget_1 = undefined;
  104291. }
  104292. });
  104293. var updateFlashlightFunction = function () {
  104294. if (_this.sceneManager.camera && flashlight) {
  104295. flashlight.position.copyFrom(_this.sceneManager.camera.position);
  104296. if (lightTarget_1) {
  104297. lightTarget_1.subtractToRef(flashlight.position, flashlight.direction);
  104298. }
  104299. }
  104300. };
  104301. this.sceneManager.scene.registerBeforeRender(updateFlashlightFunction);
  104302. this._registeredOnBeforeRenderFunctions.push(updateFlashlightFunction);
  104303. }
  104304. };
  104305. return DefaultViewer;
  104306. }(viewer_1.AbstractViewer));
  104307. exports.DefaultViewer = DefaultViewer;
  104308. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdFZpZXdlci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy92aWV3ZXIvZGVmYXVsdFZpZXdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7Ozs7Ozs7Ozs7QUFJQSxtQ0FBMEM7QUFDMUMsdUNBQTJEO0FBSTNELHVFQUFzRTtBQUV0RTs7O0dBR0c7QUFDSDtJQUFtQyxpQ0FBYztJQUk3Qzs7OztPQUlHO0lBQ0gsdUJBQW1CLGdCQUE2QixFQUFFLG9CQUFrRTtRQUFsRSxxQ0FBQSxFQUFBLHlCQUE4QyxPQUFPLEVBQUUsU0FBUyxFQUFFO1FBQXBILFlBQ0ksa0JBQU0sZ0JB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UFBRTtvQkFDeEMsVUFBVSxDQUFDLFFBQVEsQ0FBQyxRQUFRLENBQUMsS0FBSSxDQUFDLFlBQVksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLENBQUM7b0JBQ2hFLElBQUksYUFBVyxFQUFFO3dCQUNiLGFBQVcsQ0FBQyxhQUFhLENBQUMsVUFBVSxDQUFDLFFBQVEsRUFBRSxVQUFVLENBQUMsU0FBUyxDQUFDLENBQUM7cUJBQ3hFO2lCQUNKO1lBQ0wsQ0FBQyxDQUFBO1lBQ0QsSUFBSSxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsb0JBQW9CLENBQUMsd0JBQXdCLENBQUMsQ0FBQztZQUN2RSxJQUFJLENBQUMsa0NBQWtDLENBQUMsSUFBSSxDQUFDLHdCQUF3QixDQUFDLENBQUM7U0FDMUU7SUFDTCxDQUFDO0lBQ0wsb0JBQUM7QUFBRCxDQUFDLEFBcG5CRCxDQUFtQyx1QkFBYyxHQW9uQmhEO0FBcG5CWSxzQ0FBYSJ9
  104309. /***/ }),
  104310. /* 9 */
  104311. /***/ (function(module, exports, __webpack_require__) {
  104312. "use strict";
  104313. Object.defineProperty(exports, "__esModule", { value: true });
  104314. var viewerManager_1 = __webpack_require__(7);
  104315. var sceneManager_1 = __webpack_require__(23);
  104316. var loader_1 = __webpack_require__(29);
  104317. var babylonjs_1 = __webpack_require__(0);
  104318. var modelLoader_1 = __webpack_require__(13);
  104319. var globals_1 = __webpack_require__(4);
  104320. var telemetryManager_1 = __webpack_require__(6);
  104321. var _1 = __webpack_require__(1);
  104322. var observablesManager_1 = __webpack_require__(60);
  104323. var configurationContainer_1 = __webpack_require__(61);
  104324. var templateManager_1 = __webpack_require__(62);
  104325. /**
  104326. * The AbstractViewr is the center of Babylon's viewer.
  104327. * It is the basic implementation of the default viewer and is responsible of loading and showing the model and the templates
  104328. */
  104329. var AbstractViewer = /** @class */ (function () {
  104330. function AbstractViewer(containerElement, initialConfiguration) {
  104331. if (initialConfiguration === void 0) { initialConfiguration = {}; }
  104332. var _this = this;
  104333. this.containerElement = containerElement;
  104334. /**
  104335. * A flag that controls whether or not the render loop should be executed
  104336. */
  104337. this.runRenderLoop = true;
  104338. /**
  104339. * is this viewer disposed?
  104340. */
  104341. this._isDisposed = false;
  104342. this._hdToggled = false;
  104343. this._vrToggled = false;
  104344. this._vrModelRepositioning = 0;
  104345. this._vrScale = 1;
  104346. /**
  104347. * The resize function that will be registered with the window object
  104348. */
  104349. this._resize = function () {
  104350. // Only resize if Canvas is in the DOM
  104351. if (!_this.isCanvasInDOM()) {
  104352. return;
  104353. }
  104354. if (_this.canvas.clientWidth <= 0 || _this.canvas.clientHeight <= 0) {
  104355. return;
  104356. }
  104357. if (_this.configuration.engine && _this.configuration.engine.disableResize) {
  104358. return;
  104359. }
  104360. _this.engine.resize();
  104361. };
  104362. /**
  104363. * render loop that will be executed by the engine
  104364. */
  104365. this._render = function (force) {
  104366. if (force === void 0) { force = false; }
  104367. if (force || (_this.sceneManager.scene && _this.sceneManager.scene.activeCamera)) {
  104368. if (_this.runRenderLoop || force) {
  104369. _this.engine.performanceMonitor.enable();
  104370. _this.sceneManager.scene.render();
  104371. _this.onFrameRenderedObservable.notifyObservers(_this);
  104372. }
  104373. else {
  104374. _this.engine.performanceMonitor.disable();
  104375. // update camera instead of rendering
  104376. _this.sceneManager.scene.activeCamera && _this.sceneManager.scene.activeCamera.update();
  104377. }
  104378. }
  104379. };
  104380. // if exists, use the container id. otherwise, generate a random string.
  104381. if (containerElement.id) {
  104382. this.baseId = containerElement.id;
  104383. }
  104384. else {
  104385. this.baseId = containerElement.id = 'bjs' + Math.random().toString(32).substr(2, 8);
  104386. }
  104387. this._registeredOnBeforeRenderFunctions = [];
  104388. this._configurationContainer = new configurationContainer_1.ConfigurationContainer();
  104389. // add this viewer to the viewer manager
  104390. viewerManager_1.viewerManager.addViewer(this);
  104391. this.observablesManager = new observablesManager_1.ObservablesManager();
  104392. this.modelLoader = new modelLoader_1.ModelLoader(this.observablesManager, this._configurationContainer);
  104393. babylonjs_1.RenderingManager.AUTOCLEAR = false;
  104394. // extend the configuration
  104395. this._configurationLoader = new loader_1.ConfigurationLoader();
  104396. this._configurationLoader.loadConfiguration(initialConfiguration, function (configuration) {
  104397. _this._onConfigurationLoaded(configuration);
  104398. });
  104399. this.onSceneInitObservable.add(function () {
  104400. _this.updateConfiguration();
  104401. });
  104402. this.onInitDoneObservable.add(function () {
  104403. _this._isInit = true;
  104404. _this.engine.runRenderLoop(_this._render);
  104405. });
  104406. this._prepareContainerElement();
  104407. }
  104408. Object.defineProperty(AbstractViewer.prototype, "onSceneInitObservable", {
  104409. // observables
  104410. /**
  104411. * Will notify when the scene was initialized
  104412. */
  104413. get: function () {
  104414. return this.observablesManager.onSceneInitObservable;
  104415. },
  104416. enumerable: true,
  104417. configurable: true
  104418. });
  104419. Object.defineProperty(AbstractViewer.prototype, "onEngineInitObservable", {
  104420. /**
  104421. * will notify when the engine was initialized
  104422. */
  104423. get: function () {
  104424. return this.observablesManager.onEngineInitObservable;
  104425. },
  104426. enumerable: true,
  104427. configurable: true
  104428. });
  104429. Object.defineProperty(AbstractViewer.prototype, "onModelAddedObservable", {
  104430. /**
  104431. * Will notify when a new model was added to the scene.
  104432. * Note that added does not neccessarily mean loaded!
  104433. */
  104434. get: function () {
  104435. return this.observablesManager.onModelAddedObservable;
  104436. },
  104437. enumerable: true,
  104438. configurable: true
  104439. });
  104440. Object.defineProperty(AbstractViewer.prototype, "onModelLoadedObservable", {
  104441. /**
  104442. * will notify after every model load
  104443. */
  104444. get: function () {
  104445. return this.observablesManager.onModelLoadedObservable;
  104446. },
  104447. enumerable: true,
  104448. configurable: true
  104449. });
  104450. Object.defineProperty(AbstractViewer.prototype, "onModelLoadProgressObservable", {
  104451. /**
  104452. * will notify when any model notify of progress
  104453. */
  104454. get: function () {
  104455. return this.observablesManager.onModelLoadProgressObservable;
  104456. },
  104457. enumerable: true,
  104458. configurable: true
  104459. });
  104460. Object.defineProperty(AbstractViewer.prototype, "onModelLoadErrorObservable", {
  104461. /**
  104462. * will notify when any model load failed.
  104463. */
  104464. get: function () {
  104465. return this.observablesManager.onModelLoadErrorObservable;
  104466. },
  104467. enumerable: true,
  104468. configurable: true
  104469. });
  104470. Object.defineProperty(AbstractViewer.prototype, "onModelRemovedObservable", {
  104471. /**
  104472. * Will notify when a model was removed from the scene;
  104473. */
  104474. get: function () {
  104475. return this.observablesManager.onModelRemovedObservable;
  104476. },
  104477. enumerable: true,
  104478. configurable: true
  104479. });
  104480. Object.defineProperty(AbstractViewer.prototype, "onLoaderInitObservable", {
  104481. /**
  104482. * will notify when a new loader was initialized.
  104483. * Used mainly to know when a model starts loading.
  104484. */
  104485. get: function () {
  104486. return this.observablesManager.onLoaderInitObservable;
  104487. },
  104488. enumerable: true,
  104489. configurable: true
  104490. });
  104491. Object.defineProperty(AbstractViewer.prototype, "onInitDoneObservable", {
  104492. /**
  104493. * Observers registered here will be executed when the entire load process has finished.
  104494. */
  104495. get: function () {
  104496. return this.observablesManager.onViewerInitDoneObservable;
  104497. },
  104498. enumerable: true,
  104499. configurable: true
  104500. });
  104501. Object.defineProperty(AbstractViewer.prototype, "onFrameRenderedObservable", {
  104502. /**
  104503. * Functions added to this observable will be executed on each frame rendered.
  104504. */
  104505. get: function () {
  104506. return this.observablesManager.onFrameRenderedObservable;
  104507. },
  104508. enumerable: true,
  104509. configurable: true
  104510. });
  104511. Object.defineProperty(AbstractViewer.prototype, "canvas", {
  104512. /**
  104513. * The (single) canvas of this viewer
  104514. */
  104515. get: function () {
  104516. return this._canvas;
  104517. },
  104518. enumerable: true,
  104519. configurable: true
  104520. });
  104521. Object.defineProperty(AbstractViewer.prototype, "configurationContainer", {
  104522. get: function () {
  104523. return this._configurationContainer;
  104524. },
  104525. enumerable: true,
  104526. configurable: true
  104527. });
  104528. /**
  104529. * get the baseId of this viewer
  104530. */
  104531. AbstractViewer.prototype.getBaseId = function () {
  104532. return this.baseId;
  104533. };
  104534. /**
  104535. * Do we have a canvas to render on, and is it a part of the scene
  104536. */
  104537. AbstractViewer.prototype.isCanvasInDOM = function () {
  104538. return !!this._canvas && !!this._canvas.parentElement;
  104539. };
  104540. Object.defineProperty(AbstractViewer.prototype, "renderInBackground", {
  104541. /**
  104542. * Is the engine currently set to rende even when the page is in background
  104543. */
  104544. get: function () {
  104545. return this.engine && this.engine.renderEvenInBackground;
  104546. },
  104547. /**
  104548. * Set the viewer's background rendering flag.
  104549. */
  104550. set: function (value) {
  104551. if (this.engine) {
  104552. this.engine.renderEvenInBackground = value;
  104553. }
  104554. },
  104555. enumerable: true,
  104556. configurable: true
  104557. });
  104558. Object.defineProperty(AbstractViewer.prototype, "configuration", {
  104559. /**
  104560. * Get the configuration object. This is a reference only.
  104561. * The configuration can ONLY be updated using the updateConfiguration function.
  104562. * changing this object will have no direct effect on the scene.
  104563. */
  104564. get: function () {
  104565. return this._configurationContainer.configuration;
  104566. },
  104567. enumerable: true,
  104568. configurable: true
  104569. });
  104570. /**
  104571. * force resizing the engine.
  104572. */
  104573. AbstractViewer.prototype.forceResize = function () {
  104574. this._resize();
  104575. };
  104576. AbstractViewer.prototype.toggleHD = function () {
  104577. this._hdToggled = !this._hdToggled;
  104578. var scale = this._hdToggled ? Math.max(0.5, 1 / (window.devicePixelRatio || 2)) : 1;
  104579. this.engine.setHardwareScalingLevel(scale);
  104580. };
  104581. AbstractViewer.prototype.toggleVR = function () {
  104582. this._vrToggled = !this._vrToggled;
  104583. if (this._vrToggled && this.sceneManager.vrHelper) {
  104584. // make sure the floor is set
  104585. if (this.sceneManager.environmentHelper && this.sceneManager.environmentHelper.ground) {
  104586. this.sceneManager.vrHelper.addFloorMesh(this.sceneManager.environmentHelper.ground);
  104587. }
  104588. this.sceneManager.vrHelper.enterVR();
  104589. // calculate position and vr scale
  104590. if (this.sceneManager.environmentHelper) {
  104591. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(this._vrScale);
  104592. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(this._vrScale);
  104593. }
  104594. // position the vr camera to be in front of the object
  104595. if (this.sceneManager.vrHelper.currentVRCamera) {
  104596. this.sceneManager.vrHelper.currentVRCamera.position.copyFromFloats(0, this.sceneManager.vrHelper.currentVRCamera.position.y, -1);
  104597. this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion && this.sceneManager.vrHelper.currentVRCamera.rotationQuaternion.copyFromFloats(0, 0, 0, 1);
  104598. this._vrModelRepositioning = this.sceneManager.vrHelper.currentVRCamera.position.y / 2;
  104599. // enable rotation using the axels
  104600. // check if the camera is a webvr camera
  104601. if (this.sceneManager.vrHelper.currentVRCamera.getClassName() === "WebVRFreeCamera") {
  104602. }
  104603. }
  104604. else {
  104605. this._vrModelRepositioning = 0;
  104606. }
  104607. if (this.sceneManager.models.length) {
  104608. var boundingVectors = this.sceneManager.models[0].rootMesh.getHierarchyBoundingVectors();
  104609. var sizeVec = boundingVectors.max.subtract(boundingVectors.min);
  104610. var maxDimension = Math.max(sizeVec.x, sizeVec.y, sizeVec.z);
  104611. this._vrScale = (1 / maxDimension);
  104612. if (this.configuration.vr && this.configuration.vr.objectScaleFactor) {
  104613. this._vrScale *= this.configuration.vr.objectScaleFactor;
  104614. }
  104615. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(this._vrScale);
  104616. // reposition the object to "float" in front of the user
  104617. this.sceneManager.models[0].rootMesh.position.y += this._vrModelRepositioning;
  104618. this.sceneManager.models[0].rootMesh.rotationQuaternion = null;
  104619. }
  104620. // post processing
  104621. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  104622. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = false;
  104623. this.sceneManager.defaultRenderingPipeline.prepare();
  104624. }
  104625. }
  104626. else {
  104627. if (this.sceneManager.vrHelper) {
  104628. this.sceneManager.vrHelper.exitVR();
  104629. //this.sceneManager.scene.activeCamera = this.sceneManager.camera;
  104630. if (this.sceneManager.models.length) {
  104631. this.sceneManager.models[0].rootMesh.scaling.scaleInPlace(1 / this._vrScale);
  104632. this.sceneManager.models[0].rootMesh.position.y -= this._vrModelRepositioning;
  104633. }
  104634. if (this.sceneManager.environmentHelper) {
  104635. this.sceneManager.environmentHelper.ground && this.sceneManager.environmentHelper.ground.scaling.scaleInPlace(1 / this._vrScale);
  104636. this.sceneManager.environmentHelper.skybox && this.sceneManager.environmentHelper.skybox.scaling.scaleInPlace(1 / this._vrScale);
  104637. }
  104638. // post processing
  104639. if (this.sceneManager.defaultRenderingPipelineEnabled && this.sceneManager.defaultRenderingPipeline) {
  104640. this.sceneManager.defaultRenderingPipeline.imageProcessingEnabled = true;
  104641. this.sceneManager.defaultRenderingPipeline.prepare();
  104642. }
  104643. }
  104644. }
  104645. };
  104646. AbstractViewer.prototype._onConfigurationLoaded = function (configuration) {
  104647. var _this = this;
  104648. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, configuration);
  104649. if (this.configuration.observers) {
  104650. this._configureObservers(this.configuration.observers);
  104651. }
  104652. // TODO remove this after testing, as this is done in the updateCOnfiguration as well.
  104653. if (this.configuration.loaderPlugins) {
  104654. Object.keys(this.configuration.loaderPlugins).forEach((function (name) {
  104655. if (_this.configuration.loaderPlugins && _this.configuration.loaderPlugins[name]) {
  104656. _this.modelLoader.addPlugin(name);
  104657. }
  104658. }));
  104659. }
  104660. this.templateManager = new templateManager_1.TemplateManager(this.containerElement);
  104661. };
  104662. /**
  104663. * Force a single render loop execution.
  104664. */
  104665. AbstractViewer.prototype.forceRender = function () {
  104666. this._render(true);
  104667. };
  104668. /**
  104669. * Takes a screenshot of the scene and returns it as a base64 encoded png.
  104670. * @param callback optional callback that will be triggered when screenshot is done.
  104671. * @param width Optional screenshot width (default to 512).
  104672. * @param height Optional screenshot height (default to 512).
  104673. * @returns a promise with the screenshot data
  104674. */
  104675. AbstractViewer.prototype.takeScreenshot = function (callback, width, height) {
  104676. var _this = this;
  104677. if (width === void 0) { width = 0; }
  104678. if (height === void 0) { height = 0; }
  104679. width = width || this.canvas.clientWidth;
  104680. height = height || this.canvas.clientHeight;
  104681. // Create the screenshot
  104682. return new Promise(function (resolve, reject) {
  104683. try {
  104684. BABYLON.Tools.CreateScreenshot(_this.engine, _this.sceneManager.camera, { width: width, height: height }, function (data) {
  104685. if (callback) {
  104686. callback(data);
  104687. }
  104688. resolve(data);
  104689. });
  104690. }
  104691. catch (e) {
  104692. reject(e);
  104693. }
  104694. });
  104695. };
  104696. /**
  104697. * Update the current viewer configuration with new values.
  104698. * Only provided information will be updated, old configuration values will be kept.
  104699. * If this.configuration was manually changed, you can trigger this function with no parameters,
  104700. * and the entire configuration will be updated.
  104701. * @param newConfiguration the partial configuration to update
  104702. *
  104703. */
  104704. AbstractViewer.prototype.updateConfiguration = function (newConfiguration) {
  104705. var _this = this;
  104706. if (newConfiguration === void 0) { newConfiguration = this.configuration; }
  104707. // update this.configuration with the new data
  104708. this._configurationContainer.configuration = _1.deepmerge(this.configuration || {}, newConfiguration);
  104709. this.sceneManager.updateConfiguration(newConfiguration);
  104710. // observers in configuration
  104711. if (newConfiguration.observers) {
  104712. this._configureObservers(newConfiguration.observers);
  104713. }
  104714. if (newConfiguration.loaderPlugins) {
  104715. Object.keys(newConfiguration.loaderPlugins).forEach((function (name) {
  104716. if (newConfiguration.loaderPlugins && newConfiguration.loaderPlugins[name]) {
  104717. _this.modelLoader.addPlugin(name);
  104718. }
  104719. }));
  104720. }
  104721. };
  104722. /**
  104723. * this is used to register native functions using the configuration object.
  104724. * This will configure the observers.
  104725. * @param observersConfiguration observers configuration
  104726. */
  104727. AbstractViewer.prototype._configureObservers = function (observersConfiguration) {
  104728. if (observersConfiguration.onEngineInit) {
  104729. this.onEngineInitObservable.add(window[observersConfiguration.onEngineInit]);
  104730. }
  104731. else {
  104732. if (observersConfiguration.onEngineInit === '' && this.configuration.observers && this.configuration.observers.onEngineInit) {
  104733. this.onEngineInitObservable.removeCallback(window[this.configuration.observers.onEngineInit]);
  104734. }
  104735. }
  104736. if (observersConfiguration.onSceneInit) {
  104737. this.onSceneInitObservable.add(window[observersConfiguration.onSceneInit]);
  104738. }
  104739. else {
  104740. if (observersConfiguration.onSceneInit === '' && this.configuration.observers && this.configuration.observers.onSceneInit) {
  104741. this.onSceneInitObservable.removeCallback(window[this.configuration.observers.onSceneInit]);
  104742. }
  104743. }
  104744. if (observersConfiguration.onModelLoaded) {
  104745. this.onModelLoadedObservable.add(window[observersConfiguration.onModelLoaded]);
  104746. }
  104747. else {
  104748. if (observersConfiguration.onModelLoaded === '' && this.configuration.observers && this.configuration.observers.onModelLoaded) {
  104749. this.onModelLoadedObservable.removeCallback(window[this.configuration.observers.onModelLoaded]);
  104750. }
  104751. }
  104752. };
  104753. /**
  104754. * Dispoe the entire viewer including the scene and the engine
  104755. */
  104756. AbstractViewer.prototype.dispose = function () {
  104757. if (this._isDisposed) {
  104758. return;
  104759. }
  104760. window.removeEventListener('resize', this._resize);
  104761. if (this.sceneManager) {
  104762. if (this.sceneManager.scene && this.sceneManager.scene.activeCamera) {
  104763. this.sceneManager.scene.activeCamera.detachControl(this.canvas);
  104764. }
  104765. this.sceneManager.dispose();
  104766. }
  104767. this._fpsTimeoutInterval && clearInterval(this._fpsTimeoutInterval);
  104768. this.observablesManager.dispose();
  104769. this.modelLoader.dispose();
  104770. if (this.engine) {
  104771. this.engine.dispose();
  104772. }
  104773. viewerManager_1.viewerManager.removeViewer(this);
  104774. this._isDisposed = true;
  104775. };
  104776. /**
  104777. * This function will execute when the HTML templates finished initializing.
  104778. * It should initialize the engine and continue execution.
  104779. *
  104780. * @returns {Promise<AbstractViewer>} The viewer object will be returned after the object was loaded.
  104781. */
  104782. AbstractViewer.prototype._onTemplatesLoaded = function () {
  104783. return Promise.resolve(this);
  104784. };
  104785. /**
  104786. * This will force the creation of an engine and a scene.
  104787. * It will also load a model if preconfigured.
  104788. * But first - it will load the extendible onTemplateLoaded()!
  104789. */
  104790. AbstractViewer.prototype._onTemplateLoaded = function () {
  104791. var _this = this;
  104792. // check if viewer was disposed right after created
  104793. if (this._isDisposed) {
  104794. return Promise.reject("viewer was disposed");
  104795. }
  104796. return this._onTemplatesLoaded().then(function () {
  104797. var autoLoad = typeof _this.configuration.model === 'string' || (_this.configuration.model && _this.configuration.model.url);
  104798. return _this._initEngine().then(function (engine) {
  104799. return _this.onEngineInitObservable.notifyObserversWithPromise(engine);
  104800. }).then(function () {
  104801. _this._initTelemetryEvents();
  104802. if (autoLoad) {
  104803. return _this.loadModel(_this.configuration.model).catch(function () { }).then(function () { return _this.sceneManager.scene; });
  104804. }
  104805. else {
  104806. return _this.sceneManager.scene || _this.sceneManager.initScene(_this.configuration.scene);
  104807. }
  104808. }).then(function () {
  104809. return _this.onInitDoneObservable.notifyObserversWithPromise(_this);
  104810. }).catch(function (e) {
  104811. babylonjs_1.Tools.Warn(e.toString());
  104812. return _this;
  104813. });
  104814. });
  104815. };
  104816. /**
  104817. * Initialize the engine. Retruns a promise in case async calls are needed.
  104818. *
  104819. * @protected
  104820. * @returns {Promise<Engine>}
  104821. * @memberof Viewer
  104822. */
  104823. AbstractViewer.prototype._initEngine = function () {
  104824. // init custom shaders
  104825. this._injectCustomShaders();
  104826. //let canvasElement = this.templateManager.getCanvas();
  104827. if (!this.canvas) {
  104828. return Promise.reject('Canvas element not found!');
  104829. }
  104830. var config = this.configuration.engine || {};
  104831. // TDO enable further configuration
  104832. // check for webgl2 support, force-disable if needed.
  104833. if (globals_1.viewerGlobals.disableWebGL2Support) {
  104834. config.engineOptions = config.engineOptions || {};
  104835. config.engineOptions.disableWebGL2Support = true;
  104836. }
  104837. this.engine = new babylonjs_1.Engine(this.canvas, !!config.antialiasing, config.engineOptions);
  104838. // Disable manifest checking
  104839. babylonjs_1.Database.IDBStorageEnabled = false;
  104840. if (!config.disableResize) {
  104841. window.addEventListener('resize', this._resize);
  104842. }
  104843. if (this.configuration.engine) {
  104844. if (this.configuration.engine.adaptiveQuality) {
  104845. var scale = Math.max(0.5, 1 / (window.devicePixelRatio || 2));
  104846. this.engine.setHardwareScalingLevel(scale);
  104847. }
  104848. if (this.configuration.engine.hdEnabled) {
  104849. this.toggleHD();
  104850. }
  104851. }
  104852. // create a new template manager for this viewer
  104853. this.sceneManager = new sceneManager_1.SceneManager(this.engine, this._configurationContainer, this.observablesManager);
  104854. return Promise.resolve(this.engine);
  104855. };
  104856. /**
  104857. * Initialize a model loading. The returned object (a ViewerModel object) will be loaded in the background.
  104858. * The difference between this and loadModel is that loadModel will fulfill the promise when the model finished loading.
  104859. *
  104860. * @param modelConfig model configuration to use when loading the model.
  104861. * @param clearScene should the scene be cleared before loading this model
  104862. * @returns a ViewerModel object that is not yet fully loaded.
  104863. */
  104864. AbstractViewer.prototype.initModel = function (modelConfig, clearScene) {
  104865. var _this = this;
  104866. if (clearScene === void 0) { clearScene = true; }
  104867. var configuration;
  104868. if (typeof modelConfig === 'string') {
  104869. configuration = {
  104870. url: modelConfig
  104871. };
  104872. }
  104873. else if (modelConfig instanceof File) {
  104874. configuration = {
  104875. file: modelConfig,
  104876. root: "file:"
  104877. };
  104878. }
  104879. else {
  104880. configuration = modelConfig;
  104881. }
  104882. if (!configuration.url && !configuration.file) {
  104883. throw new Error("no model provided");
  104884. }
  104885. if (clearScene) {
  104886. this.sceneManager.clearScene(true, false);
  104887. }
  104888. //merge the configuration for future models:
  104889. if (this.configuration.model && typeof this.configuration.model === 'object') {
  104890. var globalConfig = _1.deepmerge({}, this.configuration.model);
  104891. configuration = _1.deepmerge(globalConfig, configuration);
  104892. if (modelConfig instanceof File) {
  104893. configuration.file = modelConfig;
  104894. }
  104895. }
  104896. else {
  104897. this.configuration.model = configuration;
  104898. }
  104899. this._isLoading = true;
  104900. var model = this.modelLoader.load(configuration);
  104901. this.lastUsedLoader = model.loader;
  104902. model.onLoadErrorObservable.add(function (errorObject) {
  104903. _this.onModelLoadErrorObservable.notifyObserversWithPromise(errorObject);
  104904. });
  104905. model.onLoadProgressObservable.add(function (progressEvent) {
  104906. _this.onModelLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  104907. });
  104908. this.onLoaderInitObservable.notifyObserversWithPromise(this.lastUsedLoader);
  104909. model.onLoadedObservable.add(function () {
  104910. _this._isLoading = false;
  104911. });
  104912. return model;
  104913. };
  104914. /**
  104915. * load a model using the provided configuration.
  104916. * This function, as opposed to initModel, will return a promise that resolves when the model is loaded, and rejects with error.
  104917. * If you want to attach to the observables of the model, use initModle instead.
  104918. *
  104919. * @param modelConfig the model configuration or URL to load.
  104920. * @param clearScene Should the scene be cleared before loading the model
  104921. * @returns a Promise the fulfills when the model finished loading successfully.
  104922. */
  104923. AbstractViewer.prototype.loadModel = function (modelConfig, clearScene) {
  104924. var _this = this;
  104925. if (clearScene === void 0) { clearScene = true; }
  104926. if (this._isLoading) {
  104927. // We can decide here whether or not to cancel the lst load, but the developer can do that.
  104928. return Promise.reject("another model is curently being loaded.");
  104929. }
  104930. return Promise.resolve(this.sceneManager.scene).then(function (scene) {
  104931. if (!scene)
  104932. return _this.sceneManager.initScene(_this.configuration.scene, _this.configuration.optimizer);
  104933. return scene;
  104934. }).then(function () {
  104935. var model = _this.initModel(modelConfig, clearScene);
  104936. return new Promise(function (resolve, reject) {
  104937. // at this point, configuration.model is an object, not a string
  104938. model.onLoadedObservable.add(function () {
  104939. resolve(model);
  104940. });
  104941. model.onLoadErrorObservable.add(function (error) {
  104942. reject(error);
  104943. });
  104944. });
  104945. });
  104946. };
  104947. AbstractViewer.prototype._initTelemetryEvents = function () {
  104948. var _this = this;
  104949. telemetryManager_1.telemetryManager.broadcast("Engine Capabilities", this.baseId, this.engine.getCaps());
  104950. telemetryManager_1.telemetryManager.broadcast("Platform Details", this.baseId, {
  104951. userAgent: navigator.userAgent,
  104952. platform: navigator.platform
  104953. });
  104954. telemetryManager_1.telemetryManager.flushWebGLErrors(this.engine, this.baseId);
  104955. var trackFPS = function () {
  104956. telemetryManager_1.telemetryManager.broadcast("Current FPS", _this.baseId, { fps: _this.engine.getFps() });
  104957. };
  104958. trackFPS();
  104959. // Track the FPS again after 60 seconds
  104960. this._fpsTimeoutInterval = window.setInterval(trackFPS, 60 * 1000);
  104961. };
  104962. /**
  104963. * Injects all the spectre shader in the babylon shader store
  104964. */
  104965. AbstractViewer.prototype._injectCustomShaders = function () {
  104966. var customShaders = this.configuration.customShaders;
  104967. // Inject all the spectre shader in the babylon shader store.
  104968. if (!customShaders) {
  104969. return;
  104970. }
  104971. if (customShaders.shaders) {
  104972. Object.keys(customShaders.shaders).forEach(function (key) {
  104973. // typescript considers a callback "unsafe", so... '!'
  104974. babylonjs_1.Effect.ShadersStore[key] = customShaders.shaders[key];
  104975. });
  104976. }
  104977. if (customShaders.includes) {
  104978. Object.keys(customShaders.includes).forEach(function (key) {
  104979. // typescript considers a callback "unsafe", so... '!'
  104980. babylonjs_1.Effect.IncludesShadersStore[key] = customShaders.includes[key];
  104981. });
  104982. }
  104983. };
  104984. return AbstractViewer;
  104985. }());
  104986. exports.AbstractViewer = AbstractViewer;
  104987. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3ZpZXdlci92aWV3ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpREFBZ0Q7QUFDaEQseURBQXdEO0FBQ3hELGtEQUE4RDtBQUM5RCx1Q0FBdU07QUFJdk0scURBQW9EO0FBQ3BELG9EQUF5RDtBQUN6RCxpRUFBZ0U7QUFDaEUsK0JBQXVDO0FBQ3ZDLHFFQUFvRTtBQUNwRSxrRkFBaUY7QUFDakYsaUVBQWdFO0FBRWhFOzs7R0FHRztBQUNIO0lBZ0pJLHdCQUFtQixnQkFBNkIsRUFBRSxvQkFBOEM7UUFBOUMscUNBQUEsRUFBQSx5QkFBOEM7UUFBaEcsaUJBc0NDO1FB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FTLENBQUMsR0FBRyxDQUFDLENBQUM7WUFDckUsQ0FBQyxDQUFDLENBQUM7U0FDTjtJQUNMLENBQUM7SUFDTCxxQkFBQztBQUFELENBQUMsQUE3dEJELElBNnRCQztBQTd0QnFCLHdDQUFjIn0=
  104988. /***/ }),
  104989. /* 10 */
  104990. /***/ (function(module, exports, __webpack_require__) {
  104991. "use strict";
  104992. function __export(m) {
  104993. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  104994. }
  104995. Object.defineProperty(exports, "__esModule", { value: true });
  104996. __export(__webpack_require__(11));
  104997. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOzs7OztBQUFBLHFDQUFnQyJ9
  104998. /***/ }),
  104999. /* 11 */
  105000. /***/ (function(module, exports, __webpack_require__) {
  105001. "use strict";
  105002. Object.defineProperty(exports, "__esModule", { value: true });
  105003. function getConfigurationKey(key, configObject) {
  105004. var splits = key.split('.');
  105005. if (splits.length === 0 || !configObject)
  105006. return;
  105007. else if (splits.length === 1) {
  105008. if (configObject[key] !== undefined) {
  105009. return configObject[key];
  105010. }
  105011. }
  105012. else {
  105013. var firstKey = splits.shift();
  105014. return getConfigurationKey(splits.join("."), configObject[firstKey]);
  105015. }
  105016. }
  105017. exports.getConfigurationKey = getConfigurationKey;
  105018. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFHQSw2QkFBb0MsR0FBVyxFQUFFLFlBQWlCO0lBQzlELElBQUksTUFBTSxHQUFHLEdBQUcsQ0FBQyxLQUFLLENBQUMsR0FBRyxDQUFDLENBQUM7SUFFNUIsSUFBSSxNQUFNLENBQUMsTUFBTSxLQUFLLENBQUMsSUFBSSxDQUFDLFlBQVk7UUFBRSxPQUFPO1NBQzVDLElBQUksTUFBTSxDQUFDLE1BQU0sS0FBSyxDQUFDLEVBQUU7UUFDMUIsSUFBSSxZQUFZLENBQUMsR0FBRyxDQUFDLEtBQUssU0FBUyxFQUFFO1lBQ2pDLE9BQU8sWUFBWSxDQUFDLEdBQUcsQ0FBQyxDQUFDO1NBQzVCO0tBQ0o7U0FBTTtRQUNILElBQUksUUFBUSxHQUFHLE1BQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztRQUM5QixPQUFPLG1CQUFtQixDQUFDLE1BQU0sQ0FBQyxJQUFJLENBQUMsR0FBRyxDQUFDLEVBQUUsWUFBWSxDQUFDLFFBQVMsQ0FBQyxDQUFDLENBQUE7S0FDeEU7QUFDTCxDQUFDO0FBWkQsa0RBWUMifQ==
  105019. /***/ }),
  105020. /* 12 */
  105021. /***/ (function(module, exports, __webpack_require__) {
  105022. "use strict";
  105023. Object.defineProperty(exports, "__esModule", { value: true });
  105024. var babylonjs_1 = __webpack_require__(0);
  105025. /**
  105026. * A minimal WebGL cubemap descriptor
  105027. */
  105028. var TextureCube = /** @class */ (function () {
  105029. /**
  105030. * constructor
  105031. * @param internalFormat WebGL pixel format for the texture on the GPU
  105032. * @param type WebGL pixel type of the supplied data and texture on the GPU
  105033. * @param source An array containing mipmap levels of faces, where each mipmap level is an array of faces and each face is a TextureSource object
  105034. */
  105035. function TextureCube(internalFormat, type, source) {
  105036. if (source === void 0) { source = []; }
  105037. this.internalFormat = internalFormat;
  105038. this.type = type;
  105039. this.source = source;
  105040. }
  105041. Object.defineProperty(TextureCube.prototype, "Width", {
  105042. /**
  105043. * Returns the width of a face of the texture or 0 if not available
  105044. */
  105045. get: function () {
  105046. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].width : 0;
  105047. },
  105048. enumerable: true,
  105049. configurable: true
  105050. });
  105051. Object.defineProperty(TextureCube.prototype, "Height", {
  105052. /**
  105053. * Returns the height of a face of the texture or 0 if not available
  105054. */
  105055. get: function () {
  105056. return (this.source && this.source[0] && this.source[0][0]) ? this.source[0][0].height : 0;
  105057. },
  105058. enumerable: true,
  105059. configurable: true
  105060. });
  105061. return TextureCube;
  105062. }());
  105063. exports.TextureCube = TextureCube;
  105064. /**
  105065. * A static class providing methods to aid working with Bablyon textures.
  105066. */
  105067. var TextureUtils = /** @class */ (function () {
  105068. function TextureUtils() {
  105069. }
  105070. /**
  105071. * Returns a BabylonCubeTexture instance from a Spectre texture cube, subject to sampling parameters.
  105072. * If such a texture has already been requested in the past, this texture will be returned, otherwise a new one will be created.
  105073. * The advantage of this is to enable working with texture objects without the need to initialize on the GPU until desired.
  105074. * @param scene A Babylon Scene instance
  105075. * @param textureCube A Spectre TextureCube object
  105076. * @param parameters WebGL texture sampling parameters
  105077. * @param automaticMipmaps Pass true to enable automatic mipmap generation where possible (requires power of images)
  105078. * @param environment Specifies that the texture will be used as an environment
  105079. * @param singleLod Specifies that the texture will be a singleLod (for environment)
  105080. * @return Babylon cube texture
  105081. */
  105082. TextureUtils.GetBabylonCubeTexture = function (scene, textureCube, automaticMipmaps, environment, singleLod) {
  105083. if (environment === void 0) { environment = false; }
  105084. if (singleLod === void 0) { singleLod = false; }
  105085. if (!textureCube)
  105086. throw new Error("no texture cube provided");
  105087. var parameters;
  105088. if (environment) {
  105089. parameters = singleLod ? TextureUtils._EnvironmentSingleMipSampling : TextureUtils._EnvironmentSampling;
  105090. }
  105091. else {
  105092. parameters = {
  105093. magFilter: 9728 /* NEAREST */,
  105094. minFilter: 9728 /* NEAREST */,
  105095. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105096. wrapT: 33071 /* CLAMP_TO_EDGE */
  105097. };
  105098. }
  105099. var key = TextureUtils.BabylonTextureKeyPrefix + parameters.magFilter + '' + parameters.minFilter + '' + parameters.wrapS + '' + parameters.wrapT;
  105100. var babylonTexture = textureCube[key];
  105101. if (!babylonTexture) {
  105102. //initialize babylon texture
  105103. babylonTexture = new babylonjs_1.CubeTexture('', scene);
  105104. if (environment) {
  105105. babylonTexture.lodGenerationOffset = TextureUtils.EnvironmentLODOffset;
  105106. babylonTexture.lodGenerationScale = TextureUtils.EnvironmentLODScale;
  105107. }
  105108. babylonTexture.gammaSpace = false;
  105109. var internalTexture_1 = new babylonjs_1.InternalTexture(scene.getEngine(), babylonjs_1.InternalTexture.DATASOURCE_CUBERAW);
  105110. var glTexture_1 = internalTexture_1._webGLTexture;
  105111. //babylon properties
  105112. internalTexture_1.isCube = true;
  105113. internalTexture_1.generateMipMaps = false;
  105114. babylonTexture._texture = internalTexture_1;
  105115. TextureUtils.ApplySamplingParameters(babylonTexture, parameters);
  105116. var maxMipLevel_1 = automaticMipmaps ? 0 : textureCube.source.length - 1;
  105117. var texturesUploaded_1 = 0;
  105118. var textureComplete = function () {
  105119. return texturesUploaded_1 === ((maxMipLevel_1 + 1) * 6);
  105120. };
  105121. var uploadFace = function (i, level, face) {
  105122. if (!glTexture_1)
  105123. return;
  105124. if (i === 0 && level === 0) {
  105125. internalTexture_1.width = face.width;
  105126. internalTexture_1.height = face.height;
  105127. }
  105128. var gl = (scene.getEngine())._gl;
  105129. gl.bindTexture(gl.TEXTURE_CUBE_MAP, glTexture_1);
  105130. scene.getEngine()._unpackFlipY(false);
  105131. if (face instanceof HTMLElement || face instanceof ImageData) {
  105132. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureCube.internalFormat, textureCube.type, face);
  105133. }
  105134. else {
  105135. var textureData = face;
  105136. gl.texImage2D(gl.TEXTURE_CUBE_MAP_POSITIVE_X + i, level, textureCube.internalFormat, textureData.width, textureData.height, 0, textureData.format, textureCube.type, textureData.data);
  105137. }
  105138. texturesUploaded_1++;
  105139. if (textureComplete()) {
  105140. //generate mipmaps
  105141. if (automaticMipmaps) {
  105142. var w = face.width;
  105143. var h = face.height;
  105144. var isPot = (((w !== 0) && (w & (w - 1))) === 0) && (((h !== 0) && (h & (h - 1))) === 0);
  105145. if (isPot) {
  105146. gl.generateMipmap(gl.TEXTURE_CUBE_MAP);
  105147. }
  105148. }
  105149. // Upload Separate lods in case there is no support for texture lod.
  105150. if (environment && !scene.getEngine().getCaps().textureLOD && !singleLod) {
  105151. var mipSlices = 3;
  105152. for (var i_1 = 0; i_1 < mipSlices; i_1++) {
  105153. var lodKey = TextureUtils.BabylonTextureKeyPrefix + 'lod' + i_1;
  105154. var lod = textureCube[lodKey];
  105155. //initialize lod texture if it doesn't already exist
  105156. if (lod == null && textureCube.Width) {
  105157. //compute LOD from even spacing in smoothness (matching shader calculation)
  105158. var smoothness = i_1 / (mipSlices - 1);
  105159. var roughness = 1 - smoothness;
  105160. var kMinimumVariance = 0.0005;
  105161. var alphaG = roughness * roughness + kMinimumVariance;
  105162. var microsurfaceAverageSlopeTexels = alphaG * textureCube.Width;
  105163. var environmentSpecularLOD = TextureUtils.EnvironmentLODScale * (babylonjs_1.Scalar.Log2(microsurfaceAverageSlopeTexels)) + TextureUtils.EnvironmentLODOffset;
  105164. var maxLODIndex = textureCube.source.length - 1;
  105165. var mipmapIndex = Math.min(Math.max(Math.round(environmentSpecularLOD), 0), maxLODIndex);
  105166. lod = TextureUtils.GetBabylonCubeTexture(scene, new TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */, [textureCube.source[mipmapIndex]]), false, true, true);
  105167. if (i_1 === 0) {
  105168. internalTexture_1._lodTextureLow = lod;
  105169. }
  105170. else if (i_1 === 1) {
  105171. internalTexture_1._lodTextureMid = lod;
  105172. }
  105173. else {
  105174. internalTexture_1._lodTextureHigh = lod;
  105175. }
  105176. textureCube[lodKey] = lod;
  105177. }
  105178. }
  105179. }
  105180. internalTexture_1.isReady = true;
  105181. }
  105182. gl.bindTexture(gl.TEXTURE_CUBE_MAP, null);
  105183. scene.getEngine().resetTextureCache();
  105184. };
  105185. var _loop_1 = function (i) {
  105186. var faces = textureCube.source[i];
  105187. var _loop_2 = function (j) {
  105188. var face = faces[j];
  105189. if (face instanceof HTMLImageElement && !face.complete) {
  105190. face.addEventListener('load', function () {
  105191. uploadFace(j, i, face);
  105192. }, false);
  105193. }
  105194. else {
  105195. uploadFace(j, i, face);
  105196. }
  105197. };
  105198. for (var j = 0; j < faces.length; j++) {
  105199. _loop_2(j);
  105200. }
  105201. };
  105202. for (var i = 0; i <= maxMipLevel_1; i++) {
  105203. _loop_1(i);
  105204. }
  105205. scene.getEngine().resetTextureCache();
  105206. babylonTexture.isReady = function () {
  105207. return textureComplete();
  105208. };
  105209. textureCube[key] = babylonTexture;
  105210. }
  105211. return babylonTexture;
  105212. };
  105213. /**
  105214. * Applies Spectre SamplingParameters to a Babylon texture by directly setting texture parameters on the internal WebGLTexture as well as setting Babylon fields
  105215. * @param babylonTexture Babylon texture to apply texture to (requires the Babylon texture has an initialize _texture field)
  105216. * @param parameters Spectre SamplingParameters to apply
  105217. */
  105218. TextureUtils.ApplySamplingParameters = function (babylonTexture, parameters) {
  105219. var scene = babylonTexture.getScene();
  105220. if (!scene)
  105221. return;
  105222. var gl = (scene.getEngine())._gl;
  105223. var target = babylonTexture.isCube ? gl.TEXTURE_CUBE_MAP : gl.TEXTURE_2D;
  105224. var internalTexture = babylonTexture._texture;
  105225. if (!internalTexture)
  105226. return;
  105227. var glTexture = internalTexture._webGLTexture;
  105228. gl.bindTexture(target, glTexture);
  105229. if (parameters.magFilter != null)
  105230. gl.texParameteri(target, gl.TEXTURE_MAG_FILTER, parameters.magFilter);
  105231. if (parameters.minFilter != null)
  105232. gl.texParameteri(target, gl.TEXTURE_MIN_FILTER, parameters.minFilter);
  105233. if (parameters.wrapS != null)
  105234. gl.texParameteri(target, gl.TEXTURE_WRAP_S, parameters.wrapS);
  105235. if (parameters.wrapT != null)
  105236. gl.texParameteri(target, gl.TEXTURE_WRAP_T, parameters.wrapT);
  105237. //set babylon wrap modes from sampling parameter
  105238. switch (parameters.wrapS) {
  105239. case 10497 /* REPEAT */:
  105240. babylonTexture.wrapU = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  105241. break;
  105242. case 33071 /* CLAMP_TO_EDGE */:
  105243. babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105244. break;
  105245. case 33648 /* MIRRORED_REPEAT */:
  105246. babylonTexture.wrapU = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  105247. break;
  105248. default: babylonTexture.wrapU = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105249. }
  105250. switch (parameters.wrapT) {
  105251. case 10497 /* REPEAT */:
  105252. babylonTexture.wrapV = babylonjs_1.Texture.WRAP_ADDRESSMODE;
  105253. break;
  105254. case 33071 /* CLAMP_TO_EDGE */:
  105255. babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105256. break;
  105257. case 33648 /* MIRRORED_REPEAT */:
  105258. babylonTexture.wrapV = babylonjs_1.Texture.MIRROR_ADDRESSMODE;
  105259. break;
  105260. default: babylonTexture.wrapV = babylonjs_1.Texture.CLAMP_ADDRESSMODE;
  105261. }
  105262. if (parameters.maxAnisotropy != null && parameters.maxAnisotropy > 1) {
  105263. var anisotropicExt = gl.getExtension('EXT_texture_filter_anisotropic');
  105264. if (anisotropicExt) {
  105265. var maxAnisotropicSamples = gl.getParameter(anisotropicExt.MAX_TEXTURE_MAX_ANISOTROPY_EXT);
  105266. var maxAnisotropy = Math.min(parameters.maxAnisotropy, maxAnisotropicSamples);
  105267. gl.texParameterf(target, anisotropicExt.TEXTURE_MAX_ANISOTROPY_EXT, maxAnisotropy);
  105268. babylonTexture.anisotropicFilteringLevel = maxAnisotropy;
  105269. }
  105270. }
  105271. gl.bindTexture(target, null);
  105272. scene.getEngine().resetTextureCache();
  105273. };
  105274. /**
  105275. * A prefix used when storing a babylon texture object reference on a Spectre texture object
  105276. */
  105277. TextureUtils.BabylonTextureKeyPrefix = '__babylonTexture_';
  105278. /**
  105279. * Controls anisotropic filtering for deserialized textures.
  105280. */
  105281. TextureUtils.MaxAnisotropy = 4;
  105282. TextureUtils._EnvironmentSampling = {
  105283. magFilter: 9729 /* LINEAR */,
  105284. minFilter: 9987 /* LINEAR_MIPMAP_LINEAR */,
  105285. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105286. wrapT: 33071 /* CLAMP_TO_EDGE */,
  105287. maxAnisotropy: 1
  105288. };
  105289. TextureUtils._EnvironmentSingleMipSampling = {
  105290. magFilter: 9729 /* LINEAR */,
  105291. minFilter: 9729 /* LINEAR */,
  105292. wrapS: 33071 /* CLAMP_TO_EDGE */,
  105293. wrapT: 33071 /* CLAMP_TO_EDGE */,
  105294. maxAnisotropy: 1
  105295. };
  105296. //from "/Internal/Lighting.EnvironmentFilterScale" in Engine/*/Configuration.cpp
  105297. /**
  105298. * Environment preprocessing dedicated value (Internal Use or Advanced only).
  105299. */
  105300. TextureUtils.EnvironmentLODScale = 0.8;
  105301. /**
  105302. * Environment preprocessing dedicated value (Internal Use or Advanced only)..
  105303. */
  105304. TextureUtils.EnvironmentLODOffset = 1.0;
  105305. return TextureUtils;
  105306. }());
  105307. exports.TextureUtils = TextureUtils;
  105308. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGV4dHVyZS5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3RleHR1cmUudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx1Q0FBOEY7QUFrSTlGOztHQUVHO0FBQ0g7SUFnQkk7Ozs7O09BS0c7SUFDSCxxQkFBbUIsY0FBMkIsRUFBUyxJQUFlLEVBQVMsTUFBd0I7UUFBeEIsdUJBQUEsRUFBQSxXQUF3Qj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UNuRixjQUFjLENBQUMseUJBQXlCLEdBQUcsYUFBYSxDQUFDO2FBQzVEO1NBQ0o7UUFFRCxFQUFFLENBQUMsV0FBVyxDQUFDLE1BQU0sRUFBRSxJQUFJLENBQUMsQ0FBQztRQUM3QixLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsaUJBQWlCLEVBQUUsQ0FBQztJQUMxQyxDQUFDO0lBN05EOztPQUVHO0lBQ1csb0NBQXVCLEdBQUcsbUJBQW1CLENBQUM7SUFFNUQ7O09BRUc7SUFDVywwQkFBYSxHQUFHLENBQUMsQ0FBQztJQXVOakIsaUNBQW9CLEdBQXVCO1FBQ3RELFNBQVMsbUJBQXlCO1FBQ2xDLFNBQVMsaUNBQXVDO1FBQ2hELEtBQUssMkJBQStCO1FBQ3BDLEtBQUssMkJBQStCO1FBQ3BDLGFBQWEsRUFBRSxDQUFDO0tBQ25CLENBQUM7SUFFYSwwQ0FBNkIsR0FBdUI7UUFDL0QsU0FBUyxtQkFBeUI7UUFDbEMsU0FBUyxtQkFBeUI7UUFDbEMsS0FBSywyQkFBK0I7UUFDcEMsS0FBSywyQkFBK0I7UUFDcEMsYUFBYSxFQUFFLENBQUM7S0FDbkIsQ0FBQztJQUVGLGdGQUFnRjtJQUNoRjs7T0FFRztJQUNXLGdDQUFtQixHQUFHLEdBQUcsQ0FBQztJQUN4Qzs7T0FFRztJQUNXLGlDQUFvQixHQUFHLEdBQUcsQ0FBQztJQUM3QyxtQkFBQztDQUFBLEFBMVBELElBMFBDO0FBMVBZLG9DQUFZIn0=
  105309. /***/ }),
  105310. /* 13 */
  105311. /***/ (function(module, exports, __webpack_require__) {
  105312. "use strict";
  105313. Object.defineProperty(exports, "__esModule", { value: true });
  105314. var babylonjs_1 = __webpack_require__(0);
  105315. var babylonjs_loaders_1 = __webpack_require__(14);
  105316. var viewerModel_1 = __webpack_require__(5);
  105317. var _1 = __webpack_require__(55);
  105318. /**
  105319. * An instance of the class is in charge of loading the model correctly.
  105320. * This class will continously be expended with tasks required from the specific loaders Babylon has.
  105321. *
  105322. * A Model loader is unique per (Abstract)Viewer. It is being generated by the viewer
  105323. */
  105324. var ModelLoader = /** @class */ (function () {
  105325. /**
  105326. * Create a new Model loader
  105327. * @param _viewer the viewer using this model loader
  105328. */
  105329. function ModelLoader(_observablesManager, _configurationContainer) {
  105330. this._observablesManager = _observablesManager;
  105331. this._configurationContainer = _configurationContainer;
  105332. this._disposed = false;
  105333. this._loaders = [];
  105334. this._loadId = 0;
  105335. this._plugins = [];
  105336. }
  105337. /**
  105338. * Adds a new plugin to the loader process.
  105339. *
  105340. * @param plugin the plugin name or the plugin itself
  105341. */
  105342. ModelLoader.prototype.addPlugin = function (plugin) {
  105343. var actualPlugin = {};
  105344. if (typeof plugin === 'string') {
  105345. var loadedPlugin = _1.getLoaderPluginByName(plugin);
  105346. if (loadedPlugin) {
  105347. actualPlugin = loadedPlugin;
  105348. }
  105349. }
  105350. else {
  105351. actualPlugin = plugin;
  105352. }
  105353. if (actualPlugin && this._plugins.indexOf(actualPlugin) === -1) {
  105354. this._plugins.push(actualPlugin);
  105355. }
  105356. };
  105357. /**
  105358. * Load a model using predefined configuration
  105359. * @param modelConfiguration the modelConfiguration to use to load the model
  105360. */
  105361. ModelLoader.prototype.load = function (modelConfiguration) {
  105362. var _this = this;
  105363. var model = new viewerModel_1.ViewerModel(this._observablesManager, modelConfiguration, this._configurationContainer);
  105364. model.loadId = this._loadId++;
  105365. if (!modelConfiguration.url) {
  105366. model.state = viewerModel_1.ModelState.ERROR;
  105367. babylonjs_1.Tools.Error("No URL provided");
  105368. return model;
  105369. }
  105370. var base;
  105371. var filename;
  105372. if (modelConfiguration.file) {
  105373. base = "file:";
  105374. filename = modelConfiguration.file;
  105375. }
  105376. else {
  105377. filename = babylonjs_1.Tools.GetFilename(modelConfiguration.url) || modelConfiguration.url;
  105378. base = modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(modelConfiguration.url);
  105379. }
  105380. var plugin = modelConfiguration.loader;
  105381. var scene = model.rootMesh.getScene();
  105382. model.loader = babylonjs_1.SceneLoader.ImportMesh(undefined, base, filename, scene, function (meshes, particleSystems, skeletons, animationGroups) {
  105383. meshes.forEach(function (mesh) {
  105384. babylonjs_1.Tags.AddTagsTo(mesh, "viewerMesh");
  105385. model.addMesh(mesh);
  105386. });
  105387. model.particleSystems = particleSystems;
  105388. model.skeletons = skeletons;
  105389. for (var _i = 0, animationGroups_1 = animationGroups; _i < animationGroups_1.length; _i++) {
  105390. var animationGroup = animationGroups_1[_i];
  105391. model.addAnimationGroup(animationGroup);
  105392. }
  105393. _this._checkAndRun("onLoaded", model);
  105394. scene.executeWhenReady(function () {
  105395. model.onLoadedObservable.notifyObservers(model);
  105396. });
  105397. }, function (progressEvent) {
  105398. _this._checkAndRun("onProgress", progressEvent);
  105399. model.onLoadProgressObservable.notifyObserversWithPromise(progressEvent);
  105400. }, function (scene, m, exception) {
  105401. model.state = viewerModel_1.ModelState.ERROR;
  105402. babylonjs_1.Tools.Error("Load Error: There was an error loading the model. " + m);
  105403. _this._checkAndRun("onError", m, exception);
  105404. model.onLoadErrorObservable.notifyObserversWithPromise({ message: m, exception: exception });
  105405. }, plugin);
  105406. if (model.loader.name === "gltf") {
  105407. var gltfLoader_1 = model.loader;
  105408. gltfLoader_1.animationStartMode = babylonjs_loaders_1.GLTFLoaderAnimationStartMode.NONE;
  105409. gltfLoader_1.compileMaterials = true;
  105410. if (!modelConfiguration.file) {
  105411. gltfLoader_1.rewriteRootURL = function (rootURL, responseURL) {
  105412. return modelConfiguration.root || babylonjs_1.Tools.GetFolderPath(responseURL || modelConfiguration.url || '');
  105413. };
  105414. }
  105415. // if ground is set to "mirror":
  105416. if (this._configurationContainer
  105417. && this._configurationContainer.configuration
  105418. && this._configurationContainer.configuration.ground
  105419. && typeof this._configurationContainer.configuration.ground === 'object'
  105420. && this._configurationContainer.configuration.ground.mirror) {
  105421. gltfLoader_1.useClipPlane = true;
  105422. }
  105423. Object.keys(gltfLoader_1).filter(function (name) { return name.indexOf('on') === 0 && name.indexOf('Observable') !== -1; }).forEach(function (functionName) {
  105424. gltfLoader_1[functionName].add(function (payload) {
  105425. _this._checkAndRun(functionName.replace("Observable", ''), payload);
  105426. });
  105427. });
  105428. gltfLoader_1.onParsedObservable.add(function (data) {
  105429. if (data && data.json && data.json['asset']) {
  105430. model.loadInfo = data.json['asset'];
  105431. }
  105432. });
  105433. gltfLoader_1.onCompleteObservable.add(function () {
  105434. model.loaderDone = true;
  105435. });
  105436. }
  105437. else {
  105438. model.loaderDone = true;
  105439. }
  105440. this._checkAndRun("onInit", model.loader, model);
  105441. this._loaders.push(model.loader);
  105442. return model;
  105443. };
  105444. ModelLoader.prototype.cancelLoad = function (model) {
  105445. var loader = model.loader || this._loaders[model.loadId];
  105446. // ATM only available in the GLTF Loader
  105447. if (loader && loader.name === "gltf") {
  105448. var gltfLoader = loader;
  105449. gltfLoader.dispose();
  105450. model.state = viewerModel_1.ModelState.CANCELED;
  105451. }
  105452. else {
  105453. babylonjs_1.Tools.Warn("This type of loader cannot cancel the request");
  105454. }
  105455. };
  105456. /**
  105457. * dispose the model loader.
  105458. * If loaders are registered and are in the middle of loading, they will be disposed and the request(s) will be cancelled.
  105459. */
  105460. ModelLoader.prototype.dispose = function () {
  105461. this._loaders.forEach(function (loader) {
  105462. if (loader.name === "gltf") {
  105463. loader.dispose();
  105464. }
  105465. });
  105466. this._loaders.length = 0;
  105467. this._disposed = true;
  105468. };
  105469. ModelLoader.prototype._checkAndRun = function (functionName) {
  105470. var _this = this;
  105471. var payload = [];
  105472. for (var _i = 1; _i < arguments.length; _i++) {
  105473. payload[_i - 1] = arguments[_i];
  105474. }
  105475. if (this._disposed)
  105476. return;
  105477. this._plugins.filter(function (p) { return p[functionName]; }).forEach(function (plugin) {
  105478. try {
  105479. plugin[functionName].apply(_this, payload);
  105480. }
  105481. catch (e) { }
  105482. });
  105483. };
  105484. return ModelLoader;
  105485. }());
  105486. exports.ModelLoader = ModelLoader;
  105487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LE9BQU8sQ0FBQyxVQUFBLE1BQU07WUFDeEIsSUFBSSxNQUFNLENBQUMsSUFBSSxLQUFLLE1BQU0sRUFBRTtnQkFDUCxNQUFPLENBQUMsT0FBTyxFQUFFLENBQUM7YUFDdEM7UUFDTCxDQUFDLENBQUMsQ0FBQztRQUNILElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxHQUFHLENBQUMsQ0FBQztRQUN6QixJQUFJLENBQUMsU0FBUyxHQUFHLElBQUksQ0FBQztJQUMxQixDQUFDO0lBRU8sa0NBQVksR0FBcEIsVUFBcUIsWUFBb0I7UUFBekMsaUJBT0M7UUFQMEMsaUJBQXNCO2FBQXRCLFVBQXNCLEVBQXRCLHFCQUFzQixFQUF0QixJQUFzQjtZQUF0QixnQ0FBc0I7O1FBQzdELElBQUksSUFBSSxDQUFDLFNBQVM7WUFBRSxPQUFPO1FBQzNCLElBQUksQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLFVBQUEsQ0FBQyxJQUFJLE9BQUEsQ0FBQyxDQUFDLFlBQVksQ0FBQyxFQUFmLENBQWUsQ0FBQyxDQUFDLE9BQU8sQ0FBQyxVQUFBLE1BQU07WUFDckQsSUFBSTtnQkFDQSxNQUFNLENBQUMsWUFBWSxDQUFDLENBQUMsS0FBSyxDQUFDLEtBQUksRUFBRSxPQUFPLENBQUMsQ0FBQzthQUM3QztZQUFDLE9BQU8sQ0FBQyxFQUFFLEdBQUc7UUFDbkIsQ0FBQyxDQUFDLENBQUE7SUFDTixDQUFDO0lBQ0wsa0JBQUM7QUFBRCxDQUFDLEFBaExELElBZ0xDO0FBaExZLGtDQUFXIn0=
  105488. /***/ }),
  105489. /* 14 */
  105490. /***/ (function(module, exports, __webpack_require__) {
  105491. (function universalModuleDefinition(root, factory) {
  105492. var amdDependencies = [];
  105493. var BABYLON = root.BABYLON || this.BABYLON;
  105494. if(true) {
  105495. BABYLON = BABYLON || __webpack_require__(0);
  105496. module.exports = factory(BABYLON);
  105497. } else if(typeof define === 'function' && define.amd) {
  105498. amdDependencies.push("babylonjs");
  105499. define("babylonjs-loaders", amdDependencies, factory);
  105500. } else if(typeof exports === 'object') {
  105501. BABYLON = BABYLON || require("babylonjs");
  105502. exports["babylonjs-loaders"] = factory(BABYLON);
  105503. } else {
  105504. root["BABYLON"] = factory(BABYLON);
  105505. }
  105506. })(this, function(BABYLON) {
  105507. BABYLON = BABYLON || this.BABYLON;
  105508. 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};
  105509. 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)}}();
  105510. var BABYLON;
  105511. (function (BABYLON) {
  105512. var STLFileLoader = /** @class */ (function () {
  105513. function STLFileLoader() {
  105514. this.solidPattern = /solid (\S*)([\S\s]*)endsolid[ ]*(\S*)/g;
  105515. this.facetsPattern = /facet([\s\S]*?)endfacet/g;
  105516. 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;
  105517. 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;
  105518. this.name = "stl";
  105519. // force data to come in as an ArrayBuffer
  105520. // we'll convert to string if it looks like it's an ASCII .stl
  105521. this.extensions = {
  105522. ".stl": { isBinary: true },
  105523. };
  105524. }
  105525. STLFileLoader.prototype.importMesh = function (meshesNames, scene, data, rootUrl, meshes, particleSystems, skeletons) {
  105526. var matches;
  105527. if (typeof data !== "string") {
  105528. if (this.isBinary(data)) {
  105529. // binary .stl
  105530. var babylonMesh = new BABYLON.Mesh("stlmesh", scene);
  105531. this.parseBinary(babylonMesh, data);
  105532. if (meshes) {
  105533. meshes.push(babylonMesh);
  105534. }
  105535. return true;
  105536. }
  105537. // ASCII .stl
  105538. // convert to string
  105539. var array_buffer = new Uint8Array(data);
  105540. var str = '';
  105541. for (var i = 0; i < data.byteLength; i++) {
  105542. str += String.fromCharCode(array_buffer[i]); // implicitly assumes little-endian
  105543. }
  105544. data = str;
  105545. }
  105546. //if arrived here, data is a string, containing the STLA data.
  105547. while (matches = this.solidPattern.exec(data)) {
  105548. var meshName = matches[1];
  105549. var meshNameFromEnd = matches[3];
  105550. if (meshName != meshNameFromEnd) {
  105551. BABYLON.Tools.Error("Error in STL, solid name != endsolid name");
  105552. return false;
  105553. }
  105554. // check meshesNames
  105555. if (meshesNames && meshName) {
  105556. if (meshesNames instanceof Array) {
  105557. if (!meshesNames.indexOf(meshName)) {
  105558. continue;
  105559. }
  105560. }
  105561. else {
  105562. if (meshName !== meshesNames) {
  105563. continue;
  105564. }
  105565. }
  105566. }
  105567. // stl mesh name can be empty as well
  105568. meshName = meshName || "stlmesh";
  105569. var babylonMesh = new BABYLON.Mesh(meshName, scene);
  105570. this.parseASCII(babylonMesh, matches[2]);
  105571. if (meshes) {
  105572. meshes.push(babylonMesh);
  105573. }
  105574. }
  105575. return true;
  105576. };
  105577. STLFileLoader.prototype.load = function (scene, data, rootUrl) {
  105578. var result = this.importMesh(null, scene, data, rootUrl, null, null, null);
  105579. if (result) {
  105580. scene.createDefaultCameraOrLight();
  105581. }
  105582. return result;
  105583. };
  105584. STLFileLoader.prototype.loadAssetContainer = function (scene, data, rootUrl, onError) {
  105585. var container = new BABYLON.AssetContainer(scene);
  105586. this.importMesh(null, scene, data, rootUrl, container.meshes, null, null);
  105587. container.removeAllFromScene();
  105588. return container;
  105589. };
  105590. STLFileLoader.prototype.isBinary = function (data) {
  105591. // check if file size is correct for binary stl
  105592. var faceSize, nFaces, reader;
  105593. reader = new DataView(data);
  105594. faceSize = (32 / 8 * 3) + ((32 / 8 * 3) * 3) + (16 / 8);
  105595. nFaces = reader.getUint32(80, true);
  105596. if (80 + (32 / 8) + (nFaces * faceSize) === reader.byteLength) {
  105597. return true;
  105598. }
  105599. // check characters higher than ASCII to confirm binary
  105600. var fileLength = reader.byteLength;
  105601. for (var index = 0; index < fileLength; index++) {
  105602. if (reader.getUint8(index) > 127) {
  105603. return true;
  105604. }
  105605. }
  105606. return false;
  105607. };
  105608. STLFileLoader.prototype.parseBinary = function (mesh, data) {
  105609. var reader = new DataView(data);
  105610. var faces = reader.getUint32(80, true);
  105611. var dataOffset = 84;
  105612. var faceLength = 12 * 4 + 2;
  105613. var offset = 0;
  105614. var positions = new Float32Array(faces * 3 * 3);
  105615. var normals = new Float32Array(faces * 3 * 3);
  105616. var indices = new Uint32Array(faces * 3);
  105617. var indicesCount = 0;
  105618. for (var face = 0; face < faces; face++) {
  105619. var start = dataOffset + face * faceLength;
  105620. var normalX = reader.getFloat32(start, true);
  105621. var normalY = reader.getFloat32(start + 4, true);
  105622. var normalZ = reader.getFloat32(start + 8, true);
  105623. for (var i = 1; i <= 3; i++) {
  105624. var vertexstart = start + i * 12;
  105625. // ordering is intentional to match ascii import
  105626. positions[offset] = reader.getFloat32(vertexstart, true);
  105627. positions[offset + 2] = reader.getFloat32(vertexstart + 4, true);
  105628. positions[offset + 1] = reader.getFloat32(vertexstart + 8, true);
  105629. normals[offset] = normalX;
  105630. normals[offset + 2] = normalY;
  105631. normals[offset + 1] = normalZ;
  105632. offset += 3;
  105633. }
  105634. indices[indicesCount] = indicesCount++;
  105635. indices[indicesCount] = indicesCount++;
  105636. indices[indicesCount] = indicesCount++;
  105637. }
  105638. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105639. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105640. mesh.setIndices(indices);
  105641. mesh.computeWorldMatrix(true);
  105642. };
  105643. STLFileLoader.prototype.parseASCII = function (mesh, solidData) {
  105644. var positions = [];
  105645. var normals = [];
  105646. var indices = [];
  105647. var indicesCount = 0;
  105648. //load facets, ignoring loop as the standard doesn't define it can contain more than vertices
  105649. var matches;
  105650. while (matches = this.facetsPattern.exec(solidData)) {
  105651. var facet = matches[1];
  105652. //one normal per face
  105653. var normalMatches = this.normalPattern.exec(facet);
  105654. this.normalPattern.lastIndex = 0;
  105655. if (!normalMatches) {
  105656. continue;
  105657. }
  105658. var normal = [Number(normalMatches[1]), Number(normalMatches[5]), Number(normalMatches[3])];
  105659. var vertexMatch;
  105660. while (vertexMatch = this.vertexPattern.exec(facet)) {
  105661. positions.push(Number(vertexMatch[1]), Number(vertexMatch[5]), Number(vertexMatch[3]));
  105662. normals.push(normal[0], normal[1], normal[2]);
  105663. }
  105664. indices.push(indicesCount++, indicesCount++, indicesCount++);
  105665. this.vertexPattern.lastIndex = 0;
  105666. }
  105667. this.facetsPattern.lastIndex = 0;
  105668. mesh.setVerticesData(BABYLON.VertexBuffer.PositionKind, positions);
  105669. mesh.setVerticesData(BABYLON.VertexBuffer.NormalKind, normals);
  105670. mesh.setIndices(indices);
  105671. mesh.computeWorldMatrix(true);
  105672. };
  105673. return STLFileLoader;
  105674. }());
  105675. BABYLON.STLFileLoader = STLFileLoader;
  105676. if (BABYLON.SceneLoader) {
  105677. BABYLON.SceneLoader.RegisterPlugin(new STLFileLoader());
  105678. }
  105679. })(BABYLON || (BABYLON = {}));
  105680. //# sourceMappingURL=babylon.stlFileLoader.js.map
  105681. var BABYLON;
  105682. (function (BABYLON) {
  105683. /**
  105684. * Class reading and parsing the MTL file bundled with the obj file.
  105685. */
  105686. var MTLFileLoader = /** @class */ (function () {
  105687. function MTLFileLoader() {
  105688. // All material loaded from the mtl will be set here
  105689. this.materials = [];
  105690. }
  105691. /**
  105692. * This function will read the mtl file and create each material described inside
  105693. * This function could be improve by adding :
  105694. * -some component missing (Ni, Tf...)
  105695. * -including the specific options available
  105696. *
  105697. * @param scene
  105698. * @param data
  105699. * @param rootUrl
  105700. */
  105701. MTLFileLoader.prototype.parseMTL = function (scene, data, rootUrl) {
  105702. if (data instanceof ArrayBuffer) {
  105703. return;
  105704. }
  105705. //Split the lines from the file
  105706. var lines = data.split('\n');
  105707. //Space char
  105708. var delimiter_pattern = /\s+/;
  105709. //Array with RGB colors
  105710. var color;
  105711. //New material
  105712. var material = null;
  105713. //Look at each line
  105714. for (var i = 0; i < lines.length; i++) {
  105715. var line = lines[i].trim();
  105716. // Blank line or comment
  105717. if (line.length === 0 || line.charAt(0) === '#') {
  105718. continue;
  105719. }
  105720. //Get the first parameter (keyword)
  105721. var pos = line.indexOf(' ');
  105722. var key = (pos >= 0) ? line.substring(0, pos) : line;
  105723. key = key.toLowerCase();
  105724. //Get the data following the key
  105725. var value = (pos >= 0) ? line.substring(pos + 1).trim() : "";
  105726. //This mtl keyword will create the new material
  105727. if (key === "newmtl") {
  105728. //Check if it is the first material.
  105729. // Materials specifications are described after this keyword.
  105730. if (material) {
  105731. //Add the previous material in the material array.
  105732. this.materials.push(material);
  105733. }
  105734. //Create a new material.
  105735. // value is the name of the material read in the mtl file
  105736. material = new BABYLON.StandardMaterial(value, scene);
  105737. }
  105738. else if (key === "kd" && material) {
  105739. // Diffuse color (color under white light) using RGB values
  105740. //value = "r g b"
  105741. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105742. //color = [r,g,b]
  105743. //Set tghe color into the material
  105744. material.diffuseColor = BABYLON.Color3.FromArray(color);
  105745. }
  105746. else if (key === "ka" && material) {
  105747. // Ambient color (color under shadow) using RGB values
  105748. //value = "r g b"
  105749. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105750. //color = [r,g,b]
  105751. //Set tghe color into the material
  105752. material.ambientColor = BABYLON.Color3.FromArray(color);
  105753. }
  105754. else if (key === "ks" && material) {
  105755. // Specular color (color when light is reflected from shiny surface) using RGB values
  105756. //value = "r g b"
  105757. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105758. //color = [r,g,b]
  105759. //Set the color into the material
  105760. material.specularColor = BABYLON.Color3.FromArray(color);
  105761. }
  105762. else if (key === "ke" && material) {
  105763. // Emissive color using RGB values
  105764. color = value.split(delimiter_pattern, 3).map(parseFloat);
  105765. material.emissiveColor = BABYLON.Color3.FromArray(color);
  105766. }
  105767. else if (key === "ns" && material) {
  105768. //value = "Integer"
  105769. material.specularPower = parseFloat(value);
  105770. }
  105771. else if (key === "d" && material) {
  105772. //d is dissolve for current material. It mean alpha for BABYLON
  105773. material.alpha = parseFloat(value);
  105774. //Texture
  105775. //This part can be improved by adding the possible options of texture
  105776. }
  105777. else if (key === "map_ka" && material) {
  105778. // ambient texture map with a loaded image
  105779. //We must first get the folder of the image
  105780. material.ambientTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105781. }
  105782. else if (key === "map_kd" && material) {
  105783. // Diffuse texture map with a loaded image
  105784. material.diffuseTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105785. }
  105786. else if (key === "map_ks" && material) {
  105787. // Specular texture map with a loaded image
  105788. //We must first get the folder of the image
  105789. material.specularTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105790. }
  105791. else if (key === "map_ns") {
  105792. //Specular
  105793. //Specular highlight component
  105794. //We must first get the folder of the image
  105795. //
  105796. //Not supported by BABYLON
  105797. //
  105798. // continue;
  105799. }
  105800. else if (key === "map_bump" && material) {
  105801. //The bump texture
  105802. material.bumpTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105803. }
  105804. else if (key === "map_d" && material) {
  105805. // The dissolve of the material
  105806. material.opacityTexture = MTLFileLoader._getTexture(rootUrl, value, scene);
  105807. //Options for illumination
  105808. }
  105809. else if (key === "illum") {
  105810. //Illumination
  105811. if (value === "0") {
  105812. //That mean Kd == Kd
  105813. }
  105814. else if (value === "1") {
  105815. //Color on and Ambient on
  105816. }
  105817. else if (value === "2") {
  105818. //Highlight on
  105819. }
  105820. else if (value === "3") {
  105821. //Reflection on and Ray trace on
  105822. }
  105823. else if (value === "4") {
  105824. //Transparency: Glass on, Reflection: Ray trace on
  105825. }
  105826. else if (value === "5") {
  105827. //Reflection: Fresnel on and Ray trace on
  105828. }
  105829. else if (value === "6") {
  105830. //Transparency: Refraction on, Reflection: Fresnel off and Ray trace on
  105831. }
  105832. else if (value === "7") {
  105833. //Transparency: Refraction on, Reflection: Fresnel on and Ray trace on
  105834. }
  105835. else if (value === "8") {
  105836. //Reflection on and Ray trace off
  105837. }
  105838. else if (value === "9") {
  105839. //Transparency: Glass on, Reflection: Ray trace off
  105840. }
  105841. else if (value === "10") {
  105842. //Casts shadows onto invisible surfaces
  105843. }
  105844. }
  105845. else {
  105846. // console.log("Unhandled expression at line : " + i +'\n' + "with value : " + line);
  105847. }
  105848. }
  105849. //At the end of the file, add the last material
  105850. if (material) {
  105851. this.materials.push(material);
  105852. }
  105853. };
  105854. /**
  105855. * Gets the texture for the material.
  105856. *
  105857. * If the material is imported from input file,
  105858. * We sanitize the url to ensure it takes the textre from aside the material.
  105859. *
  105860. * @param rootUrl The root url to load from
  105861. * @param value The value stored in the mtl
  105862. * @return The Texture
  105863. */
  105864. MTLFileLoader._getTexture = function (rootUrl, value, scene) {
  105865. if (!value) {
  105866. return null;
  105867. }
  105868. var url = rootUrl;
  105869. // Load from input file.
  105870. if (rootUrl === "file:") {
  105871. var lastDelimiter = value.lastIndexOf("\\");
  105872. if (lastDelimiter === -1) {
  105873. lastDelimiter = value.lastIndexOf("/");
  105874. }
  105875. if (lastDelimiter > -1) {
  105876. url += value.substr(lastDelimiter + 1);
  105877. }
  105878. else {
  105879. url += value;
  105880. }
  105881. }
  105882. // Not from input file.
  105883. else {
  105884. url += value;
  105885. }
  105886. return new BABYLON.Texture(url, scene);
  105887. };
  105888. return MTLFileLoader;
  105889. }());
  105890. BABYLON.MTLFileLoader = MTLFileLoader;
  105891. var OBJFileLoader = /** @class */ (function () {
  105892. function OBJFileLoader() {
  105893. this.name = "obj";
  105894. this.extensions = ".obj";
  105895. this.obj = /^o/;
  105896. this.group = /^g/;
  105897. this.mtllib = /^mtllib /;
  105898. this.usemtl = /^usemtl /;
  105899. this.smooth = /^s /;
  105900. this.vertexPattern = /v( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105901. // vn float float float
  105902. this.normalPattern = /vn( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105903. // vt float float
  105904. this.uvPattern = /vt( +[\d|\.|\+|\-|e|E]+)( +[\d|\.|\+|\-|e|E]+)/;
  105905. // f vertex vertex vertex ...
  105906. this.facePattern1 = /f\s+(([\d]{1,}[\s]?){3,})+/;
  105907. // f vertex/uvs vertex/uvs vertex/uvs ...
  105908. this.facePattern2 = /f\s+((([\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105909. // f vertex/uvs/normal vertex/uvs/normal vertex/uvs/normal ...
  105910. this.facePattern3 = /f\s+((([\d]{1,}\/[\d]{1,}\/[\d]{1,}[\s]?){3,})+)/;
  105911. // f vertex//normal vertex//normal vertex//normal ...
  105912. this.facePattern4 = /f\s+((([\d]{1,}\/\/[\d]{1,}[\s]?){3,})+)/;
  105913. }
  105914. /**
  105915. * Calls synchronously the MTL file attached to this obj.
  105916. * Load function or importMesh function don't enable to load 2 files in the same time asynchronously.
  105917. * Without this function materials are not displayed in the first frame (but displayed after).
  105918. * In consequence it is impossible to get material information in your HTML file
  105919. *
  105920. * @param url The URL of the MTL file
  105921. * @param rootUrl
  105922. * @param onSuccess Callback function to be called when the MTL file is loaded
  105923. * @private
  105924. */
  105925. OBJFileLoader.prototype._loadMTL = function (url, rootUrl, onSuccess) {
  105926. //The complete path to the mtl file
  105927. var pathOfFile = BABYLON.Tools.BaseUrl + rootUrl + url;
  105928. // Loads through the babylon tools to allow fileInput search.
  105929. BABYLON.Tools.LoadFile(pathOfFile, onSuccess, undefined, undefined, false, function () { console.warn("Error - Unable to load " + pathOfFile); });
  105930. };
  105931. OBJFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  105932. //get the meshes from OBJ file
  105933. return this._parseSolid(meshesNames, scene, data, rootUrl).then(function (meshes) {
  105934. return {
  105935. meshes: meshes,
  105936. particleSystems: [],
  105937. skeletons: [],
  105938. animationGroups: []
  105939. };
  105940. });
  105941. };
  105942. OBJFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  105943. //Get the 3D model
  105944. return this.importMeshAsync(null, scene, data, rootUrl, onProgress).then(function () {
  105945. // return void
  105946. });
  105947. };
  105948. OBJFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  105949. return this.importMeshAsync(null, scene, data, rootUrl).then(function (result) {
  105950. var container = new BABYLON.AssetContainer(scene);
  105951. result.meshes.forEach(function (mesh) { return container.meshes.push(mesh); });
  105952. container.removeAllFromScene();
  105953. return container;
  105954. });
  105955. };
  105956. /**
  105957. * Read the OBJ file and create an Array of meshes.
  105958. * Each mesh contains all information given by the OBJ and the MTL file.
  105959. * i.e. vertices positions and indices, optional normals values, optional UV values, optional material
  105960. *
  105961. * @param meshesNames
  105962. * @param scene BABYLON.Scene The scene where are displayed the data
  105963. * @param data String The content of the obj file
  105964. * @param rootUrl String The path to the folder
  105965. * @returns Array<AbstractMesh>
  105966. * @private
  105967. */
  105968. OBJFileLoader.prototype._parseSolid = function (meshesNames, scene, data, rootUrl) {
  105969. var _this = this;
  105970. var positions = []; //values for the positions of vertices
  105971. var normals = []; //Values for the normals
  105972. var uvs = []; //Values for the textures
  105973. var meshesFromObj = []; //[mesh] Contains all the obj meshes
  105974. var handledMesh; //The current mesh of meshes array
  105975. var indicesForBabylon = []; //The list of indices for VertexData
  105976. var wrappedPositionForBabylon = []; //The list of position in vectors
  105977. var wrappedUvsForBabylon = []; //Array with all value of uvs to match with the indices
  105978. var wrappedNormalsForBabylon = []; //Array with all value of normals to match with the indices
  105979. var tuplePosNorm = []; //Create a tuple with indice of Position, Normal, UV [pos, norm, uvs]
  105980. var curPositionInIndices = 0;
  105981. var hasMeshes = false; //Meshes are defined in the file
  105982. var unwrappedPositionsForBabylon = []; //Value of positionForBabylon w/o Vector3() [x,y,z]
  105983. var unwrappedNormalsForBabylon = []; //Value of normalsForBabylon w/o Vector3() [x,y,z]
  105984. var unwrappedUVForBabylon = []; //Value of uvsForBabylon w/o Vector3() [x,y,z]
  105985. var triangles = []; //Indices from new triangles coming from polygons
  105986. var materialNameFromObj = ""; //The name of the current material
  105987. var fileToLoad = ""; //The name of the mtlFile to load
  105988. var materialsFromMTLFile = new MTLFileLoader();
  105989. var objMeshName = ""; //The name of the current obj mesh
  105990. var increment = 1; //Id for meshes created by the multimaterial
  105991. var isFirstMaterial = true;
  105992. /**
  105993. * Search for obj in the given array.
  105994. * This function is called to check if a couple of data already exists in an array.
  105995. *
  105996. * If found, returns the index of the founded tuple index. Returns -1 if not found
  105997. * @param arr Array<{ normals: Array<number>, idx: Array<number> }>
  105998. * @param obj Array<number>
  105999. * @returns {boolean}
  106000. */
  106001. var isInArray = function (arr, obj) {
  106002. if (!arr[obj[0]])
  106003. arr[obj[0]] = { normals: [], idx: [] };
  106004. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106005. return idx === -1 ? -1 : arr[obj[0]].idx[idx];
  106006. };
  106007. var isInArrayUV = function (arr, obj) {
  106008. if (!arr[obj[0]])
  106009. arr[obj[0]] = { normals: [], idx: [], uv: [] };
  106010. var idx = arr[obj[0]].normals.indexOf(obj[1]);
  106011. if (idx != 1 && (obj[2] == arr[obj[0]].uv[idx])) {
  106012. return arr[obj[0]].idx[idx];
  106013. }
  106014. return -1;
  106015. };
  106016. /**
  106017. * This function set the data for each triangle.
  106018. * Data are position, normals and uvs
  106019. * If a tuple of (position, normal) is not set, add the data into the corresponding array
  106020. * If the tuple already exist, add only their indice
  106021. *
  106022. * @param indicePositionFromObj Integer The index in positions array
  106023. * @param indiceUvsFromObj Integer The index in uvs array
  106024. * @param indiceNormalFromObj Integer The index in normals array
  106025. * @param positionVectorFromOBJ Vector3 The value of position at index objIndice
  106026. * @param textureVectorFromOBJ Vector3 The value of uvs
  106027. * @param normalsVectorFromOBJ Vector3 The value of normals at index objNormale
  106028. */
  106029. var setData = function (indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positionVectorFromOBJ, textureVectorFromOBJ, normalsVectorFromOBJ) {
  106030. //Check if this tuple already exists in the list of tuples
  106031. var _index;
  106032. if (OBJFileLoader.OPTIMIZE_WITH_UV) {
  106033. _index = isInArrayUV(tuplePosNorm, [
  106034. indicePositionFromObj,
  106035. indiceNormalFromObj,
  106036. indiceUvsFromObj
  106037. ]);
  106038. }
  106039. else {
  106040. _index = isInArray(tuplePosNorm, [
  106041. indicePositionFromObj,
  106042. indiceNormalFromObj
  106043. ]);
  106044. }
  106045. //If it not exists
  106046. if (_index == -1) {
  106047. //Add an new indice.
  106048. //The array of indices is only an array with his length equal to the number of triangles - 1.
  106049. //We add vertices data in this order
  106050. indicesForBabylon.push(wrappedPositionForBabylon.length);
  106051. //Push the position of vertice for Babylon
  106052. //Each element is a BABYLON.Vector3(x,y,z)
  106053. wrappedPositionForBabylon.push(positionVectorFromOBJ);
  106054. //Push the uvs for Babylon
  106055. //Each element is a BABYLON.Vector3(u,v)
  106056. wrappedUvsForBabylon.push(textureVectorFromOBJ);
  106057. //Push the normals for Babylon
  106058. //Each element is a BABYLON.Vector3(x,y,z)
  106059. wrappedNormalsForBabylon.push(normalsVectorFromOBJ);
  106060. //Add the tuple in the comparison list
  106061. tuplePosNorm[indicePositionFromObj].normals.push(indiceNormalFromObj);
  106062. tuplePosNorm[indicePositionFromObj].idx.push(curPositionInIndices++);
  106063. if (OBJFileLoader.OPTIMIZE_WITH_UV)
  106064. tuplePosNorm[indicePositionFromObj].uv.push(indiceUvsFromObj);
  106065. }
  106066. else {
  106067. //The tuple already exists
  106068. //Add the index of the already existing tuple
  106069. //At this index we can get the value of position, normal and uvs of vertex
  106070. indicesForBabylon.push(_index);
  106071. }
  106072. };
  106073. /**
  106074. * Transform BABYLON.Vector() object onto 3 digits in an array
  106075. */
  106076. var unwrapData = function () {
  106077. //Every array has the same length
  106078. for (var l = 0; l < wrappedPositionForBabylon.length; l++) {
  106079. //Push the x, y, z values of each element in the unwrapped array
  106080. unwrappedPositionsForBabylon.push(wrappedPositionForBabylon[l].x, wrappedPositionForBabylon[l].y, wrappedPositionForBabylon[l].z);
  106081. unwrappedNormalsForBabylon.push(wrappedNormalsForBabylon[l].x, wrappedNormalsForBabylon[l].y, wrappedNormalsForBabylon[l].z);
  106082. unwrappedUVForBabylon.push(wrappedUvsForBabylon[l].x, wrappedUvsForBabylon[l].y); //z is an optional value not supported by BABYLON
  106083. }
  106084. // Reset arrays for the next new meshes
  106085. wrappedPositionForBabylon = [];
  106086. wrappedNormalsForBabylon = [];
  106087. wrappedUvsForBabylon = [];
  106088. tuplePosNorm = [];
  106089. curPositionInIndices = 0;
  106090. };
  106091. /**
  106092. * Create triangles from polygons by recursion
  106093. * The best to understand how it works is to draw it in the same time you get the recursion.
  106094. * It is important to notice that a triangle is a polygon
  106095. * We get 4 patterns of face defined in OBJ File :
  106096. * facePattern1 = ["1","2","3","4","5","6"]
  106097. * facePattern2 = ["1/1","2/2","3/3","4/4","5/5","6/6"]
  106098. * facePattern3 = ["1/1/1","2/2/2","3/3/3","4/4/4","5/5/5","6/6/6"]
  106099. * facePattern4 = ["1//1","2//2","3//3","4//4","5//5","6//6"]
  106100. * Each pattern is divided by the same method
  106101. * @param face Array[String] The indices of elements
  106102. * @param v Integer The variable to increment
  106103. */
  106104. var getTriangles = function (face, v) {
  106105. //Work for each element of the array
  106106. if (v + 1 < face.length) {
  106107. //Add on the triangle variable the indexes to obtain triangles
  106108. triangles.push(face[0], face[v], face[v + 1]);
  106109. //Incrementation for recursion
  106110. v += 1;
  106111. //Recursion
  106112. getTriangles(face, v);
  106113. }
  106114. //Result obtained after 2 iterations:
  106115. //Pattern1 => triangle = ["1","2","3","1","3","4"];
  106116. //Pattern2 => triangle = ["1/1","2/2","3/3","1/1","3/3","4/4"];
  106117. //Pattern3 => triangle = ["1/1/1","2/2/2","3/3/3","1/1/1","3/3/3","4/4/4"];
  106118. //Pattern4 => triangle = ["1//1","2//2","3//3","1//1","3//3","4//4"];
  106119. };
  106120. /**
  106121. * Create triangles and push the data for each polygon for the pattern 1
  106122. * In this pattern we get vertice positions
  106123. * @param face
  106124. * @param v
  106125. */
  106126. var setDataForCurrentFaceWithPattern1 = function (face, v) {
  106127. //Get the indices of triangles for each polygon
  106128. getTriangles(face, v);
  106129. //For each element in the triangles array.
  106130. //This var could contains 1 to an infinity of triangles
  106131. for (var k = 0; k < triangles.length; k++) {
  106132. // Set position indice
  106133. var indicePositionFromObj = parseInt(triangles[k]) - 1;
  106134. setData(indicePositionFromObj, 0, 0, //In the pattern 1, normals and uvs are not defined
  106135. positions[indicePositionFromObj], //Get the vectors data
  106136. BABYLON.Vector2.Zero(), BABYLON.Vector3.Up() //Create default vectors
  106137. );
  106138. }
  106139. //Reset variable for the next line
  106140. triangles = [];
  106141. };
  106142. /**
  106143. * Create triangles and push the data for each polygon for the pattern 2
  106144. * In this pattern we get vertice positions and uvsu
  106145. * @param face
  106146. * @param v
  106147. */
  106148. var setDataForCurrentFaceWithPattern2 = function (face, v) {
  106149. //Get the indices of triangles for each polygon
  106150. getTriangles(face, v);
  106151. for (var k = 0; k < triangles.length; k++) {
  106152. //triangle[k] = "1/1"
  106153. //Split the data for getting position and uv
  106154. var point = triangles[k].split("/"); // ["1", "1"]
  106155. //Set position indice
  106156. var indicePositionFromObj = parseInt(point[0]) - 1;
  106157. //Set uv indice
  106158. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106159. setData(indicePositionFromObj, indiceUvsFromObj, 0, //Default value for normals
  106160. positions[indicePositionFromObj], //Get the values for each element
  106161. uvs[indiceUvsFromObj], BABYLON.Vector3.Up() //Default value for normals
  106162. );
  106163. }
  106164. //Reset variable for the next line
  106165. triangles = [];
  106166. };
  106167. /**
  106168. * Create triangles and push the data for each polygon for the pattern 3
  106169. * In this pattern we get vertice positions, uvs and normals
  106170. * @param face
  106171. * @param v
  106172. */
  106173. var setDataForCurrentFaceWithPattern3 = function (face, v) {
  106174. //Get the indices of triangles for each polygon
  106175. getTriangles(face, v);
  106176. for (var k = 0; k < triangles.length; k++) {
  106177. //triangle[k] = "1/1/1"
  106178. //Split the data for getting position, uv, and normals
  106179. var point = triangles[k].split("/"); // ["1", "1", "1"]
  106180. // Set position indice
  106181. var indicePositionFromObj = parseInt(point[0]) - 1;
  106182. // Set uv indice
  106183. var indiceUvsFromObj = parseInt(point[1]) - 1;
  106184. // Set normal indice
  106185. var indiceNormalFromObj = parseInt(point[2]) - 1;
  106186. setData(indicePositionFromObj, indiceUvsFromObj, indiceNormalFromObj, positions[indicePositionFromObj], uvs[indiceUvsFromObj], normals[indiceNormalFromObj] //Set the vector for each component
  106187. );
  106188. }
  106189. //Reset variable for the next line
  106190. triangles = [];
  106191. };
  106192. /**
  106193. * Create triangles and push the data for each polygon for the pattern 4
  106194. * In this pattern we get vertice positions and normals
  106195. * @param face
  106196. * @param v
  106197. */
  106198. var setDataForCurrentFaceWithPattern4 = function (face, v) {
  106199. getTriangles(face, v);
  106200. for (var k = 0; k < triangles.length; k++) {
  106201. //triangle[k] = "1//1"
  106202. //Split the data for getting position and normals
  106203. var point = triangles[k].split("//"); // ["1", "1"]
  106204. // We check indices, and normals
  106205. var indicePositionFromObj = parseInt(point[0]) - 1;
  106206. var indiceNormalFromObj = parseInt(point[1]) - 1;
  106207. setData(indicePositionFromObj, 1, //Default value for uv
  106208. indiceNormalFromObj, positions[indicePositionFromObj], //Get each vector of data
  106209. BABYLON.Vector2.Zero(), normals[indiceNormalFromObj]);
  106210. }
  106211. //Reset variable for the next line
  106212. triangles = [];
  106213. };
  106214. var addPreviousObjMesh = function () {
  106215. //Check if it is not the first mesh. Otherwise we don't have data.
  106216. if (meshesFromObj.length > 0) {
  106217. //Get the previous mesh for applying the data about the faces
  106218. //=> in obj file, faces definition append after the name of the mesh
  106219. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106220. //Set the data into Array for the mesh
  106221. unwrapData();
  106222. // Reverse tab. Otherwise face are displayed in the wrong sens
  106223. indicesForBabylon.reverse();
  106224. //Set the information for the mesh
  106225. //Slice the array to avoid rewriting because of the fact this is the same var which be rewrited
  106226. handledMesh.indices = indicesForBabylon.slice();
  106227. handledMesh.positions = unwrappedPositionsForBabylon.slice();
  106228. handledMesh.normals = unwrappedNormalsForBabylon.slice();
  106229. handledMesh.uvs = unwrappedUVForBabylon.slice();
  106230. //Reset the array for the next mesh
  106231. indicesForBabylon = [];
  106232. unwrappedPositionsForBabylon = [];
  106233. unwrappedNormalsForBabylon = [];
  106234. unwrappedUVForBabylon = [];
  106235. }
  106236. };
  106237. //Main function
  106238. //Split the file into lines
  106239. var lines = data.split('\n');
  106240. //Look at each line
  106241. for (var i = 0; i < lines.length; i++) {
  106242. var line = lines[i].trim();
  106243. var result;
  106244. //Comment or newLine
  106245. if (line.length === 0 || line.charAt(0) === '#') {
  106246. continue;
  106247. //Get information about one position possible for the vertices
  106248. }
  106249. else if ((result = this.vertexPattern.exec(line)) !== null) {
  106250. //Create a Vector3 with the position x, y, z
  106251. //Value of result:
  106252. // ["v 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106253. //Add the Vector in the list of positions
  106254. positions.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106255. }
  106256. else if ((result = this.normalPattern.exec(line)) !== null) {
  106257. //Create a Vector3 with the normals x, y, z
  106258. //Value of result
  106259. // ["vn 1.0 2.0 3.0", "1.0", "2.0", "3.0"]
  106260. //Add the Vector in the list of normals
  106261. normals.push(new BABYLON.Vector3(parseFloat(result[1]), parseFloat(result[2]), parseFloat(result[3])));
  106262. }
  106263. else if ((result = this.uvPattern.exec(line)) !== null) {
  106264. //Create a Vector2 with the normals u, v
  106265. //Value of result
  106266. // ["vt 0.1 0.2 0.3", "0.1", "0.2"]
  106267. //Add the Vector in the list of uvs
  106268. uvs.push(new BABYLON.Vector2(parseFloat(result[1]), parseFloat(result[2])));
  106269. //Identify patterns of faces
  106270. //Face could be defined in different type of pattern
  106271. }
  106272. else if ((result = this.facePattern3.exec(line)) !== null) {
  106273. //Value of result:
  106274. //["f 1/1/1 2/2/2 3/3/3", "1/1/1 2/2/2 3/3/3"...]
  106275. //Set the data for this face
  106276. setDataForCurrentFaceWithPattern3(result[1].trim().split(" "), // ["1/1/1", "2/2/2", "3/3/3"]
  106277. 1);
  106278. }
  106279. else if ((result = this.facePattern4.exec(line)) !== null) {
  106280. //Value of result:
  106281. //["f 1//1 2//2 3//3", "1//1 2//2 3//3"...]
  106282. //Set the data for this face
  106283. setDataForCurrentFaceWithPattern4(result[1].trim().split(" "), // ["1//1", "2//2", "3//3"]
  106284. 1);
  106285. }
  106286. else if ((result = this.facePattern2.exec(line)) !== null) {
  106287. //Value of result:
  106288. //["f 1/1 2/2 3/3", "1/1 2/2 3/3"...]
  106289. //Set the data for this face
  106290. setDataForCurrentFaceWithPattern2(result[1].trim().split(" "), // ["1/1", "2/2", "3/3"]
  106291. 1);
  106292. }
  106293. else if ((result = this.facePattern1.exec(line)) !== null) {
  106294. //Value of result
  106295. //["f 1 2 3", "1 2 3"...]
  106296. //Set the data for this face
  106297. setDataForCurrentFaceWithPattern1(result[1].trim().split(" "), // ["1", "2", "3"]
  106298. 1);
  106299. //Define a mesh or an object
  106300. //Each time this keyword is analysed, create a new Object with all data for creating a babylonMesh
  106301. }
  106302. else if (this.group.test(line) || this.obj.test(line)) {
  106303. //Create a new mesh corresponding to the name of the group.
  106304. //Definition of the mesh
  106305. var objMesh =
  106306. //Set the name of the current obj mesh
  106307. {
  106308. name: line.substring(2).trim(),
  106309. indices: undefined,
  106310. positions: undefined,
  106311. normals: undefined,
  106312. uvs: undefined,
  106313. materialName: ""
  106314. };
  106315. addPreviousObjMesh();
  106316. //Push the last mesh created with only the name
  106317. meshesFromObj.push(objMesh);
  106318. //Set this variable to indicate that now meshesFromObj has objects defined inside
  106319. hasMeshes = true;
  106320. isFirstMaterial = true;
  106321. increment = 1;
  106322. //Keyword for applying a material
  106323. }
  106324. else if (this.usemtl.test(line)) {
  106325. //Get the name of the material
  106326. materialNameFromObj = line.substring(7).trim();
  106327. //If this new material is in the same mesh
  106328. if (!isFirstMaterial) {
  106329. //Set the data for the previous mesh
  106330. addPreviousObjMesh();
  106331. //Create a new mesh
  106332. var objMesh =
  106333. //Set the name of the current obj mesh
  106334. {
  106335. name: objMeshName + "_mm" + increment.toString(),
  106336. indices: undefined,
  106337. positions: undefined,
  106338. normals: undefined,
  106339. uvs: undefined,
  106340. materialName: materialNameFromObj
  106341. };
  106342. increment++;
  106343. //If meshes are already defined
  106344. meshesFromObj.push(objMesh);
  106345. }
  106346. //Set the material name if the previous line define a mesh
  106347. if (hasMeshes && isFirstMaterial) {
  106348. //Set the material name to the previous mesh (1 material per mesh)
  106349. meshesFromObj[meshesFromObj.length - 1].materialName = materialNameFromObj;
  106350. isFirstMaterial = false;
  106351. }
  106352. //Keyword for loading the mtl file
  106353. }
  106354. else if (this.mtllib.test(line)) {
  106355. //Get the name of mtl file
  106356. fileToLoad = line.substring(7).trim();
  106357. //Apply smoothing
  106358. }
  106359. else if (this.smooth.test(line)) {
  106360. // smooth shading => apply smoothing
  106361. //Toda y I don't know it work with babylon and with obj.
  106362. //With the obj file an integer is set
  106363. }
  106364. else {
  106365. //If there is another possibility
  106366. console.log("Unhandled expression at line : " + line);
  106367. }
  106368. }
  106369. //At the end of the file, add the last mesh into the meshesFromObj array
  106370. if (hasMeshes) {
  106371. //Set the data for the last mesh
  106372. handledMesh = meshesFromObj[meshesFromObj.length - 1];
  106373. //Reverse indices for displaying faces in the good sens
  106374. indicesForBabylon.reverse();
  106375. //Get the good array
  106376. unwrapData();
  106377. //Set array
  106378. handledMesh.indices = indicesForBabylon;
  106379. handledMesh.positions = unwrappedPositionsForBabylon;
  106380. handledMesh.normals = unwrappedNormalsForBabylon;
  106381. handledMesh.uvs = unwrappedUVForBabylon;
  106382. }
  106383. //If any o or g keyword found, create a mesj with a random id
  106384. if (!hasMeshes) {
  106385. // reverse tab of indices
  106386. indicesForBabylon.reverse();
  106387. //Get positions normals uvs
  106388. unwrapData();
  106389. //Set data for one mesh
  106390. meshesFromObj.push({
  106391. name: BABYLON.Geometry.RandomId(),
  106392. indices: indicesForBabylon,
  106393. positions: unwrappedPositionsForBabylon,
  106394. normals: unwrappedNormalsForBabylon,
  106395. uvs: unwrappedUVForBabylon,
  106396. materialName: materialNameFromObj
  106397. });
  106398. }
  106399. //Create a BABYLON.Mesh list
  106400. var babylonMeshesArray = []; //The mesh for babylon
  106401. var materialToUse = new Array();
  106402. //Set data for each mesh
  106403. for (var j = 0; j < meshesFromObj.length; j++) {
  106404. //check meshesNames (stlFileLoader)
  106405. if (meshesNames && meshesFromObj[j].name) {
  106406. if (meshesNames instanceof Array) {
  106407. if (meshesNames.indexOf(meshesFromObj[j].name) == -1) {
  106408. continue;
  106409. }
  106410. }
  106411. else {
  106412. if (meshesFromObj[j].name !== meshesNames) {
  106413. continue;
  106414. }
  106415. }
  106416. }
  106417. //Get the current mesh
  106418. //Set the data with VertexBuffer for each mesh
  106419. handledMesh = meshesFromObj[j];
  106420. //Create a BABYLON.Mesh with the name of the obj mesh
  106421. var babylonMesh = new BABYLON.Mesh(meshesFromObj[j].name, scene);
  106422. //Push the name of the material to an array
  106423. //This is indispensable for the importMesh function
  106424. materialToUse.push(meshesFromObj[j].materialName);
  106425. var vertexData = new BABYLON.VertexData(); //The container for the values
  106426. //Set the data for the babylonMesh
  106427. vertexData.positions = handledMesh.positions;
  106428. vertexData.normals = handledMesh.normals;
  106429. vertexData.uvs = handledMesh.uvs;
  106430. vertexData.indices = handledMesh.indices;
  106431. //Set the data from the VertexBuffer to the current BABYLON.Mesh
  106432. vertexData.applyToMesh(babylonMesh);
  106433. if (OBJFileLoader.INVERT_Y) {
  106434. babylonMesh.scaling.y *= -1;
  106435. }
  106436. //Push the mesh into an array
  106437. babylonMeshesArray.push(babylonMesh);
  106438. }
  106439. var mtlPromises = [];
  106440. //load the materials
  106441. //Check if we have a file to load
  106442. if (fileToLoad !== "") {
  106443. //Load the file synchronously
  106444. mtlPromises.push(new Promise(function (resolve, reject) {
  106445. _this._loadMTL(fileToLoad, rootUrl, function (dataLoaded) {
  106446. try {
  106447. //Create materials thanks MTLLoader function
  106448. materialsFromMTLFile.parseMTL(scene, dataLoaded, rootUrl);
  106449. //Look at each material loaded in the mtl file
  106450. for (var n = 0; n < materialsFromMTLFile.materials.length; n++) {
  106451. //Three variables to get all meshes with the same material
  106452. var startIndex = 0;
  106453. var _indices = [];
  106454. var _index;
  106455. //The material from MTL file is used in the meshes loaded
  106456. //Push the indice in an array
  106457. //Check if the material is not used for another mesh
  106458. while ((_index = materialToUse.indexOf(materialsFromMTLFile.materials[n].name, startIndex)) > -1) {
  106459. _indices.push(_index);
  106460. startIndex = _index + 1;
  106461. }
  106462. //If the material is not used dispose it
  106463. if (_index == -1 && _indices.length == 0) {
  106464. //If the material is not needed, remove it
  106465. materialsFromMTLFile.materials[n].dispose();
  106466. }
  106467. else {
  106468. for (var o = 0; o < _indices.length; o++) {
  106469. //Apply the material to the BABYLON.Mesh for each mesh with the material
  106470. babylonMeshesArray[_indices[o]].material = materialsFromMTLFile.materials[n];
  106471. }
  106472. }
  106473. }
  106474. resolve();
  106475. }
  106476. catch (e) {
  106477. reject(e);
  106478. }
  106479. });
  106480. }));
  106481. }
  106482. //Return an array with all BABYLON.Mesh
  106483. return Promise.all(mtlPromises).then(function () {
  106484. return babylonMeshesArray;
  106485. });
  106486. };
  106487. OBJFileLoader.OPTIMIZE_WITH_UV = false;
  106488. OBJFileLoader.INVERT_Y = false;
  106489. return OBJFileLoader;
  106490. }());
  106491. BABYLON.OBJFileLoader = OBJFileLoader;
  106492. if (BABYLON.SceneLoader) {
  106493. //Add this loader into the register plugin
  106494. BABYLON.SceneLoader.RegisterPlugin(new OBJFileLoader());
  106495. }
  106496. })(BABYLON || (BABYLON = {}));
  106497. //# sourceMappingURL=babylon.objFileLoader.js.map
  106498. var BABYLON;
  106499. (function (BABYLON) {
  106500. /**
  106501. * Mode that determines the coordinate system to use.
  106502. */
  106503. var GLTFLoaderCoordinateSystemMode;
  106504. (function (GLTFLoaderCoordinateSystemMode) {
  106505. /**
  106506. * Automatically convert the glTF right-handed data to the appropriate system based on the current coordinate system mode of the scene.
  106507. */
  106508. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["AUTO"] = 0] = "AUTO";
  106509. /**
  106510. * Sets the useRightHandedSystem flag on the scene.
  106511. */
  106512. GLTFLoaderCoordinateSystemMode[GLTFLoaderCoordinateSystemMode["FORCE_RIGHT_HANDED"] = 1] = "FORCE_RIGHT_HANDED";
  106513. })(GLTFLoaderCoordinateSystemMode = BABYLON.GLTFLoaderCoordinateSystemMode || (BABYLON.GLTFLoaderCoordinateSystemMode = {}));
  106514. /**
  106515. * Mode that determines what animations will start.
  106516. */
  106517. var GLTFLoaderAnimationStartMode;
  106518. (function (GLTFLoaderAnimationStartMode) {
  106519. /**
  106520. * No animation will start.
  106521. */
  106522. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["NONE"] = 0] = "NONE";
  106523. /**
  106524. * The first animation will start.
  106525. */
  106526. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["FIRST"] = 1] = "FIRST";
  106527. /**
  106528. * All animations will start.
  106529. */
  106530. GLTFLoaderAnimationStartMode[GLTFLoaderAnimationStartMode["ALL"] = 2] = "ALL";
  106531. })(GLTFLoaderAnimationStartMode = BABYLON.GLTFLoaderAnimationStartMode || (BABYLON.GLTFLoaderAnimationStartMode = {}));
  106532. /**
  106533. * Loader state.
  106534. */
  106535. var GLTFLoaderState;
  106536. (function (GLTFLoaderState) {
  106537. /**
  106538. * The asset is loading.
  106539. */
  106540. GLTFLoaderState[GLTFLoaderState["LOADING"] = 0] = "LOADING";
  106541. /**
  106542. * The asset is ready for rendering.
  106543. */
  106544. GLTFLoaderState[GLTFLoaderState["READY"] = 1] = "READY";
  106545. /**
  106546. * The asset is completely loaded.
  106547. */
  106548. GLTFLoaderState[GLTFLoaderState["COMPLETE"] = 2] = "COMPLETE";
  106549. })(GLTFLoaderState = BABYLON.GLTFLoaderState || (BABYLON.GLTFLoaderState = {}));
  106550. /**
  106551. * File loader for loading glTF files into a scene.
  106552. */
  106553. var GLTFFileLoader = /** @class */ (function () {
  106554. function GLTFFileLoader() {
  106555. // #region Common options
  106556. /**
  106557. * Raised when the asset has been parsed
  106558. */
  106559. this.onParsedObservable = new BABYLON.Observable();
  106560. // #endregion
  106561. // #region V2 options
  106562. /**
  106563. * The coordinate system mode. Defaults to AUTO.
  106564. */
  106565. this.coordinateSystemMode = GLTFLoaderCoordinateSystemMode.AUTO;
  106566. /**
  106567. * The animation start mode. Defaults to FIRST.
  106568. */
  106569. this.animationStartMode = GLTFLoaderAnimationStartMode.FIRST;
  106570. /**
  106571. * Defines if the loader should compile materials before raising the success callback. Defaults to false.
  106572. */
  106573. this.compileMaterials = false;
  106574. /**
  106575. * Defines if the loader should also compile materials with clip planes. Defaults to false.
  106576. */
  106577. this.useClipPlane = false;
  106578. /**
  106579. * Defines if the loader should compile shadow generators before raising the success callback. Defaults to false.
  106580. */
  106581. this.compileShadowGenerators = false;
  106582. /**
  106583. * Defines if the Alpha blended materials are only applied as coverage.
  106584. * If false, (default) The luminance of each pixel will reduce its opacity to simulate the behaviour of most physical materials.
  106585. * If true, no extra effects are applied to transparent pixels.
  106586. */
  106587. this.transparencyAsCoverage = false;
  106588. /** @hidden */
  106589. this._normalizeAnimationGroupsToBeginAtZero = true;
  106590. /**
  106591. * Function called before loading a url referenced by the asset.
  106592. */
  106593. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106594. /**
  106595. * Observable raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106596. */
  106597. this.onMeshLoadedObservable = new BABYLON.Observable();
  106598. /**
  106599. * Observable raised when the loader creates a texture after parsing the glTF properties of the texture.
  106600. */
  106601. this.onTextureLoadedObservable = new BABYLON.Observable();
  106602. /**
  106603. * Observable raised when the loader creates a material after parsing the glTF properties of the material.
  106604. */
  106605. this.onMaterialLoadedObservable = new BABYLON.Observable();
  106606. /**
  106607. * Observable raised when the loader creates a camera after parsing the glTF properties of the camera.
  106608. */
  106609. this.onCameraLoadedObservable = new BABYLON.Observable();
  106610. /**
  106611. * Observable raised when the asset is completely loaded, immediately before the loader is disposed.
  106612. * For assets with LODs, raised when all of the LODs are complete.
  106613. * For assets without LODs, raised when the model is complete, immediately after the loader resolves the returned promise.
  106614. */
  106615. this.onCompleteObservable = new BABYLON.Observable();
  106616. /**
  106617. * Observable raised after the loader is disposed.
  106618. */
  106619. this.onDisposeObservable = new BABYLON.Observable();
  106620. /**
  106621. * Observable raised after a loader extension is created.
  106622. * Set additional options for a loader extension in this event.
  106623. */
  106624. this.onExtensionLoadedObservable = new BABYLON.Observable();
  106625. // #endregion
  106626. this._loader = null;
  106627. /**
  106628. * Name of the loader ("gltf")
  106629. */
  106630. this.name = "gltf";
  106631. /**
  106632. * Supported file extensions of the loader (.gltf, .glb)
  106633. */
  106634. this.extensions = {
  106635. ".gltf": { isBinary: false },
  106636. ".glb": { isBinary: true }
  106637. };
  106638. this._logIndentLevel = 0;
  106639. this._loggingEnabled = false;
  106640. /** @hidden */
  106641. this._log = this._logDisabled;
  106642. this._capturePerformanceCounters = false;
  106643. /** @hidden */
  106644. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  106645. /** @hidden */
  106646. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  106647. }
  106648. Object.defineProperty(GLTFFileLoader.prototype, "onParsed", {
  106649. /**
  106650. * Raised when the asset has been parsed
  106651. */
  106652. set: function (callback) {
  106653. if (this._onParsedObserver) {
  106654. this.onParsedObservable.remove(this._onParsedObserver);
  106655. }
  106656. this._onParsedObserver = this.onParsedObservable.add(callback);
  106657. },
  106658. enumerable: true,
  106659. configurable: true
  106660. });
  106661. Object.defineProperty(GLTFFileLoader.prototype, "onMeshLoaded", {
  106662. /**
  106663. * Callback raised when the loader creates a mesh after parsing the glTF properties of the mesh.
  106664. */
  106665. set: function (callback) {
  106666. if (this._onMeshLoadedObserver) {
  106667. this.onMeshLoadedObservable.remove(this._onMeshLoadedObserver);
  106668. }
  106669. this._onMeshLoadedObserver = this.onMeshLoadedObservable.add(callback);
  106670. },
  106671. enumerable: true,
  106672. configurable: true
  106673. });
  106674. Object.defineProperty(GLTFFileLoader.prototype, "onTextureLoaded", {
  106675. /**
  106676. * Callback raised when the loader creates a texture after parsing the glTF properties of the texture.
  106677. */
  106678. set: function (callback) {
  106679. if (this._onTextureLoadedObserver) {
  106680. this.onTextureLoadedObservable.remove(this._onTextureLoadedObserver);
  106681. }
  106682. this._onTextureLoadedObserver = this.onTextureLoadedObservable.add(callback);
  106683. },
  106684. enumerable: true,
  106685. configurable: true
  106686. });
  106687. Object.defineProperty(GLTFFileLoader.prototype, "onMaterialLoaded", {
  106688. /**
  106689. * Callback raised when the loader creates a material after parsing the glTF properties of the material.
  106690. */
  106691. set: function (callback) {
  106692. if (this._onMaterialLoadedObserver) {
  106693. this.onMaterialLoadedObservable.remove(this._onMaterialLoadedObserver);
  106694. }
  106695. this._onMaterialLoadedObserver = this.onMaterialLoadedObservable.add(callback);
  106696. },
  106697. enumerable: true,
  106698. configurable: true
  106699. });
  106700. Object.defineProperty(GLTFFileLoader.prototype, "onCameraLoaded", {
  106701. /**
  106702. * Callback raised when the loader creates a camera after parsing the glTF properties of the camera.
  106703. */
  106704. set: function (callback) {
  106705. if (this._onCameraLoadedObserver) {
  106706. this.onCameraLoadedObservable.remove(this._onCameraLoadedObserver);
  106707. }
  106708. this._onCameraLoadedObserver = this.onCameraLoadedObservable.add(callback);
  106709. },
  106710. enumerable: true,
  106711. configurable: true
  106712. });
  106713. Object.defineProperty(GLTFFileLoader.prototype, "onComplete", {
  106714. /**
  106715. * Callback raised when the asset is completely loaded, immediately before the loader is disposed.
  106716. */
  106717. set: function (callback) {
  106718. if (this._onCompleteObserver) {
  106719. this.onCompleteObservable.remove(this._onCompleteObserver);
  106720. }
  106721. this._onCompleteObserver = this.onCompleteObservable.add(callback);
  106722. },
  106723. enumerable: true,
  106724. configurable: true
  106725. });
  106726. Object.defineProperty(GLTFFileLoader.prototype, "onDispose", {
  106727. /**
  106728. * Callback raised after the loader is disposed.
  106729. */
  106730. set: function (callback) {
  106731. if (this._onDisposeObserver) {
  106732. this.onDisposeObservable.remove(this._onDisposeObserver);
  106733. }
  106734. this._onDisposeObserver = this.onDisposeObservable.add(callback);
  106735. },
  106736. enumerable: true,
  106737. configurable: true
  106738. });
  106739. Object.defineProperty(GLTFFileLoader.prototype, "onExtensionLoaded", {
  106740. /**
  106741. * Callback raised after a loader extension is created.
  106742. */
  106743. set: function (callback) {
  106744. if (this._onExtensionLoadedObserver) {
  106745. this.onExtensionLoadedObservable.remove(this._onExtensionLoadedObserver);
  106746. }
  106747. this._onExtensionLoadedObserver = this.onExtensionLoadedObservable.add(callback);
  106748. },
  106749. enumerable: true,
  106750. configurable: true
  106751. });
  106752. /**
  106753. * Returns a promise that resolves when the asset is completely loaded.
  106754. * @returns a promise that resolves when the asset is completely loaded.
  106755. */
  106756. GLTFFileLoader.prototype.whenCompleteAsync = function () {
  106757. var _this = this;
  106758. return new Promise(function (resolve) {
  106759. _this.onCompleteObservable.addOnce(function () {
  106760. resolve();
  106761. });
  106762. });
  106763. };
  106764. Object.defineProperty(GLTFFileLoader.prototype, "loaderState", {
  106765. /**
  106766. * The loader state or null if the loader is not active.
  106767. */
  106768. get: function () {
  106769. return this._loader ? this._loader.state : null;
  106770. },
  106771. enumerable: true,
  106772. configurable: true
  106773. });
  106774. Object.defineProperty(GLTFFileLoader.prototype, "loggingEnabled", {
  106775. /**
  106776. * Defines if the loader logging is enabled.
  106777. */
  106778. get: function () {
  106779. return this._loggingEnabled;
  106780. },
  106781. set: function (value) {
  106782. if (this._loggingEnabled === value) {
  106783. return;
  106784. }
  106785. this._loggingEnabled = value;
  106786. if (this._loggingEnabled) {
  106787. this._log = this._logEnabled;
  106788. }
  106789. else {
  106790. this._log = this._logDisabled;
  106791. }
  106792. },
  106793. enumerable: true,
  106794. configurable: true
  106795. });
  106796. Object.defineProperty(GLTFFileLoader.prototype, "capturePerformanceCounters", {
  106797. /**
  106798. * Defines if the loader should capture performance counters.
  106799. */
  106800. get: function () {
  106801. return this._capturePerformanceCounters;
  106802. },
  106803. set: function (value) {
  106804. if (this._capturePerformanceCounters === value) {
  106805. return;
  106806. }
  106807. this._capturePerformanceCounters = value;
  106808. if (this._capturePerformanceCounters) {
  106809. this._startPerformanceCounter = this._startPerformanceCounterEnabled;
  106810. this._endPerformanceCounter = this._endPerformanceCounterEnabled;
  106811. }
  106812. else {
  106813. this._startPerformanceCounter = this._startPerformanceCounterDisabled;
  106814. this._endPerformanceCounter = this._endPerformanceCounterDisabled;
  106815. }
  106816. },
  106817. enumerable: true,
  106818. configurable: true
  106819. });
  106820. /**
  106821. * Disposes the loader, releases resources during load, and cancels any outstanding requests.
  106822. */
  106823. GLTFFileLoader.prototype.dispose = function () {
  106824. if (this._loader) {
  106825. this._loader.dispose();
  106826. this._loader = null;
  106827. }
  106828. this._clear();
  106829. this.onDisposeObservable.notifyObservers(undefined);
  106830. this.onDisposeObservable.clear();
  106831. };
  106832. /** @hidden */
  106833. GLTFFileLoader.prototype._clear = function () {
  106834. this.preprocessUrlAsync = function (url) { return Promise.resolve(url); };
  106835. this.onMeshLoadedObservable.clear();
  106836. this.onTextureLoadedObservable.clear();
  106837. this.onMaterialLoadedObservable.clear();
  106838. this.onCameraLoadedObservable.clear();
  106839. this.onCompleteObservable.clear();
  106840. this.onExtensionLoadedObservable.clear();
  106841. };
  106842. /**
  106843. * Imports one or more meshes from the loaded glTF data and adds them to the scene
  106844. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  106845. * @param scene the scene the meshes should be added to
  106846. * @param data the glTF data to load
  106847. * @param rootUrl root url to load from
  106848. * @param onProgress event that fires when loading progress has occured
  106849. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  106850. */
  106851. GLTFFileLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  106852. var _this = this;
  106853. return Promise.resolve().then(function () {
  106854. var loaderData = _this._parse(data);
  106855. _this._loader = _this._getLoader(loaderData);
  106856. return _this._loader.importMeshAsync(meshesNames, scene, loaderData, rootUrl, onProgress);
  106857. });
  106858. };
  106859. /**
  106860. * Imports all objects from the loaded glTF data and adds them to the scene
  106861. * @param scene the scene the objects should be added to
  106862. * @param data the glTF data to load
  106863. * @param rootUrl root url to load from
  106864. * @param onProgress event that fires when loading progress has occured
  106865. * @returns a promise which completes when objects have been loaded to the scene
  106866. */
  106867. GLTFFileLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  106868. var _this = this;
  106869. return Promise.resolve().then(function () {
  106870. var loaderData = _this._parse(data);
  106871. _this._loader = _this._getLoader(loaderData);
  106872. return _this._loader.loadAsync(scene, loaderData, rootUrl, onProgress);
  106873. });
  106874. };
  106875. /**
  106876. * Load into an asset container.
  106877. * @param scene The scene to load into
  106878. * @param data The data to import
  106879. * @param rootUrl The root url for scene and resources
  106880. * @param onProgress The callback when the load progresses
  106881. * @returns The loaded asset container
  106882. */
  106883. GLTFFileLoader.prototype.loadAssetContainerAsync = function (scene, data, rootUrl, onProgress) {
  106884. var _this = this;
  106885. return Promise.resolve().then(function () {
  106886. var loaderData = _this._parse(data);
  106887. _this._loader = _this._getLoader(loaderData);
  106888. return _this._loader.importMeshAsync(null, scene, loaderData, rootUrl, onProgress).then(function (result) {
  106889. var container = new BABYLON.AssetContainer(scene);
  106890. Array.prototype.push.apply(container.meshes, result.meshes);
  106891. Array.prototype.push.apply(container.particleSystems, result.particleSystems);
  106892. Array.prototype.push.apply(container.skeletons, result.skeletons);
  106893. Array.prototype.push.apply(container.animationGroups, result.animationGroups);
  106894. container.removeAllFromScene();
  106895. return container;
  106896. });
  106897. });
  106898. };
  106899. /**
  106900. * If the data string can be loaded directly.
  106901. * @param data string contianing the file data
  106902. * @returns if the data can be loaded directly
  106903. */
  106904. GLTFFileLoader.prototype.canDirectLoad = function (data) {
  106905. return ((data.indexOf("scene") !== -1) && (data.indexOf("node") !== -1));
  106906. };
  106907. /**
  106908. * Instantiates a glTF file loader plugin.
  106909. * @returns the created plugin
  106910. */
  106911. GLTFFileLoader.prototype.createPlugin = function () {
  106912. return new GLTFFileLoader();
  106913. };
  106914. GLTFFileLoader.prototype._parse = function (data) {
  106915. this._startPerformanceCounter("Parse");
  106916. var parsedData;
  106917. if (data instanceof ArrayBuffer) {
  106918. this._log("Parsing binary");
  106919. parsedData = this._parseBinary(data);
  106920. }
  106921. else {
  106922. this._log("Parsing JSON");
  106923. this._log("JSON length: " + data.length);
  106924. parsedData = {
  106925. json: JSON.parse(data),
  106926. bin: null
  106927. };
  106928. }
  106929. this.onParsedObservable.notifyObservers(parsedData);
  106930. this.onParsedObservable.clear();
  106931. this._endPerformanceCounter("Parse");
  106932. return parsedData;
  106933. };
  106934. GLTFFileLoader.prototype._getLoader = function (loaderData) {
  106935. var asset = loaderData.json.asset || {};
  106936. this._log("Asset version: " + asset.version);
  106937. asset.minVersion && this._log("Asset minimum version: " + asset.minVersion);
  106938. asset.generator && this._log("Asset generator: " + asset.generator);
  106939. var version = GLTFFileLoader._parseVersion(asset.version);
  106940. if (!version) {
  106941. throw new Error("Invalid version: " + asset.version);
  106942. }
  106943. if (asset.minVersion !== undefined) {
  106944. var minVersion = GLTFFileLoader._parseVersion(asset.minVersion);
  106945. if (!minVersion) {
  106946. throw new Error("Invalid minimum version: " + asset.minVersion);
  106947. }
  106948. if (GLTFFileLoader._compareVersion(minVersion, { major: 2, minor: 0 }) > 0) {
  106949. throw new Error("Incompatible minimum version: " + asset.minVersion);
  106950. }
  106951. }
  106952. var createLoaders = {
  106953. 1: GLTFFileLoader._CreateGLTFLoaderV1,
  106954. 2: GLTFFileLoader._CreateGLTFLoaderV2
  106955. };
  106956. var createLoader = createLoaders[version.major];
  106957. if (!createLoader) {
  106958. throw new Error("Unsupported version: " + asset.version);
  106959. }
  106960. return createLoader(this);
  106961. };
  106962. GLTFFileLoader.prototype._parseBinary = function (data) {
  106963. var Binary = {
  106964. Magic: 0x46546C67
  106965. };
  106966. this._log("Binary length: " + data.byteLength);
  106967. var binaryReader = new BinaryReader(data);
  106968. var magic = binaryReader.readUint32();
  106969. if (magic !== Binary.Magic) {
  106970. throw new Error("Unexpected magic: " + magic);
  106971. }
  106972. var version = binaryReader.readUint32();
  106973. if (this.loggingEnabled) {
  106974. this._log("Binary version: " + version);
  106975. }
  106976. switch (version) {
  106977. case 1: return this._parseV1(binaryReader);
  106978. case 2: return this._parseV2(binaryReader);
  106979. }
  106980. throw new Error("Unsupported version: " + version);
  106981. };
  106982. GLTFFileLoader.prototype._parseV1 = function (binaryReader) {
  106983. var ContentFormat = {
  106984. JSON: 0
  106985. };
  106986. var length = binaryReader.readUint32();
  106987. if (length != binaryReader.getLength()) {
  106988. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  106989. }
  106990. var contentLength = binaryReader.readUint32();
  106991. var contentFormat = binaryReader.readUint32();
  106992. var content;
  106993. switch (contentFormat) {
  106994. case ContentFormat.JSON: {
  106995. content = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(contentLength)));
  106996. break;
  106997. }
  106998. default: {
  106999. throw new Error("Unexpected content format: " + contentFormat);
  107000. }
  107001. }
  107002. var bytesRemaining = binaryReader.getLength() - binaryReader.getPosition();
  107003. var body = binaryReader.readUint8Array(bytesRemaining);
  107004. return {
  107005. json: content,
  107006. bin: body
  107007. };
  107008. };
  107009. GLTFFileLoader.prototype._parseV2 = function (binaryReader) {
  107010. var ChunkFormat = {
  107011. JSON: 0x4E4F534A,
  107012. BIN: 0x004E4942
  107013. };
  107014. var length = binaryReader.readUint32();
  107015. if (length !== binaryReader.getLength()) {
  107016. throw new Error("Length in header does not match actual data length: " + length + " != " + binaryReader.getLength());
  107017. }
  107018. // JSON chunk
  107019. var chunkLength = binaryReader.readUint32();
  107020. var chunkFormat = binaryReader.readUint32();
  107021. if (chunkFormat !== ChunkFormat.JSON) {
  107022. throw new Error("First chunk format is not JSON");
  107023. }
  107024. var json = JSON.parse(GLTFFileLoader._decodeBufferToText(binaryReader.readUint8Array(chunkLength)));
  107025. // Look for BIN chunk
  107026. var bin = null;
  107027. while (binaryReader.getPosition() < binaryReader.getLength()) {
  107028. var chunkLength_1 = binaryReader.readUint32();
  107029. var chunkFormat_1 = binaryReader.readUint32();
  107030. switch (chunkFormat_1) {
  107031. case ChunkFormat.JSON: {
  107032. throw new Error("Unexpected JSON chunk");
  107033. }
  107034. case ChunkFormat.BIN: {
  107035. bin = binaryReader.readUint8Array(chunkLength_1);
  107036. break;
  107037. }
  107038. default: {
  107039. // ignore unrecognized chunkFormat
  107040. binaryReader.skipBytes(chunkLength_1);
  107041. break;
  107042. }
  107043. }
  107044. }
  107045. return {
  107046. json: json,
  107047. bin: bin
  107048. };
  107049. };
  107050. GLTFFileLoader._parseVersion = function (version) {
  107051. if (version === "1.0" || version === "1.0.1") {
  107052. return {
  107053. major: 1,
  107054. minor: 0
  107055. };
  107056. }
  107057. var match = (version + "").match(/^(\d+)\.(\d+)/);
  107058. if (!match) {
  107059. return null;
  107060. }
  107061. return {
  107062. major: parseInt(match[1]),
  107063. minor: parseInt(match[2])
  107064. };
  107065. };
  107066. GLTFFileLoader._compareVersion = function (a, b) {
  107067. if (a.major > b.major)
  107068. return 1;
  107069. if (a.major < b.major)
  107070. return -1;
  107071. if (a.minor > b.minor)
  107072. return 1;
  107073. if (a.minor < b.minor)
  107074. return -1;
  107075. return 0;
  107076. };
  107077. GLTFFileLoader._decodeBufferToText = function (buffer) {
  107078. var result = "";
  107079. var length = buffer.byteLength;
  107080. for (var i = 0; i < length; i++) {
  107081. result += String.fromCharCode(buffer[i]);
  107082. }
  107083. return result;
  107084. };
  107085. /** @hidden */
  107086. GLTFFileLoader.prototype._logOpen = function (message) {
  107087. this._log(message);
  107088. this._logIndentLevel++;
  107089. };
  107090. /** @hidden */
  107091. GLTFFileLoader.prototype._logClose = function () {
  107092. --this._logIndentLevel;
  107093. };
  107094. GLTFFileLoader.prototype._logEnabled = function (message) {
  107095. var spaces = GLTFFileLoader._logSpaces.substr(0, this._logIndentLevel * 2);
  107096. BABYLON.Tools.Log("" + spaces + message);
  107097. };
  107098. GLTFFileLoader.prototype._logDisabled = function (message) {
  107099. };
  107100. GLTFFileLoader.prototype._startPerformanceCounterEnabled = function (counterName) {
  107101. BABYLON.Tools.StartPerformanceCounter(counterName);
  107102. };
  107103. GLTFFileLoader.prototype._startPerformanceCounterDisabled = function (counterName) {
  107104. };
  107105. GLTFFileLoader.prototype._endPerformanceCounterEnabled = function (counterName) {
  107106. BABYLON.Tools.EndPerformanceCounter(counterName);
  107107. };
  107108. GLTFFileLoader.prototype._endPerformanceCounterDisabled = function (counterName) {
  107109. };
  107110. // #endregion
  107111. // #region V1 options
  107112. /**
  107113. * 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.
  107114. * Textures always loads asynchronously. For example, the success callback can compute the bounding information of the loaded meshes when incremental loading is disabled.
  107115. * Defaults to true.
  107116. * @hidden
  107117. */
  107118. GLTFFileLoader.IncrementalLoading = true;
  107119. /**
  107120. * Set this property to true in order to work with homogeneous coordinates, available with some converters and exporters.
  107121. * Defaults to false. See https://en.wikipedia.org/wiki/Homogeneous_coordinates.
  107122. * @hidden
  107123. */
  107124. GLTFFileLoader.HomogeneousCoordinates = false;
  107125. GLTFFileLoader._logSpaces = " ";
  107126. return GLTFFileLoader;
  107127. }());
  107128. BABYLON.GLTFFileLoader = GLTFFileLoader;
  107129. var BinaryReader = /** @class */ (function () {
  107130. function BinaryReader(arrayBuffer) {
  107131. this._arrayBuffer = arrayBuffer;
  107132. this._dataView = new DataView(arrayBuffer);
  107133. this._byteOffset = 0;
  107134. }
  107135. BinaryReader.prototype.getPosition = function () {
  107136. return this._byteOffset;
  107137. };
  107138. BinaryReader.prototype.getLength = function () {
  107139. return this._arrayBuffer.byteLength;
  107140. };
  107141. BinaryReader.prototype.readUint32 = function () {
  107142. var value = this._dataView.getUint32(this._byteOffset, true);
  107143. this._byteOffset += 4;
  107144. return value;
  107145. };
  107146. BinaryReader.prototype.readUint8Array = function (length) {
  107147. var value = new Uint8Array(this._arrayBuffer, this._byteOffset, length);
  107148. this._byteOffset += length;
  107149. return value;
  107150. };
  107151. BinaryReader.prototype.skipBytes = function (length) {
  107152. this._byteOffset += length;
  107153. };
  107154. return BinaryReader;
  107155. }());
  107156. if (BABYLON.SceneLoader) {
  107157. BABYLON.SceneLoader.RegisterPlugin(new GLTFFileLoader());
  107158. }
  107159. })(BABYLON || (BABYLON = {}));
  107160. //# sourceMappingURL=babylon.glTFFileLoader.js.map
  107161. var BABYLON;
  107162. (function (BABYLON) {
  107163. var GLTF1;
  107164. (function (GLTF1) {
  107165. /**
  107166. * Enums
  107167. */
  107168. var EComponentType;
  107169. (function (EComponentType) {
  107170. EComponentType[EComponentType["BYTE"] = 5120] = "BYTE";
  107171. EComponentType[EComponentType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107172. EComponentType[EComponentType["SHORT"] = 5122] = "SHORT";
  107173. EComponentType[EComponentType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107174. EComponentType[EComponentType["FLOAT"] = 5126] = "FLOAT";
  107175. })(EComponentType = GLTF1.EComponentType || (GLTF1.EComponentType = {}));
  107176. var EShaderType;
  107177. (function (EShaderType) {
  107178. EShaderType[EShaderType["FRAGMENT"] = 35632] = "FRAGMENT";
  107179. EShaderType[EShaderType["VERTEX"] = 35633] = "VERTEX";
  107180. })(EShaderType = GLTF1.EShaderType || (GLTF1.EShaderType = {}));
  107181. var EParameterType;
  107182. (function (EParameterType) {
  107183. EParameterType[EParameterType["BYTE"] = 5120] = "BYTE";
  107184. EParameterType[EParameterType["UNSIGNED_BYTE"] = 5121] = "UNSIGNED_BYTE";
  107185. EParameterType[EParameterType["SHORT"] = 5122] = "SHORT";
  107186. EParameterType[EParameterType["UNSIGNED_SHORT"] = 5123] = "UNSIGNED_SHORT";
  107187. EParameterType[EParameterType["INT"] = 5124] = "INT";
  107188. EParameterType[EParameterType["UNSIGNED_INT"] = 5125] = "UNSIGNED_INT";
  107189. EParameterType[EParameterType["FLOAT"] = 5126] = "FLOAT";
  107190. EParameterType[EParameterType["FLOAT_VEC2"] = 35664] = "FLOAT_VEC2";
  107191. EParameterType[EParameterType["FLOAT_VEC3"] = 35665] = "FLOAT_VEC3";
  107192. EParameterType[EParameterType["FLOAT_VEC4"] = 35666] = "FLOAT_VEC4";
  107193. EParameterType[EParameterType["INT_VEC2"] = 35667] = "INT_VEC2";
  107194. EParameterType[EParameterType["INT_VEC3"] = 35668] = "INT_VEC3";
  107195. EParameterType[EParameterType["INT_VEC4"] = 35669] = "INT_VEC4";
  107196. EParameterType[EParameterType["BOOL"] = 35670] = "BOOL";
  107197. EParameterType[EParameterType["BOOL_VEC2"] = 35671] = "BOOL_VEC2";
  107198. EParameterType[EParameterType["BOOL_VEC3"] = 35672] = "BOOL_VEC3";
  107199. EParameterType[EParameterType["BOOL_VEC4"] = 35673] = "BOOL_VEC4";
  107200. EParameterType[EParameterType["FLOAT_MAT2"] = 35674] = "FLOAT_MAT2";
  107201. EParameterType[EParameterType["FLOAT_MAT3"] = 35675] = "FLOAT_MAT3";
  107202. EParameterType[EParameterType["FLOAT_MAT4"] = 35676] = "FLOAT_MAT4";
  107203. EParameterType[EParameterType["SAMPLER_2D"] = 35678] = "SAMPLER_2D";
  107204. })(EParameterType = GLTF1.EParameterType || (GLTF1.EParameterType = {}));
  107205. var ETextureWrapMode;
  107206. (function (ETextureWrapMode) {
  107207. ETextureWrapMode[ETextureWrapMode["CLAMP_TO_EDGE"] = 33071] = "CLAMP_TO_EDGE";
  107208. ETextureWrapMode[ETextureWrapMode["MIRRORED_REPEAT"] = 33648] = "MIRRORED_REPEAT";
  107209. ETextureWrapMode[ETextureWrapMode["REPEAT"] = 10497] = "REPEAT";
  107210. })(ETextureWrapMode = GLTF1.ETextureWrapMode || (GLTF1.ETextureWrapMode = {}));
  107211. var ETextureFilterType;
  107212. (function (ETextureFilterType) {
  107213. ETextureFilterType[ETextureFilterType["NEAREST"] = 9728] = "NEAREST";
  107214. ETextureFilterType[ETextureFilterType["LINEAR"] = 9728] = "LINEAR";
  107215. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_NEAREST"] = 9984] = "NEAREST_MIPMAP_NEAREST";
  107216. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_NEAREST"] = 9985] = "LINEAR_MIPMAP_NEAREST";
  107217. ETextureFilterType[ETextureFilterType["NEAREST_MIPMAP_LINEAR"] = 9986] = "NEAREST_MIPMAP_LINEAR";
  107218. ETextureFilterType[ETextureFilterType["LINEAR_MIPMAP_LINEAR"] = 9987] = "LINEAR_MIPMAP_LINEAR";
  107219. })(ETextureFilterType = GLTF1.ETextureFilterType || (GLTF1.ETextureFilterType = {}));
  107220. var ETextureFormat;
  107221. (function (ETextureFormat) {
  107222. ETextureFormat[ETextureFormat["ALPHA"] = 6406] = "ALPHA";
  107223. ETextureFormat[ETextureFormat["RGB"] = 6407] = "RGB";
  107224. ETextureFormat[ETextureFormat["RGBA"] = 6408] = "RGBA";
  107225. ETextureFormat[ETextureFormat["LUMINANCE"] = 6409] = "LUMINANCE";
  107226. ETextureFormat[ETextureFormat["LUMINANCE_ALPHA"] = 6410] = "LUMINANCE_ALPHA";
  107227. })(ETextureFormat = GLTF1.ETextureFormat || (GLTF1.ETextureFormat = {}));
  107228. var ECullingType;
  107229. (function (ECullingType) {
  107230. ECullingType[ECullingType["FRONT"] = 1028] = "FRONT";
  107231. ECullingType[ECullingType["BACK"] = 1029] = "BACK";
  107232. ECullingType[ECullingType["FRONT_AND_BACK"] = 1032] = "FRONT_AND_BACK";
  107233. })(ECullingType = GLTF1.ECullingType || (GLTF1.ECullingType = {}));
  107234. var EBlendingFunction;
  107235. (function (EBlendingFunction) {
  107236. EBlendingFunction[EBlendingFunction["ZERO"] = 0] = "ZERO";
  107237. EBlendingFunction[EBlendingFunction["ONE"] = 1] = "ONE";
  107238. EBlendingFunction[EBlendingFunction["SRC_COLOR"] = 768] = "SRC_COLOR";
  107239. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_COLOR"] = 769] = "ONE_MINUS_SRC_COLOR";
  107240. EBlendingFunction[EBlendingFunction["DST_COLOR"] = 774] = "DST_COLOR";
  107241. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_COLOR"] = 775] = "ONE_MINUS_DST_COLOR";
  107242. EBlendingFunction[EBlendingFunction["SRC_ALPHA"] = 770] = "SRC_ALPHA";
  107243. EBlendingFunction[EBlendingFunction["ONE_MINUS_SRC_ALPHA"] = 771] = "ONE_MINUS_SRC_ALPHA";
  107244. EBlendingFunction[EBlendingFunction["DST_ALPHA"] = 772] = "DST_ALPHA";
  107245. EBlendingFunction[EBlendingFunction["ONE_MINUS_DST_ALPHA"] = 773] = "ONE_MINUS_DST_ALPHA";
  107246. EBlendingFunction[EBlendingFunction["CONSTANT_COLOR"] = 32769] = "CONSTANT_COLOR";
  107247. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_COLOR"] = 32770] = "ONE_MINUS_CONSTANT_COLOR";
  107248. EBlendingFunction[EBlendingFunction["CONSTANT_ALPHA"] = 32771] = "CONSTANT_ALPHA";
  107249. EBlendingFunction[EBlendingFunction["ONE_MINUS_CONSTANT_ALPHA"] = 32772] = "ONE_MINUS_CONSTANT_ALPHA";
  107250. EBlendingFunction[EBlendingFunction["SRC_ALPHA_SATURATE"] = 776] = "SRC_ALPHA_SATURATE";
  107251. })(EBlendingFunction = GLTF1.EBlendingFunction || (GLTF1.EBlendingFunction = {}));
  107252. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  107253. })(BABYLON || (BABYLON = {}));
  107254. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  107255. var BABYLON;
  107256. (function (BABYLON) {
  107257. var GLTF1;
  107258. (function (GLTF1) {
  107259. /**
  107260. * Tokenizer. Used for shaders compatibility
  107261. * Automatically map world, view, projection, worldViewProjection, attributes and so on
  107262. */
  107263. var ETokenType;
  107264. (function (ETokenType) {
  107265. ETokenType[ETokenType["IDENTIFIER"] = 1] = "IDENTIFIER";
  107266. ETokenType[ETokenType["UNKNOWN"] = 2] = "UNKNOWN";
  107267. ETokenType[ETokenType["END_OF_INPUT"] = 3] = "END_OF_INPUT";
  107268. })(ETokenType || (ETokenType = {}));
  107269. var Tokenizer = /** @class */ (function () {
  107270. function Tokenizer(toParse) {
  107271. this._pos = 0;
  107272. this.currentToken = ETokenType.UNKNOWN;
  107273. this.currentIdentifier = "";
  107274. this.currentString = "";
  107275. this.isLetterOrDigitPattern = /^[a-zA-Z0-9]+$/;
  107276. this._toParse = toParse;
  107277. this._maxPos = toParse.length;
  107278. }
  107279. Tokenizer.prototype.getNextToken = function () {
  107280. if (this.isEnd())
  107281. return ETokenType.END_OF_INPUT;
  107282. this.currentString = this.read();
  107283. this.currentToken = ETokenType.UNKNOWN;
  107284. if (this.currentString === "_" || this.isLetterOrDigitPattern.test(this.currentString)) {
  107285. this.currentToken = ETokenType.IDENTIFIER;
  107286. this.currentIdentifier = this.currentString;
  107287. while (!this.isEnd() && (this.isLetterOrDigitPattern.test(this.currentString = this.peek()) || this.currentString === "_")) {
  107288. this.currentIdentifier += this.currentString;
  107289. this.forward();
  107290. }
  107291. }
  107292. return this.currentToken;
  107293. };
  107294. Tokenizer.prototype.peek = function () {
  107295. return this._toParse[this._pos];
  107296. };
  107297. Tokenizer.prototype.read = function () {
  107298. return this._toParse[this._pos++];
  107299. };
  107300. Tokenizer.prototype.forward = function () {
  107301. this._pos++;
  107302. };
  107303. Tokenizer.prototype.isEnd = function () {
  107304. return this._pos >= this._maxPos;
  107305. };
  107306. return Tokenizer;
  107307. }());
  107308. /**
  107309. * Values
  107310. */
  107311. var glTFTransforms = ["MODEL", "VIEW", "PROJECTION", "MODELVIEW", "MODELVIEWPROJECTION", "JOINTMATRIX"];
  107312. var babylonTransforms = ["world", "view", "projection", "worldView", "worldViewProjection", "mBones"];
  107313. var glTFAnimationPaths = ["translation", "rotation", "scale"];
  107314. var babylonAnimationPaths = ["position", "rotationQuaternion", "scaling"];
  107315. /**
  107316. * Parse
  107317. */
  107318. var parseBuffers = function (parsedBuffers, gltfRuntime) {
  107319. for (var buf in parsedBuffers) {
  107320. var parsedBuffer = parsedBuffers[buf];
  107321. gltfRuntime.buffers[buf] = parsedBuffer;
  107322. gltfRuntime.buffersCount++;
  107323. }
  107324. };
  107325. var parseShaders = function (parsedShaders, gltfRuntime) {
  107326. for (var sha in parsedShaders) {
  107327. var parsedShader = parsedShaders[sha];
  107328. gltfRuntime.shaders[sha] = parsedShader;
  107329. gltfRuntime.shaderscount++;
  107330. }
  107331. };
  107332. var parseObject = function (parsedObjects, runtimeProperty, gltfRuntime) {
  107333. for (var object in parsedObjects) {
  107334. var parsedObject = parsedObjects[object];
  107335. gltfRuntime[runtimeProperty][object] = parsedObject;
  107336. }
  107337. };
  107338. /**
  107339. * Utils
  107340. */
  107341. var normalizeUVs = function (buffer) {
  107342. if (!buffer) {
  107343. return;
  107344. }
  107345. for (var i = 0; i < buffer.length / 2; i++) {
  107346. buffer[i * 2 + 1] = 1.0 - buffer[i * 2 + 1];
  107347. }
  107348. };
  107349. var getAttribute = function (attributeParameter) {
  107350. if (attributeParameter.semantic === "NORMAL") {
  107351. return "normal";
  107352. }
  107353. else if (attributeParameter.semantic === "POSITION") {
  107354. return "position";
  107355. }
  107356. else if (attributeParameter.semantic === "JOINT") {
  107357. return "matricesIndices";
  107358. }
  107359. else if (attributeParameter.semantic === "WEIGHT") {
  107360. return "matricesWeights";
  107361. }
  107362. else if (attributeParameter.semantic === "COLOR") {
  107363. return "color";
  107364. }
  107365. else if (attributeParameter.semantic && attributeParameter.semantic.indexOf("TEXCOORD_") !== -1) {
  107366. var channel = Number(attributeParameter.semantic.split("_")[1]);
  107367. return "uv" + (channel === 0 ? "" : channel + 1);
  107368. }
  107369. return null;
  107370. };
  107371. /**
  107372. * Loads and creates animations
  107373. */
  107374. var loadAnimations = function (gltfRuntime) {
  107375. for (var anim in gltfRuntime.animations) {
  107376. var animation = gltfRuntime.animations[anim];
  107377. if (!animation.channels || !animation.samplers) {
  107378. continue;
  107379. }
  107380. var lastAnimation = null;
  107381. for (var i = 0; i < animation.channels.length; i++) {
  107382. // Get parameters and load buffers
  107383. var channel = animation.channels[i];
  107384. var sampler = animation.samplers[channel.sampler];
  107385. if (!sampler) {
  107386. continue;
  107387. }
  107388. var inputData = null;
  107389. var outputData = null;
  107390. if (animation.parameters) {
  107391. inputData = animation.parameters[sampler.input];
  107392. outputData = animation.parameters[sampler.output];
  107393. }
  107394. else {
  107395. inputData = sampler.input;
  107396. outputData = sampler.output;
  107397. }
  107398. var bufferInput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[inputData]);
  107399. var bufferOutput = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, gltfRuntime.accessors[outputData]);
  107400. var targetID = channel.target.id;
  107401. var targetNode = gltfRuntime.scene.getNodeByID(targetID);
  107402. if (targetNode === null) {
  107403. targetNode = gltfRuntime.scene.getNodeByName(targetID);
  107404. }
  107405. if (targetNode === null) {
  107406. BABYLON.Tools.Warn("Creating animation named " + anim + ". But cannot find node named " + targetID + " to attach to");
  107407. continue;
  107408. }
  107409. var isBone = targetNode instanceof BABYLON.Bone;
  107410. // Get target path (position, rotation or scaling)
  107411. var targetPath = channel.target.path;
  107412. var targetPathIndex = glTFAnimationPaths.indexOf(targetPath);
  107413. if (targetPathIndex !== -1) {
  107414. targetPath = babylonAnimationPaths[targetPathIndex];
  107415. }
  107416. // Determine animation type
  107417. var animationType = BABYLON.Animation.ANIMATIONTYPE_MATRIX;
  107418. if (!isBone) {
  107419. if (targetPath === "rotationQuaternion") {
  107420. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  107421. targetNode.rotationQuaternion = new BABYLON.Quaternion();
  107422. }
  107423. else {
  107424. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  107425. }
  107426. }
  107427. // Create animation and key frames
  107428. var babylonAnimation = null;
  107429. var keys = [];
  107430. var arrayOffset = 0;
  107431. var modifyKey = false;
  107432. if (isBone && lastAnimation && lastAnimation.getKeys().length === bufferInput.length) {
  107433. babylonAnimation = lastAnimation;
  107434. modifyKey = true;
  107435. }
  107436. if (!modifyKey) {
  107437. babylonAnimation = new BABYLON.Animation(anim, isBone ? "_matrix" : targetPath, 1, animationType, BABYLON.Animation.ANIMATIONLOOPMODE_CYCLE);
  107438. }
  107439. // For each frame
  107440. for (var j = 0; j < bufferInput.length; j++) {
  107441. var value = null;
  107442. if (targetPath === "rotationQuaternion") { // VEC4
  107443. value = BABYLON.Quaternion.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2], bufferOutput[arrayOffset + 3]]);
  107444. arrayOffset += 4;
  107445. }
  107446. else { // Position and scaling are VEC3
  107447. value = BABYLON.Vector3.FromArray([bufferOutput[arrayOffset], bufferOutput[arrayOffset + 1], bufferOutput[arrayOffset + 2]]);
  107448. arrayOffset += 3;
  107449. }
  107450. if (isBone) {
  107451. var bone = targetNode;
  107452. var translation = BABYLON.Vector3.Zero();
  107453. var rotationQuaternion = new BABYLON.Quaternion();
  107454. var scaling = BABYLON.Vector3.Zero();
  107455. // Warning on decompose
  107456. var mat = bone.getBaseMatrix();
  107457. if (modifyKey && lastAnimation) {
  107458. mat = lastAnimation.getKeys()[j].value;
  107459. }
  107460. mat.decompose(scaling, rotationQuaternion, translation);
  107461. if (targetPath === "position") {
  107462. translation = value;
  107463. }
  107464. else if (targetPath === "rotationQuaternion") {
  107465. rotationQuaternion = value;
  107466. }
  107467. else {
  107468. scaling = value;
  107469. }
  107470. value = BABYLON.Matrix.Compose(scaling, rotationQuaternion, translation);
  107471. }
  107472. if (!modifyKey) {
  107473. keys.push({
  107474. frame: bufferInput[j],
  107475. value: value
  107476. });
  107477. }
  107478. else if (lastAnimation) {
  107479. lastAnimation.getKeys()[j].value = value;
  107480. }
  107481. }
  107482. // Finish
  107483. if (!modifyKey && babylonAnimation) {
  107484. babylonAnimation.setKeys(keys);
  107485. targetNode.animations.push(babylonAnimation);
  107486. }
  107487. lastAnimation = babylonAnimation;
  107488. gltfRuntime.scene.stopAnimation(targetNode);
  107489. gltfRuntime.scene.beginAnimation(targetNode, 0, bufferInput[bufferInput.length - 1], true, 1.0);
  107490. }
  107491. }
  107492. };
  107493. /**
  107494. * Returns the bones transformation matrix
  107495. */
  107496. var configureBoneTransformation = function (node) {
  107497. var mat = null;
  107498. if (node.translation || node.rotation || node.scale) {
  107499. var scale = BABYLON.Vector3.FromArray(node.scale || [1, 1, 1]);
  107500. var rotation = BABYLON.Quaternion.FromArray(node.rotation || [0, 0, 0, 1]);
  107501. var position = BABYLON.Vector3.FromArray(node.translation || [0, 0, 0]);
  107502. mat = BABYLON.Matrix.Compose(scale, rotation, position);
  107503. }
  107504. else {
  107505. mat = BABYLON.Matrix.FromArray(node.matrix);
  107506. }
  107507. return mat;
  107508. };
  107509. /**
  107510. * Returns the parent bone
  107511. */
  107512. var getParentBone = function (gltfRuntime, skins, jointName, newSkeleton) {
  107513. // Try to find
  107514. for (var i = 0; i < newSkeleton.bones.length; i++) {
  107515. if (newSkeleton.bones[i].name === jointName) {
  107516. return newSkeleton.bones[i];
  107517. }
  107518. }
  107519. // Not found, search in gltf nodes
  107520. var nodes = gltfRuntime.nodes;
  107521. for (var nde in nodes) {
  107522. var node = nodes[nde];
  107523. if (!node.jointName) {
  107524. continue;
  107525. }
  107526. var children = node.children;
  107527. for (var i = 0; i < children.length; i++) {
  107528. var child = gltfRuntime.nodes[children[i]];
  107529. if (!child.jointName) {
  107530. continue;
  107531. }
  107532. if (child.jointName === jointName) {
  107533. var mat = configureBoneTransformation(node);
  107534. var bone = new BABYLON.Bone(node.name || "", newSkeleton, getParentBone(gltfRuntime, skins, node.jointName, newSkeleton), mat);
  107535. bone.id = nde;
  107536. return bone;
  107537. }
  107538. }
  107539. }
  107540. return null;
  107541. };
  107542. /**
  107543. * Returns the appropriate root node
  107544. */
  107545. var getNodeToRoot = function (nodesToRoot, id) {
  107546. for (var i = 0; i < nodesToRoot.length; i++) {
  107547. var nodeToRoot = nodesToRoot[i];
  107548. for (var j = 0; j < nodeToRoot.node.children.length; j++) {
  107549. var child = nodeToRoot.node.children[j];
  107550. if (child === id) {
  107551. return nodeToRoot.bone;
  107552. }
  107553. }
  107554. }
  107555. return null;
  107556. };
  107557. /**
  107558. * Returns the node with the joint name
  107559. */
  107560. var getJointNode = function (gltfRuntime, jointName) {
  107561. var nodes = gltfRuntime.nodes;
  107562. var node = nodes[jointName];
  107563. if (node) {
  107564. return {
  107565. node: node,
  107566. id: jointName
  107567. };
  107568. }
  107569. for (var nde in nodes) {
  107570. node = nodes[nde];
  107571. if (node.jointName === jointName) {
  107572. return {
  107573. node: node,
  107574. id: nde
  107575. };
  107576. }
  107577. }
  107578. return null;
  107579. };
  107580. /**
  107581. * Checks if a nodes is in joints
  107582. */
  107583. var nodeIsInJoints = function (skins, id) {
  107584. for (var i = 0; i < skins.jointNames.length; i++) {
  107585. if (skins.jointNames[i] === id) {
  107586. return true;
  107587. }
  107588. }
  107589. return false;
  107590. };
  107591. /**
  107592. * Fills the nodes to root for bones and builds hierarchy
  107593. */
  107594. var getNodesToRoot = function (gltfRuntime, newSkeleton, skins, nodesToRoot) {
  107595. // Creates nodes for root
  107596. for (var nde in gltfRuntime.nodes) {
  107597. var node = gltfRuntime.nodes[nde];
  107598. var id = nde;
  107599. if (!node.jointName || nodeIsInJoints(skins, node.jointName)) {
  107600. continue;
  107601. }
  107602. // Create node to root bone
  107603. var mat = configureBoneTransformation(node);
  107604. var bone = new BABYLON.Bone(node.name || "", newSkeleton, null, mat);
  107605. bone.id = id;
  107606. nodesToRoot.push({ bone: bone, node: node, id: id });
  107607. }
  107608. // Parenting
  107609. for (var i = 0; i < nodesToRoot.length; i++) {
  107610. var nodeToRoot = nodesToRoot[i];
  107611. var children = nodeToRoot.node.children;
  107612. for (var j = 0; j < children.length; j++) {
  107613. var child = null;
  107614. for (var k = 0; k < nodesToRoot.length; k++) {
  107615. if (nodesToRoot[k].id === children[j]) {
  107616. child = nodesToRoot[k];
  107617. break;
  107618. }
  107619. }
  107620. if (child) {
  107621. child.bone._parent = nodeToRoot.bone;
  107622. nodeToRoot.bone.children.push(child.bone);
  107623. }
  107624. }
  107625. }
  107626. };
  107627. /**
  107628. * Imports a skeleton
  107629. */
  107630. var importSkeleton = function (gltfRuntime, skins, mesh, newSkeleton, id) {
  107631. if (!newSkeleton) {
  107632. newSkeleton = new BABYLON.Skeleton(skins.name || "", "", gltfRuntime.scene);
  107633. }
  107634. if (!skins.babylonSkeleton) {
  107635. return newSkeleton;
  107636. }
  107637. // Find the root bones
  107638. var nodesToRoot = [];
  107639. var nodesToRootToAdd = [];
  107640. getNodesToRoot(gltfRuntime, newSkeleton, skins, nodesToRoot);
  107641. newSkeleton.bones = [];
  107642. // Joints
  107643. for (var i = 0; i < skins.jointNames.length; i++) {
  107644. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107645. if (!jointNode) {
  107646. continue;
  107647. }
  107648. var node = jointNode.node;
  107649. if (!node) {
  107650. BABYLON.Tools.Warn("Joint named " + skins.jointNames[i] + " does not exist");
  107651. continue;
  107652. }
  107653. var id = jointNode.id;
  107654. // Optimize, if the bone already exists...
  107655. var existingBone = gltfRuntime.scene.getBoneByID(id);
  107656. if (existingBone) {
  107657. newSkeleton.bones.push(existingBone);
  107658. continue;
  107659. }
  107660. // Search for parent bone
  107661. var foundBone = false;
  107662. var parentBone = null;
  107663. for (var j = 0; j < i; j++) {
  107664. var jointNode_1 = getJointNode(gltfRuntime, skins.jointNames[j]);
  107665. if (!jointNode_1) {
  107666. continue;
  107667. }
  107668. var joint = jointNode_1.node;
  107669. if (!joint) {
  107670. BABYLON.Tools.Warn("Joint named " + skins.jointNames[j] + " does not exist when looking for parent");
  107671. continue;
  107672. }
  107673. var children = joint.children;
  107674. if (!children) {
  107675. continue;
  107676. }
  107677. foundBone = false;
  107678. for (var k = 0; k < children.length; k++) {
  107679. if (children[k] === id) {
  107680. parentBone = getParentBone(gltfRuntime, skins, skins.jointNames[j], newSkeleton);
  107681. foundBone = true;
  107682. break;
  107683. }
  107684. }
  107685. if (foundBone) {
  107686. break;
  107687. }
  107688. }
  107689. // Create bone
  107690. var mat = configureBoneTransformation(node);
  107691. if (!parentBone && nodesToRoot.length > 0) {
  107692. parentBone = getNodeToRoot(nodesToRoot, id);
  107693. if (parentBone) {
  107694. if (nodesToRootToAdd.indexOf(parentBone) === -1) {
  107695. nodesToRootToAdd.push(parentBone);
  107696. }
  107697. }
  107698. }
  107699. var bone = new BABYLON.Bone(node.jointName || "", newSkeleton, parentBone, mat);
  107700. bone.id = id;
  107701. }
  107702. // Polish
  107703. var bones = newSkeleton.bones;
  107704. newSkeleton.bones = [];
  107705. for (var i = 0; i < skins.jointNames.length; i++) {
  107706. var jointNode = getJointNode(gltfRuntime, skins.jointNames[i]);
  107707. if (!jointNode) {
  107708. continue;
  107709. }
  107710. for (var j = 0; j < bones.length; j++) {
  107711. if (bones[j].id === jointNode.id) {
  107712. newSkeleton.bones.push(bones[j]);
  107713. break;
  107714. }
  107715. }
  107716. }
  107717. newSkeleton.prepare();
  107718. // Finish
  107719. for (var i = 0; i < nodesToRootToAdd.length; i++) {
  107720. newSkeleton.bones.push(nodesToRootToAdd[i]);
  107721. }
  107722. return newSkeleton;
  107723. };
  107724. /**
  107725. * Imports a mesh and its geometries
  107726. */
  107727. var importMesh = function (gltfRuntime, node, meshes, id, newMesh) {
  107728. if (!newMesh) {
  107729. newMesh = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  107730. newMesh.id = id;
  107731. }
  107732. if (!node.babylonNode) {
  107733. return newMesh;
  107734. }
  107735. var subMaterials = [];
  107736. var vertexData = null;
  107737. var verticesStarts = new Array();
  107738. var verticesCounts = new Array();
  107739. var indexStarts = new Array();
  107740. var indexCounts = new Array();
  107741. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107742. var meshID = meshes[meshIndex];
  107743. var mesh = gltfRuntime.meshes[meshID];
  107744. if (!mesh) {
  107745. continue;
  107746. }
  107747. // Positions, normals and UVs
  107748. for (var i = 0; i < mesh.primitives.length; i++) {
  107749. // Temporary vertex data
  107750. var tempVertexData = new BABYLON.VertexData();
  107751. var primitive = mesh.primitives[i];
  107752. if (primitive.mode !== 4) {
  107753. // continue;
  107754. }
  107755. var attributes = primitive.attributes;
  107756. var accessor = null;
  107757. var buffer = null;
  107758. // Set positions, normal and uvs
  107759. for (var semantic in attributes) {
  107760. // Link accessor and buffer view
  107761. accessor = gltfRuntime.accessors[attributes[semantic]];
  107762. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107763. if (semantic === "NORMAL") {
  107764. tempVertexData.normals = new Float32Array(buffer.length);
  107765. tempVertexData.normals.set(buffer);
  107766. }
  107767. else if (semantic === "POSITION") {
  107768. if (BABYLON.GLTFFileLoader.HomogeneousCoordinates) {
  107769. tempVertexData.positions = new Float32Array(buffer.length - buffer.length / 4);
  107770. for (var j = 0; j < buffer.length; j += 4) {
  107771. tempVertexData.positions[j] = buffer[j];
  107772. tempVertexData.positions[j + 1] = buffer[j + 1];
  107773. tempVertexData.positions[j + 2] = buffer[j + 2];
  107774. }
  107775. }
  107776. else {
  107777. tempVertexData.positions = new Float32Array(buffer.length);
  107778. tempVertexData.positions.set(buffer);
  107779. }
  107780. verticesCounts.push(tempVertexData.positions.length);
  107781. }
  107782. else if (semantic.indexOf("TEXCOORD_") !== -1) {
  107783. var channel = Number(semantic.split("_")[1]);
  107784. var uvKind = BABYLON.VertexBuffer.UVKind + (channel === 0 ? "" : (channel + 1));
  107785. var uvs = new Float32Array(buffer.length);
  107786. uvs.set(buffer);
  107787. normalizeUVs(uvs);
  107788. tempVertexData.set(uvs, uvKind);
  107789. }
  107790. else if (semantic === "JOINT") {
  107791. tempVertexData.matricesIndices = new Float32Array(buffer.length);
  107792. tempVertexData.matricesIndices.set(buffer);
  107793. }
  107794. else if (semantic === "WEIGHT") {
  107795. tempVertexData.matricesWeights = new Float32Array(buffer.length);
  107796. tempVertexData.matricesWeights.set(buffer);
  107797. }
  107798. else if (semantic === "COLOR") {
  107799. tempVertexData.colors = new Float32Array(buffer.length);
  107800. tempVertexData.colors.set(buffer);
  107801. }
  107802. }
  107803. // Indices
  107804. accessor = gltfRuntime.accessors[primitive.indices];
  107805. if (accessor) {
  107806. buffer = GLTF1.GLTFUtils.GetBufferFromAccessor(gltfRuntime, accessor);
  107807. tempVertexData.indices = new Int32Array(buffer.length);
  107808. tempVertexData.indices.set(buffer);
  107809. indexCounts.push(tempVertexData.indices.length);
  107810. }
  107811. else {
  107812. // Set indices on the fly
  107813. var indices = [];
  107814. for (var j = 0; j < tempVertexData.positions.length / 3; j++) {
  107815. indices.push(j);
  107816. }
  107817. tempVertexData.indices = new Int32Array(indices);
  107818. indexCounts.push(tempVertexData.indices.length);
  107819. }
  107820. if (!vertexData) {
  107821. vertexData = tempVertexData;
  107822. }
  107823. else {
  107824. vertexData.merge(tempVertexData);
  107825. }
  107826. // Sub material
  107827. var material_1 = gltfRuntime.scene.getMaterialByID(primitive.material);
  107828. subMaterials.push(material_1 === null ? GLTF1.GLTFUtils.GetDefaultMaterial(gltfRuntime.scene) : material_1);
  107829. // Update vertices start and index start
  107830. verticesStarts.push(verticesStarts.length === 0 ? 0 : verticesStarts[verticesStarts.length - 1] + verticesCounts[verticesCounts.length - 2]);
  107831. indexStarts.push(indexStarts.length === 0 ? 0 : indexStarts[indexStarts.length - 1] + indexCounts[indexCounts.length - 2]);
  107832. }
  107833. }
  107834. var material;
  107835. if (subMaterials.length > 1) {
  107836. material = new BABYLON.MultiMaterial("multimat" + id, gltfRuntime.scene);
  107837. material.subMaterials = subMaterials;
  107838. }
  107839. else {
  107840. material = new BABYLON.StandardMaterial("multimat" + id, gltfRuntime.scene);
  107841. }
  107842. if (subMaterials.length === 1) {
  107843. material = subMaterials[0];
  107844. }
  107845. if (!newMesh.material) {
  107846. newMesh.material = material;
  107847. }
  107848. // Apply geometry
  107849. new BABYLON.Geometry(id, gltfRuntime.scene, vertexData, false, newMesh);
  107850. newMesh.computeWorldMatrix(true);
  107851. // Apply submeshes
  107852. newMesh.subMeshes = [];
  107853. var index = 0;
  107854. for (var meshIndex = 0; meshIndex < meshes.length; meshIndex++) {
  107855. var meshID = meshes[meshIndex];
  107856. var mesh = gltfRuntime.meshes[meshID];
  107857. if (!mesh) {
  107858. continue;
  107859. }
  107860. for (var i = 0; i < mesh.primitives.length; i++) {
  107861. if (mesh.primitives[i].mode !== 4) {
  107862. //continue;
  107863. }
  107864. BABYLON.SubMesh.AddToMesh(index, verticesStarts[index], verticesCounts[index], indexStarts[index], indexCounts[index], newMesh, newMesh, true);
  107865. index++;
  107866. }
  107867. }
  107868. // Finish
  107869. return newMesh;
  107870. };
  107871. /**
  107872. * Configure node transformation from position, rotation and scaling
  107873. */
  107874. var configureNode = function (newNode, position, rotation, scaling) {
  107875. if (newNode.position) {
  107876. newNode.position = position;
  107877. }
  107878. if (newNode.rotationQuaternion || newNode.rotation) {
  107879. newNode.rotationQuaternion = rotation;
  107880. }
  107881. if (newNode.scaling) {
  107882. newNode.scaling = scaling;
  107883. }
  107884. };
  107885. /**
  107886. * Configures node from transformation matrix
  107887. */
  107888. var configureNodeFromMatrix = function (newNode, node, parent) {
  107889. if (node.matrix) {
  107890. var position = new BABYLON.Vector3(0, 0, 0);
  107891. var rotation = new BABYLON.Quaternion();
  107892. var scaling = new BABYLON.Vector3(0, 0, 0);
  107893. var mat = BABYLON.Matrix.FromArray(node.matrix);
  107894. mat.decompose(scaling, rotation, position);
  107895. configureNode(newNode, position, rotation, scaling);
  107896. }
  107897. else if (node.translation && node.rotation && node.scale) {
  107898. configureNode(newNode, BABYLON.Vector3.FromArray(node.translation), BABYLON.Quaternion.FromArray(node.rotation), BABYLON.Vector3.FromArray(node.scale));
  107899. }
  107900. newNode.computeWorldMatrix(true);
  107901. };
  107902. /**
  107903. * Imports a node
  107904. */
  107905. var importNode = function (gltfRuntime, node, id, parent) {
  107906. var lastNode = null;
  107907. if (gltfRuntime.importOnlyMeshes && (node.skin || node.meshes)) {
  107908. if (gltfRuntime.importMeshesNames && gltfRuntime.importMeshesNames.length > 0 && gltfRuntime.importMeshesNames.indexOf(node.name || "") === -1) {
  107909. return null;
  107910. }
  107911. }
  107912. // Meshes
  107913. if (node.skin) {
  107914. if (node.meshes) {
  107915. var skin = gltfRuntime.skins[node.skin];
  107916. var newMesh = importMesh(gltfRuntime, node, node.meshes, id, node.babylonNode);
  107917. newMesh.skeleton = gltfRuntime.scene.getLastSkeletonByID(node.skin);
  107918. if (newMesh.skeleton === null) {
  107919. newMesh.skeleton = importSkeleton(gltfRuntime, skin, newMesh, skin.babylonSkeleton, node.skin);
  107920. if (!skin.babylonSkeleton) {
  107921. skin.babylonSkeleton = newMesh.skeleton;
  107922. }
  107923. }
  107924. lastNode = newMesh;
  107925. }
  107926. }
  107927. else if (node.meshes) {
  107928. /**
  107929. * Improve meshes property
  107930. */
  107931. var newMesh = importMesh(gltfRuntime, node, node.mesh ? [node.mesh] : node.meshes, id, node.babylonNode);
  107932. lastNode = newMesh;
  107933. }
  107934. // Lights
  107935. else if (node.light && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107936. var light = gltfRuntime.lights[node.light];
  107937. if (light) {
  107938. if (light.type === "ambient") {
  107939. var ambienLight = light[light.type];
  107940. var hemiLight = new BABYLON.HemisphericLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107941. hemiLight.name = node.name || "";
  107942. if (ambienLight.color) {
  107943. hemiLight.diffuse = BABYLON.Color3.FromArray(ambienLight.color);
  107944. }
  107945. lastNode = hemiLight;
  107946. }
  107947. else if (light.type === "directional") {
  107948. var directionalLight = light[light.type];
  107949. var dirLight = new BABYLON.DirectionalLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107950. dirLight.name = node.name || "";
  107951. if (directionalLight.color) {
  107952. dirLight.diffuse = BABYLON.Color3.FromArray(directionalLight.color);
  107953. }
  107954. lastNode = dirLight;
  107955. }
  107956. else if (light.type === "point") {
  107957. var pointLight = light[light.type];
  107958. var ptLight = new BABYLON.PointLight(node.light, BABYLON.Vector3.Zero(), gltfRuntime.scene);
  107959. ptLight.name = node.name || "";
  107960. if (pointLight.color) {
  107961. ptLight.diffuse = BABYLON.Color3.FromArray(pointLight.color);
  107962. }
  107963. lastNode = ptLight;
  107964. }
  107965. else if (light.type === "spot") {
  107966. var spotLight = light[light.type];
  107967. var spLight = new BABYLON.SpotLight(node.light, BABYLON.Vector3.Zero(), BABYLON.Vector3.Zero(), 0, 0, gltfRuntime.scene);
  107968. spLight.name = node.name || "";
  107969. if (spotLight.color) {
  107970. spLight.diffuse = BABYLON.Color3.FromArray(spotLight.color);
  107971. }
  107972. if (spotLight.fallOfAngle) {
  107973. spLight.angle = spotLight.fallOfAngle;
  107974. }
  107975. if (spotLight.fallOffExponent) {
  107976. spLight.exponent = spotLight.fallOffExponent;
  107977. }
  107978. lastNode = spLight;
  107979. }
  107980. }
  107981. }
  107982. // Cameras
  107983. else if (node.camera && !node.babylonNode && !gltfRuntime.importOnlyMeshes) {
  107984. var camera = gltfRuntime.cameras[node.camera];
  107985. if (camera) {
  107986. if (camera.type === "orthographic") {
  107987. var orthoCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107988. orthoCamera.name = node.name || "";
  107989. orthoCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  107990. orthoCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107991. lastNode = orthoCamera;
  107992. }
  107993. else if (camera.type === "perspective") {
  107994. var perspectiveCamera = camera[camera.type];
  107995. var persCamera = new BABYLON.FreeCamera(node.camera, BABYLON.Vector3.Zero(), gltfRuntime.scene, false);
  107996. persCamera.name = node.name || "";
  107997. persCamera.attachControl(gltfRuntime.scene.getEngine().getRenderingCanvas());
  107998. if (!perspectiveCamera.aspectRatio) {
  107999. perspectiveCamera.aspectRatio = gltfRuntime.scene.getEngine().getRenderWidth() / gltfRuntime.scene.getEngine().getRenderHeight();
  108000. }
  108001. if (perspectiveCamera.znear && perspectiveCamera.zfar) {
  108002. persCamera.maxZ = perspectiveCamera.zfar;
  108003. persCamera.minZ = perspectiveCamera.znear;
  108004. }
  108005. lastNode = persCamera;
  108006. }
  108007. }
  108008. }
  108009. // Empty node
  108010. if (!node.jointName) {
  108011. if (node.babylonNode) {
  108012. return node.babylonNode;
  108013. }
  108014. else if (lastNode === null) {
  108015. var dummy = new BABYLON.Mesh(node.name || "", gltfRuntime.scene);
  108016. node.babylonNode = dummy;
  108017. lastNode = dummy;
  108018. }
  108019. }
  108020. if (lastNode !== null) {
  108021. if (node.matrix && lastNode instanceof BABYLON.Mesh) {
  108022. configureNodeFromMatrix(lastNode, node, parent);
  108023. }
  108024. else {
  108025. var translation = node.translation || [0, 0, 0];
  108026. var rotation = node.rotation || [0, 0, 0, 1];
  108027. var scale = node.scale || [1, 1, 1];
  108028. configureNode(lastNode, BABYLON.Vector3.FromArray(translation), BABYLON.Quaternion.FromArray(rotation), BABYLON.Vector3.FromArray(scale));
  108029. }
  108030. lastNode.updateCache(true);
  108031. node.babylonNode = lastNode;
  108032. }
  108033. return lastNode;
  108034. };
  108035. /**
  108036. * Traverses nodes and creates them
  108037. */
  108038. var traverseNodes = function (gltfRuntime, id, parent, meshIncluded) {
  108039. if (meshIncluded === void 0) { meshIncluded = false; }
  108040. var node = gltfRuntime.nodes[id];
  108041. var newNode = null;
  108042. if (gltfRuntime.importOnlyMeshes && !meshIncluded && gltfRuntime.importMeshesNames) {
  108043. if (gltfRuntime.importMeshesNames.indexOf(node.name || "") !== -1 || gltfRuntime.importMeshesNames.length === 0) {
  108044. meshIncluded = true;
  108045. }
  108046. else {
  108047. meshIncluded = false;
  108048. }
  108049. }
  108050. else {
  108051. meshIncluded = true;
  108052. }
  108053. if (!node.jointName && meshIncluded) {
  108054. newNode = importNode(gltfRuntime, node, id, parent);
  108055. if (newNode !== null) {
  108056. newNode.id = id;
  108057. newNode.parent = parent;
  108058. }
  108059. }
  108060. if (node.children) {
  108061. for (var i = 0; i < node.children.length; i++) {
  108062. traverseNodes(gltfRuntime, node.children[i], newNode, meshIncluded);
  108063. }
  108064. }
  108065. };
  108066. /**
  108067. * do stuff after buffers, shaders are loaded (e.g. hook up materials, load animations, etc.)
  108068. */
  108069. var postLoad = function (gltfRuntime) {
  108070. // Nodes
  108071. var currentScene = gltfRuntime.currentScene;
  108072. if (currentScene) {
  108073. for (var i = 0; i < currentScene.nodes.length; i++) {
  108074. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108075. }
  108076. }
  108077. else {
  108078. for (var thing in gltfRuntime.scenes) {
  108079. currentScene = gltfRuntime.scenes[thing];
  108080. for (var i = 0; i < currentScene.nodes.length; i++) {
  108081. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108082. }
  108083. }
  108084. }
  108085. // Set animations
  108086. loadAnimations(gltfRuntime);
  108087. for (var i = 0; i < gltfRuntime.scene.skeletons.length; i++) {
  108088. var skeleton = gltfRuntime.scene.skeletons[i];
  108089. gltfRuntime.scene.beginAnimation(skeleton, 0, Number.MAX_VALUE, true, 1.0);
  108090. }
  108091. };
  108092. /**
  108093. * onBind shaderrs callback to set uniforms and matrices
  108094. */
  108095. var onBindShaderMaterial = function (mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess) {
  108096. var materialValues = material.values || technique.parameters;
  108097. for (var unif in unTreatedUniforms) {
  108098. var uniform = unTreatedUniforms[unif];
  108099. var type = uniform.type;
  108100. if (type === GLTF1.EParameterType.FLOAT_MAT2 || type === GLTF1.EParameterType.FLOAT_MAT3 || type === GLTF1.EParameterType.FLOAT_MAT4) {
  108101. if (uniform.semantic && !uniform.source && !uniform.node) {
  108102. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, mesh, uniform, unif, shaderMaterial.getEffect());
  108103. }
  108104. else if (uniform.semantic && (uniform.source || uniform.node)) {
  108105. var source = gltfRuntime.scene.getNodeByName(uniform.source || uniform.node || "");
  108106. if (source === null) {
  108107. source = gltfRuntime.scene.getNodeByID(uniform.source || uniform.node || "");
  108108. }
  108109. if (source === null) {
  108110. continue;
  108111. }
  108112. GLTF1.GLTFUtils.SetMatrix(gltfRuntime.scene, source, uniform, unif, shaderMaterial.getEffect());
  108113. }
  108114. }
  108115. else {
  108116. var value = materialValues[technique.uniforms[unif]];
  108117. if (!value) {
  108118. continue;
  108119. }
  108120. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108121. var texture = gltfRuntime.textures[material.values ? value : uniform.value].babylonTexture;
  108122. if (texture === null || texture === undefined) {
  108123. continue;
  108124. }
  108125. shaderMaterial.getEffect().setTexture(unif, texture);
  108126. }
  108127. else {
  108128. GLTF1.GLTFUtils.SetUniform((shaderMaterial.getEffect()), unif, value, type);
  108129. }
  108130. }
  108131. }
  108132. onSuccess(shaderMaterial);
  108133. };
  108134. /**
  108135. * Prepare uniforms to send the only one time
  108136. * Loads the appropriate textures
  108137. */
  108138. var prepareShaderMaterialUniforms = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms) {
  108139. var materialValues = material.values || technique.parameters;
  108140. var techniqueUniforms = technique.uniforms;
  108141. /**
  108142. * Prepare values here (not matrices)
  108143. */
  108144. for (var unif in unTreatedUniforms) {
  108145. var uniform = unTreatedUniforms[unif];
  108146. var type = uniform.type;
  108147. var value = materialValues[techniqueUniforms[unif]];
  108148. if (value === undefined) {
  108149. // In case the value is the same for all materials
  108150. value = uniform.value;
  108151. }
  108152. if (!value) {
  108153. continue;
  108154. }
  108155. var onLoadTexture = function (uniformName) {
  108156. return function (texture) {
  108157. if (uniform.value && uniformName) {
  108158. // Static uniform
  108159. shaderMaterial.setTexture(uniformName, texture);
  108160. delete unTreatedUniforms[uniformName];
  108161. }
  108162. };
  108163. };
  108164. // Texture (sampler2D)
  108165. if (type === GLTF1.EParameterType.SAMPLER_2D) {
  108166. GLTF1.GLTFLoaderExtension.LoadTextureAsync(gltfRuntime, material.values ? value : uniform.value, onLoadTexture(unif), function () { return onLoadTexture(null); });
  108167. }
  108168. // Others
  108169. else {
  108170. if (uniform.value && GLTF1.GLTFUtils.SetUniform(shaderMaterial, unif, material.values ? value : uniform.value, type)) {
  108171. // Static uniform
  108172. delete unTreatedUniforms[unif];
  108173. }
  108174. }
  108175. }
  108176. };
  108177. /**
  108178. * Shader compilation failed
  108179. */
  108180. var onShaderCompileError = function (program, shaderMaterial, onError) {
  108181. return function (effect, error) {
  108182. shaderMaterial.dispose(true);
  108183. onError("Cannot compile program named " + program.name + ". Error: " + error + ". Default material will be applied");
  108184. };
  108185. };
  108186. /**
  108187. * Shader compilation success
  108188. */
  108189. var onShaderCompileSuccess = function (gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess) {
  108190. return function (_) {
  108191. prepareShaderMaterialUniforms(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms);
  108192. shaderMaterial.onBind = function (mesh) {
  108193. onBindShaderMaterial(mesh, gltfRuntime, unTreatedUniforms, shaderMaterial, technique, material, onSuccess);
  108194. };
  108195. };
  108196. };
  108197. /**
  108198. * Returns the appropriate uniform if already handled by babylon
  108199. */
  108200. var parseShaderUniforms = function (tokenizer, technique, unTreatedUniforms) {
  108201. for (var unif in technique.uniforms) {
  108202. var uniform = technique.uniforms[unif];
  108203. var uniformParameter = technique.parameters[uniform];
  108204. if (tokenizer.currentIdentifier === unif) {
  108205. if (uniformParameter.semantic && !uniformParameter.source && !uniformParameter.node) {
  108206. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108207. if (transformIndex !== -1) {
  108208. delete unTreatedUniforms[unif];
  108209. return babylonTransforms[transformIndex];
  108210. }
  108211. }
  108212. }
  108213. }
  108214. return tokenizer.currentIdentifier;
  108215. };
  108216. /**
  108217. * All shaders loaded. Create materials one by one
  108218. */
  108219. var importMaterials = function (gltfRuntime) {
  108220. // Create materials
  108221. for (var mat in gltfRuntime.materials) {
  108222. GLTF1.GLTFLoaderExtension.LoadMaterialAsync(gltfRuntime, mat, function (material) { }, function () { });
  108223. }
  108224. };
  108225. /**
  108226. * Implementation of the base glTF spec
  108227. */
  108228. var GLTFLoaderBase = /** @class */ (function () {
  108229. function GLTFLoaderBase() {
  108230. }
  108231. GLTFLoaderBase.CreateRuntime = function (parsedData, scene, rootUrl) {
  108232. var gltfRuntime = {
  108233. extensions: {},
  108234. accessors: {},
  108235. buffers: {},
  108236. bufferViews: {},
  108237. meshes: {},
  108238. lights: {},
  108239. cameras: {},
  108240. nodes: {},
  108241. images: {},
  108242. textures: {},
  108243. shaders: {},
  108244. programs: {},
  108245. samplers: {},
  108246. techniques: {},
  108247. materials: {},
  108248. animations: {},
  108249. skins: {},
  108250. extensionsUsed: [],
  108251. scenes: {},
  108252. buffersCount: 0,
  108253. shaderscount: 0,
  108254. scene: scene,
  108255. rootUrl: rootUrl,
  108256. loadedBufferCount: 0,
  108257. loadedBufferViews: {},
  108258. loadedShaderCount: 0,
  108259. importOnlyMeshes: false,
  108260. dummyNodes: []
  108261. };
  108262. // Parse
  108263. if (parsedData.extensions) {
  108264. parseObject(parsedData.extensions, "extensions", gltfRuntime);
  108265. }
  108266. if (parsedData.extensionsUsed) {
  108267. parseObject(parsedData.extensionsUsed, "extensionsUsed", gltfRuntime);
  108268. }
  108269. if (parsedData.buffers) {
  108270. parseBuffers(parsedData.buffers, gltfRuntime);
  108271. }
  108272. if (parsedData.bufferViews) {
  108273. parseObject(parsedData.bufferViews, "bufferViews", gltfRuntime);
  108274. }
  108275. if (parsedData.accessors) {
  108276. parseObject(parsedData.accessors, "accessors", gltfRuntime);
  108277. }
  108278. if (parsedData.meshes) {
  108279. parseObject(parsedData.meshes, "meshes", gltfRuntime);
  108280. }
  108281. if (parsedData.lights) {
  108282. parseObject(parsedData.lights, "lights", gltfRuntime);
  108283. }
  108284. if (parsedData.cameras) {
  108285. parseObject(parsedData.cameras, "cameras", gltfRuntime);
  108286. }
  108287. if (parsedData.nodes) {
  108288. parseObject(parsedData.nodes, "nodes", gltfRuntime);
  108289. }
  108290. if (parsedData.images) {
  108291. parseObject(parsedData.images, "images", gltfRuntime);
  108292. }
  108293. if (parsedData.textures) {
  108294. parseObject(parsedData.textures, "textures", gltfRuntime);
  108295. }
  108296. if (parsedData.shaders) {
  108297. parseShaders(parsedData.shaders, gltfRuntime);
  108298. }
  108299. if (parsedData.programs) {
  108300. parseObject(parsedData.programs, "programs", gltfRuntime);
  108301. }
  108302. if (parsedData.samplers) {
  108303. parseObject(parsedData.samplers, "samplers", gltfRuntime);
  108304. }
  108305. if (parsedData.techniques) {
  108306. parseObject(parsedData.techniques, "techniques", gltfRuntime);
  108307. }
  108308. if (parsedData.materials) {
  108309. parseObject(parsedData.materials, "materials", gltfRuntime);
  108310. }
  108311. if (parsedData.animations) {
  108312. parseObject(parsedData.animations, "animations", gltfRuntime);
  108313. }
  108314. if (parsedData.skins) {
  108315. parseObject(parsedData.skins, "skins", gltfRuntime);
  108316. }
  108317. if (parsedData.scenes) {
  108318. gltfRuntime.scenes = parsedData.scenes;
  108319. }
  108320. if (parsedData.scene && parsedData.scenes) {
  108321. gltfRuntime.currentScene = parsedData.scenes[parsedData.scene];
  108322. }
  108323. return gltfRuntime;
  108324. };
  108325. GLTFLoaderBase.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  108326. var buffer = gltfRuntime.buffers[id];
  108327. if (BABYLON.Tools.IsBase64(buffer.uri)) {
  108328. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(buffer.uri))); });
  108329. }
  108330. else {
  108331. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + buffer.uri, function (data) { return onSuccess(new Uint8Array(data)); }, onProgress, undefined, true, function (request) {
  108332. if (request) {
  108333. onError(request.status + " " + request.statusText);
  108334. }
  108335. });
  108336. }
  108337. };
  108338. GLTFLoaderBase.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  108339. var texture = gltfRuntime.textures[id];
  108340. if (!texture || !texture.source) {
  108341. onError("");
  108342. return;
  108343. }
  108344. if (texture.babylonTexture) {
  108345. onSuccess(null);
  108346. return;
  108347. }
  108348. var source = gltfRuntime.images[texture.source];
  108349. if (BABYLON.Tools.IsBase64(source.uri)) {
  108350. setTimeout(function () { return onSuccess(new Uint8Array(BABYLON.Tools.DecodeBase64(source.uri))); });
  108351. }
  108352. else {
  108353. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + source.uri, function (data) { return onSuccess(new Uint8Array(data)); }, undefined, undefined, true, function (request) {
  108354. if (request) {
  108355. onError(request.status + " " + request.statusText);
  108356. }
  108357. });
  108358. }
  108359. };
  108360. GLTFLoaderBase.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  108361. var texture = gltfRuntime.textures[id];
  108362. if (texture.babylonTexture) {
  108363. onSuccess(texture.babylonTexture);
  108364. return;
  108365. }
  108366. var sampler = gltfRuntime.samplers[texture.sampler];
  108367. var createMipMaps = (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST) ||
  108368. (sampler.minFilter === GLTF1.ETextureFilterType.NEAREST_MIPMAP_LINEAR) ||
  108369. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST) ||
  108370. (sampler.minFilter === GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR);
  108371. var samplingMode = BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108372. var blob = new Blob([buffer]);
  108373. var blobURL = URL.createObjectURL(blob);
  108374. var revokeBlobURL = function () { return URL.revokeObjectURL(blobURL); };
  108375. var newTexture = new BABYLON.Texture(blobURL, gltfRuntime.scene, !createMipMaps, true, samplingMode, revokeBlobURL, revokeBlobURL);
  108376. if (sampler.wrapS !== undefined) {
  108377. newTexture.wrapU = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapS);
  108378. }
  108379. if (sampler.wrapT !== undefined) {
  108380. newTexture.wrapV = GLTF1.GLTFUtils.GetWrapMode(sampler.wrapT);
  108381. }
  108382. newTexture.name = id;
  108383. texture.babylonTexture = newTexture;
  108384. onSuccess(newTexture);
  108385. };
  108386. GLTFLoaderBase.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  108387. var shader = gltfRuntime.shaders[id];
  108388. if (BABYLON.Tools.IsBase64(shader.uri)) {
  108389. var shaderString = atob(shader.uri.split(",")[1]);
  108390. if (onSuccess) {
  108391. onSuccess(shaderString);
  108392. }
  108393. }
  108394. else {
  108395. BABYLON.Tools.LoadFile(gltfRuntime.rootUrl + shader.uri, onSuccess, undefined, undefined, false, function (request) {
  108396. if (request && onError) {
  108397. onError(request.status + " " + request.statusText);
  108398. }
  108399. });
  108400. }
  108401. };
  108402. GLTFLoaderBase.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  108403. var material = gltfRuntime.materials[id];
  108404. if (!material.technique) {
  108405. if (onError) {
  108406. onError("No technique found.");
  108407. }
  108408. return;
  108409. }
  108410. var technique = gltfRuntime.techniques[material.technique];
  108411. if (!technique) {
  108412. var defaultMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  108413. defaultMaterial.diffuseColor = new BABYLON.Color3(0.5, 0.5, 0.5);
  108414. defaultMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108415. onSuccess(defaultMaterial);
  108416. return;
  108417. }
  108418. var program = gltfRuntime.programs[technique.program];
  108419. var states = technique.states;
  108420. var vertexShader = BABYLON.Effect.ShadersStore[program.vertexShader + "VertexShader"];
  108421. var pixelShader = BABYLON.Effect.ShadersStore[program.fragmentShader + "PixelShader"];
  108422. var newVertexShader = "";
  108423. var newPixelShader = "";
  108424. var vertexTokenizer = new Tokenizer(vertexShader);
  108425. var pixelTokenizer = new Tokenizer(pixelShader);
  108426. var unTreatedUniforms = {};
  108427. var uniforms = [];
  108428. var attributes = [];
  108429. var samplers = [];
  108430. // Fill uniform, sampler2D and attributes
  108431. for (var unif in technique.uniforms) {
  108432. var uniform = technique.uniforms[unif];
  108433. var uniformParameter = technique.parameters[uniform];
  108434. unTreatedUniforms[unif] = uniformParameter;
  108435. if (uniformParameter.semantic && !uniformParameter.node && !uniformParameter.source) {
  108436. var transformIndex = glTFTransforms.indexOf(uniformParameter.semantic);
  108437. if (transformIndex !== -1) {
  108438. uniforms.push(babylonTransforms[transformIndex]);
  108439. delete unTreatedUniforms[unif];
  108440. }
  108441. else {
  108442. uniforms.push(unif);
  108443. }
  108444. }
  108445. else if (uniformParameter.type === GLTF1.EParameterType.SAMPLER_2D) {
  108446. samplers.push(unif);
  108447. }
  108448. else {
  108449. uniforms.push(unif);
  108450. }
  108451. }
  108452. for (var attr in technique.attributes) {
  108453. var attribute = technique.attributes[attr];
  108454. var attributeParameter = technique.parameters[attribute];
  108455. if (attributeParameter.semantic) {
  108456. attributes.push(getAttribute(attributeParameter));
  108457. }
  108458. }
  108459. // Configure vertex shader
  108460. while (!vertexTokenizer.isEnd() && vertexTokenizer.getNextToken()) {
  108461. var tokenType = vertexTokenizer.currentToken;
  108462. if (tokenType !== ETokenType.IDENTIFIER) {
  108463. newVertexShader += vertexTokenizer.currentString;
  108464. continue;
  108465. }
  108466. var foundAttribute = false;
  108467. for (var attr in technique.attributes) {
  108468. var attribute = technique.attributes[attr];
  108469. var attributeParameter = technique.parameters[attribute];
  108470. if (vertexTokenizer.currentIdentifier === attr && attributeParameter.semantic) {
  108471. newVertexShader += getAttribute(attributeParameter);
  108472. foundAttribute = true;
  108473. break;
  108474. }
  108475. }
  108476. if (foundAttribute) {
  108477. continue;
  108478. }
  108479. newVertexShader += parseShaderUniforms(vertexTokenizer, technique, unTreatedUniforms);
  108480. }
  108481. // Configure pixel shader
  108482. while (!pixelTokenizer.isEnd() && pixelTokenizer.getNextToken()) {
  108483. var tokenType = pixelTokenizer.currentToken;
  108484. if (tokenType !== ETokenType.IDENTIFIER) {
  108485. newPixelShader += pixelTokenizer.currentString;
  108486. continue;
  108487. }
  108488. newPixelShader += parseShaderUniforms(pixelTokenizer, technique, unTreatedUniforms);
  108489. }
  108490. // Create shader material
  108491. var shaderPath = {
  108492. vertex: program.vertexShader + id,
  108493. fragment: program.fragmentShader + id
  108494. };
  108495. var options = {
  108496. attributes: attributes,
  108497. uniforms: uniforms,
  108498. samplers: samplers,
  108499. needAlphaBlending: states && states.enable && states.enable.indexOf(3042) !== -1
  108500. };
  108501. BABYLON.Effect.ShadersStore[program.vertexShader + id + "VertexShader"] = newVertexShader;
  108502. BABYLON.Effect.ShadersStore[program.fragmentShader + id + "PixelShader"] = newPixelShader;
  108503. var shaderMaterial = new BABYLON.ShaderMaterial(id, gltfRuntime.scene, shaderPath, options);
  108504. shaderMaterial.onError = onShaderCompileError(program, shaderMaterial, onError);
  108505. shaderMaterial.onCompiled = onShaderCompileSuccess(gltfRuntime, shaderMaterial, technique, material, unTreatedUniforms, onSuccess);
  108506. shaderMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  108507. if (states && states.functions) {
  108508. var functions = states.functions;
  108509. if (functions.cullFace && functions.cullFace[0] !== GLTF1.ECullingType.BACK) {
  108510. shaderMaterial.backFaceCulling = false;
  108511. }
  108512. var blendFunc = functions.blendFuncSeparate;
  108513. if (blendFunc) {
  108514. 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) {
  108515. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_COMBINE;
  108516. }
  108517. else if (blendFunc[0] === GLTF1.EBlendingFunction.ONE && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108518. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ONEONE;
  108519. }
  108520. else if (blendFunc[0] === GLTF1.EBlendingFunction.SRC_ALPHA && blendFunc[1] === GLTF1.EBlendingFunction.ONE && blendFunc[2] === GLTF1.EBlendingFunction.ZERO && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108521. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_ADD;
  108522. }
  108523. 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) {
  108524. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_SUBTRACT;
  108525. }
  108526. else if (blendFunc[0] === GLTF1.EBlendingFunction.DST_COLOR && blendFunc[1] === GLTF1.EBlendingFunction.ZERO && blendFunc[2] === GLTF1.EBlendingFunction.ONE && blendFunc[3] === GLTF1.EBlendingFunction.ONE) {
  108527. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MULTIPLY;
  108528. }
  108529. 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) {
  108530. shaderMaterial.alphaMode = BABYLON.Engine.ALPHA_MAXIMIZED;
  108531. }
  108532. }
  108533. }
  108534. };
  108535. return GLTFLoaderBase;
  108536. }());
  108537. GLTF1.GLTFLoaderBase = GLTFLoaderBase;
  108538. /**
  108539. * glTF V1 Loader
  108540. */
  108541. var GLTFLoader = /** @class */ (function () {
  108542. function GLTFLoader() {
  108543. this.state = null;
  108544. }
  108545. GLTFLoader.RegisterExtension = function (extension) {
  108546. if (GLTFLoader.Extensions[extension.name]) {
  108547. BABYLON.Tools.Error("Tool with the same name \"" + extension.name + "\" already exists");
  108548. return;
  108549. }
  108550. GLTFLoader.Extensions[extension.name] = extension;
  108551. };
  108552. GLTFLoader.prototype.dispose = function () {
  108553. // do nothing
  108554. };
  108555. GLTFLoader.prototype._importMeshAsync = function (meshesNames, scene, data, rootUrl, onSuccess, onProgress, onError) {
  108556. var _this = this;
  108557. scene.useRightHandedSystem = true;
  108558. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108559. gltfRuntime.importOnlyMeshes = true;
  108560. if (meshesNames === "") {
  108561. gltfRuntime.importMeshesNames = [];
  108562. }
  108563. else if (typeof meshesNames === "string") {
  108564. gltfRuntime.importMeshesNames = [meshesNames];
  108565. }
  108566. else if (meshesNames && !(meshesNames instanceof Array)) {
  108567. gltfRuntime.importMeshesNames = [meshesNames];
  108568. }
  108569. else {
  108570. gltfRuntime.importMeshesNames = [];
  108571. BABYLON.Tools.Warn("Argument meshesNames must be of type string or string[]");
  108572. }
  108573. // Create nodes
  108574. _this._createNodes(gltfRuntime);
  108575. var meshes = new Array();
  108576. var skeletons = new Array();
  108577. // Fill arrays of meshes and skeletons
  108578. for (var nde in gltfRuntime.nodes) {
  108579. var node = gltfRuntime.nodes[nde];
  108580. if (node.babylonNode instanceof BABYLON.AbstractMesh) {
  108581. meshes.push(node.babylonNode);
  108582. }
  108583. }
  108584. for (var skl in gltfRuntime.skins) {
  108585. var skin = gltfRuntime.skins[skl];
  108586. if (skin.babylonSkeleton instanceof BABYLON.Skeleton) {
  108587. skeletons.push(skin.babylonSkeleton);
  108588. }
  108589. }
  108590. // Load buffers, shaders, materials, etc.
  108591. _this._loadBuffersAsync(gltfRuntime, function () {
  108592. _this._loadShadersAsync(gltfRuntime, function () {
  108593. importMaterials(gltfRuntime);
  108594. postLoad(gltfRuntime);
  108595. if (!BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108596. onSuccess(meshes, skeletons);
  108597. }
  108598. });
  108599. }, onProgress);
  108600. if (BABYLON.GLTFFileLoader.IncrementalLoading && onSuccess) {
  108601. onSuccess(meshes, skeletons);
  108602. }
  108603. }, onError);
  108604. return true;
  108605. };
  108606. /**
  108607. * Imports one or more meshes from a loaded gltf file and adds them to the scene
  108608. * @param meshesNames a string or array of strings of the mesh names that should be loaded from the file
  108609. * @param scene the scene the meshes should be added to
  108610. * @param data gltf data containing information of the meshes in a loaded file
  108611. * @param rootUrl root url to load from
  108612. * @param onProgress event that fires when loading progress has occured
  108613. * @returns a promise containg the loaded meshes, particles, skeletons and animations
  108614. */
  108615. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  108616. var _this = this;
  108617. return new Promise(function (resolve, reject) {
  108618. _this._importMeshAsync(meshesNames, scene, data, rootUrl, function (meshes, skeletons) {
  108619. resolve({
  108620. meshes: meshes,
  108621. particleSystems: [],
  108622. skeletons: skeletons,
  108623. animationGroups: []
  108624. });
  108625. }, onProgress, function (message) {
  108626. reject(new Error(message));
  108627. });
  108628. });
  108629. };
  108630. GLTFLoader.prototype._loadAsync = function (scene, data, rootUrl, onSuccess, onProgress, onError) {
  108631. var _this = this;
  108632. scene.useRightHandedSystem = true;
  108633. GLTF1.GLTFLoaderExtension.LoadRuntimeAsync(scene, data, rootUrl, function (gltfRuntime) {
  108634. // Load runtime extensios
  108635. GLTF1.GLTFLoaderExtension.LoadRuntimeExtensionsAsync(gltfRuntime, function () {
  108636. // Create nodes
  108637. _this._createNodes(gltfRuntime);
  108638. // Load buffers, shaders, materials, etc.
  108639. _this._loadBuffersAsync(gltfRuntime, function () {
  108640. _this._loadShadersAsync(gltfRuntime, function () {
  108641. importMaterials(gltfRuntime);
  108642. postLoad(gltfRuntime);
  108643. if (!BABYLON.GLTFFileLoader.IncrementalLoading) {
  108644. onSuccess();
  108645. }
  108646. });
  108647. });
  108648. if (BABYLON.GLTFFileLoader.IncrementalLoading) {
  108649. onSuccess();
  108650. }
  108651. }, onError);
  108652. }, onError);
  108653. };
  108654. /**
  108655. * Imports all objects from a loaded gltf file and adds them to the scene
  108656. * @param scene the scene the objects should be added to
  108657. * @param data gltf data containing information of the meshes in a loaded file
  108658. * @param rootUrl root url to load from
  108659. * @param onProgress event that fires when loading progress has occured
  108660. * @returns a promise which completes when objects have been loaded to the scene
  108661. */
  108662. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  108663. var _this = this;
  108664. return new Promise(function (resolve, reject) {
  108665. _this._loadAsync(scene, data, rootUrl, function () {
  108666. resolve();
  108667. }, onProgress, function (message) {
  108668. reject(new Error(message));
  108669. });
  108670. });
  108671. };
  108672. GLTFLoader.prototype._loadShadersAsync = function (gltfRuntime, onload) {
  108673. var hasShaders = false;
  108674. var processShader = function (sha, shader) {
  108675. GLTF1.GLTFLoaderExtension.LoadShaderStringAsync(gltfRuntime, sha, function (shaderString) {
  108676. if (shaderString instanceof ArrayBuffer) {
  108677. return;
  108678. }
  108679. gltfRuntime.loadedShaderCount++;
  108680. if (shaderString) {
  108681. BABYLON.Effect.ShadersStore[sha + (shader.type === GLTF1.EShaderType.VERTEX ? "VertexShader" : "PixelShader")] = shaderString;
  108682. }
  108683. if (gltfRuntime.loadedShaderCount === gltfRuntime.shaderscount) {
  108684. onload();
  108685. }
  108686. }, function () {
  108687. BABYLON.Tools.Error("Error when loading shader program named " + sha + " located at " + shader.uri);
  108688. });
  108689. };
  108690. for (var sha in gltfRuntime.shaders) {
  108691. hasShaders = true;
  108692. var shader = gltfRuntime.shaders[sha];
  108693. if (shader) {
  108694. processShader.bind(this, sha, shader)();
  108695. }
  108696. else {
  108697. BABYLON.Tools.Error("No shader named: " + sha);
  108698. }
  108699. }
  108700. if (!hasShaders) {
  108701. onload();
  108702. }
  108703. };
  108704. ;
  108705. GLTFLoader.prototype._loadBuffersAsync = function (gltfRuntime, onLoad, onProgress) {
  108706. var hasBuffers = false;
  108707. var processBuffer = function (buf, buffer) {
  108708. GLTF1.GLTFLoaderExtension.LoadBufferAsync(gltfRuntime, buf, function (bufferView) {
  108709. gltfRuntime.loadedBufferCount++;
  108710. if (bufferView) {
  108711. if (bufferView.byteLength != gltfRuntime.buffers[buf].byteLength) {
  108712. BABYLON.Tools.Error("Buffer named " + buf + " is length " + bufferView.byteLength + ". Expected: " + buffer.byteLength); // Improve error message
  108713. }
  108714. gltfRuntime.loadedBufferViews[buf] = bufferView;
  108715. }
  108716. if (gltfRuntime.loadedBufferCount === gltfRuntime.buffersCount) {
  108717. onLoad();
  108718. }
  108719. }, function () {
  108720. BABYLON.Tools.Error("Error when loading buffer named " + buf + " located at " + buffer.uri);
  108721. });
  108722. };
  108723. for (var buf in gltfRuntime.buffers) {
  108724. hasBuffers = true;
  108725. var buffer = gltfRuntime.buffers[buf];
  108726. if (buffer) {
  108727. processBuffer.bind(this, buf, buffer)();
  108728. }
  108729. else {
  108730. BABYLON.Tools.Error("No buffer named: " + buf);
  108731. }
  108732. }
  108733. if (!hasBuffers) {
  108734. onLoad();
  108735. }
  108736. };
  108737. GLTFLoader.prototype._createNodes = function (gltfRuntime) {
  108738. var currentScene = gltfRuntime.currentScene;
  108739. if (currentScene) {
  108740. // Only one scene even if multiple scenes are defined
  108741. for (var i = 0; i < currentScene.nodes.length; i++) {
  108742. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108743. }
  108744. }
  108745. else {
  108746. // Load all scenes
  108747. for (var thing in gltfRuntime.scenes) {
  108748. currentScene = gltfRuntime.scenes[thing];
  108749. for (var i = 0; i < currentScene.nodes.length; i++) {
  108750. traverseNodes(gltfRuntime, currentScene.nodes[i], null);
  108751. }
  108752. }
  108753. }
  108754. };
  108755. GLTFLoader.Extensions = {};
  108756. return GLTFLoader;
  108757. }());
  108758. GLTF1.GLTFLoader = GLTFLoader;
  108759. ;
  108760. BABYLON.GLTFFileLoader._CreateGLTFLoaderV1 = function () { return new GLTFLoader(); };
  108761. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108762. })(BABYLON || (BABYLON = {}));
  108763. //# sourceMappingURL=babylon.glTFLoader.js.map
  108764. var BABYLON;
  108765. (function (BABYLON) {
  108766. var GLTF1;
  108767. (function (GLTF1) {
  108768. /**
  108769. * Utils functions for GLTF
  108770. */
  108771. var GLTFUtils = /** @class */ (function () {
  108772. function GLTFUtils() {
  108773. }
  108774. /**
  108775. * Sets the given "parameter" matrix
  108776. * @param scene: the {BABYLON.Scene} object
  108777. * @param source: the source node where to pick the matrix
  108778. * @param parameter: the GLTF technique parameter
  108779. * @param uniformName: the name of the shader's uniform
  108780. * @param shaderMaterial: the shader material
  108781. */
  108782. GLTFUtils.SetMatrix = function (scene, source, parameter, uniformName, shaderMaterial) {
  108783. var mat = null;
  108784. if (parameter.semantic === "MODEL") {
  108785. mat = source.getWorldMatrix();
  108786. }
  108787. else if (parameter.semantic === "PROJECTION") {
  108788. mat = scene.getProjectionMatrix();
  108789. }
  108790. else if (parameter.semantic === "VIEW") {
  108791. mat = scene.getViewMatrix();
  108792. }
  108793. else if (parameter.semantic === "MODELVIEWINVERSETRANSPOSE") {
  108794. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().multiply(scene.getViewMatrix()).invert());
  108795. }
  108796. else if (parameter.semantic === "MODELVIEW") {
  108797. mat = source.getWorldMatrix().multiply(scene.getViewMatrix());
  108798. }
  108799. else if (parameter.semantic === "MODELVIEWPROJECTION") {
  108800. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix());
  108801. }
  108802. else if (parameter.semantic === "MODELINVERSE") {
  108803. mat = source.getWorldMatrix().invert();
  108804. }
  108805. else if (parameter.semantic === "VIEWINVERSE") {
  108806. mat = scene.getViewMatrix().invert();
  108807. }
  108808. else if (parameter.semantic === "PROJECTIONINVERSE") {
  108809. mat = scene.getProjectionMatrix().invert();
  108810. }
  108811. else if (parameter.semantic === "MODELVIEWINVERSE") {
  108812. mat = source.getWorldMatrix().multiply(scene.getViewMatrix()).invert();
  108813. }
  108814. else if (parameter.semantic === "MODELVIEWPROJECTIONINVERSE") {
  108815. mat = source.getWorldMatrix().multiply(scene.getTransformMatrix()).invert();
  108816. }
  108817. else if (parameter.semantic === "MODELINVERSETRANSPOSE") {
  108818. mat = BABYLON.Matrix.Transpose(source.getWorldMatrix().invert());
  108819. }
  108820. else {
  108821. debugger;
  108822. }
  108823. if (mat) {
  108824. switch (parameter.type) {
  108825. case GLTF1.EParameterType.FLOAT_MAT2:
  108826. shaderMaterial.setMatrix2x2(uniformName, BABYLON.Matrix.GetAsMatrix2x2(mat));
  108827. break;
  108828. case GLTF1.EParameterType.FLOAT_MAT3:
  108829. shaderMaterial.setMatrix3x3(uniformName, BABYLON.Matrix.GetAsMatrix3x3(mat));
  108830. break;
  108831. case GLTF1.EParameterType.FLOAT_MAT4:
  108832. shaderMaterial.setMatrix(uniformName, mat);
  108833. break;
  108834. default: break;
  108835. }
  108836. }
  108837. };
  108838. /**
  108839. * Sets the given "parameter" matrix
  108840. * @param shaderMaterial: the shader material
  108841. * @param uniform: the name of the shader's uniform
  108842. * @param value: the value of the uniform
  108843. * @param type: the uniform's type (EParameterType FLOAT, VEC2, VEC3 or VEC4)
  108844. */
  108845. GLTFUtils.SetUniform = function (shaderMaterial, uniform, value, type) {
  108846. switch (type) {
  108847. case GLTF1.EParameterType.FLOAT:
  108848. shaderMaterial.setFloat(uniform, value);
  108849. return true;
  108850. case GLTF1.EParameterType.FLOAT_VEC2:
  108851. shaderMaterial.setVector2(uniform, BABYLON.Vector2.FromArray(value));
  108852. return true;
  108853. case GLTF1.EParameterType.FLOAT_VEC3:
  108854. shaderMaterial.setVector3(uniform, BABYLON.Vector3.FromArray(value));
  108855. return true;
  108856. case GLTF1.EParameterType.FLOAT_VEC4:
  108857. shaderMaterial.setVector4(uniform, BABYLON.Vector4.FromArray(value));
  108858. return true;
  108859. default: return false;
  108860. }
  108861. };
  108862. /**
  108863. * Returns the wrap mode of the texture
  108864. * @param mode: the mode value
  108865. */
  108866. GLTFUtils.GetWrapMode = function (mode) {
  108867. switch (mode) {
  108868. case GLTF1.ETextureWrapMode.CLAMP_TO_EDGE: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  108869. case GLTF1.ETextureWrapMode.MIRRORED_REPEAT: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  108870. case GLTF1.ETextureWrapMode.REPEAT: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108871. default: return BABYLON.Texture.WRAP_ADDRESSMODE;
  108872. }
  108873. };
  108874. /**
  108875. * Returns the byte stride giving an accessor
  108876. * @param accessor: the GLTF accessor objet
  108877. */
  108878. GLTFUtils.GetByteStrideFromType = function (accessor) {
  108879. // Needs this function since "byteStride" isn't requiered in glTF format
  108880. var type = accessor.type;
  108881. switch (type) {
  108882. case "VEC2": return 2;
  108883. case "VEC3": return 3;
  108884. case "VEC4": return 4;
  108885. case "MAT2": return 4;
  108886. case "MAT3": return 9;
  108887. case "MAT4": return 16;
  108888. default: return 1;
  108889. }
  108890. };
  108891. /**
  108892. * Returns the texture filter mode giving a mode value
  108893. * @param mode: the filter mode value
  108894. */
  108895. GLTFUtils.GetTextureFilterMode = function (mode) {
  108896. switch (mode) {
  108897. case GLTF1.ETextureFilterType.LINEAR:
  108898. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_NEAREST:
  108899. case GLTF1.ETextureFilterType.LINEAR_MIPMAP_LINEAR: return BABYLON.Texture.TRILINEAR_SAMPLINGMODE;
  108900. case GLTF1.ETextureFilterType.NEAREST:
  108901. case GLTF1.ETextureFilterType.NEAREST_MIPMAP_NEAREST: return BABYLON.Texture.NEAREST_SAMPLINGMODE;
  108902. default: return BABYLON.Texture.BILINEAR_SAMPLINGMODE;
  108903. }
  108904. };
  108905. GLTFUtils.GetBufferFromBufferView = function (gltfRuntime, bufferView, byteOffset, byteLength, componentType) {
  108906. var byteOffset = bufferView.byteOffset + byteOffset;
  108907. var loadedBufferView = gltfRuntime.loadedBufferViews[bufferView.buffer];
  108908. if (byteOffset + byteLength > loadedBufferView.byteLength) {
  108909. throw new Error("Buffer access is out of range");
  108910. }
  108911. var buffer = loadedBufferView.buffer;
  108912. byteOffset += loadedBufferView.byteOffset;
  108913. switch (componentType) {
  108914. case GLTF1.EComponentType.BYTE: return new Int8Array(buffer, byteOffset, byteLength);
  108915. case GLTF1.EComponentType.UNSIGNED_BYTE: return new Uint8Array(buffer, byteOffset, byteLength);
  108916. case GLTF1.EComponentType.SHORT: return new Int16Array(buffer, byteOffset, byteLength);
  108917. case GLTF1.EComponentType.UNSIGNED_SHORT: return new Uint16Array(buffer, byteOffset, byteLength);
  108918. default: return new Float32Array(buffer, byteOffset, byteLength);
  108919. }
  108920. };
  108921. /**
  108922. * Returns a buffer from its accessor
  108923. * @param gltfRuntime: the GLTF runtime
  108924. * @param accessor: the GLTF accessor
  108925. */
  108926. GLTFUtils.GetBufferFromAccessor = function (gltfRuntime, accessor) {
  108927. var bufferView = gltfRuntime.bufferViews[accessor.bufferView];
  108928. var byteLength = accessor.count * GLTFUtils.GetByteStrideFromType(accessor);
  108929. return GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, accessor.byteOffset, byteLength, accessor.componentType);
  108930. };
  108931. /**
  108932. * Decodes a buffer view into a string
  108933. * @param view: the buffer view
  108934. */
  108935. GLTFUtils.DecodeBufferToText = function (view) {
  108936. var result = "";
  108937. var length = view.byteLength;
  108938. for (var i = 0; i < length; ++i) {
  108939. result += String.fromCharCode(view[i]);
  108940. }
  108941. return result;
  108942. };
  108943. /**
  108944. * Returns the default material of gltf. Related to
  108945. * https://github.com/KhronosGroup/glTF/tree/master/specification/1.0#appendix-a-default-material
  108946. * @param scene: the Babylon.js scene
  108947. */
  108948. GLTFUtils.GetDefaultMaterial = function (scene) {
  108949. if (!GLTFUtils._DefaultMaterial) {
  108950. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialVertexShader"] = [
  108951. "precision highp float;",
  108952. "",
  108953. "uniform mat4 worldView;",
  108954. "uniform mat4 projection;",
  108955. "",
  108956. "attribute vec3 position;",
  108957. "",
  108958. "void main(void)",
  108959. "{",
  108960. " gl_Position = projection * worldView * vec4(position, 1.0);",
  108961. "}"
  108962. ].join("\n");
  108963. BABYLON.Effect.ShadersStore["GLTFDefaultMaterialPixelShader"] = [
  108964. "precision highp float;",
  108965. "",
  108966. "uniform vec4 u_emission;",
  108967. "",
  108968. "void main(void)",
  108969. "{",
  108970. " gl_FragColor = u_emission;",
  108971. "}"
  108972. ].join("\n");
  108973. var shaderPath = {
  108974. vertex: "GLTFDefaultMaterial",
  108975. fragment: "GLTFDefaultMaterial"
  108976. };
  108977. var options = {
  108978. attributes: ["position"],
  108979. uniforms: ["worldView", "projection", "u_emission"],
  108980. samplers: new Array(),
  108981. needAlphaBlending: false
  108982. };
  108983. GLTFUtils._DefaultMaterial = new BABYLON.ShaderMaterial("GLTFDefaultMaterial", scene, shaderPath, options);
  108984. GLTFUtils._DefaultMaterial.setColor4("u_emission", new BABYLON.Color4(0.5, 0.5, 0.5, 1.0));
  108985. }
  108986. return GLTFUtils._DefaultMaterial;
  108987. };
  108988. // The GLTF default material
  108989. GLTFUtils._DefaultMaterial = null;
  108990. return GLTFUtils;
  108991. }());
  108992. GLTF1.GLTFUtils = GLTFUtils;
  108993. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  108994. })(BABYLON || (BABYLON = {}));
  108995. //# sourceMappingURL=babylon.glTFLoaderUtils.js.map
  108996. var BABYLON;
  108997. (function (BABYLON) {
  108998. var GLTF1;
  108999. (function (GLTF1) {
  109000. var GLTFLoaderExtension = /** @class */ (function () {
  109001. function GLTFLoaderExtension(name) {
  109002. this._name = name;
  109003. }
  109004. Object.defineProperty(GLTFLoaderExtension.prototype, "name", {
  109005. get: function () {
  109006. return this._name;
  109007. },
  109008. enumerable: true,
  109009. configurable: true
  109010. });
  109011. /**
  109012. * Defines an override for loading the runtime
  109013. * Return true to stop further extensions from loading the runtime
  109014. */
  109015. GLTFLoaderExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109016. return false;
  109017. };
  109018. /**
  109019. * Defines an onverride for creating gltf runtime
  109020. * Return true to stop further extensions from creating the runtime
  109021. */
  109022. GLTFLoaderExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109023. return false;
  109024. };
  109025. /**
  109026. * Defines an override for loading buffers
  109027. * Return true to stop further extensions from loading this buffer
  109028. */
  109029. GLTFLoaderExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109030. return false;
  109031. };
  109032. /**
  109033. * Defines an override for loading texture buffers
  109034. * Return true to stop further extensions from loading this texture data
  109035. */
  109036. GLTFLoaderExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109037. return false;
  109038. };
  109039. /**
  109040. * Defines an override for creating textures
  109041. * Return true to stop further extensions from loading this texture
  109042. */
  109043. GLTFLoaderExtension.prototype.createTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109044. return false;
  109045. };
  109046. /**
  109047. * Defines an override for loading shader strings
  109048. * Return true to stop further extensions from loading this shader data
  109049. */
  109050. GLTFLoaderExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109051. return false;
  109052. };
  109053. /**
  109054. * Defines an override for loading materials
  109055. * Return true to stop further extensions from loading this material
  109056. */
  109057. GLTFLoaderExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109058. return false;
  109059. };
  109060. // ---------
  109061. // Utilities
  109062. // ---------
  109063. GLTFLoaderExtension.LoadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109064. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109065. return loaderExtension.loadRuntimeAsync(scene, data, rootUrl, onSuccess, onError);
  109066. }, function () {
  109067. setTimeout(function () {
  109068. if (!onSuccess) {
  109069. return;
  109070. }
  109071. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109072. });
  109073. });
  109074. };
  109075. GLTFLoaderExtension.LoadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109076. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109077. return loaderExtension.loadRuntimeExtensionsAsync(gltfRuntime, onSuccess, onError);
  109078. }, function () {
  109079. setTimeout(function () {
  109080. onSuccess();
  109081. });
  109082. });
  109083. };
  109084. GLTFLoaderExtension.LoadBufferAsync = function (gltfRuntime, id, onSuccess, onError, onProgress) {
  109085. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109086. return loaderExtension.loadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109087. }, function () {
  109088. GLTF1.GLTFLoaderBase.LoadBufferAsync(gltfRuntime, id, onSuccess, onError, onProgress);
  109089. });
  109090. };
  109091. GLTFLoaderExtension.LoadTextureAsync = function (gltfRuntime, id, onSuccess, onError) {
  109092. GLTFLoaderExtension.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109093. if (buffer) {
  109094. GLTFLoaderExtension.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109095. }
  109096. }, onError);
  109097. };
  109098. GLTFLoaderExtension.LoadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109099. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109100. return loaderExtension.loadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109101. }, function () {
  109102. GLTF1.GLTFLoaderBase.LoadShaderStringAsync(gltfRuntime, id, onSuccess, onError);
  109103. });
  109104. };
  109105. GLTFLoaderExtension.LoadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109106. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109107. return loaderExtension.loadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109108. }, function () {
  109109. GLTF1.GLTFLoaderBase.LoadMaterialAsync(gltfRuntime, id, onSuccess, onError);
  109110. });
  109111. };
  109112. GLTFLoaderExtension.LoadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109113. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109114. return loaderExtension.loadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109115. }, function () {
  109116. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, onSuccess, onError);
  109117. });
  109118. };
  109119. GLTFLoaderExtension.CreateTextureAsync = function (gltfRuntime, id, buffer, onSuccess, onError) {
  109120. GLTFLoaderExtension.ApplyExtensions(function (loaderExtension) {
  109121. return loaderExtension.createTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109122. }, function () {
  109123. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, onSuccess, onError);
  109124. });
  109125. };
  109126. GLTFLoaderExtension.ApplyExtensions = function (func, defaultFunc) {
  109127. for (var extensionName in GLTF1.GLTFLoader.Extensions) {
  109128. var loaderExtension = GLTF1.GLTFLoader.Extensions[extensionName];
  109129. if (func(loaderExtension)) {
  109130. return;
  109131. }
  109132. }
  109133. defaultFunc();
  109134. };
  109135. return GLTFLoaderExtension;
  109136. }());
  109137. GLTF1.GLTFLoaderExtension = GLTFLoaderExtension;
  109138. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109139. })(BABYLON || (BABYLON = {}));
  109140. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  109141. var BABYLON;
  109142. (function (BABYLON) {
  109143. var GLTF1;
  109144. (function (GLTF1) {
  109145. var BinaryExtensionBufferName = "binary_glTF";
  109146. ;
  109147. ;
  109148. var GLTFBinaryExtension = /** @class */ (function (_super) {
  109149. __extends(GLTFBinaryExtension, _super);
  109150. function GLTFBinaryExtension() {
  109151. return _super.call(this, "KHR_binary_glTF") || this;
  109152. }
  109153. GLTFBinaryExtension.prototype.loadRuntimeAsync = function (scene, data, rootUrl, onSuccess, onError) {
  109154. var extensionsUsed = data.json.extensionsUsed;
  109155. if (!extensionsUsed || extensionsUsed.indexOf(this.name) === -1 || !data.bin) {
  109156. return false;
  109157. }
  109158. this._bin = data.bin;
  109159. onSuccess(GLTF1.GLTFLoaderBase.CreateRuntime(data.json, scene, rootUrl));
  109160. return true;
  109161. };
  109162. GLTFBinaryExtension.prototype.loadBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109163. if (gltfRuntime.extensionsUsed.indexOf(this.name) === -1) {
  109164. return false;
  109165. }
  109166. if (id !== BinaryExtensionBufferName) {
  109167. return false;
  109168. }
  109169. onSuccess(this._bin);
  109170. return true;
  109171. };
  109172. GLTFBinaryExtension.prototype.loadTextureBufferAsync = function (gltfRuntime, id, onSuccess, onError) {
  109173. var texture = gltfRuntime.textures[id];
  109174. var source = gltfRuntime.images[texture.source];
  109175. if (!source.extensions || !(this.name in source.extensions)) {
  109176. return false;
  109177. }
  109178. var sourceExt = source.extensions[this.name];
  109179. var bufferView = gltfRuntime.bufferViews[sourceExt.bufferView];
  109180. var buffer = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109181. onSuccess(buffer);
  109182. return true;
  109183. };
  109184. GLTFBinaryExtension.prototype.loadShaderStringAsync = function (gltfRuntime, id, onSuccess, onError) {
  109185. var shader = gltfRuntime.shaders[id];
  109186. if (!shader.extensions || !(this.name in shader.extensions)) {
  109187. return false;
  109188. }
  109189. var binaryExtensionShader = shader.extensions[this.name];
  109190. var bufferView = gltfRuntime.bufferViews[binaryExtensionShader.bufferView];
  109191. var shaderBytes = GLTF1.GLTFUtils.GetBufferFromBufferView(gltfRuntime, bufferView, 0, bufferView.byteLength, GLTF1.EComponentType.UNSIGNED_BYTE);
  109192. setTimeout(function () {
  109193. var shaderString = GLTF1.GLTFUtils.DecodeBufferToText(shaderBytes);
  109194. onSuccess(shaderString);
  109195. });
  109196. return true;
  109197. };
  109198. return GLTFBinaryExtension;
  109199. }(GLTF1.GLTFLoaderExtension));
  109200. GLTF1.GLTFBinaryExtension = GLTFBinaryExtension;
  109201. GLTF1.GLTFLoader.RegisterExtension(new GLTFBinaryExtension());
  109202. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109203. })(BABYLON || (BABYLON = {}));
  109204. //# sourceMappingURL=babylon.glTFBinaryExtension.js.map
  109205. var BABYLON;
  109206. (function (BABYLON) {
  109207. var GLTF1;
  109208. (function (GLTF1) {
  109209. ;
  109210. ;
  109211. ;
  109212. var GLTFMaterialsCommonExtension = /** @class */ (function (_super) {
  109213. __extends(GLTFMaterialsCommonExtension, _super);
  109214. function GLTFMaterialsCommonExtension() {
  109215. return _super.call(this, "KHR_materials_common") || this;
  109216. }
  109217. GLTFMaterialsCommonExtension.prototype.loadRuntimeExtensionsAsync = function (gltfRuntime, onSuccess, onError) {
  109218. if (!gltfRuntime.extensions)
  109219. return false;
  109220. var extension = gltfRuntime.extensions[this.name];
  109221. if (!extension)
  109222. return false;
  109223. // Create lights
  109224. var lights = extension.lights;
  109225. if (lights) {
  109226. for (var thing in lights) {
  109227. var light = lights[thing];
  109228. switch (light.type) {
  109229. case "ambient":
  109230. var ambientLight = new BABYLON.HemisphericLight(light.name, new BABYLON.Vector3(0, 1, 0), gltfRuntime.scene);
  109231. var ambient = light.ambient;
  109232. if (ambient) {
  109233. ambientLight.diffuse = BABYLON.Color3.FromArray(ambient.color || [1, 1, 1]);
  109234. }
  109235. break;
  109236. case "point":
  109237. var pointLight = new BABYLON.PointLight(light.name, new BABYLON.Vector3(10, 10, 10), gltfRuntime.scene);
  109238. var point = light.point;
  109239. if (point) {
  109240. pointLight.diffuse = BABYLON.Color3.FromArray(point.color || [1, 1, 1]);
  109241. }
  109242. break;
  109243. case "directional":
  109244. var dirLight = new BABYLON.DirectionalLight(light.name, new BABYLON.Vector3(0, -1, 0), gltfRuntime.scene);
  109245. var directional = light.directional;
  109246. if (directional) {
  109247. dirLight.diffuse = BABYLON.Color3.FromArray(directional.color || [1, 1, 1]);
  109248. }
  109249. break;
  109250. case "spot":
  109251. var spot = light.spot;
  109252. if (spot) {
  109253. 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);
  109254. spotLight.diffuse = BABYLON.Color3.FromArray(spot.color || [1, 1, 1]);
  109255. }
  109256. break;
  109257. default:
  109258. BABYLON.Tools.Warn("GLTF Material Common extension: light type \"" + light.type + "\” not supported");
  109259. break;
  109260. }
  109261. }
  109262. }
  109263. return false;
  109264. };
  109265. GLTFMaterialsCommonExtension.prototype.loadMaterialAsync = function (gltfRuntime, id, onSuccess, onError) {
  109266. var material = gltfRuntime.materials[id];
  109267. if (!material || !material.extensions)
  109268. return false;
  109269. var extension = material.extensions[this.name];
  109270. if (!extension)
  109271. return false;
  109272. var standardMaterial = new BABYLON.StandardMaterial(id, gltfRuntime.scene);
  109273. standardMaterial.sideOrientation = BABYLON.Material.CounterClockWiseSideOrientation;
  109274. if (extension.technique === "CONSTANT") {
  109275. standardMaterial.disableLighting = true;
  109276. }
  109277. standardMaterial.backFaceCulling = extension.doubleSided === undefined ? false : !extension.doubleSided;
  109278. standardMaterial.alpha = extension.values.transparency === undefined ? 1.0 : extension.values.transparency;
  109279. standardMaterial.specularPower = extension.values.shininess === undefined ? 0.0 : extension.values.shininess;
  109280. // Ambient
  109281. if (typeof extension.values.ambient === "string") {
  109282. this._loadTexture(gltfRuntime, extension.values.ambient, standardMaterial, "ambientTexture", onError);
  109283. }
  109284. else {
  109285. standardMaterial.ambientColor = BABYLON.Color3.FromArray(extension.values.ambient || [0, 0, 0]);
  109286. }
  109287. // Diffuse
  109288. if (typeof extension.values.diffuse === "string") {
  109289. this._loadTexture(gltfRuntime, extension.values.diffuse, standardMaterial, "diffuseTexture", onError);
  109290. }
  109291. else {
  109292. standardMaterial.diffuseColor = BABYLON.Color3.FromArray(extension.values.diffuse || [0, 0, 0]);
  109293. }
  109294. // Emission
  109295. if (typeof extension.values.emission === "string") {
  109296. this._loadTexture(gltfRuntime, extension.values.emission, standardMaterial, "emissiveTexture", onError);
  109297. }
  109298. else {
  109299. standardMaterial.emissiveColor = BABYLON.Color3.FromArray(extension.values.emission || [0, 0, 0]);
  109300. }
  109301. // Specular
  109302. if (typeof extension.values.specular === "string") {
  109303. this._loadTexture(gltfRuntime, extension.values.specular, standardMaterial, "specularTexture", onError);
  109304. }
  109305. else {
  109306. standardMaterial.specularColor = BABYLON.Color3.FromArray(extension.values.specular || [0, 0, 0]);
  109307. }
  109308. return true;
  109309. };
  109310. GLTFMaterialsCommonExtension.prototype._loadTexture = function (gltfRuntime, id, material, propertyPath, onError) {
  109311. // Create buffer from texture url
  109312. GLTF1.GLTFLoaderBase.LoadTextureBufferAsync(gltfRuntime, id, function (buffer) {
  109313. // Create texture from buffer
  109314. GLTF1.GLTFLoaderBase.CreateTextureAsync(gltfRuntime, id, buffer, function (texture) { return material[propertyPath] = texture; }, onError);
  109315. }, onError);
  109316. };
  109317. return GLTFMaterialsCommonExtension;
  109318. }(GLTF1.GLTFLoaderExtension));
  109319. GLTF1.GLTFMaterialsCommonExtension = GLTFMaterialsCommonExtension;
  109320. GLTF1.GLTFLoader.RegisterExtension(new GLTFMaterialsCommonExtension());
  109321. })(GLTF1 = BABYLON.GLTF1 || (BABYLON.GLTF1 = {}));
  109322. })(BABYLON || (BABYLON = {}));
  109323. //# sourceMappingURL=babylon.glTFMaterialsCommonExtension.js.map
  109324. //# sourceMappingURL=babylon.glTFLoaderInterfaces.js.map
  109325. /**
  109326. * Defines the module used to import/export glTF 2.0 assets
  109327. */
  109328. var BABYLON;
  109329. (function (BABYLON) {
  109330. var GLTF2;
  109331. (function (GLTF2) {
  109332. var _ArrayItem = /** @class */ (function () {
  109333. function _ArrayItem() {
  109334. }
  109335. _ArrayItem.Assign = function (values) {
  109336. if (values) {
  109337. for (var index = 0; index < values.length; index++) {
  109338. values[index]._index = index;
  109339. }
  109340. }
  109341. };
  109342. return _ArrayItem;
  109343. }());
  109344. /** @hidden */
  109345. var GLTFLoader = /** @class */ (function () {
  109346. function GLTFLoader(parent) {
  109347. this._completePromises = new Array();
  109348. this._disposed = false;
  109349. this._state = null;
  109350. this._extensions = {};
  109351. this._defaultSampler = {};
  109352. this._defaultBabylonMaterials = {};
  109353. this._requests = new Array();
  109354. this._parent = parent;
  109355. }
  109356. GLTFLoader._Register = function (name, factory) {
  109357. if (GLTFLoader._ExtensionFactories[name]) {
  109358. BABYLON.Tools.Error("Extension with the name '" + name + "' already exists");
  109359. return;
  109360. }
  109361. GLTFLoader._ExtensionFactories[name] = factory;
  109362. // Keep the order of registration so that extensions registered first are called first.
  109363. GLTFLoader._ExtensionNames.push(name);
  109364. };
  109365. Object.defineProperty(GLTFLoader.prototype, "state", {
  109366. /**
  109367. * Loader state or null if the loader is not active.
  109368. */
  109369. get: function () {
  109370. return this._state;
  109371. },
  109372. enumerable: true,
  109373. configurable: true
  109374. });
  109375. GLTFLoader.prototype.dispose = function () {
  109376. if (this._disposed) {
  109377. return;
  109378. }
  109379. this._disposed = true;
  109380. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  109381. var request = _a[_i];
  109382. request.abort();
  109383. }
  109384. this._requests.length = 0;
  109385. delete this._gltf;
  109386. delete this._babylonScene;
  109387. delete this._readyPromise;
  109388. this._completePromises.length = 0;
  109389. for (var name_1 in this._extensions) {
  109390. this._extensions[name_1].dispose();
  109391. }
  109392. this._extensions = {};
  109393. delete this._rootBabylonMesh;
  109394. delete this._progressCallback;
  109395. this._parent._clear();
  109396. };
  109397. GLTFLoader.prototype.importMeshAsync = function (meshesNames, scene, data, rootUrl, onProgress) {
  109398. var _this = this;
  109399. return Promise.resolve().then(function () {
  109400. _this._babylonScene = scene;
  109401. _this._rootUrl = rootUrl;
  109402. _this._progressCallback = onProgress;
  109403. _this._loadData(data);
  109404. var nodes = null;
  109405. if (meshesNames) {
  109406. var nodeMap_1 = {};
  109407. if (_this._gltf.nodes) {
  109408. for (var _i = 0, _a = _this._gltf.nodes; _i < _a.length; _i++) {
  109409. var node = _a[_i];
  109410. if (node.name) {
  109411. nodeMap_1[node.name] = node._index;
  109412. }
  109413. }
  109414. }
  109415. var names = (meshesNames instanceof Array) ? meshesNames : [meshesNames];
  109416. nodes = names.map(function (name) {
  109417. var node = nodeMap_1[name];
  109418. if (node === undefined) {
  109419. throw new Error("Failed to find node '" + name + "'");
  109420. }
  109421. return node;
  109422. });
  109423. }
  109424. return _this._loadAsync(nodes).then(function () {
  109425. return {
  109426. meshes: _this._getMeshes(),
  109427. particleSystems: [],
  109428. skeletons: _this._getSkeletons(),
  109429. animationGroups: _this._getAnimationGroups()
  109430. };
  109431. });
  109432. });
  109433. };
  109434. GLTFLoader.prototype.loadAsync = function (scene, data, rootUrl, onProgress) {
  109435. var _this = this;
  109436. return Promise.resolve().then(function () {
  109437. _this._babylonScene = scene;
  109438. _this._rootUrl = rootUrl;
  109439. _this._progressCallback = onProgress;
  109440. _this._loadData(data);
  109441. return _this._loadAsync(null);
  109442. });
  109443. };
  109444. GLTFLoader.prototype._loadAsync = function (nodes) {
  109445. var _this = this;
  109446. return Promise.resolve().then(function () {
  109447. _this._parent._startPerformanceCounter("Loading => Ready");
  109448. _this._parent._startPerformanceCounter("Loading => Complete");
  109449. _this._state = BABYLON.GLTFLoaderState.LOADING;
  109450. _this._parent._log("Loading");
  109451. var readyDeferred = new BABYLON.Deferred();
  109452. _this._readyPromise = readyDeferred.promise;
  109453. _this._loadExtensions();
  109454. _this._checkExtensions();
  109455. var promises = new Array();
  109456. if (nodes) {
  109457. promises.push(_this._loadSceneAsync("#/nodes", { nodes: nodes, _index: -1 }));
  109458. }
  109459. else {
  109460. var scene = GLTFLoader._GetProperty("#/scene", _this._gltf.scenes, _this._gltf.scene || 0);
  109461. promises.push(_this._loadSceneAsync("#/scenes/" + scene._index, scene));
  109462. }
  109463. if (_this._parent.compileMaterials) {
  109464. promises.push(_this._compileMaterialsAsync());
  109465. }
  109466. if (_this._parent.compileShadowGenerators) {
  109467. promises.push(_this._compileShadowGeneratorsAsync());
  109468. }
  109469. var resultPromise = Promise.all(promises).then(function () {
  109470. _this._state = BABYLON.GLTFLoaderState.READY;
  109471. _this._parent._log("Ready");
  109472. readyDeferred.resolve();
  109473. _this._startAnimations();
  109474. });
  109475. resultPromise.then(function () {
  109476. _this._parent._endPerformanceCounter("Loading => Ready");
  109477. BABYLON.Tools.SetImmediate(function () {
  109478. if (!_this._disposed) {
  109479. Promise.all(_this._completePromises).then(function () {
  109480. _this._parent._endPerformanceCounter("Loading => Complete");
  109481. _this._state = BABYLON.GLTFLoaderState.COMPLETE;
  109482. _this._parent._log("Complete");
  109483. _this._parent.onCompleteObservable.notifyObservers(undefined);
  109484. _this._parent.onCompleteObservable.clear();
  109485. _this.dispose();
  109486. }).catch(function (error) {
  109487. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109488. _this.dispose();
  109489. });
  109490. }
  109491. });
  109492. });
  109493. return resultPromise;
  109494. }).catch(function (error) {
  109495. if (!_this._disposed) {
  109496. BABYLON.Tools.Error("glTF Loader: " + error.message);
  109497. _this.dispose();
  109498. throw error;
  109499. }
  109500. });
  109501. };
  109502. GLTFLoader.prototype._loadData = function (data) {
  109503. this._gltf = data.json;
  109504. this._setupData();
  109505. if (data.bin) {
  109506. var buffers = this._gltf.buffers;
  109507. if (buffers && buffers[0] && !buffers[0].uri) {
  109508. var binaryBuffer = buffers[0];
  109509. if (binaryBuffer.byteLength < data.bin.byteLength - 3 || binaryBuffer.byteLength > data.bin.byteLength) {
  109510. BABYLON.Tools.Warn("Binary buffer length (" + binaryBuffer.byteLength + ") from JSON does not match chunk length (" + data.bin.byteLength + ")");
  109511. }
  109512. binaryBuffer._data = Promise.resolve(data.bin);
  109513. }
  109514. else {
  109515. BABYLON.Tools.Warn("Unexpected BIN chunk");
  109516. }
  109517. }
  109518. };
  109519. GLTFLoader.prototype._setupData = function () {
  109520. _ArrayItem.Assign(this._gltf.accessors);
  109521. _ArrayItem.Assign(this._gltf.animations);
  109522. _ArrayItem.Assign(this._gltf.buffers);
  109523. _ArrayItem.Assign(this._gltf.bufferViews);
  109524. _ArrayItem.Assign(this._gltf.cameras);
  109525. _ArrayItem.Assign(this._gltf.images);
  109526. _ArrayItem.Assign(this._gltf.materials);
  109527. _ArrayItem.Assign(this._gltf.meshes);
  109528. _ArrayItem.Assign(this._gltf.nodes);
  109529. _ArrayItem.Assign(this._gltf.samplers);
  109530. _ArrayItem.Assign(this._gltf.scenes);
  109531. _ArrayItem.Assign(this._gltf.skins);
  109532. _ArrayItem.Assign(this._gltf.textures);
  109533. if (this._gltf.nodes) {
  109534. var nodeParents = {};
  109535. for (var _i = 0, _a = this._gltf.nodes; _i < _a.length; _i++) {
  109536. var node = _a[_i];
  109537. if (node.children) {
  109538. for (var _b = 0, _c = node.children; _b < _c.length; _b++) {
  109539. var index = _c[_b];
  109540. nodeParents[index] = node._index;
  109541. }
  109542. }
  109543. }
  109544. var rootNode = this._createRootNode();
  109545. for (var _d = 0, _e = this._gltf.nodes; _d < _e.length; _d++) {
  109546. var node = _e[_d];
  109547. var parentIndex = nodeParents[node._index];
  109548. node._parent = parentIndex === undefined ? rootNode : this._gltf.nodes[parentIndex];
  109549. }
  109550. }
  109551. };
  109552. GLTFLoader.prototype._loadExtensions = function () {
  109553. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  109554. var name_2 = _a[_i];
  109555. var extension = GLTFLoader._ExtensionFactories[name_2](this);
  109556. this._extensions[name_2] = extension;
  109557. this._parent.onExtensionLoadedObservable.notifyObservers(extension);
  109558. }
  109559. this._parent.onExtensionLoadedObservable.clear();
  109560. };
  109561. GLTFLoader.prototype._checkExtensions = function () {
  109562. if (this._gltf.extensionsRequired) {
  109563. for (var _i = 0, _a = this._gltf.extensionsRequired; _i < _a.length; _i++) {
  109564. var name_3 = _a[_i];
  109565. var extension = this._extensions[name_3];
  109566. if (!extension || !extension.enabled) {
  109567. throw new Error("Require extension " + name_3 + " is not available");
  109568. }
  109569. }
  109570. }
  109571. };
  109572. GLTFLoader.prototype._createRootNode = function () {
  109573. this._rootBabylonMesh = new BABYLON.Mesh("__root__", this._babylonScene);
  109574. var rootNode = { _babylonMesh: this._rootBabylonMesh };
  109575. switch (this._parent.coordinateSystemMode) {
  109576. case BABYLON.GLTFLoaderCoordinateSystemMode.AUTO: {
  109577. if (!this._babylonScene.useRightHandedSystem) {
  109578. rootNode.rotation = [0, 1, 0, 0];
  109579. rootNode.scale = [1, 1, -1];
  109580. GLTFLoader._LoadTransform(rootNode, this._rootBabylonMesh);
  109581. }
  109582. break;
  109583. }
  109584. case BABYLON.GLTFLoaderCoordinateSystemMode.FORCE_RIGHT_HANDED: {
  109585. this._babylonScene.useRightHandedSystem = true;
  109586. break;
  109587. }
  109588. default: {
  109589. throw new Error("Invalid coordinate system mode (" + this._parent.coordinateSystemMode + ")");
  109590. }
  109591. }
  109592. this._parent.onMeshLoadedObservable.notifyObservers(this._rootBabylonMesh);
  109593. return rootNode;
  109594. };
  109595. GLTFLoader.prototype._loadSceneAsync = function (context, scene) {
  109596. var promise = GLTF2.GLTFLoaderExtension._LoadSceneAsync(this, context, scene);
  109597. if (promise) {
  109598. return promise;
  109599. }
  109600. var promises = new Array();
  109601. this._parent._logOpen(context + " " + (scene.name || ""));
  109602. if (scene.nodes) {
  109603. for (var _i = 0, _a = scene.nodes; _i < _a.length; _i++) {
  109604. var index = _a[_i];
  109605. var node = GLTFLoader._GetProperty(context + "/nodes/" + index, this._gltf.nodes, index);
  109606. promises.push(this._loadNodeAsync("#/nodes/" + node._index, node));
  109607. }
  109608. }
  109609. promises.push(this._loadAnimationsAsync());
  109610. this._parent._logClose();
  109611. return Promise.all(promises).then(function () { });
  109612. };
  109613. GLTFLoader.prototype._forEachPrimitive = function (node, callback) {
  109614. if (node._primitiveBabylonMeshes) {
  109615. for (var _i = 0, _a = node._primitiveBabylonMeshes; _i < _a.length; _i++) {
  109616. var babylonMesh = _a[_i];
  109617. callback(babylonMesh);
  109618. }
  109619. }
  109620. else {
  109621. callback(node._babylonMesh);
  109622. }
  109623. };
  109624. GLTFLoader.prototype._getMeshes = function () {
  109625. var meshes = new Array();
  109626. // Root mesh is always first.
  109627. meshes.push(this._rootBabylonMesh);
  109628. var nodes = this._gltf.nodes;
  109629. if (nodes) {
  109630. for (var _i = 0, nodes_1 = nodes; _i < nodes_1.length; _i++) {
  109631. var node = nodes_1[_i];
  109632. if (node._babylonMesh) {
  109633. meshes.push(node._babylonMesh);
  109634. }
  109635. if (node._primitiveBabylonMeshes) {
  109636. for (var _a = 0, _b = node._primitiveBabylonMeshes; _a < _b.length; _a++) {
  109637. var babylonMesh = _b[_a];
  109638. meshes.push(babylonMesh);
  109639. }
  109640. }
  109641. }
  109642. }
  109643. return meshes;
  109644. };
  109645. GLTFLoader.prototype._getSkeletons = function () {
  109646. var skeletons = new Array();
  109647. var skins = this._gltf.skins;
  109648. if (skins) {
  109649. for (var _i = 0, skins_1 = skins; _i < skins_1.length; _i++) {
  109650. var skin = skins_1[_i];
  109651. if (skin._babylonSkeleton) {
  109652. skeletons.push(skin._babylonSkeleton);
  109653. }
  109654. }
  109655. }
  109656. return skeletons;
  109657. };
  109658. GLTFLoader.prototype._getAnimationGroups = function () {
  109659. var animationGroups = new Array();
  109660. var animations = this._gltf.animations;
  109661. if (animations) {
  109662. for (var _i = 0, animations_1 = animations; _i < animations_1.length; _i++) {
  109663. var animation = animations_1[_i];
  109664. if (animation._babylonAnimationGroup) {
  109665. animationGroups.push(animation._babylonAnimationGroup);
  109666. }
  109667. }
  109668. }
  109669. return animationGroups;
  109670. };
  109671. GLTFLoader.prototype._startAnimations = function () {
  109672. switch (this._parent.animationStartMode) {
  109673. case BABYLON.GLTFLoaderAnimationStartMode.NONE: {
  109674. // do nothing
  109675. break;
  109676. }
  109677. case BABYLON.GLTFLoaderAnimationStartMode.FIRST: {
  109678. var babylonAnimationGroups = this._getAnimationGroups();
  109679. if (babylonAnimationGroups.length !== 0) {
  109680. babylonAnimationGroups[0].start(true);
  109681. }
  109682. break;
  109683. }
  109684. case BABYLON.GLTFLoaderAnimationStartMode.ALL: {
  109685. var babylonAnimationGroups = this._getAnimationGroups();
  109686. for (var _i = 0, babylonAnimationGroups_1 = babylonAnimationGroups; _i < babylonAnimationGroups_1.length; _i++) {
  109687. var babylonAnimationGroup = babylonAnimationGroups_1[_i];
  109688. babylonAnimationGroup.start(true);
  109689. }
  109690. break;
  109691. }
  109692. default: {
  109693. BABYLON.Tools.Error("Invalid animation start mode (" + this._parent.animationStartMode + ")");
  109694. return;
  109695. }
  109696. }
  109697. };
  109698. GLTFLoader.prototype._loadNodeAsync = function (context, node) {
  109699. var promise = GLTF2.GLTFLoaderExtension._LoadNodeAsync(this, context, node);
  109700. if (promise) {
  109701. return promise;
  109702. }
  109703. if (node._babylonMesh) {
  109704. throw new Error(context + ": Invalid recursive node hierarchy");
  109705. }
  109706. var promises = new Array();
  109707. this._parent._logOpen(context + " " + (node.name || ""));
  109708. var babylonMesh = new BABYLON.Mesh(node.name || "node" + node._index, this._babylonScene, node._parent ? node._parent._babylonMesh : null);
  109709. node._babylonMesh = babylonMesh;
  109710. babylonMesh.setEnabled(false);
  109711. GLTFLoader._LoadTransform(node, babylonMesh);
  109712. if (node.mesh != undefined) {
  109713. var mesh = GLTFLoader._GetProperty(context + "/mesh", this._gltf.meshes, node.mesh);
  109714. promises.push(this._loadMeshAsync("#/meshes/" + mesh._index, node, mesh, babylonMesh));
  109715. }
  109716. if (node.camera != undefined) {
  109717. var camera = GLTFLoader._GetProperty(context + "/camera", this._gltf.cameras, node.camera);
  109718. this._loadCamera("#/cameras/" + camera._index, camera, babylonMesh);
  109719. }
  109720. if (node.children) {
  109721. for (var _i = 0, _a = node.children; _i < _a.length; _i++) {
  109722. var index = _a[_i];
  109723. var childNode = GLTFLoader._GetProperty(context + "/children/" + index, this._gltf.nodes, index);
  109724. promises.push(this._loadNodeAsync("#/nodes/" + index, childNode));
  109725. }
  109726. }
  109727. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109728. this._parent._logClose();
  109729. return Promise.all(promises).then(function () {
  109730. babylonMesh.setEnabled(true);
  109731. });
  109732. };
  109733. GLTFLoader.prototype._loadMeshAsync = function (context, node, mesh, babylonMesh) {
  109734. var _this = this;
  109735. var promises = new Array();
  109736. this._parent._logOpen(context + " " + (mesh.name || ""));
  109737. var primitives = mesh.primitives;
  109738. if (!primitives || primitives.length === 0) {
  109739. throw new Error(context + ": Primitives are missing");
  109740. }
  109741. _ArrayItem.Assign(primitives);
  109742. if (primitives.length === 1) {
  109743. var primitive = primitives[0];
  109744. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, babylonMesh));
  109745. }
  109746. else {
  109747. node._primitiveBabylonMeshes = [];
  109748. for (var _i = 0, primitives_1 = primitives; _i < primitives_1.length; _i++) {
  109749. var primitive = primitives_1[_i];
  109750. var primitiveBabylonMesh = new BABYLON.Mesh((mesh.name || babylonMesh.name) + "_" + primitive._index, this._babylonScene, babylonMesh);
  109751. node._primitiveBabylonMeshes.push(primitiveBabylonMesh);
  109752. promises.push(this._loadPrimitiveAsync(context + "/primitives/" + primitive._index, node, mesh, primitive, primitiveBabylonMesh));
  109753. this._parent.onMeshLoadedObservable.notifyObservers(babylonMesh);
  109754. }
  109755. }
  109756. if (node.skin != undefined) {
  109757. var skin = GLTFLoader._GetProperty(context + "/skin", this._gltf.skins, node.skin);
  109758. promises.push(this._loadSkinAsync("#/skins/" + skin._index, node, mesh, skin));
  109759. }
  109760. this._parent._logClose();
  109761. return Promise.all(promises).then(function () {
  109762. _this._forEachPrimitive(node, function (babylonMesh) {
  109763. babylonMesh._refreshBoundingInfo(true);
  109764. });
  109765. });
  109766. };
  109767. GLTFLoader.prototype._loadPrimitiveAsync = function (context, node, mesh, primitive, babylonMesh) {
  109768. var _this = this;
  109769. var promises = new Array();
  109770. this._parent._logOpen("" + context);
  109771. this._createMorphTargets(context, node, mesh, primitive, babylonMesh);
  109772. promises.push(this._loadVertexDataAsync(context, primitive, babylonMesh).then(function (babylonGeometry) {
  109773. return _this._loadMorphTargetsAsync(context, primitive, babylonMesh, babylonGeometry).then(function () {
  109774. babylonGeometry.applyToMesh(babylonMesh);
  109775. });
  109776. }));
  109777. var babylonDrawMode = GLTFLoader._GetDrawMode(context, primitive.mode);
  109778. if (primitive.material == undefined) {
  109779. babylonMesh.material = this._getDefaultMaterial(babylonDrawMode);
  109780. }
  109781. else {
  109782. var material = GLTFLoader._GetProperty(context + "/material}", this._gltf.materials, primitive.material);
  109783. promises.push(this._loadMaterialAsync("#/materials/" + material._index, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  109784. babylonMesh.material = babylonMaterial;
  109785. }));
  109786. }
  109787. this._parent._logClose();
  109788. return Promise.all(promises).then(function () { });
  109789. };
  109790. GLTFLoader.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  109791. var _this = this;
  109792. var promise = GLTF2.GLTFLoaderExtension._LoadVertexDataAsync(this, context, primitive, babylonMesh);
  109793. if (promise) {
  109794. return promise;
  109795. }
  109796. var attributes = primitive.attributes;
  109797. if (!attributes) {
  109798. throw new Error(context + ": Attributes are missing");
  109799. }
  109800. var promises = new Array();
  109801. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, this._babylonScene);
  109802. if (primitive.indices == undefined) {
  109803. babylonMesh.isUnIndexed = true;
  109804. }
  109805. else {
  109806. var accessor = GLTFLoader._GetProperty(context + "/indices", this._gltf.accessors, primitive.indices);
  109807. promises.push(this._loadIndicesAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109808. babylonGeometry.setIndices(data);
  109809. }));
  109810. }
  109811. var loadAttribute = function (attribute, kind, callback) {
  109812. if (attributes[attribute] == undefined) {
  109813. return;
  109814. }
  109815. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  109816. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  109817. babylonMesh._delayInfo.push(kind);
  109818. }
  109819. var accessor = GLTFLoader._GetProperty(context + "/attributes/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109820. promises.push(_this._loadVertexAccessorAsync("#/accessors/" + accessor._index, accessor, kind).then(function (babylonVertexBuffer) {
  109821. babylonGeometry.setVerticesBuffer(babylonVertexBuffer, accessor.count);
  109822. }));
  109823. if (callback) {
  109824. callback(accessor);
  109825. }
  109826. };
  109827. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  109828. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  109829. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  109830. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  109831. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  109832. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  109833. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  109834. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind, function (accessor) {
  109835. if (accessor.type === "VEC4" /* VEC4 */) {
  109836. babylonMesh.hasVertexAlpha = true;
  109837. }
  109838. });
  109839. return Promise.all(promises).then(function () {
  109840. return babylonGeometry;
  109841. });
  109842. };
  109843. GLTFLoader.prototype._createMorphTargets = function (context, node, mesh, primitive, babylonMesh) {
  109844. if (!primitive.targets) {
  109845. return;
  109846. }
  109847. if (node._numMorphTargets == undefined) {
  109848. node._numMorphTargets = primitive.targets.length;
  109849. }
  109850. else if (primitive.targets.length !== node._numMorphTargets) {
  109851. throw new Error(context + ": Primitives do not have the same number of targets");
  109852. }
  109853. babylonMesh.morphTargetManager = new BABYLON.MorphTargetManager();
  109854. for (var index = 0; index < primitive.targets.length; index++) {
  109855. var weight = node.weights ? node.weights[index] : mesh.weights ? mesh.weights[index] : 0;
  109856. babylonMesh.morphTargetManager.addTarget(new BABYLON.MorphTarget("morphTarget" + index, weight));
  109857. // TODO: tell the target whether it has positions, normals, tangents
  109858. }
  109859. };
  109860. GLTFLoader.prototype._loadMorphTargetsAsync = function (context, primitive, babylonMesh, babylonGeometry) {
  109861. if (!primitive.targets) {
  109862. return Promise.resolve();
  109863. }
  109864. var promises = new Array();
  109865. var morphTargetManager = babylonMesh.morphTargetManager;
  109866. for (var index = 0; index < morphTargetManager.numTargets; index++) {
  109867. var babylonMorphTarget = morphTargetManager.getTarget(index);
  109868. promises.push(this._loadMorphTargetVertexDataAsync(context + "/targets/" + index, babylonGeometry, primitive.targets[index], babylonMorphTarget));
  109869. }
  109870. return Promise.all(promises).then(function () { });
  109871. };
  109872. GLTFLoader.prototype._loadMorphTargetVertexDataAsync = function (context, babylonGeometry, attributes, babylonMorphTarget) {
  109873. var _this = this;
  109874. var promises = new Array();
  109875. var loadAttribute = function (attribute, kind, setData) {
  109876. if (attributes[attribute] == undefined) {
  109877. return;
  109878. }
  109879. var babylonVertexBuffer = babylonGeometry.getVertexBuffer(kind);
  109880. if (!babylonVertexBuffer) {
  109881. return;
  109882. }
  109883. var accessor = GLTFLoader._GetProperty(context + "/" + attribute, _this._gltf.accessors, attributes[attribute]);
  109884. promises.push(_this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor).then(function (data) {
  109885. setData(babylonVertexBuffer, data);
  109886. }));
  109887. };
  109888. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind, function (babylonVertexBuffer, data) {
  109889. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109890. data[index] += value;
  109891. });
  109892. babylonMorphTarget.setPositions(data);
  109893. });
  109894. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind, function (babylonVertexBuffer, data) {
  109895. babylonVertexBuffer.forEach(data.length, function (value, index) {
  109896. data[index] += value;
  109897. });
  109898. babylonMorphTarget.setNormals(data);
  109899. });
  109900. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind, function (babylonVertexBuffer, data) {
  109901. var dataIndex = 0;
  109902. babylonVertexBuffer.forEach(data.length / 3 * 4, function (value, index) {
  109903. // Tangent data for morph targets is stored as xyz delta.
  109904. // The vertexData.tangent is stored as xyzw.
  109905. // So we need to skip every fourth vertexData.tangent.
  109906. if (((index + 1) % 4) !== 0) {
  109907. data[dataIndex++] += value;
  109908. }
  109909. });
  109910. babylonMorphTarget.setTangents(data);
  109911. });
  109912. return Promise.all(promises).then(function () { });
  109913. };
  109914. GLTFLoader._LoadTransform = function (node, babylonNode) {
  109915. var position = BABYLON.Vector3.Zero();
  109916. var rotation = BABYLON.Quaternion.Identity();
  109917. var scaling = BABYLON.Vector3.One();
  109918. if (node.matrix) {
  109919. var matrix = BABYLON.Matrix.FromArray(node.matrix);
  109920. matrix.decompose(scaling, rotation, position);
  109921. }
  109922. else {
  109923. if (node.translation)
  109924. position = BABYLON.Vector3.FromArray(node.translation);
  109925. if (node.rotation)
  109926. rotation = BABYLON.Quaternion.FromArray(node.rotation);
  109927. if (node.scale)
  109928. scaling = BABYLON.Vector3.FromArray(node.scale);
  109929. }
  109930. babylonNode.position = position;
  109931. babylonNode.rotationQuaternion = rotation;
  109932. babylonNode.scaling = scaling;
  109933. };
  109934. GLTFLoader.prototype._loadSkinAsync = function (context, node, mesh, skin) {
  109935. var _this = this;
  109936. var assignSkeleton = function (skeleton) {
  109937. _this._forEachPrimitive(node, function (babylonMesh) {
  109938. babylonMesh.skeleton = skeleton;
  109939. });
  109940. // Ignore the TRS of skinned nodes.
  109941. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  109942. node._babylonMesh.parent = _this._rootBabylonMesh;
  109943. node._babylonMesh.position = BABYLON.Vector3.Zero();
  109944. node._babylonMesh.rotationQuaternion = BABYLON.Quaternion.Identity();
  109945. node._babylonMesh.scaling = BABYLON.Vector3.One();
  109946. };
  109947. if (skin._loaded) {
  109948. return skin._loaded.then(function () {
  109949. assignSkeleton(skin._babylonSkeleton);
  109950. });
  109951. }
  109952. var skeletonId = "skeleton" + skin._index;
  109953. var babylonSkeleton = new BABYLON.Skeleton(skin.name || skeletonId, skeletonId, this._babylonScene);
  109954. skin._babylonSkeleton = babylonSkeleton;
  109955. this._loadBones(context, skin);
  109956. assignSkeleton(babylonSkeleton);
  109957. return (skin._loaded = this._loadSkinInverseBindMatricesDataAsync(context, skin).then(function (inverseBindMatricesData) {
  109958. _this._updateBoneMatrices(babylonSkeleton, inverseBindMatricesData);
  109959. }));
  109960. };
  109961. GLTFLoader.prototype._loadBones = function (context, skin) {
  109962. var babylonBones = {};
  109963. for (var _i = 0, _a = skin.joints; _i < _a.length; _i++) {
  109964. var index = _a[_i];
  109965. var node = GLTFLoader._GetProperty(context + "/joints/" + index, this._gltf.nodes, index);
  109966. this._loadBone(node, skin, babylonBones);
  109967. }
  109968. };
  109969. GLTFLoader.prototype._loadBone = function (node, skin, babylonBones) {
  109970. var babylonBone = babylonBones[node._index];
  109971. if (babylonBone) {
  109972. return babylonBone;
  109973. }
  109974. var babylonParentBone = null;
  109975. if (node._parent && node._parent._babylonMesh !== this._rootBabylonMesh) {
  109976. babylonParentBone = this._loadBone(node._parent, skin, babylonBones);
  109977. }
  109978. var boneIndex = skin.joints.indexOf(node._index);
  109979. babylonBone = new BABYLON.Bone(node.name || "joint" + node._index, skin._babylonSkeleton, babylonParentBone, this._getNodeMatrix(node), null, null, boneIndex);
  109980. babylonBones[node._index] = babylonBone;
  109981. node._babylonBones = node._babylonBones || [];
  109982. node._babylonBones.push(babylonBone);
  109983. return babylonBone;
  109984. };
  109985. GLTFLoader.prototype._loadSkinInverseBindMatricesDataAsync = function (context, skin) {
  109986. if (skin.inverseBindMatrices == undefined) {
  109987. return Promise.resolve(null);
  109988. }
  109989. var accessor = GLTFLoader._GetProperty(context + "/inverseBindMatrices", this._gltf.accessors, skin.inverseBindMatrices);
  109990. return this._loadFloatAccessorAsync("#/accessors/" + accessor._index, accessor);
  109991. };
  109992. GLTFLoader.prototype._updateBoneMatrices = function (babylonSkeleton, inverseBindMatricesData) {
  109993. for (var _i = 0, _a = babylonSkeleton.bones; _i < _a.length; _i++) {
  109994. var babylonBone = _a[_i];
  109995. var baseMatrix = BABYLON.Matrix.Identity();
  109996. var boneIndex = babylonBone._index;
  109997. if (inverseBindMatricesData && boneIndex !== -1) {
  109998. BABYLON.Matrix.FromArrayToRef(inverseBindMatricesData, boneIndex * 16, baseMatrix);
  109999. baseMatrix.invertToRef(baseMatrix);
  110000. }
  110001. var babylonParentBone = babylonBone.getParent();
  110002. if (babylonParentBone) {
  110003. baseMatrix.multiplyToRef(babylonParentBone.getInvertedAbsoluteTransform(), baseMatrix);
  110004. }
  110005. babylonBone.updateMatrix(baseMatrix, false, false);
  110006. babylonBone._updateDifferenceMatrix(undefined, false);
  110007. }
  110008. };
  110009. GLTFLoader.prototype._getNodeMatrix = function (node) {
  110010. return node.matrix ?
  110011. BABYLON.Matrix.FromArray(node.matrix) :
  110012. 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());
  110013. };
  110014. GLTFLoader.prototype._loadCamera = function (context, camera, babylonMesh) {
  110015. var babylonCamera = new BABYLON.FreeCamera(camera.name || "camera" + camera._index, BABYLON.Vector3.Zero(), this._babylonScene, false);
  110016. babylonCamera.parent = babylonMesh;
  110017. babylonCamera.rotation = new BABYLON.Vector3(0, Math.PI, 0);
  110018. switch (camera.type) {
  110019. case "perspective" /* PERSPECTIVE */: {
  110020. var perspective = camera.perspective;
  110021. if (!perspective) {
  110022. throw new Error(context + ": Camera perspective properties are missing");
  110023. }
  110024. babylonCamera.fov = perspective.yfov;
  110025. babylonCamera.minZ = perspective.znear;
  110026. babylonCamera.maxZ = perspective.zfar || Number.MAX_VALUE;
  110027. break;
  110028. }
  110029. case "orthographic" /* ORTHOGRAPHIC */: {
  110030. if (!camera.orthographic) {
  110031. throw new Error(context + ": Camera orthographic properties are missing");
  110032. }
  110033. babylonCamera.mode = BABYLON.Camera.ORTHOGRAPHIC_CAMERA;
  110034. babylonCamera.orthoLeft = -camera.orthographic.xmag;
  110035. babylonCamera.orthoRight = camera.orthographic.xmag;
  110036. babylonCamera.orthoBottom = -camera.orthographic.ymag;
  110037. babylonCamera.orthoTop = camera.orthographic.ymag;
  110038. babylonCamera.minZ = camera.orthographic.znear;
  110039. babylonCamera.maxZ = camera.orthographic.zfar;
  110040. break;
  110041. }
  110042. default: {
  110043. throw new Error(context + ": Invalid camera type (" + camera.type + ")");
  110044. }
  110045. }
  110046. this._parent.onCameraLoadedObservable.notifyObservers(babylonCamera);
  110047. };
  110048. GLTFLoader.prototype._loadAnimationsAsync = function () {
  110049. var animations = this._gltf.animations;
  110050. if (!animations) {
  110051. return Promise.resolve();
  110052. }
  110053. var promises = new Array();
  110054. for (var index = 0; index < animations.length; index++) {
  110055. var animation = animations[index];
  110056. promises.push(this._loadAnimationAsync("#/animations/" + index, animation));
  110057. }
  110058. return Promise.all(promises).then(function () { });
  110059. };
  110060. GLTFLoader.prototype._loadAnimationAsync = function (context, animation) {
  110061. var _this = this;
  110062. var babylonAnimationGroup = new BABYLON.AnimationGroup(animation.name || "animation" + animation._index, this._babylonScene);
  110063. animation._babylonAnimationGroup = babylonAnimationGroup;
  110064. var promises = new Array();
  110065. _ArrayItem.Assign(animation.channels);
  110066. _ArrayItem.Assign(animation.samplers);
  110067. for (var _i = 0, _a = animation.channels; _i < _a.length; _i++) {
  110068. var channel = _a[_i];
  110069. promises.push(this._loadAnimationChannelAsync(context + "/channels/" + channel._index, context, animation, channel, babylonAnimationGroup));
  110070. }
  110071. return Promise.all(promises).then(function () {
  110072. babylonAnimationGroup.normalize(_this._parent._normalizeAnimationGroupsToBeginAtZero ? 0 : null);
  110073. });
  110074. };
  110075. GLTFLoader.prototype._loadAnimationChannelAsync = function (context, animationContext, animation, channel, babylonAnimationGroup) {
  110076. var _this = this;
  110077. var targetNode = GLTFLoader._GetProperty(context + "/target/node", this._gltf.nodes, channel.target.node);
  110078. // Ignore animations that have no animation targets.
  110079. if ((channel.target.path === "weights" /* WEIGHTS */ && !targetNode._numMorphTargets) ||
  110080. (channel.target.path !== "weights" /* WEIGHTS */ && !targetNode._babylonMesh)) {
  110081. return Promise.resolve();
  110082. }
  110083. // Ignore animations targeting TRS of skinned nodes.
  110084. // See https://github.com/KhronosGroup/glTF/tree/master/specification/2.0#skins (second implementation note)
  110085. if (targetNode.skin != undefined && channel.target.path !== "weights" /* WEIGHTS */) {
  110086. return Promise.resolve();
  110087. }
  110088. var sampler = GLTFLoader._GetProperty(context + "/sampler", animation.samplers, channel.sampler);
  110089. return this._loadAnimationSamplerAsync(animationContext + "/samplers/" + channel.sampler, sampler).then(function (data) {
  110090. var targetPath;
  110091. var animationType;
  110092. switch (channel.target.path) {
  110093. case "translation" /* TRANSLATION */: {
  110094. targetPath = "position";
  110095. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110096. break;
  110097. }
  110098. case "rotation" /* ROTATION */: {
  110099. targetPath = "rotationQuaternion";
  110100. animationType = BABYLON.Animation.ANIMATIONTYPE_QUATERNION;
  110101. break;
  110102. }
  110103. case "scale" /* SCALE */: {
  110104. targetPath = "scaling";
  110105. animationType = BABYLON.Animation.ANIMATIONTYPE_VECTOR3;
  110106. break;
  110107. }
  110108. case "weights" /* WEIGHTS */: {
  110109. targetPath = "influence";
  110110. animationType = BABYLON.Animation.ANIMATIONTYPE_FLOAT;
  110111. break;
  110112. }
  110113. default: {
  110114. throw new Error(context + ": Invalid target path (" + channel.target.path + ")");
  110115. }
  110116. }
  110117. var outputBufferOffset = 0;
  110118. var getNextOutputValue;
  110119. switch (targetPath) {
  110120. case "position": {
  110121. getNextOutputValue = function () {
  110122. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110123. outputBufferOffset += 3;
  110124. return value;
  110125. };
  110126. break;
  110127. }
  110128. case "rotationQuaternion": {
  110129. getNextOutputValue = function () {
  110130. var value = BABYLON.Quaternion.FromArray(data.output, outputBufferOffset);
  110131. outputBufferOffset += 4;
  110132. return value;
  110133. };
  110134. break;
  110135. }
  110136. case "scaling": {
  110137. getNextOutputValue = function () {
  110138. var value = BABYLON.Vector3.FromArray(data.output, outputBufferOffset);
  110139. outputBufferOffset += 3;
  110140. return value;
  110141. };
  110142. break;
  110143. }
  110144. case "influence": {
  110145. getNextOutputValue = function () {
  110146. var value = new Array(targetNode._numMorphTargets);
  110147. for (var i = 0; i < targetNode._numMorphTargets; i++) {
  110148. value[i] = data.output[outputBufferOffset++];
  110149. }
  110150. return value;
  110151. };
  110152. break;
  110153. }
  110154. }
  110155. var getNextKey;
  110156. switch (data.interpolation) {
  110157. case "STEP" /* STEP */: {
  110158. getNextKey = function (frameIndex) { return ({
  110159. frame: data.input[frameIndex],
  110160. value: getNextOutputValue(),
  110161. interpolation: BABYLON.AnimationKeyInterpolation.STEP
  110162. }); };
  110163. break;
  110164. }
  110165. case "LINEAR" /* LINEAR */: {
  110166. getNextKey = function (frameIndex) { return ({
  110167. frame: data.input[frameIndex],
  110168. value: getNextOutputValue()
  110169. }); };
  110170. break;
  110171. }
  110172. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110173. getNextKey = function (frameIndex) { return ({
  110174. frame: data.input[frameIndex],
  110175. inTangent: getNextOutputValue(),
  110176. value: getNextOutputValue(),
  110177. outTangent: getNextOutputValue()
  110178. }); };
  110179. break;
  110180. }
  110181. }
  110182. var keys = new Array(data.input.length);
  110183. for (var frameIndex = 0; frameIndex < data.input.length; frameIndex++) {
  110184. keys[frameIndex] = getNextKey(frameIndex);
  110185. }
  110186. if (targetPath === "influence") {
  110187. var _loop_1 = function (targetIndex) {
  110188. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110189. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110190. babylonAnimation.setKeys(keys.map(function (key) { return ({
  110191. frame: key.frame,
  110192. inTangent: key.inTangent ? key.inTangent[targetIndex] : undefined,
  110193. value: key.value[targetIndex],
  110194. outTangent: key.outTangent ? key.outTangent[targetIndex] : undefined
  110195. }); }));
  110196. _this._forEachPrimitive(targetNode, function (babylonMesh) {
  110197. var morphTarget = babylonMesh.morphTargetManager.getTarget(targetIndex);
  110198. var babylonAnimationClone = babylonAnimation.clone();
  110199. morphTarget.animations.push(babylonAnimationClone);
  110200. babylonAnimationGroup.addTargetedAnimation(babylonAnimationClone, morphTarget);
  110201. });
  110202. };
  110203. for (var targetIndex = 0; targetIndex < targetNode._numMorphTargets; targetIndex++) {
  110204. _loop_1(targetIndex);
  110205. }
  110206. }
  110207. else {
  110208. var animationName = babylonAnimationGroup.name + "_channel" + babylonAnimationGroup.targetedAnimations.length;
  110209. var babylonAnimation = new BABYLON.Animation(animationName, targetPath, 1, animationType);
  110210. babylonAnimation.setKeys(keys);
  110211. if (targetNode._babylonBones) {
  110212. var babylonAnimationTargets = [targetNode._babylonMesh].concat(targetNode._babylonBones);
  110213. for (var _i = 0, babylonAnimationTargets_1 = babylonAnimationTargets; _i < babylonAnimationTargets_1.length; _i++) {
  110214. var babylonAnimationTarget = babylonAnimationTargets_1[_i];
  110215. babylonAnimationTarget.animations.push(babylonAnimation);
  110216. }
  110217. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, babylonAnimationTargets);
  110218. }
  110219. else {
  110220. targetNode._babylonMesh.animations.push(babylonAnimation);
  110221. babylonAnimationGroup.addTargetedAnimation(babylonAnimation, targetNode._babylonMesh);
  110222. }
  110223. }
  110224. });
  110225. };
  110226. GLTFLoader.prototype._loadAnimationSamplerAsync = function (context, sampler) {
  110227. if (sampler._data) {
  110228. return sampler._data;
  110229. }
  110230. var interpolation = sampler.interpolation || "LINEAR" /* LINEAR */;
  110231. switch (interpolation) {
  110232. case "STEP" /* STEP */:
  110233. case "LINEAR" /* LINEAR */:
  110234. case "CUBICSPLINE" /* CUBICSPLINE */: {
  110235. break;
  110236. }
  110237. default: {
  110238. throw new Error(context + ": Invalid interpolation (" + sampler.interpolation + ")");
  110239. }
  110240. }
  110241. var inputAccessor = GLTFLoader._GetProperty(context + "/input", this._gltf.accessors, sampler.input);
  110242. var outputAccessor = GLTFLoader._GetProperty(context + "/output", this._gltf.accessors, sampler.output);
  110243. sampler._data = Promise.all([
  110244. this._loadFloatAccessorAsync("#/accessors/" + inputAccessor._index, inputAccessor),
  110245. this._loadFloatAccessorAsync("#/accessors/" + outputAccessor._index, outputAccessor)
  110246. ]).then(function (_a) {
  110247. var inputData = _a[0], outputData = _a[1];
  110248. return {
  110249. input: inputData,
  110250. interpolation: interpolation,
  110251. output: outputData,
  110252. };
  110253. });
  110254. return sampler._data;
  110255. };
  110256. GLTFLoader.prototype._loadBufferAsync = function (context, buffer) {
  110257. if (buffer._data) {
  110258. return buffer._data;
  110259. }
  110260. if (!buffer.uri) {
  110261. throw new Error(context + ": Uri is missing");
  110262. }
  110263. buffer._data = this._loadUriAsync(context, buffer.uri);
  110264. return buffer._data;
  110265. };
  110266. GLTFLoader.prototype._loadBufferViewAsync = function (context, bufferView) {
  110267. if (bufferView._data) {
  110268. return bufferView._data;
  110269. }
  110270. var buffer = GLTFLoader._GetProperty(context + "/buffer", this._gltf.buffers, bufferView.buffer);
  110271. bufferView._data = this._loadBufferAsync("#/buffers/" + buffer._index, buffer).then(function (data) {
  110272. try {
  110273. return new Uint8Array(data.buffer, data.byteOffset + (bufferView.byteOffset || 0), bufferView.byteLength);
  110274. }
  110275. catch (e) {
  110276. throw new Error(context + ": " + e.message);
  110277. }
  110278. });
  110279. return bufferView._data;
  110280. };
  110281. GLTFLoader.prototype._loadIndicesAccessorAsync = function (context, accessor) {
  110282. if (accessor.type !== "SCALAR" /* SCALAR */) {
  110283. throw new Error(context + ": Invalid type " + accessor.type);
  110284. }
  110285. if (accessor.componentType !== 5121 /* UNSIGNED_BYTE */ &&
  110286. accessor.componentType !== 5123 /* UNSIGNED_SHORT */ &&
  110287. accessor.componentType !== 5125 /* UNSIGNED_INT */) {
  110288. throw new Error(context + ": Invalid component type " + accessor.componentType);
  110289. }
  110290. if (accessor._data) {
  110291. return accessor._data;
  110292. }
  110293. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110294. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110295. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, accessor.count);
  110296. });
  110297. return accessor._data;
  110298. };
  110299. GLTFLoader.prototype._loadFloatAccessorAsync = function (context, accessor) {
  110300. // TODO: support normalized and stride
  110301. var _this = this;
  110302. if (accessor.componentType !== 5126 /* FLOAT */) {
  110303. throw new Error("Invalid component type " + accessor.componentType);
  110304. }
  110305. if (accessor._data) {
  110306. return accessor._data;
  110307. }
  110308. var numComponents = GLTFLoader._GetNumComponents(context, accessor.type);
  110309. var length = numComponents * accessor.count;
  110310. if (accessor.bufferView == undefined) {
  110311. accessor._data = Promise.resolve(new Float32Array(length));
  110312. }
  110313. else {
  110314. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110315. accessor._data = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  110316. return GLTFLoader._GetTypedArray(context, accessor.componentType, data, accessor.byteOffset, length);
  110317. });
  110318. }
  110319. if (accessor.sparse) {
  110320. var sparse_1 = accessor.sparse;
  110321. accessor._data = accessor._data.then(function (data) {
  110322. var indicesBufferView = GLTFLoader._GetProperty(context + "/sparse/indices/bufferView", _this._gltf.bufferViews, sparse_1.indices.bufferView);
  110323. var valuesBufferView = GLTFLoader._GetProperty(context + "/sparse/values/bufferView", _this._gltf.bufferViews, sparse_1.values.bufferView);
  110324. return Promise.all([
  110325. _this._loadBufferViewAsync("#/bufferViews/" + indicesBufferView._index, indicesBufferView),
  110326. _this._loadBufferViewAsync("#/bufferViews/" + valuesBufferView._index, valuesBufferView)
  110327. ]).then(function (_a) {
  110328. var indicesData = _a[0], valuesData = _a[1];
  110329. var indices = GLTFLoader._GetTypedArray(context + "/sparse/indices", sparse_1.indices.componentType, indicesData, sparse_1.indices.byteOffset, sparse_1.count);
  110330. var values = GLTFLoader._GetTypedArray(context + "/sparse/values", accessor.componentType, valuesData, sparse_1.values.byteOffset, numComponents * sparse_1.count);
  110331. var valuesIndex = 0;
  110332. for (var indicesIndex = 0; indicesIndex < indices.length; indicesIndex++) {
  110333. var dataIndex = indices[indicesIndex] * numComponents;
  110334. for (var componentIndex = 0; componentIndex < numComponents; componentIndex++) {
  110335. data[dataIndex++] = values[valuesIndex++];
  110336. }
  110337. }
  110338. return data;
  110339. });
  110340. });
  110341. }
  110342. return accessor._data;
  110343. };
  110344. GLTFLoader.prototype._loadVertexBufferViewAsync = function (context, bufferView, kind) {
  110345. var _this = this;
  110346. if (bufferView._babylonBuffer) {
  110347. return bufferView._babylonBuffer;
  110348. }
  110349. bufferView._babylonBuffer = this._loadBufferViewAsync(context, bufferView).then(function (data) {
  110350. return new BABYLON.Buffer(_this._babylonScene.getEngine(), data, false);
  110351. });
  110352. return bufferView._babylonBuffer;
  110353. };
  110354. GLTFLoader.prototype._loadVertexAccessorAsync = function (context, accessor, kind) {
  110355. var _this = this;
  110356. if (accessor._babylonVertexBuffer) {
  110357. return accessor._babylonVertexBuffer;
  110358. }
  110359. if (accessor.sparse) {
  110360. accessor._babylonVertexBuffer = this._loadFloatAccessorAsync(context, accessor).then(function (data) {
  110361. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), data, kind, false);
  110362. });
  110363. }
  110364. else {
  110365. var bufferView_1 = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, accessor.bufferView);
  110366. accessor._babylonVertexBuffer = this._loadVertexBufferViewAsync("#/bufferViews/" + bufferView_1._index, bufferView_1, kind).then(function (buffer) {
  110367. var size = GLTFLoader._GetNumComponents(context, accessor.type);
  110368. return new BABYLON.VertexBuffer(_this._babylonScene.getEngine(), buffer, kind, false, false, bufferView_1.byteStride, false, accessor.byteOffset, size, accessor.componentType, accessor.normalized, true);
  110369. });
  110370. }
  110371. return accessor._babylonVertexBuffer;
  110372. };
  110373. GLTFLoader.prototype._getDefaultMaterial = function (drawMode) {
  110374. var babylonMaterial = this._defaultBabylonMaterials[drawMode];
  110375. if (!babylonMaterial) {
  110376. babylonMaterial = this._createMaterial("__gltf_default", drawMode);
  110377. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110378. babylonMaterial.metallic = 1;
  110379. babylonMaterial.roughness = 1;
  110380. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110381. }
  110382. return babylonMaterial;
  110383. };
  110384. GLTFLoader.prototype._loadMaterialMetallicRoughnessPropertiesAsync = function (context, material, babylonMaterial) {
  110385. var promises = new Array();
  110386. // Ensure metallic workflow
  110387. babylonMaterial.metallic = 1;
  110388. babylonMaterial.roughness = 1;
  110389. var properties = material.pbrMetallicRoughness;
  110390. if (properties) {
  110391. if (properties.baseColorFactor) {
  110392. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  110393. babylonMaterial.alpha = properties.baseColorFactor[3];
  110394. }
  110395. else {
  110396. babylonMaterial.albedoColor = BABYLON.Color3.White();
  110397. }
  110398. babylonMaterial.metallic = properties.metallicFactor == undefined ? 1 : properties.metallicFactor;
  110399. babylonMaterial.roughness = properties.roughnessFactor == undefined ? 1 : properties.roughnessFactor;
  110400. if (properties.baseColorTexture) {
  110401. promises.push(this._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  110402. babylonMaterial.albedoTexture = texture;
  110403. }));
  110404. }
  110405. if (properties.metallicRoughnessTexture) {
  110406. promises.push(this._loadTextureAsync(context + "/metallicRoughnessTexture", properties.metallicRoughnessTexture, function (texture) {
  110407. babylonMaterial.metallicTexture = texture;
  110408. }));
  110409. babylonMaterial.useMetallnessFromMetallicTextureBlue = true;
  110410. babylonMaterial.useRoughnessFromMetallicTextureGreen = true;
  110411. babylonMaterial.useRoughnessFromMetallicTextureAlpha = false;
  110412. }
  110413. }
  110414. this._loadMaterialAlphaProperties(context, material, babylonMaterial);
  110415. return Promise.all(promises).then(function () { });
  110416. };
  110417. GLTFLoader.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110418. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialAsync(this, context, material, mesh, babylonMesh, babylonDrawMode, assign);
  110419. if (promise) {
  110420. return promise;
  110421. }
  110422. material._babylonData = material._babylonData || {};
  110423. var babylonData = material._babylonData[babylonDrawMode];
  110424. if (!babylonData) {
  110425. this._parent._logOpen(context + " " + (material.name || ""));
  110426. var name_4 = material.name || "material" + material._index;
  110427. var babylonMaterial = this._createMaterial(name_4, babylonDrawMode);
  110428. babylonData = {
  110429. material: babylonMaterial,
  110430. meshes: [],
  110431. loaded: this._loadMaterialPropertiesAsync(context, material, babylonMaterial)
  110432. };
  110433. material._babylonData[babylonDrawMode] = babylonData;
  110434. this._parent.onMaterialLoadedObservable.notifyObservers(babylonMaterial);
  110435. this._parent._logClose();
  110436. }
  110437. babylonData.meshes.push(babylonMesh);
  110438. babylonMesh.onDisposeObservable.addOnce(function () {
  110439. var index = babylonData.meshes.indexOf(babylonMesh);
  110440. if (index !== -1) {
  110441. babylonData.meshes.splice(index, 1);
  110442. }
  110443. });
  110444. assign(babylonData.material);
  110445. return babylonData.loaded;
  110446. };
  110447. GLTFLoader.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  110448. var promise = GLTF2.GLTFLoaderExtension._LoadMaterialPropertiesAsync(this, context, material, babylonMaterial);
  110449. if (promise) {
  110450. return promise;
  110451. }
  110452. var promises = new Array();
  110453. promises.push(this._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  110454. promises.push(this._loadMaterialMetallicRoughnessPropertiesAsync(context, material, babylonMaterial));
  110455. return Promise.all(promises).then(function () { });
  110456. };
  110457. GLTFLoader.prototype._createMaterial = function (name, drawMode) {
  110458. var babylonMaterial = new BABYLON.PBRMaterial(name, this._babylonScene);
  110459. babylonMaterial.sideOrientation = this._babylonScene.useRightHandedSystem ? BABYLON.Material.CounterClockWiseSideOrientation : BABYLON.Material.ClockWiseSideOrientation;
  110460. babylonMaterial.fillMode = drawMode;
  110461. babylonMaterial.enableSpecularAntiAliasing = true;
  110462. babylonMaterial.useRadianceOverAlpha = !this._parent.transparencyAsCoverage;
  110463. babylonMaterial.useSpecularOverAlpha = !this._parent.transparencyAsCoverage;
  110464. return babylonMaterial;
  110465. };
  110466. GLTFLoader.prototype._loadMaterialBasePropertiesAsync = function (context, material, babylonMaterial) {
  110467. var promises = new Array();
  110468. babylonMaterial.emissiveColor = material.emissiveFactor ? BABYLON.Color3.FromArray(material.emissiveFactor) : new BABYLON.Color3(0, 0, 0);
  110469. if (material.doubleSided) {
  110470. babylonMaterial.backFaceCulling = false;
  110471. babylonMaterial.twoSidedLighting = true;
  110472. }
  110473. if (material.normalTexture) {
  110474. promises.push(this._loadTextureAsync(context + "/normalTexture", material.normalTexture, function (texture) {
  110475. babylonMaterial.bumpTexture = texture;
  110476. }));
  110477. babylonMaterial.invertNormalMapX = !this._babylonScene.useRightHandedSystem;
  110478. babylonMaterial.invertNormalMapY = this._babylonScene.useRightHandedSystem;
  110479. if (material.normalTexture.scale != undefined) {
  110480. babylonMaterial.bumpTexture.level = material.normalTexture.scale;
  110481. }
  110482. }
  110483. if (material.occlusionTexture) {
  110484. promises.push(this._loadTextureAsync(context + "/occlusionTexture", material.occlusionTexture, function (texture) {
  110485. babylonMaterial.ambientTexture = texture;
  110486. }));
  110487. babylonMaterial.useAmbientInGrayScale = true;
  110488. if (material.occlusionTexture.strength != undefined) {
  110489. babylonMaterial.ambientTextureStrength = material.occlusionTexture.strength;
  110490. }
  110491. }
  110492. if (material.emissiveTexture) {
  110493. promises.push(this._loadTextureAsync(context + "/emissiveTexture", material.emissiveTexture, function (texture) {
  110494. babylonMaterial.emissiveTexture = texture;
  110495. }));
  110496. }
  110497. return Promise.all(promises).then(function () { });
  110498. };
  110499. GLTFLoader.prototype._loadMaterialAlphaProperties = function (context, material, babylonMaterial) {
  110500. var alphaMode = material.alphaMode || "OPAQUE" /* OPAQUE */;
  110501. switch (alphaMode) {
  110502. case "OPAQUE" /* OPAQUE */: {
  110503. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_OPAQUE;
  110504. break;
  110505. }
  110506. case "MASK" /* MASK */: {
  110507. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHATEST;
  110508. babylonMaterial.alphaCutOff = (material.alphaCutoff == undefined ? 0.5 : material.alphaCutoff);
  110509. if (babylonMaterial.albedoTexture) {
  110510. babylonMaterial.albedoTexture.hasAlpha = true;
  110511. }
  110512. break;
  110513. }
  110514. case "BLEND" /* BLEND */: {
  110515. babylonMaterial.transparencyMode = BABYLON.PBRMaterial.PBRMATERIAL_ALPHABLEND;
  110516. if (babylonMaterial.albedoTexture) {
  110517. babylonMaterial.albedoTexture.hasAlpha = true;
  110518. babylonMaterial.useAlphaFromAlbedoTexture = true;
  110519. }
  110520. break;
  110521. }
  110522. default: {
  110523. throw new Error(context + ": Invalid alpha mode (" + material.alphaMode + ")");
  110524. }
  110525. }
  110526. };
  110527. GLTFLoader.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  110528. var _this = this;
  110529. var promise = GLTF2.GLTFLoaderExtension._LoadTextureAsync(this, context, textureInfo, assign);
  110530. if (promise) {
  110531. return promise;
  110532. }
  110533. this._parent._logOpen("" + context);
  110534. var texture = GLTFLoader._GetProperty(context + "/index", this._gltf.textures, textureInfo.index);
  110535. context = "#/textures/" + textureInfo.index;
  110536. var promises = new Array();
  110537. this._parent._logOpen(context + " " + (texture.name || ""));
  110538. var sampler = (texture.sampler == undefined ? this._defaultSampler : GLTFLoader._GetProperty(context + "/sampler", this._gltf.samplers, texture.sampler));
  110539. var samplerData = this._loadSampler("#/samplers/" + sampler._index, sampler);
  110540. var deferred = new BABYLON.Deferred();
  110541. var babylonTexture = new BABYLON.Texture(null, this._babylonScene, samplerData.noMipMaps, false, samplerData.samplingMode, function () {
  110542. if (!_this._disposed) {
  110543. deferred.resolve();
  110544. }
  110545. }, function (message, exception) {
  110546. if (!_this._disposed) {
  110547. deferred.reject(new Error(context + ": " + ((exception && exception.message) ? exception.message : message || "Failed to load texture")));
  110548. }
  110549. });
  110550. promises.push(deferred.promise);
  110551. babylonTexture.name = texture.name || "texture" + texture._index;
  110552. babylonTexture.wrapU = samplerData.wrapU;
  110553. babylonTexture.wrapV = samplerData.wrapV;
  110554. babylonTexture.coordinatesIndex = textureInfo.texCoord || 0;
  110555. var image = GLTFLoader._GetProperty(context + "/source", this._gltf.images, texture.source);
  110556. promises.push(this._loadImageAsync("#/images/" + image._index, image).then(function (blob) {
  110557. var dataUrl = "data:" + _this._rootUrl + (image.uri || "image" + image._index);
  110558. babylonTexture.updateURL(dataUrl, blob);
  110559. }));
  110560. assign(babylonTexture);
  110561. this._parent.onTextureLoadedObservable.notifyObservers(babylonTexture);
  110562. this._parent._logClose();
  110563. this._parent._logClose();
  110564. return Promise.all(promises).then(function () { });
  110565. };
  110566. GLTFLoader.prototype._loadSampler = function (context, sampler) {
  110567. if (!sampler._data) {
  110568. sampler._data = {
  110569. noMipMaps: (sampler.minFilter === 9728 /* NEAREST */ || sampler.minFilter === 9729 /* LINEAR */),
  110570. samplingMode: GLTFLoader._GetTextureSamplingMode(context, sampler.magFilter, sampler.minFilter),
  110571. wrapU: GLTFLoader._GetTextureWrapMode(context, sampler.wrapS),
  110572. wrapV: GLTFLoader._GetTextureWrapMode(context, sampler.wrapT)
  110573. };
  110574. }
  110575. ;
  110576. return sampler._data;
  110577. };
  110578. GLTFLoader.prototype._loadImageAsync = function (context, image) {
  110579. if (!image._blob) {
  110580. this._parent._logOpen(context + " " + (image.name || ""));
  110581. var promise = void 0;
  110582. if (image.uri) {
  110583. promise = this._loadUriAsync(context, image.uri);
  110584. }
  110585. else {
  110586. var bufferView = GLTFLoader._GetProperty(context + "/bufferView", this._gltf.bufferViews, image.bufferView);
  110587. promise = this._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView);
  110588. }
  110589. image._blob = promise.then(function (data) {
  110590. return new Blob([data], { type: image.mimeType });
  110591. });
  110592. this._parent._logClose();
  110593. }
  110594. return image._blob;
  110595. };
  110596. GLTFLoader.prototype._loadUriAsync = function (context, uri) {
  110597. var _this = this;
  110598. var promise = GLTF2.GLTFLoaderExtension._LoadUriAsync(this, context, uri);
  110599. if (promise) {
  110600. return promise;
  110601. }
  110602. if (!GLTFLoader._ValidateUri(uri)) {
  110603. throw new Error(context + ": Uri '" + uri + "' is invalid");
  110604. }
  110605. if (BABYLON.Tools.IsBase64(uri)) {
  110606. var data = new Uint8Array(BABYLON.Tools.DecodeBase64(uri));
  110607. this._parent._log("Decoded " + uri.substr(0, 64) + "... (" + data.length + " bytes)");
  110608. return Promise.resolve(data);
  110609. }
  110610. this._parent._log("Loading " + uri);
  110611. return this._parent.preprocessUrlAsync(this._rootUrl + uri).then(function (url) {
  110612. return new Promise(function (resolve, reject) {
  110613. if (!_this._disposed) {
  110614. var request_1 = BABYLON.Tools.LoadFile(url, function (fileData) {
  110615. if (!_this._disposed) {
  110616. var data = new Uint8Array(fileData);
  110617. _this._parent._log("Loaded " + uri + " (" + data.length + " bytes)");
  110618. resolve(data);
  110619. }
  110620. }, function (event) {
  110621. if (!_this._disposed) {
  110622. if (request_1) {
  110623. request_1._lengthComputable = event.lengthComputable;
  110624. request_1._loaded = event.loaded;
  110625. request_1._total = event.total;
  110626. }
  110627. if (_this._state === BABYLON.GLTFLoaderState.LOADING) {
  110628. try {
  110629. _this._onProgress();
  110630. }
  110631. catch (e) {
  110632. reject(e);
  110633. }
  110634. }
  110635. }
  110636. }, _this._babylonScene.database, true, function (request, exception) {
  110637. if (!_this._disposed) {
  110638. reject(new BABYLON.LoadFileError(context + ": Failed to load '" + uri + "'" + (request ? ": " + request.status + " " + request.statusText : ""), request));
  110639. }
  110640. });
  110641. _this._requests.push(request_1);
  110642. }
  110643. });
  110644. });
  110645. };
  110646. GLTFLoader.prototype._onProgress = function () {
  110647. if (!this._progressCallback) {
  110648. return;
  110649. }
  110650. var lengthComputable = true;
  110651. var loaded = 0;
  110652. var total = 0;
  110653. for (var _i = 0, _a = this._requests; _i < _a.length; _i++) {
  110654. var request = _a[_i];
  110655. if (request._lengthComputable === undefined || request._loaded === undefined || request._total === undefined) {
  110656. return;
  110657. }
  110658. lengthComputable = lengthComputable && request._lengthComputable;
  110659. loaded += request._loaded;
  110660. total += request._total;
  110661. }
  110662. this._progressCallback(new BABYLON.SceneLoaderProgressEvent(lengthComputable, loaded, lengthComputable ? total : 0));
  110663. };
  110664. GLTFLoader._GetProperty = function (context, array, index) {
  110665. if (!array || index == undefined || !array[index]) {
  110666. throw new Error(context + ": Failed to find index (" + index + ")");
  110667. }
  110668. return array[index];
  110669. };
  110670. GLTFLoader._GetTextureWrapMode = function (context, mode) {
  110671. // Set defaults if undefined
  110672. mode = mode == undefined ? 10497 /* REPEAT */ : mode;
  110673. switch (mode) {
  110674. case 33071 /* CLAMP_TO_EDGE */: return BABYLON.Texture.CLAMP_ADDRESSMODE;
  110675. case 33648 /* MIRRORED_REPEAT */: return BABYLON.Texture.MIRROR_ADDRESSMODE;
  110676. case 10497 /* REPEAT */: return BABYLON.Texture.WRAP_ADDRESSMODE;
  110677. default:
  110678. BABYLON.Tools.Warn(context + ": Invalid texture wrap mode (" + mode + ")");
  110679. return BABYLON.Texture.WRAP_ADDRESSMODE;
  110680. }
  110681. };
  110682. GLTFLoader._GetTextureSamplingMode = function (context, magFilter, minFilter) {
  110683. // Set defaults if undefined
  110684. magFilter = magFilter == undefined ? 9729 /* LINEAR */ : magFilter;
  110685. minFilter = minFilter == undefined ? 9987 /* LINEAR_MIPMAP_LINEAR */ : minFilter;
  110686. if (magFilter === 9729 /* LINEAR */) {
  110687. switch (minFilter) {
  110688. case 9728 /* NEAREST */: return BABYLON.Texture.LINEAR_NEAREST;
  110689. case 9729 /* LINEAR */: return BABYLON.Texture.LINEAR_LINEAR;
  110690. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_NEAREST_MIPNEAREST;
  110691. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.LINEAR_LINEAR_MIPNEAREST;
  110692. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_NEAREST_MIPLINEAR;
  110693. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110694. default:
  110695. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110696. return BABYLON.Texture.LINEAR_LINEAR_MIPLINEAR;
  110697. }
  110698. }
  110699. else {
  110700. if (magFilter !== 9728 /* NEAREST */) {
  110701. BABYLON.Tools.Warn(context + ": Invalid texture magnification filter (" + magFilter + ")");
  110702. }
  110703. switch (minFilter) {
  110704. case 9728 /* NEAREST */: return BABYLON.Texture.NEAREST_NEAREST;
  110705. case 9729 /* LINEAR */: return BABYLON.Texture.NEAREST_LINEAR;
  110706. case 9984 /* NEAREST_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110707. case 9985 /* LINEAR_MIPMAP_NEAREST */: return BABYLON.Texture.NEAREST_LINEAR_MIPNEAREST;
  110708. case 9986 /* NEAREST_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_NEAREST_MIPLINEAR;
  110709. case 9987 /* LINEAR_MIPMAP_LINEAR */: return BABYLON.Texture.NEAREST_LINEAR_MIPLINEAR;
  110710. default:
  110711. BABYLON.Tools.Warn(context + ": Invalid texture minification filter (" + minFilter + ")");
  110712. return BABYLON.Texture.NEAREST_NEAREST_MIPNEAREST;
  110713. }
  110714. }
  110715. };
  110716. GLTFLoader._GetTypedArray = function (context, componentType, bufferView, byteOffset, length) {
  110717. var buffer = bufferView.buffer;
  110718. byteOffset = bufferView.byteOffset + (byteOffset || 0);
  110719. try {
  110720. switch (componentType) {
  110721. case 5120 /* BYTE */: return new Int8Array(buffer, byteOffset, length);
  110722. case 5121 /* UNSIGNED_BYTE */: return new Uint8Array(buffer, byteOffset, length);
  110723. case 5122 /* SHORT */: return new Int16Array(buffer, byteOffset, length);
  110724. case 5123 /* UNSIGNED_SHORT */: return new Uint16Array(buffer, byteOffset, length);
  110725. case 5125 /* UNSIGNED_INT */: return new Uint32Array(buffer, byteOffset, length);
  110726. case 5126 /* FLOAT */: return new Float32Array(buffer, byteOffset, length);
  110727. default: throw new Error("Invalid component type " + componentType);
  110728. }
  110729. }
  110730. catch (e) {
  110731. throw new Error(context + ": " + e);
  110732. }
  110733. };
  110734. GLTFLoader._GetNumComponents = function (context, type) {
  110735. switch (type) {
  110736. case "SCALAR": return 1;
  110737. case "VEC2": return 2;
  110738. case "VEC3": return 3;
  110739. case "VEC4": return 4;
  110740. case "MAT2": return 4;
  110741. case "MAT3": return 9;
  110742. case "MAT4": return 16;
  110743. }
  110744. throw new Error(context + ": Invalid type (" + type + ")");
  110745. };
  110746. GLTFLoader._ValidateUri = function (uri) {
  110747. return (BABYLON.Tools.IsBase64(uri) || uri.indexOf("..") === -1);
  110748. };
  110749. GLTFLoader._GetDrawMode = function (context, mode) {
  110750. if (mode == undefined) {
  110751. mode = 4 /* TRIANGLES */;
  110752. }
  110753. switch (mode) {
  110754. case 0 /* POINTS */: return BABYLON.Material.PointListDrawMode;
  110755. case 1 /* LINES */: return BABYLON.Material.LineListDrawMode;
  110756. case 2 /* LINE_LOOP */: return BABYLON.Material.LineLoopDrawMode;
  110757. case 3 /* LINE_STRIP */: return BABYLON.Material.LineStripDrawMode;
  110758. case 4 /* TRIANGLES */: return BABYLON.Material.TriangleFillMode;
  110759. case 5 /* TRIANGLE_STRIP */: return BABYLON.Material.TriangleStripDrawMode;
  110760. case 6 /* TRIANGLE_FAN */: return BABYLON.Material.TriangleFanDrawMode;
  110761. }
  110762. throw new Error(context + ": Invalid mesh primitive mode (" + mode + ")");
  110763. };
  110764. GLTFLoader.prototype._compileMaterialsAsync = function () {
  110765. var _this = this;
  110766. this._parent._startPerformanceCounter("Compile materials");
  110767. var promises = new Array();
  110768. if (this._gltf.materials) {
  110769. for (var _i = 0, _a = this._gltf.materials; _i < _a.length; _i++) {
  110770. var material = _a[_i];
  110771. if (material._babylonData) {
  110772. for (var babylonDrawMode in material._babylonData) {
  110773. var babylonData = material._babylonData[babylonDrawMode];
  110774. for (var _b = 0, _c = babylonData.meshes; _b < _c.length; _b++) {
  110775. var babylonMesh = _c[_b];
  110776. // Ensure nonUniformScaling is set if necessary.
  110777. babylonMesh.computeWorldMatrix(true);
  110778. var babylonMaterial = babylonData.material;
  110779. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh));
  110780. if (this._parent.useClipPlane) {
  110781. promises.push(babylonMaterial.forceCompilationAsync(babylonMesh, { clipPlane: true }));
  110782. }
  110783. }
  110784. }
  110785. }
  110786. }
  110787. }
  110788. return Promise.all(promises).then(function () {
  110789. _this._parent._endPerformanceCounter("Compile materials");
  110790. });
  110791. };
  110792. GLTFLoader.prototype._compileShadowGeneratorsAsync = function () {
  110793. var _this = this;
  110794. this._parent._startPerformanceCounter("Compile shadow generators");
  110795. var promises = new Array();
  110796. var lights = this._babylonScene.lights;
  110797. for (var _i = 0, lights_1 = lights; _i < lights_1.length; _i++) {
  110798. var light = lights_1[_i];
  110799. var generator = light.getShadowGenerator();
  110800. if (generator) {
  110801. promises.push(generator.forceCompilationAsync());
  110802. }
  110803. }
  110804. return Promise.all(promises).then(function () {
  110805. _this._parent._endPerformanceCounter("Compile shadow generators");
  110806. });
  110807. };
  110808. GLTFLoader.prototype._applyExtensions = function (actionAsync) {
  110809. for (var _i = 0, _a = GLTFLoader._ExtensionNames; _i < _a.length; _i++) {
  110810. var name_5 = _a[_i];
  110811. var extension = this._extensions[name_5];
  110812. if (extension.enabled) {
  110813. var promise = actionAsync(extension);
  110814. if (promise) {
  110815. return promise;
  110816. }
  110817. }
  110818. }
  110819. return null;
  110820. };
  110821. GLTFLoader._ExtensionNames = new Array();
  110822. GLTFLoader._ExtensionFactories = {};
  110823. return GLTFLoader;
  110824. }());
  110825. GLTF2.GLTFLoader = GLTFLoader;
  110826. BABYLON.GLTFFileLoader._CreateGLTFLoaderV2 = function (parent) { return new GLTFLoader(parent); };
  110827. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110828. })(BABYLON || (BABYLON = {}));
  110829. //# sourceMappingURL=babylon.glTFLoader.js.map
  110830. var BABYLON;
  110831. (function (BABYLON) {
  110832. var GLTF2;
  110833. (function (GLTF2) {
  110834. /**
  110835. * Abstract class that can be implemented to extend existing glTF loader behavior.
  110836. */
  110837. var GLTFLoaderExtension = /** @class */ (function () {
  110838. /**
  110839. * Creates new GLTFLoaderExtension
  110840. * @param loader defines the GLTFLoader to use
  110841. */
  110842. function GLTFLoaderExtension(loader) {
  110843. /**
  110844. * Gets or sets a boolean indicating if the extension is enabled
  110845. */
  110846. this.enabled = true;
  110847. this._loader = loader;
  110848. }
  110849. /**
  110850. * Release all resources
  110851. */
  110852. GLTFLoaderExtension.prototype.dispose = function () {
  110853. delete this._loader;
  110854. };
  110855. // #region Overridable Methods
  110856. /**
  110857. * Override this method to modify the default behavior for loading scenes.
  110858. * @hidden
  110859. */
  110860. GLTFLoaderExtension.prototype._loadSceneAsync = function (context, node) { return null; };
  110861. /**
  110862. * Override this method to modify the default behavior for loading nodes.
  110863. * @hidden
  110864. */
  110865. GLTFLoaderExtension.prototype._loadNodeAsync = function (context, node) { return null; };
  110866. /**
  110867. * Override this method to modify the default behavior for loading mesh primitive vertex data.
  110868. * @hidden
  110869. */
  110870. GLTFLoaderExtension.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) { return null; };
  110871. /**
  110872. * Override this method to modify the default behavior for loading materials.
  110873. * @hidden
  110874. */
  110875. GLTFLoaderExtension.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) { return null; };
  110876. /**
  110877. * Override this method to modify the default behavior for loading material properties.
  110878. * @hidden
  110879. */
  110880. GLTFLoaderExtension.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) { return null; };
  110881. /**
  110882. * Override this method to modify the default behavior for loading textures.
  110883. * @hidden
  110884. */
  110885. GLTFLoaderExtension.prototype._loadTextureAsync = function (context, textureInfo, assign) { return null; };
  110886. /**
  110887. * Override this method to modify the default behavior for loading uris.
  110888. * @hidden
  110889. */
  110890. GLTFLoaderExtension.prototype._loadUriAsync = function (context, uri) { return null; };
  110891. // #endregion
  110892. /**
  110893. * Helper method called by a loader extension to load an glTF extension.
  110894. * @hidden
  110895. */
  110896. GLTFLoaderExtension.prototype._loadExtensionAsync = function (context, property, actionAsync) {
  110897. if (!property.extensions) {
  110898. return null;
  110899. }
  110900. var extensions = property.extensions;
  110901. var extension = extensions[this.name];
  110902. if (!extension) {
  110903. return null;
  110904. }
  110905. // Clear out the extension before executing the action to avoid infinite recursion.
  110906. delete extensions[this.name];
  110907. try {
  110908. return actionAsync(context + "/extensions/" + this.name, extension);
  110909. }
  110910. finally {
  110911. // Restore the extension after executing the action.
  110912. extensions[this.name] = extension;
  110913. }
  110914. };
  110915. /**
  110916. * Helper method called by the loader to allow extensions to override loading scenes.
  110917. * @hidden
  110918. */
  110919. GLTFLoaderExtension.prototype._loadExtrasValueAsync = function (context, property, actionAsync) {
  110920. if (!property.extras) {
  110921. return null;
  110922. }
  110923. var extras = property.extras;
  110924. var value = extras[this.name];
  110925. if (value === undefined) {
  110926. return null;
  110927. }
  110928. // Clear out the extras value before executing the action to avoid infinite recursion.
  110929. delete extras[this.name];
  110930. try {
  110931. return actionAsync(context + "/extras/" + this.name, value);
  110932. }
  110933. finally {
  110934. // Restore the extras value after executing the action.
  110935. extras[this.name] = value;
  110936. }
  110937. };
  110938. /**
  110939. * Helper method called by the loader to allow extensions to override loading scenes.
  110940. * @hidden
  110941. */
  110942. GLTFLoaderExtension._LoadSceneAsync = function (loader, context, scene) {
  110943. return loader._applyExtensions(function (extension) { return extension._loadSceneAsync(context, scene); });
  110944. };
  110945. /**
  110946. * Helper method called by the loader to allow extensions to override loading nodes.
  110947. * @hidden
  110948. */
  110949. GLTFLoaderExtension._LoadNodeAsync = function (loader, context, node) {
  110950. return loader._applyExtensions(function (extension) { return extension._loadNodeAsync(context, node); });
  110951. };
  110952. /**
  110953. * Helper method called by the loader to allow extensions to override loading mesh primitive vertex data.
  110954. * @hidden
  110955. */
  110956. GLTFLoaderExtension._LoadVertexDataAsync = function (loader, context, primitive, babylonMesh) {
  110957. return loader._applyExtensions(function (extension) { return extension._loadVertexDataAsync(context, primitive, babylonMesh); });
  110958. };
  110959. /**
  110960. * Helper method called by the loader to allow extensions to override loading materials.
  110961. * @hidden
  110962. */
  110963. GLTFLoaderExtension._LoadMaterialAsync = function (loader, context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  110964. return loader._applyExtensions(function (extension) { return extension._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, assign); });
  110965. };
  110966. /**
  110967. * Helper method called by the loader to allow extensions to override loading material properties.
  110968. * @hidden
  110969. */
  110970. GLTFLoaderExtension._LoadMaterialPropertiesAsync = function (loader, context, material, babylonMaterial) {
  110971. return loader._applyExtensions(function (extension) { return extension._loadMaterialPropertiesAsync(context, material, babylonMaterial); });
  110972. };
  110973. /**
  110974. * Helper method called by the loader to allow extensions to override loading textures.
  110975. * @hidden
  110976. */
  110977. GLTFLoaderExtension._LoadTextureAsync = function (loader, context, textureInfo, assign) {
  110978. return loader._applyExtensions(function (extension) { return extension._loadTextureAsync(context, textureInfo, assign); });
  110979. };
  110980. /**
  110981. * Helper method called by the loader to allow extensions to override loading uris.
  110982. * @hidden
  110983. */
  110984. GLTFLoaderExtension._LoadUriAsync = function (loader, context, uri) {
  110985. return loader._applyExtensions(function (extension) { return extension._loadUriAsync(context, uri); });
  110986. };
  110987. return GLTFLoaderExtension;
  110988. }());
  110989. GLTF2.GLTFLoaderExtension = GLTFLoaderExtension;
  110990. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  110991. })(BABYLON || (BABYLON = {}));
  110992. //# sourceMappingURL=babylon.glTFLoaderExtension.js.map
  110993. var BABYLON;
  110994. (function (BABYLON) {
  110995. var GLTF2;
  110996. (function (GLTF2) {
  110997. var Extensions;
  110998. (function (Extensions) {
  110999. var NAME = "MSFT_lod";
  111000. /**
  111001. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Vendor/MSFT_lod)
  111002. */
  111003. var MSFT_lod = /** @class */ (function (_super) {
  111004. __extends(MSFT_lod, _super);
  111005. function MSFT_lod(loader) {
  111006. var _this = _super.call(this, loader) || this;
  111007. _this.name = NAME;
  111008. /**
  111009. * Maximum number of LODs to load, starting from the lowest LOD.
  111010. */
  111011. _this.maxLODsToLoad = Number.MAX_VALUE;
  111012. /**
  111013. * Observable raised when all node LODs of one level are loaded.
  111014. * The event data is the index of the loaded LOD starting from zero.
  111015. * Dispose the loader to cancel the loading of the next level of LODs.
  111016. */
  111017. _this.onNodeLODsLoadedObservable = new BABYLON.Observable();
  111018. /**
  111019. * Observable raised when all material LODs of one level are loaded.
  111020. * The event data is the index of the loaded LOD starting from zero.
  111021. * Dispose the loader to cancel the loading of the next level of LODs.
  111022. */
  111023. _this.onMaterialLODsLoadedObservable = new BABYLON.Observable();
  111024. _this._nodeIndexLOD = null;
  111025. _this._nodeSignalLODs = new Array();
  111026. _this._nodePromiseLODs = new Array();
  111027. _this._materialIndexLOD = null;
  111028. _this._materialSignalLODs = new Array();
  111029. _this._materialPromiseLODs = new Array();
  111030. _this._loader._readyPromise.then(function () {
  111031. var _loop_1 = function (indexLOD) {
  111032. var promise = Promise.all(_this._nodePromiseLODs[indexLOD]).then(function () {
  111033. if (indexLOD !== 0) {
  111034. _this._loader._parent._endPerformanceCounter("Node LOD " + indexLOD);
  111035. }
  111036. _this._loader._parent._log("Loaded node LOD " + indexLOD);
  111037. _this.onNodeLODsLoadedObservable.notifyObservers(indexLOD);
  111038. if (indexLOD !== _this._nodePromiseLODs.length - 1) {
  111039. _this._loader._parent._startPerformanceCounter("Node LOD " + (indexLOD + 1));
  111040. _this._nodeSignalLODs[indexLOD].resolve();
  111041. }
  111042. });
  111043. _this._loader._completePromises.push(promise);
  111044. };
  111045. for (var indexLOD = 0; indexLOD < _this._nodePromiseLODs.length; indexLOD++) {
  111046. _loop_1(indexLOD);
  111047. }
  111048. var _loop_2 = function (indexLOD) {
  111049. var promise = Promise.all(_this._materialPromiseLODs[indexLOD]).then(function () {
  111050. if (indexLOD !== 0) {
  111051. _this._loader._parent._endPerformanceCounter("Material LOD " + indexLOD);
  111052. }
  111053. _this._loader._parent._log("Loaded material LOD " + indexLOD);
  111054. _this.onMaterialLODsLoadedObservable.notifyObservers(indexLOD);
  111055. if (indexLOD !== _this._materialPromiseLODs.length - 1) {
  111056. _this._loader._parent._startPerformanceCounter("Material LOD " + (indexLOD + 1));
  111057. _this._materialSignalLODs[indexLOD].resolve();
  111058. }
  111059. });
  111060. _this._loader._completePromises.push(promise);
  111061. };
  111062. for (var indexLOD = 0; indexLOD < _this._materialPromiseLODs.length; indexLOD++) {
  111063. _loop_2(indexLOD);
  111064. }
  111065. });
  111066. return _this;
  111067. }
  111068. MSFT_lod.prototype.dispose = function () {
  111069. _super.prototype.dispose.call(this);
  111070. this._nodeIndexLOD = null;
  111071. this._nodeSignalLODs.length = 0;
  111072. this._nodePromiseLODs.length = 0;
  111073. this._materialIndexLOD = null;
  111074. this._materialSignalLODs.length = 0;
  111075. this._materialPromiseLODs.length = 0;
  111076. this.onMaterialLODsLoadedObservable.clear();
  111077. this.onNodeLODsLoadedObservable.clear();
  111078. };
  111079. MSFT_lod.prototype._loadNodeAsync = function (context, node) {
  111080. var _this = this;
  111081. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  111082. var firstPromise;
  111083. var nodeLODs = _this._getLODs(extensionContext, node, _this._loader._gltf.nodes, extension.ids);
  111084. _this._loader._parent._logOpen("" + extensionContext);
  111085. var _loop_3 = function (indexLOD) {
  111086. var nodeLOD = nodeLODs[indexLOD];
  111087. if (indexLOD !== 0) {
  111088. _this._nodeIndexLOD = indexLOD;
  111089. _this._nodeSignalLODs[indexLOD] = _this._nodeSignalLODs[indexLOD] || new BABYLON.Deferred();
  111090. }
  111091. var promise = _this._loader._loadNodeAsync("#/nodes/" + nodeLOD._index, nodeLOD).then(function () {
  111092. if (indexLOD !== 0) {
  111093. var previousNodeLOD = nodeLODs[indexLOD - 1];
  111094. if (previousNodeLOD._babylonMesh) {
  111095. previousNodeLOD._babylonMesh.dispose();
  111096. delete previousNodeLOD._babylonMesh;
  111097. _this._disposeUnusedMaterials();
  111098. }
  111099. }
  111100. });
  111101. if (indexLOD === 0) {
  111102. firstPromise = promise;
  111103. }
  111104. else {
  111105. _this._nodeIndexLOD = null;
  111106. }
  111107. _this._nodePromiseLODs[indexLOD] = _this._nodePromiseLODs[indexLOD] || [];
  111108. _this._nodePromiseLODs[indexLOD].push(promise);
  111109. };
  111110. for (var indexLOD = 0; indexLOD < nodeLODs.length; indexLOD++) {
  111111. _loop_3(indexLOD);
  111112. }
  111113. _this._loader._parent._logClose();
  111114. return firstPromise;
  111115. });
  111116. };
  111117. MSFT_lod.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111118. var _this = this;
  111119. // Don't load material LODs if already loading a node LOD.
  111120. if (this._nodeIndexLOD) {
  111121. return null;
  111122. }
  111123. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  111124. var firstPromise;
  111125. var materialLODs = _this._getLODs(extensionContext, material, _this._loader._gltf.materials, extension.ids);
  111126. _this._loader._parent._logOpen("" + extensionContext);
  111127. var _loop_4 = function (indexLOD) {
  111128. var materialLOD = materialLODs[indexLOD];
  111129. if (indexLOD !== 0) {
  111130. _this._materialIndexLOD = indexLOD;
  111131. }
  111132. var promise = _this._loader._loadMaterialAsync("#/materials/" + materialLOD._index, materialLOD, mesh, babylonMesh, babylonDrawMode, indexLOD === 0 ? assign : function () { }).then(function () {
  111133. if (indexLOD !== 0) {
  111134. var babylonDataLOD = materialLOD._babylonData;
  111135. assign(babylonDataLOD[babylonDrawMode].material);
  111136. var previousBabylonDataLOD = materialLODs[indexLOD - 1]._babylonData;
  111137. if (previousBabylonDataLOD[babylonDrawMode]) {
  111138. previousBabylonDataLOD[babylonDrawMode].material.dispose();
  111139. delete previousBabylonDataLOD[babylonDrawMode];
  111140. }
  111141. }
  111142. });
  111143. if (indexLOD === 0) {
  111144. firstPromise = promise;
  111145. }
  111146. else {
  111147. _this._materialIndexLOD = null;
  111148. }
  111149. _this._materialPromiseLODs[indexLOD] = _this._materialPromiseLODs[indexLOD] || [];
  111150. _this._materialPromiseLODs[indexLOD].push(promise);
  111151. };
  111152. for (var indexLOD = 0; indexLOD < materialLODs.length; indexLOD++) {
  111153. _loop_4(indexLOD);
  111154. }
  111155. _this._loader._parent._logClose();
  111156. return firstPromise;
  111157. });
  111158. };
  111159. MSFT_lod.prototype._loadUriAsync = function (context, uri) {
  111160. var _this = this;
  111161. // Defer the loading of uris if loading a material or node LOD.
  111162. if (this._materialIndexLOD !== null) {
  111163. this._loader._parent._log("deferred");
  111164. var previousIndexLOD = this._materialIndexLOD - 1;
  111165. this._materialSignalLODs[previousIndexLOD] = this._materialSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111166. return this._materialSignalLODs[previousIndexLOD].promise.then(function () {
  111167. return _this._loader._loadUriAsync(context, uri);
  111168. });
  111169. }
  111170. else if (this._nodeIndexLOD !== null) {
  111171. this._loader._parent._log("deferred");
  111172. var previousIndexLOD = this._nodeIndexLOD - 1;
  111173. this._nodeSignalLODs[previousIndexLOD] = this._nodeSignalLODs[previousIndexLOD] || new BABYLON.Deferred();
  111174. return this._nodeSignalLODs[this._nodeIndexLOD - 1].promise.then(function () {
  111175. return _this._loader._loadUriAsync(context, uri);
  111176. });
  111177. }
  111178. return null;
  111179. };
  111180. /**
  111181. * Gets an array of LOD properties from lowest to highest.
  111182. */
  111183. MSFT_lod.prototype._getLODs = function (context, property, array, ids) {
  111184. if (this.maxLODsToLoad <= 0) {
  111185. throw new Error("maxLODsToLoad must be greater than zero");
  111186. }
  111187. var properties = new Array();
  111188. for (var i = ids.length - 1; i >= 0; i--) {
  111189. properties.push(GLTF2.GLTFLoader._GetProperty(context + "/ids/" + ids[i], array, ids[i]));
  111190. if (properties.length === this.maxLODsToLoad) {
  111191. return properties;
  111192. }
  111193. }
  111194. properties.push(property);
  111195. return properties;
  111196. };
  111197. MSFT_lod.prototype._disposeUnusedMaterials = function () {
  111198. var materials = this._loader._gltf.materials;
  111199. if (materials) {
  111200. for (var _i = 0, materials_1 = materials; _i < materials_1.length; _i++) {
  111201. var material = materials_1[_i];
  111202. if (material._babylonData) {
  111203. for (var drawMode in material._babylonData) {
  111204. var babylonData = material._babylonData[drawMode];
  111205. if (babylonData.meshes.length === 0) {
  111206. babylonData.material.dispose(false, true);
  111207. delete material._babylonData[drawMode];
  111208. }
  111209. }
  111210. }
  111211. }
  111212. }
  111213. };
  111214. return MSFT_lod;
  111215. }(GLTF2.GLTFLoaderExtension));
  111216. Extensions.MSFT_lod = MSFT_lod;
  111217. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_lod(loader); });
  111218. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111219. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111220. })(BABYLON || (BABYLON = {}));
  111221. //# sourceMappingURL=MSFT_lod.js.map
  111222. var BABYLON;
  111223. (function (BABYLON) {
  111224. var GLTF2;
  111225. (function (GLTF2) {
  111226. var Extensions;
  111227. (function (Extensions) {
  111228. var NAME = "MSFT_minecraftMesh";
  111229. /** @hidden */
  111230. var MSFT_minecraftMesh = /** @class */ (function (_super) {
  111231. __extends(MSFT_minecraftMesh, _super);
  111232. function MSFT_minecraftMesh() {
  111233. var _this = _super !== null && _super.apply(this, arguments) || this;
  111234. _this.name = NAME;
  111235. return _this;
  111236. }
  111237. MSFT_minecraftMesh.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111238. var _this = this;
  111239. return this._loadExtrasValueAsync(context, mesh, function (extensionContext, value) {
  111240. if (value) {
  111241. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111242. if (babylonMaterial.needAlphaBlending()) {
  111243. babylonMaterial.forceDepthWrite = true;
  111244. babylonMaterial.separateCullingPass = true;
  111245. }
  111246. babylonMaterial.backFaceCulling = babylonMaterial.forceDepthWrite;
  111247. babylonMaterial.twoSidedLighting = true;
  111248. assign(babylonMaterial);
  111249. });
  111250. }
  111251. return null;
  111252. });
  111253. };
  111254. return MSFT_minecraftMesh;
  111255. }(GLTF2.GLTFLoaderExtension));
  111256. Extensions.MSFT_minecraftMesh = MSFT_minecraftMesh;
  111257. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_minecraftMesh(loader); });
  111258. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111259. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111260. })(BABYLON || (BABYLON = {}));
  111261. //# sourceMappingURL=MSFT_minecraftMesh.js.map
  111262. var BABYLON;
  111263. (function (BABYLON) {
  111264. var GLTF2;
  111265. (function (GLTF2) {
  111266. var Extensions;
  111267. (function (Extensions) {
  111268. var NAME = "MSFT_sRGBFactors";
  111269. /** @hidden */
  111270. var MSFT_sRGBFactors = /** @class */ (function (_super) {
  111271. __extends(MSFT_sRGBFactors, _super);
  111272. function MSFT_sRGBFactors() {
  111273. var _this = _super !== null && _super.apply(this, arguments) || this;
  111274. _this.name = NAME;
  111275. return _this;
  111276. }
  111277. MSFT_sRGBFactors.prototype._loadMaterialAsync = function (context, material, mesh, babylonMesh, babylonDrawMode, assign) {
  111278. var _this = this;
  111279. return this._loadExtrasValueAsync(context, material, function (extensionContext, value) {
  111280. if (value) {
  111281. return _this._loader._loadMaterialAsync(context, material, mesh, babylonMesh, babylonDrawMode, function (babylonMaterial) {
  111282. if (!babylonMaterial.albedoTexture) {
  111283. babylonMaterial.albedoColor.toLinearSpaceToRef(babylonMaterial.albedoColor);
  111284. }
  111285. if (!babylonMaterial.reflectivityTexture) {
  111286. babylonMaterial.reflectivityColor.toLinearSpaceToRef(babylonMaterial.reflectivityColor);
  111287. }
  111288. assign(babylonMaterial);
  111289. });
  111290. }
  111291. return null;
  111292. });
  111293. };
  111294. return MSFT_sRGBFactors;
  111295. }(GLTF2.GLTFLoaderExtension));
  111296. Extensions.MSFT_sRGBFactors = MSFT_sRGBFactors;
  111297. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new MSFT_sRGBFactors(loader); });
  111298. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111299. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111300. })(BABYLON || (BABYLON = {}));
  111301. //# sourceMappingURL=MSFT_sRGBFactors.js.map
  111302. var BABYLON;
  111303. (function (BABYLON) {
  111304. var GLTF2;
  111305. (function (GLTF2) {
  111306. var Extensions;
  111307. (function (Extensions) {
  111308. var NAME = "KHR_draco_mesh_compression";
  111309. /**
  111310. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_draco_mesh_compression)
  111311. */
  111312. var KHR_draco_mesh_compression = /** @class */ (function (_super) {
  111313. __extends(KHR_draco_mesh_compression, _super);
  111314. function KHR_draco_mesh_compression(loader) {
  111315. var _this = _super.call(this, loader) || this;
  111316. _this.name = NAME;
  111317. _this._dracoCompression = null;
  111318. // Disable extension if decoder is not available.
  111319. if (!BABYLON.DracoCompression.DecoderAvailable) {
  111320. _this.enabled = false;
  111321. }
  111322. return _this;
  111323. }
  111324. KHR_draco_mesh_compression.prototype.dispose = function () {
  111325. if (this._dracoCompression) {
  111326. this._dracoCompression.dispose();
  111327. }
  111328. _super.prototype.dispose.call(this);
  111329. };
  111330. KHR_draco_mesh_compression.prototype._loadVertexDataAsync = function (context, primitive, babylonMesh) {
  111331. var _this = this;
  111332. return this._loadExtensionAsync(context, primitive, function (extensionContext, extension) {
  111333. if (primitive.mode != undefined) {
  111334. if (primitive.mode !== 5 /* TRIANGLE_STRIP */ &&
  111335. primitive.mode !== 4 /* TRIANGLES */) {
  111336. throw new Error(context + ": Unsupported mode " + primitive.mode);
  111337. }
  111338. // TODO: handle triangle strips
  111339. if (primitive.mode === 5 /* TRIANGLE_STRIP */) {
  111340. throw new Error(context + ": Mode " + primitive.mode + " is not currently supported");
  111341. }
  111342. }
  111343. var attributes = {};
  111344. var loadAttribute = function (name, kind) {
  111345. var uniqueId = extension.attributes[name];
  111346. if (uniqueId == undefined) {
  111347. return;
  111348. }
  111349. babylonMesh._delayInfo = babylonMesh._delayInfo || [];
  111350. if (babylonMesh._delayInfo.indexOf(kind) === -1) {
  111351. babylonMesh._delayInfo.push(kind);
  111352. }
  111353. attributes[kind] = uniqueId;
  111354. };
  111355. loadAttribute("POSITION", BABYLON.VertexBuffer.PositionKind);
  111356. loadAttribute("NORMAL", BABYLON.VertexBuffer.NormalKind);
  111357. loadAttribute("TANGENT", BABYLON.VertexBuffer.TangentKind);
  111358. loadAttribute("TEXCOORD_0", BABYLON.VertexBuffer.UVKind);
  111359. loadAttribute("TEXCOORD_1", BABYLON.VertexBuffer.UV2Kind);
  111360. loadAttribute("JOINTS_0", BABYLON.VertexBuffer.MatricesIndicesKind);
  111361. loadAttribute("WEIGHTS_0", BABYLON.VertexBuffer.MatricesWeightsKind);
  111362. loadAttribute("COLOR_0", BABYLON.VertexBuffer.ColorKind);
  111363. var bufferView = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._loader._gltf.bufferViews, extension.bufferView);
  111364. if (!bufferView._dracoBabylonGeometry) {
  111365. bufferView._dracoBabylonGeometry = _this._loader._loadBufferViewAsync("#/bufferViews/" + bufferView._index, bufferView).then(function (data) {
  111366. if (!_this._dracoCompression) {
  111367. _this._dracoCompression = new BABYLON.DracoCompression();
  111368. }
  111369. return _this._dracoCompression.decodeMeshAsync(data, attributes).then(function (babylonVertexData) {
  111370. var babylonGeometry = new BABYLON.Geometry(babylonMesh.name, _this._loader._babylonScene);
  111371. babylonVertexData.applyToGeometry(babylonGeometry);
  111372. return babylonGeometry;
  111373. }).catch(function (error) {
  111374. throw new Error(context + ": " + error.message);
  111375. });
  111376. });
  111377. }
  111378. return bufferView._dracoBabylonGeometry;
  111379. });
  111380. };
  111381. return KHR_draco_mesh_compression;
  111382. }(GLTF2.GLTFLoaderExtension));
  111383. Extensions.KHR_draco_mesh_compression = KHR_draco_mesh_compression;
  111384. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_draco_mesh_compression(loader); });
  111385. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111386. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111387. })(BABYLON || (BABYLON = {}));
  111388. //# sourceMappingURL=KHR_draco_mesh_compression.js.map
  111389. var BABYLON;
  111390. (function (BABYLON) {
  111391. var GLTF2;
  111392. (function (GLTF2) {
  111393. var Extensions;
  111394. (function (Extensions) {
  111395. var NAME = "KHR_materials_pbrSpecularGlossiness";
  111396. /**
  111397. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_pbrSpecularGlossiness)
  111398. */
  111399. var KHR_materials_pbrSpecularGlossiness = /** @class */ (function (_super) {
  111400. __extends(KHR_materials_pbrSpecularGlossiness, _super);
  111401. function KHR_materials_pbrSpecularGlossiness() {
  111402. var _this = _super !== null && _super.apply(this, arguments) || this;
  111403. _this.name = NAME;
  111404. return _this;
  111405. }
  111406. KHR_materials_pbrSpecularGlossiness.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111407. var _this = this;
  111408. return this._loadExtensionAsync(context, material, function (extensionContext, extension) {
  111409. var promises = new Array();
  111410. promises.push(_this._loader._loadMaterialBasePropertiesAsync(context, material, babylonMaterial));
  111411. promises.push(_this._loadSpecularGlossinessPropertiesAsync(extensionContext, material, extension, babylonMaterial));
  111412. return Promise.all(promises).then(function () { });
  111413. });
  111414. };
  111415. KHR_materials_pbrSpecularGlossiness.prototype._loadSpecularGlossinessPropertiesAsync = function (context, material, properties, babylonMaterial) {
  111416. var promises = new Array();
  111417. if (properties.diffuseFactor) {
  111418. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.diffuseFactor);
  111419. babylonMaterial.alpha = properties.diffuseFactor[3];
  111420. }
  111421. else {
  111422. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111423. }
  111424. babylonMaterial.reflectivityColor = properties.specularFactor ? BABYLON.Color3.FromArray(properties.specularFactor) : BABYLON.Color3.White();
  111425. babylonMaterial.microSurface = properties.glossinessFactor == undefined ? 1 : properties.glossinessFactor;
  111426. if (properties.diffuseTexture) {
  111427. promises.push(this._loader._loadTextureAsync(context + "/diffuseTexture", properties.diffuseTexture, function (texture) {
  111428. babylonMaterial.albedoTexture = texture;
  111429. }));
  111430. }
  111431. if (properties.specularGlossinessTexture) {
  111432. promises.push(this._loader._loadTextureAsync(context + "/specularGlossinessTexture", properties.specularGlossinessTexture, function (texture) {
  111433. babylonMaterial.reflectivityTexture = texture;
  111434. }));
  111435. babylonMaterial.reflectivityTexture.hasAlpha = true;
  111436. babylonMaterial.useMicroSurfaceFromReflectivityMapAlpha = true;
  111437. }
  111438. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111439. return Promise.all(promises).then(function () { });
  111440. };
  111441. return KHR_materials_pbrSpecularGlossiness;
  111442. }(GLTF2.GLTFLoaderExtension));
  111443. Extensions.KHR_materials_pbrSpecularGlossiness = KHR_materials_pbrSpecularGlossiness;
  111444. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_pbrSpecularGlossiness(loader); });
  111445. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111446. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111447. })(BABYLON || (BABYLON = {}));
  111448. //# sourceMappingURL=KHR_materials_pbrSpecularGlossiness.js.map
  111449. var BABYLON;
  111450. (function (BABYLON) {
  111451. var GLTF2;
  111452. (function (GLTF2) {
  111453. var Extensions;
  111454. (function (Extensions) {
  111455. var NAME = "KHR_materials_unlit";
  111456. /**
  111457. * [Specification](https://github.com/KhronosGroup/glTF/tree/master/extensions/2.0/Khronos/KHR_materials_unlit)
  111458. */
  111459. var KHR_materials_unlit = /** @class */ (function (_super) {
  111460. __extends(KHR_materials_unlit, _super);
  111461. function KHR_materials_unlit() {
  111462. var _this = _super !== null && _super.apply(this, arguments) || this;
  111463. _this.name = NAME;
  111464. return _this;
  111465. }
  111466. KHR_materials_unlit.prototype._loadMaterialPropertiesAsync = function (context, material, babylonMaterial) {
  111467. var _this = this;
  111468. return this._loadExtensionAsync(context, material, function () {
  111469. return _this._loadUnlitPropertiesAsync(context, material, babylonMaterial);
  111470. });
  111471. };
  111472. KHR_materials_unlit.prototype._loadUnlitPropertiesAsync = function (context, material, babylonMaterial) {
  111473. var promises = new Array();
  111474. babylonMaterial.unlit = true;
  111475. // Ensure metallic workflow
  111476. babylonMaterial.metallic = 1;
  111477. babylonMaterial.roughness = 1;
  111478. var properties = material.pbrMetallicRoughness;
  111479. if (properties) {
  111480. if (properties.baseColorFactor) {
  111481. babylonMaterial.albedoColor = BABYLON.Color3.FromArray(properties.baseColorFactor);
  111482. babylonMaterial.alpha = properties.baseColorFactor[3];
  111483. }
  111484. else {
  111485. babylonMaterial.albedoColor = BABYLON.Color3.White();
  111486. }
  111487. if (properties.baseColorTexture) {
  111488. promises.push(this._loader._loadTextureAsync(context + "/baseColorTexture", properties.baseColorTexture, function (texture) {
  111489. babylonMaterial.albedoTexture = texture;
  111490. }));
  111491. }
  111492. }
  111493. if (material.doubleSided) {
  111494. babylonMaterial.backFaceCulling = false;
  111495. babylonMaterial.twoSidedLighting = true;
  111496. }
  111497. this._loader._loadMaterialAlphaProperties(context, material, babylonMaterial);
  111498. return Promise.all(promises).then(function () { });
  111499. };
  111500. return KHR_materials_unlit;
  111501. }(GLTF2.GLTFLoaderExtension));
  111502. Extensions.KHR_materials_unlit = KHR_materials_unlit;
  111503. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_materials_unlit(loader); });
  111504. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111505. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111506. })(BABYLON || (BABYLON = {}));
  111507. //# sourceMappingURL=KHR_materials_unlit.js.map
  111508. var BABYLON;
  111509. (function (BABYLON) {
  111510. var GLTF2;
  111511. (function (GLTF2) {
  111512. var Extensions;
  111513. (function (Extensions) {
  111514. var NAME = "KHR_lights";
  111515. var LightType;
  111516. (function (LightType) {
  111517. LightType["AMBIENT"] = "ambient";
  111518. LightType["DIRECTIONAL"] = "directional";
  111519. LightType["POINT"] = "point";
  111520. LightType["SPOT"] = "spot";
  111521. })(LightType || (LightType = {}));
  111522. /**
  111523. * [Specification](https://github.com/MiiBond/glTF/tree/khr_lights_v1/extensions/Khronos/KHR_lights) (Experimental)
  111524. */
  111525. var KHR_lights = /** @class */ (function (_super) {
  111526. __extends(KHR_lights, _super);
  111527. function KHR_lights() {
  111528. var _this = _super !== null && _super.apply(this, arguments) || this;
  111529. _this.name = NAME;
  111530. return _this;
  111531. }
  111532. KHR_lights.prototype._loadSceneAsync = function (context, scene) {
  111533. var _this = this;
  111534. return this._loadExtensionAsync(context, scene, function (extensionContext, extension) {
  111535. var promise = _this._loader._loadSceneAsync(extensionContext, scene);
  111536. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  111537. if (light.type !== LightType.AMBIENT) {
  111538. throw new Error(extensionContext + ": Only ambient lights are allowed on a scene");
  111539. }
  111540. _this._loader._babylonScene.ambientColor = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.Black();
  111541. return promise;
  111542. });
  111543. };
  111544. KHR_lights.prototype._loadNodeAsync = function (context, node) {
  111545. var _this = this;
  111546. return this._loadExtensionAsync(context, node, function (extensionContext, extension) {
  111547. var promise = _this._loader._loadNodeAsync(extensionContext, node);
  111548. var babylonLight;
  111549. var light = GLTF2.GLTFLoader._GetProperty(extensionContext, _this._lights, extension.light);
  111550. var name = node._babylonMesh.name;
  111551. switch (light.type) {
  111552. case LightType.AMBIENT: {
  111553. throw new Error(extensionContext + ": Ambient lights are not allowed on a node");
  111554. }
  111555. case LightType.DIRECTIONAL: {
  111556. babylonLight = new BABYLON.DirectionalLight(name, BABYLON.Vector3.Forward(), _this._loader._babylonScene);
  111557. break;
  111558. }
  111559. case LightType.POINT: {
  111560. babylonLight = new BABYLON.PointLight(name, BABYLON.Vector3.Zero(), _this._loader._babylonScene);
  111561. break;
  111562. }
  111563. case LightType.SPOT: {
  111564. var spotLight = light;
  111565. // TODO: support inner and outer cone angles
  111566. //const innerConeAngle = spotLight.innerConeAngle || 0;
  111567. var outerConeAngle = spotLight.outerConeAngle || Math.PI / 4;
  111568. babylonLight = new BABYLON.SpotLight(name, BABYLON.Vector3.Zero(), BABYLON.Vector3.Forward(), outerConeAngle, 2, _this._loader._babylonScene);
  111569. break;
  111570. }
  111571. default: {
  111572. throw new Error(extensionContext + ": Invalid light type (" + light.type + ")");
  111573. }
  111574. }
  111575. babylonLight.diffuse = light.color ? BABYLON.Color3.FromArray(light.color) : BABYLON.Color3.White();
  111576. babylonLight.intensity = light.intensity == undefined ? 1 : light.intensity;
  111577. babylonLight.parent = node._babylonMesh;
  111578. return promise;
  111579. });
  111580. };
  111581. Object.defineProperty(KHR_lights.prototype, "_lights", {
  111582. get: function () {
  111583. var extensions = this._loader._gltf.extensions;
  111584. if (!extensions || !extensions[this.name]) {
  111585. throw new Error("#/extensions: '" + this.name + "' not found");
  111586. }
  111587. var extension = extensions[this.name];
  111588. return extension.lights;
  111589. },
  111590. enumerable: true,
  111591. configurable: true
  111592. });
  111593. return KHR_lights;
  111594. }(GLTF2.GLTFLoaderExtension));
  111595. Extensions.KHR_lights = KHR_lights;
  111596. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_lights(loader); });
  111597. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111598. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111599. })(BABYLON || (BABYLON = {}));
  111600. var BABYLON;
  111601. (function (BABYLON) {
  111602. var GLTF2;
  111603. (function (GLTF2) {
  111604. var Extensions;
  111605. (function (Extensions) {
  111606. var NAME = "KHR_texture_transform";
  111607. /**
  111608. * [Specification](https://github.com/AltspaceVR/glTF/blob/avr-sampler-offset-tile/extensions/2.0/Khronos/KHR_texture_transform/README.md) (Experimental)
  111609. */
  111610. var KHR_texture_transform = /** @class */ (function (_super) {
  111611. __extends(KHR_texture_transform, _super);
  111612. function KHR_texture_transform() {
  111613. var _this = _super !== null && _super.apply(this, arguments) || this;
  111614. _this.name = NAME;
  111615. return _this;
  111616. }
  111617. KHR_texture_transform.prototype._loadTextureAsync = function (context, textureInfo, assign) {
  111618. var _this = this;
  111619. return this._loadExtensionAsync(context, textureInfo, function (extensionContext, extension) {
  111620. return _this._loader._loadTextureAsync(context, textureInfo, function (babylonTexture) {
  111621. if (extension.offset) {
  111622. babylonTexture.uOffset = extension.offset[0];
  111623. babylonTexture.vOffset = extension.offset[1];
  111624. }
  111625. // Always rotate around the origin.
  111626. babylonTexture.uRotationCenter = 0;
  111627. babylonTexture.vRotationCenter = 0;
  111628. if (extension.rotation) {
  111629. babylonTexture.wAng = -extension.rotation;
  111630. }
  111631. if (extension.scale) {
  111632. babylonTexture.uScale = extension.scale[0];
  111633. babylonTexture.vScale = extension.scale[1];
  111634. }
  111635. if (extension.texCoord != undefined) {
  111636. babylonTexture.coordinatesIndex = extension.texCoord;
  111637. }
  111638. assign(babylonTexture);
  111639. });
  111640. });
  111641. };
  111642. return KHR_texture_transform;
  111643. }(GLTF2.GLTFLoaderExtension));
  111644. Extensions.KHR_texture_transform = KHR_texture_transform;
  111645. GLTF2.GLTFLoader._Register(NAME, function (loader) { return new KHR_texture_transform(loader); });
  111646. })(Extensions = GLTF2.Extensions || (GLTF2.Extensions = {}));
  111647. })(GLTF2 = BABYLON.GLTF2 || (BABYLON.GLTF2 = {}));
  111648. })(BABYLON || (BABYLON = {}));
  111649. return BABYLON;
  111650. });
  111651. /***/ }),
  111652. /* 15 */
  111653. /***/ (function(module, exports, __webpack_require__) {
  111654. /**!
  111655. @license
  111656. handlebars v4.0.11
  111657. Copyright (C) 2011-2017 by Yehuda Katz
  111658. Permission is hereby granted, free of charge, to any person obtaining a copy
  111659. of this software and associated documentation files (the "Software"), to deal
  111660. in the Software without restriction, including without limitation the rights
  111661. to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  111662. copies of the Software, and to permit persons to whom the Software is
  111663. furnished to do so, subject to the following conditions:
  111664. The above copyright notice and this permission notice shall be included in
  111665. all copies or substantial portions of the Software.
  111666. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  111667. IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  111668. FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  111669. AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  111670. LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  111671. OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  111672. THE SOFTWARE.
  111673. */
  111674. (function webpackUniversalModuleDefinition(root, factory) {
  111675. if(true)
  111676. module.exports = factory();
  111677. else if(typeof define === 'function' && define.amd)
  111678. define([], factory);
  111679. else if(typeof exports === 'object')
  111680. exports["Handlebars"] = factory();
  111681. else
  111682. root["Handlebars"] = factory();
  111683. })(this, function() {
  111684. return /******/ (function(modules) { // webpackBootstrap
  111685. /******/ // The module cache
  111686. /******/ var installedModules = {};
  111687. /******/ // The require function
  111688. /******/ function __webpack_require__(moduleId) {
  111689. /******/ // Check if module is in cache
  111690. /******/ if(installedModules[moduleId])
  111691. /******/ return installedModules[moduleId].exports;
  111692. /******/ // Create a new module (and put it into the cache)
  111693. /******/ var module = installedModules[moduleId] = {
  111694. /******/ exports: {},
  111695. /******/ id: moduleId,
  111696. /******/ loaded: false
  111697. /******/ };
  111698. /******/ // Execute the module function
  111699. /******/ modules[moduleId].call(module.exports, module, module.exports, __webpack_require__);
  111700. /******/ // Flag the module as loaded
  111701. /******/ module.loaded = true;
  111702. /******/ // Return the exports of the module
  111703. /******/ return module.exports;
  111704. /******/ }
  111705. /******/ // expose the modules object (__webpack_modules__)
  111706. /******/ __webpack_require__.m = modules;
  111707. /******/ // expose the module cache
  111708. /******/ __webpack_require__.c = installedModules;
  111709. /******/ // __webpack_public_path__
  111710. /******/ __webpack_require__.p = "";
  111711. /******/ // Load entry module and return exports
  111712. /******/ return __webpack_require__(0);
  111713. /******/ })
  111714. /************************************************************************/
  111715. /******/ ([
  111716. /* 0 */
  111717. /***/ (function(module, exports, __webpack_require__) {
  111718. 'use strict';
  111719. var _interopRequireDefault = __webpack_require__(1)['default'];
  111720. exports.__esModule = true;
  111721. var _handlebarsRuntime = __webpack_require__(2);
  111722. var _handlebarsRuntime2 = _interopRequireDefault(_handlebarsRuntime);
  111723. // Compiler imports
  111724. var _handlebarsCompilerAst = __webpack_require__(35);
  111725. var _handlebarsCompilerAst2 = _interopRequireDefault(_handlebarsCompilerAst);
  111726. var _handlebarsCompilerBase = __webpack_require__(36);
  111727. var _handlebarsCompilerCompiler = __webpack_require__(41);
  111728. var _handlebarsCompilerJavascriptCompiler = __webpack_require__(42);
  111729. var _handlebarsCompilerJavascriptCompiler2 = _interopRequireDefault(_handlebarsCompilerJavascriptCompiler);
  111730. var _handlebarsCompilerVisitor = __webpack_require__(39);
  111731. var _handlebarsCompilerVisitor2 = _interopRequireDefault(_handlebarsCompilerVisitor);
  111732. var _handlebarsNoConflict = __webpack_require__(34);
  111733. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  111734. var _create = _handlebarsRuntime2['default'].create;
  111735. function create() {
  111736. var hb = _create();
  111737. hb.compile = function (input, options) {
  111738. return _handlebarsCompilerCompiler.compile(input, options, hb);
  111739. };
  111740. hb.precompile = function (input, options) {
  111741. return _handlebarsCompilerCompiler.precompile(input, options, hb);
  111742. };
  111743. hb.AST = _handlebarsCompilerAst2['default'];
  111744. hb.Compiler = _handlebarsCompilerCompiler.Compiler;
  111745. hb.JavaScriptCompiler = _handlebarsCompilerJavascriptCompiler2['default'];
  111746. hb.Parser = _handlebarsCompilerBase.parser;
  111747. hb.parse = _handlebarsCompilerBase.parse;
  111748. return hb;
  111749. }
  111750. var inst = create();
  111751. inst.create = create;
  111752. _handlebarsNoConflict2['default'](inst);
  111753. inst.Visitor = _handlebarsCompilerVisitor2['default'];
  111754. inst['default'] = inst;
  111755. exports['default'] = inst;
  111756. module.exports = exports['default'];
  111757. /***/ }),
  111758. /* 1 */
  111759. /***/ (function(module, exports) {
  111760. "use strict";
  111761. exports["default"] = function (obj) {
  111762. return obj && obj.__esModule ? obj : {
  111763. "default": obj
  111764. };
  111765. };
  111766. exports.__esModule = true;
  111767. /***/ }),
  111768. /* 2 */
  111769. /***/ (function(module, exports, __webpack_require__) {
  111770. 'use strict';
  111771. var _interopRequireWildcard = __webpack_require__(3)['default'];
  111772. var _interopRequireDefault = __webpack_require__(1)['default'];
  111773. exports.__esModule = true;
  111774. var _handlebarsBase = __webpack_require__(4);
  111775. var base = _interopRequireWildcard(_handlebarsBase);
  111776. // Each of these augment the Handlebars object. No need to setup here.
  111777. // (This is done to easily share code between commonjs and browse envs)
  111778. var _handlebarsSafeString = __webpack_require__(21);
  111779. var _handlebarsSafeString2 = _interopRequireDefault(_handlebarsSafeString);
  111780. var _handlebarsException = __webpack_require__(6);
  111781. var _handlebarsException2 = _interopRequireDefault(_handlebarsException);
  111782. var _handlebarsUtils = __webpack_require__(5);
  111783. var Utils = _interopRequireWildcard(_handlebarsUtils);
  111784. var _handlebarsRuntime = __webpack_require__(22);
  111785. var runtime = _interopRequireWildcard(_handlebarsRuntime);
  111786. var _handlebarsNoConflict = __webpack_require__(34);
  111787. var _handlebarsNoConflict2 = _interopRequireDefault(_handlebarsNoConflict);
  111788. // For compatibility and usage outside of module systems, make the Handlebars object a namespace
  111789. function create() {
  111790. var hb = new base.HandlebarsEnvironment();
  111791. Utils.extend(hb, base);
  111792. hb.SafeString = _handlebarsSafeString2['default'];
  111793. hb.Exception = _handlebarsException2['default'];
  111794. hb.Utils = Utils;
  111795. hb.escapeExpression = Utils.escapeExpression;
  111796. hb.VM = runtime;
  111797. hb.template = function (spec) {
  111798. return runtime.template(spec, hb);
  111799. };
  111800. return hb;
  111801. }
  111802. var inst = create();
  111803. inst.create = create;
  111804. _handlebarsNoConflict2['default'](inst);
  111805. inst['default'] = inst;
  111806. exports['default'] = inst;
  111807. module.exports = exports['default'];
  111808. /***/ }),
  111809. /* 3 */
  111810. /***/ (function(module, exports) {
  111811. "use strict";
  111812. exports["default"] = function (obj) {
  111813. if (obj && obj.__esModule) {
  111814. return obj;
  111815. } else {
  111816. var newObj = {};
  111817. if (obj != null) {
  111818. for (var key in obj) {
  111819. if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key];
  111820. }
  111821. }
  111822. newObj["default"] = obj;
  111823. return newObj;
  111824. }
  111825. };
  111826. exports.__esModule = true;
  111827. /***/ }),
  111828. /* 4 */
  111829. /***/ (function(module, exports, __webpack_require__) {
  111830. 'use strict';
  111831. var _interopRequireDefault = __webpack_require__(1)['default'];
  111832. exports.__esModule = true;
  111833. exports.HandlebarsEnvironment = HandlebarsEnvironment;
  111834. var _utils = __webpack_require__(5);
  111835. var _exception = __webpack_require__(6);
  111836. var _exception2 = _interopRequireDefault(_exception);
  111837. var _helpers = __webpack_require__(10);
  111838. var _decorators = __webpack_require__(18);
  111839. var _logger = __webpack_require__(20);
  111840. var _logger2 = _interopRequireDefault(_logger);
  111841. var VERSION = '4.0.11';
  111842. exports.VERSION = VERSION;
  111843. var COMPILER_REVISION = 7;
  111844. exports.COMPILER_REVISION = COMPILER_REVISION;
  111845. var REVISION_CHANGES = {
  111846. 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it
  111847. 2: '== 1.0.0-rc.3',
  111848. 3: '== 1.0.0-rc.4',
  111849. 4: '== 1.x.x',
  111850. 5: '== 2.0.0-alpha.x',
  111851. 6: '>= 2.0.0-beta.1',
  111852. 7: '>= 4.0.0'
  111853. };
  111854. exports.REVISION_CHANGES = REVISION_CHANGES;
  111855. var objectType = '[object Object]';
  111856. function HandlebarsEnvironment(helpers, partials, decorators) {
  111857. this.helpers = helpers || {};
  111858. this.partials = partials || {};
  111859. this.decorators = decorators || {};
  111860. _helpers.registerDefaultHelpers(this);
  111861. _decorators.registerDefaultDecorators(this);
  111862. }
  111863. HandlebarsEnvironment.prototype = {
  111864. constructor: HandlebarsEnvironment,
  111865. logger: _logger2['default'],
  111866. log: _logger2['default'].log,
  111867. registerHelper: function registerHelper(name, fn) {
  111868. if (_utils.toString.call(name) === objectType) {
  111869. if (fn) {
  111870. throw new _exception2['default']('Arg not supported with multiple helpers');
  111871. }
  111872. _utils.extend(this.helpers, name);
  111873. } else {
  111874. this.helpers[name] = fn;
  111875. }
  111876. },
  111877. unregisterHelper: function unregisterHelper(name) {
  111878. delete this.helpers[name];
  111879. },
  111880. registerPartial: function registerPartial(name, partial) {
  111881. if (_utils.toString.call(name) === objectType) {
  111882. _utils.extend(this.partials, name);
  111883. } else {
  111884. if (typeof partial === 'undefined') {
  111885. throw new _exception2['default']('Attempting to register a partial called "' + name + '" as undefined');
  111886. }
  111887. this.partials[name] = partial;
  111888. }
  111889. },
  111890. unregisterPartial: function unregisterPartial(name) {
  111891. delete this.partials[name];
  111892. },
  111893. registerDecorator: function registerDecorator(name, fn) {
  111894. if (_utils.toString.call(name) === objectType) {
  111895. if (fn) {
  111896. throw new _exception2['default']('Arg not supported with multiple decorators');
  111897. }
  111898. _utils.extend(this.decorators, name);
  111899. } else {
  111900. this.decorators[name] = fn;
  111901. }
  111902. },
  111903. unregisterDecorator: function unregisterDecorator(name) {
  111904. delete this.decorators[name];
  111905. }
  111906. };
  111907. var log = _logger2['default'].log;
  111908. exports.log = log;
  111909. exports.createFrame = _utils.createFrame;
  111910. exports.logger = _logger2['default'];
  111911. /***/ }),
  111912. /* 5 */
  111913. /***/ (function(module, exports) {
  111914. 'use strict';
  111915. exports.__esModule = true;
  111916. exports.extend = extend;
  111917. exports.indexOf = indexOf;
  111918. exports.escapeExpression = escapeExpression;
  111919. exports.isEmpty = isEmpty;
  111920. exports.createFrame = createFrame;
  111921. exports.blockParams = blockParams;
  111922. exports.appendContextPath = appendContextPath;
  111923. var escape = {
  111924. '&': '&amp;',
  111925. '<': '&lt;',
  111926. '>': '&gt;',
  111927. '"': '&quot;',
  111928. "'": '&#x27;',
  111929. '`': '&#x60;',
  111930. '=': '&#x3D;'
  111931. };
  111932. var badChars = /[&<>"'`=]/g,
  111933. possible = /[&<>"'`=]/;
  111934. function escapeChar(chr) {
  111935. return escape[chr];
  111936. }
  111937. function extend(obj /* , ...source */) {
  111938. for (var i = 1; i < arguments.length; i++) {
  111939. for (var key in arguments[i]) {
  111940. if (Object.prototype.hasOwnProperty.call(arguments[i], key)) {
  111941. obj[key] = arguments[i][key];
  111942. }
  111943. }
  111944. }
  111945. return obj;
  111946. }
  111947. var toString = Object.prototype.toString;
  111948. exports.toString = toString;
  111949. // Sourced from lodash
  111950. // https://github.com/bestiejs/lodash/blob/master/LICENSE.txt
  111951. /* eslint-disable func-style */
  111952. var isFunction = function isFunction(value) {
  111953. return typeof value === 'function';
  111954. };
  111955. // fallback for older versions of Chrome and Safari
  111956. /* istanbul ignore next */
  111957. if (isFunction(/x/)) {
  111958. exports.isFunction = isFunction = function (value) {
  111959. return typeof value === 'function' && toString.call(value) === '[object Function]';
  111960. };
  111961. }
  111962. exports.isFunction = isFunction;
  111963. /* eslint-enable func-style */
  111964. /* istanbul ignore next */
  111965. var isArray = Array.isArray || function (value) {
  111966. return value && typeof value === 'object' ? toString.call(value) === '[object Array]' : false;
  111967. };
  111968. exports.isArray = isArray;
  111969. // Older IE versions do not directly support indexOf so we must implement our own, sadly.
  111970. function indexOf(array, value) {
  111971. for (var i = 0, len = array.length; i < len; i++) {
  111972. if (array[i] === value) {
  111973. return i;
  111974. }
  111975. }
  111976. return -1;
  111977. }
  111978. function escapeExpression(string) {
  111979. if (typeof string !== 'string') {
  111980. // don't escape SafeStrings, since they're already safe
  111981. if (string && string.toHTML) {
  111982. return string.toHTML();
  111983. } else if (string == null) {
  111984. return '';
  111985. } else if (!string) {
  111986. return string + '';
  111987. }
  111988. // Force a string conversion as this will be done by the append regardless and
  111989. // the regex test will do this transparently behind the scenes, causing issues if
  111990. // an object's to string has escaped characters in it.
  111991. string = '' + string;
  111992. }
  111993. if (!possible.test(string)) {
  111994. return string;
  111995. }
  111996. return string.replace(badChars, escapeChar);
  111997. }
  111998. function isEmpty(value) {
  111999. if (!value && value !== 0) {
  112000. return true;
  112001. } else if (isArray(value) && value.length === 0) {
  112002. return true;
  112003. } else {
  112004. return false;
  112005. }
  112006. }
  112007. function createFrame(object) {
  112008. var frame = extend({}, object);
  112009. frame._parent = object;
  112010. return frame;
  112011. }
  112012. function blockParams(params, ids) {
  112013. params.path = ids;
  112014. return params;
  112015. }
  112016. function appendContextPath(contextPath, id) {
  112017. return (contextPath ? contextPath + '.' : '') + id;
  112018. }
  112019. /***/ }),
  112020. /* 6 */
  112021. /***/ (function(module, exports, __webpack_require__) {
  112022. 'use strict';
  112023. var _Object$defineProperty = __webpack_require__(7)['default'];
  112024. exports.__esModule = true;
  112025. var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack'];
  112026. function Exception(message, node) {
  112027. var loc = node && node.loc,
  112028. line = undefined,
  112029. column = undefined;
  112030. if (loc) {
  112031. line = loc.start.line;
  112032. column = loc.start.column;
  112033. message += ' - ' + line + ':' + column;
  112034. }
  112035. var tmp = Error.prototype.constructor.call(this, message);
  112036. // Unfortunately errors are not enumerable in Chrome (at least), so `for prop in tmp` doesn't work.
  112037. for (var idx = 0; idx < errorProps.length; idx++) {
  112038. this[errorProps[idx]] = tmp[errorProps[idx]];
  112039. }
  112040. /* istanbul ignore else */
  112041. if (Error.captureStackTrace) {
  112042. Error.captureStackTrace(this, Exception);
  112043. }
  112044. try {
  112045. if (loc) {
  112046. this.lineNumber = line;
  112047. // Work around issue under safari where we can't directly set the column value
  112048. /* istanbul ignore next */
  112049. if (_Object$defineProperty) {
  112050. Object.defineProperty(this, 'column', {
  112051. value: column,
  112052. enumerable: true
  112053. });
  112054. } else {
  112055. this.column = column;
  112056. }
  112057. }
  112058. } catch (nop) {
  112059. /* Ignore if the browser is very particular */
  112060. }
  112061. }
  112062. Exception.prototype = new Error();
  112063. exports['default'] = Exception;
  112064. module.exports = exports['default'];
  112065. /***/ }),
  112066. /* 7 */
  112067. /***/ (function(module, exports, __webpack_require__) {
  112068. module.exports = { "default": __webpack_require__(8), __esModule: true };
  112069. /***/ }),
  112070. /* 8 */
  112071. /***/ (function(module, exports, __webpack_require__) {
  112072. var $ = __webpack_require__(9);
  112073. module.exports = function defineProperty(it, key, desc){
  112074. return $.setDesc(it, key, desc);
  112075. };
  112076. /***/ }),
  112077. /* 9 */
  112078. /***/ (function(module, exports) {
  112079. var $Object = Object;
  112080. module.exports = {
  112081. create: $Object.create,
  112082. getProto: $Object.getPrototypeOf,
  112083. isEnum: {}.propertyIsEnumerable,
  112084. getDesc: $Object.getOwnPropertyDescriptor,
  112085. setDesc: $Object.defineProperty,
  112086. setDescs: $Object.defineProperties,
  112087. getKeys: $Object.keys,
  112088. getNames: $Object.getOwnPropertyNames,
  112089. getSymbols: $Object.getOwnPropertySymbols,
  112090. each: [].forEach
  112091. };
  112092. /***/ }),
  112093. /* 10 */
  112094. /***/ (function(module, exports, __webpack_require__) {
  112095. 'use strict';
  112096. var _interopRequireDefault = __webpack_require__(1)['default'];
  112097. exports.__esModule = true;
  112098. exports.registerDefaultHelpers = registerDefaultHelpers;
  112099. var _helpersBlockHelperMissing = __webpack_require__(11);
  112100. var _helpersBlockHelperMissing2 = _interopRequireDefault(_helpersBlockHelperMissing);
  112101. var _helpersEach = __webpack_require__(12);
  112102. var _helpersEach2 = _interopRequireDefault(_helpersEach);
  112103. var _helpersHelperMissing = __webpack_require__(13);
  112104. var _helpersHelperMissing2 = _interopRequireDefault(_helpersHelperMissing);
  112105. var _helpersIf = __webpack_require__(14);
  112106. var _helpersIf2 = _interopRequireDefault(_helpersIf);
  112107. var _helpersLog = __webpack_require__(15);
  112108. var _helpersLog2 = _interopRequireDefault(_helpersLog);
  112109. var _helpersLookup = __webpack_require__(16);
  112110. var _helpersLookup2 = _interopRequireDefault(_helpersLookup);
  112111. var _helpersWith = __webpack_require__(17);
  112112. var _helpersWith2 = _interopRequireDefault(_helpersWith);
  112113. function registerDefaultHelpers(instance) {
  112114. _helpersBlockHelperMissing2['default'](instance);
  112115. _helpersEach2['default'](instance);
  112116. _helpersHelperMissing2['default'](instance);
  112117. _helpersIf2['default'](instance);
  112118. _helpersLog2['default'](instance);
  112119. _helpersLookup2['default'](instance);
  112120. _helpersWith2['default'](instance);
  112121. }
  112122. /***/ }),
  112123. /* 11 */
  112124. /***/ (function(module, exports, __webpack_require__) {
  112125. 'use strict';
  112126. exports.__esModule = true;
  112127. var _utils = __webpack_require__(5);
  112128. exports['default'] = function (instance) {
  112129. instance.registerHelper('blockHelperMissing', function (context, options) {
  112130. var inverse = options.inverse,
  112131. fn = options.fn;
  112132. if (context === true) {
  112133. return fn(this);
  112134. } else if (context === false || context == null) {
  112135. return inverse(this);
  112136. } else if (_utils.isArray(context)) {
  112137. if (context.length > 0) {
  112138. if (options.ids) {
  112139. options.ids = [options.name];
  112140. }
  112141. return instance.helpers.each(context, options);
  112142. } else {
  112143. return inverse(this);
  112144. }
  112145. } else {
  112146. if (options.data && options.ids) {
  112147. var data = _utils.createFrame(options.data);
  112148. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name);
  112149. options = { data: data };
  112150. }
  112151. return fn(context, options);
  112152. }
  112153. });
  112154. };
  112155. module.exports = exports['default'];
  112156. /***/ }),
  112157. /* 12 */
  112158. /***/ (function(module, exports, __webpack_require__) {
  112159. 'use strict';
  112160. var _interopRequireDefault = __webpack_require__(1)['default'];
  112161. exports.__esModule = true;
  112162. var _utils = __webpack_require__(5);
  112163. var _exception = __webpack_require__(6);
  112164. var _exception2 = _interopRequireDefault(_exception);
  112165. exports['default'] = function (instance) {
  112166. instance.registerHelper('each', function (context, options) {
  112167. if (!options) {
  112168. throw new _exception2['default']('Must pass iterator to #each');
  112169. }
  112170. var fn = options.fn,
  112171. inverse = options.inverse,
  112172. i = 0,
  112173. ret = '',
  112174. data = undefined,
  112175. contextPath = undefined;
  112176. if (options.data && options.ids) {
  112177. contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.';
  112178. }
  112179. if (_utils.isFunction(context)) {
  112180. context = context.call(this);
  112181. }
  112182. if (options.data) {
  112183. data = _utils.createFrame(options.data);
  112184. }
  112185. function execIteration(field, index, last) {
  112186. if (data) {
  112187. data.key = field;
  112188. data.index = index;
  112189. data.first = index === 0;
  112190. data.last = !!last;
  112191. if (contextPath) {
  112192. data.contextPath = contextPath + field;
  112193. }
  112194. }
  112195. ret = ret + fn(context[field], {
  112196. data: data,
  112197. blockParams: _utils.blockParams([context[field], field], [contextPath + field, null])
  112198. });
  112199. }
  112200. if (context && typeof context === 'object') {
  112201. if (_utils.isArray(context)) {
  112202. for (var j = context.length; i < j; i++) {
  112203. if (i in context) {
  112204. execIteration(i, i, i === context.length - 1);
  112205. }
  112206. }
  112207. } else {
  112208. var priorKey = undefined;
  112209. for (var key in context) {
  112210. if (context.hasOwnProperty(key)) {
  112211. // We're running the iterations one step out of sync so we can detect
  112212. // the last iteration without have to scan the object twice and create
  112213. // an itermediate keys array.
  112214. if (priorKey !== undefined) {
  112215. execIteration(priorKey, i - 1);
  112216. }
  112217. priorKey = key;
  112218. i++;
  112219. }
  112220. }
  112221. if (priorKey !== undefined) {
  112222. execIteration(priorKey, i - 1, true);
  112223. }
  112224. }
  112225. }
  112226. if (i === 0) {
  112227. ret = inverse(this);
  112228. }
  112229. return ret;
  112230. });
  112231. };
  112232. module.exports = exports['default'];
  112233. /***/ }),
  112234. /* 13 */
  112235. /***/ (function(module, exports, __webpack_require__) {
  112236. 'use strict';
  112237. var _interopRequireDefault = __webpack_require__(1)['default'];
  112238. exports.__esModule = true;
  112239. var _exception = __webpack_require__(6);
  112240. var _exception2 = _interopRequireDefault(_exception);
  112241. exports['default'] = function (instance) {
  112242. instance.registerHelper('helperMissing', function () /* [args, ]options */{
  112243. if (arguments.length === 1) {
  112244. // A missing field in a {{foo}} construct.
  112245. return undefined;
  112246. } else {
  112247. // Someone is actually trying to call something, blow up.
  112248. throw new _exception2['default']('Missing helper: "' + arguments[arguments.length - 1].name + '"');
  112249. }
  112250. });
  112251. };
  112252. module.exports = exports['default'];
  112253. /***/ }),
  112254. /* 14 */
  112255. /***/ (function(module, exports, __webpack_require__) {
  112256. 'use strict';
  112257. exports.__esModule = true;
  112258. var _utils = __webpack_require__(5);
  112259. exports['default'] = function (instance) {
  112260. instance.registerHelper('if', function (conditional, options) {
  112261. if (_utils.isFunction(conditional)) {
  112262. conditional = conditional.call(this);
  112263. }
  112264. // Default behavior is to render the positive path if the value is truthy and not empty.
  112265. // The `includeZero` option may be set to treat the condtional as purely not empty based on the
  112266. // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative.
  112267. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) {
  112268. return options.inverse(this);
  112269. } else {
  112270. return options.fn(this);
  112271. }
  112272. });
  112273. instance.registerHelper('unless', function (conditional, options) {
  112274. return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash });
  112275. });
  112276. };
  112277. module.exports = exports['default'];
  112278. /***/ }),
  112279. /* 15 */
  112280. /***/ (function(module, exports) {
  112281. 'use strict';
  112282. exports.__esModule = true;
  112283. exports['default'] = function (instance) {
  112284. instance.registerHelper('log', function () /* message, options */{
  112285. var args = [undefined],
  112286. options = arguments[arguments.length - 1];
  112287. for (var i = 0; i < arguments.length - 1; i++) {
  112288. args.push(arguments[i]);
  112289. }
  112290. var level = 1;
  112291. if (options.hash.level != null) {
  112292. level = options.hash.level;
  112293. } else if (options.data && options.data.level != null) {
  112294. level = options.data.level;
  112295. }
  112296. args[0] = level;
  112297. instance.log.apply(instance, args);
  112298. });
  112299. };
  112300. module.exports = exports['default'];
  112301. /***/ }),
  112302. /* 16 */
  112303. /***/ (function(module, exports) {
  112304. 'use strict';
  112305. exports.__esModule = true;
  112306. exports['default'] = function (instance) {
  112307. instance.registerHelper('lookup', function (obj, field) {
  112308. return obj && obj[field];
  112309. });
  112310. };
  112311. module.exports = exports['default'];
  112312. /***/ }),
  112313. /* 17 */
  112314. /***/ (function(module, exports, __webpack_require__) {
  112315. 'use strict';
  112316. exports.__esModule = true;
  112317. var _utils = __webpack_require__(5);
  112318. exports['default'] = function (instance) {
  112319. instance.registerHelper('with', function (context, options) {
  112320. if (_utils.isFunction(context)) {
  112321. context = context.call(this);
  112322. }
  112323. var fn = options.fn;
  112324. if (!_utils.isEmpty(context)) {
  112325. var data = options.data;
  112326. if (options.data && options.ids) {
  112327. data = _utils.createFrame(options.data);
  112328. data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]);
  112329. }
  112330. return fn(context, {
  112331. data: data,
  112332. blockParams: _utils.blockParams([context], [data && data.contextPath])
  112333. });
  112334. } else {
  112335. return options.inverse(this);
  112336. }
  112337. });
  112338. };
  112339. module.exports = exports['default'];
  112340. /***/ }),
  112341. /* 18 */
  112342. /***/ (function(module, exports, __webpack_require__) {
  112343. 'use strict';
  112344. var _interopRequireDefault = __webpack_require__(1)['default'];
  112345. exports.__esModule = true;
  112346. exports.registerDefaultDecorators = registerDefaultDecorators;
  112347. var _decoratorsInline = __webpack_require__(19);
  112348. var _decoratorsInline2 = _interopRequireDefault(_decoratorsInline);
  112349. function registerDefaultDecorators(instance) {
  112350. _decoratorsInline2['default'](instance);
  112351. }
  112352. /***/ }),
  112353. /* 19 */
  112354. /***/ (function(module, exports, __webpack_require__) {
  112355. 'use strict';
  112356. exports.__esModule = true;
  112357. var _utils = __webpack_require__(5);
  112358. exports['default'] = function (instance) {
  112359. instance.registerDecorator('inline', function (fn, props, container, options) {
  112360. var ret = fn;
  112361. if (!props.partials) {
  112362. props.partials = {};
  112363. ret = function (context, options) {
  112364. // Create a new partials stack frame prior to exec.
  112365. var original = container.partials;
  112366. container.partials = _utils.extend({}, original, props.partials);
  112367. var ret = fn(context, options);
  112368. container.partials = original;
  112369. return ret;
  112370. };
  112371. }
  112372. props.partials[options.args[0]] = options.fn;
  112373. return ret;
  112374. });
  112375. };
  112376. module.exports = exports['default'];
  112377. /***/ }),
  112378. /* 20 */
  112379. /***/ (function(module, exports, __webpack_require__) {
  112380. 'use strict';
  112381. exports.__esModule = true;
  112382. var _utils = __webpack_require__(5);
  112383. var logger = {
  112384. methodMap: ['debug', 'info', 'warn', 'error'],
  112385. level: 'info',
  112386. // Maps a given level value to the `methodMap` indexes above.
  112387. lookupLevel: function lookupLevel(level) {
  112388. if (typeof level === 'string') {
  112389. var levelMap = _utils.indexOf(logger.methodMap, level.toLowerCase());
  112390. if (levelMap >= 0) {
  112391. level = levelMap;
  112392. } else {
  112393. level = parseInt(level, 10);
  112394. }
  112395. }
  112396. return level;
  112397. },
  112398. // Can be overridden in the host environment
  112399. log: function log(level) {
  112400. level = logger.lookupLevel(level);
  112401. if (typeof console !== 'undefined' && logger.lookupLevel(logger.level) <= level) {
  112402. var method = logger.methodMap[level];
  112403. if (!console[method]) {
  112404. // eslint-disable-line no-console
  112405. method = 'log';
  112406. }
  112407. for (var _len = arguments.length, message = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
  112408. message[_key - 1] = arguments[_key];
  112409. }
  112410. console[method].apply(console, message); // eslint-disable-line no-console
  112411. }
  112412. }
  112413. };
  112414. exports['default'] = logger;
  112415. module.exports = exports['default'];
  112416. /***/ }),
  112417. /* 21 */
  112418. /***/ (function(module, exports) {
  112419. // Build out our basic SafeString type
  112420. 'use strict';
  112421. exports.__esModule = true;
  112422. function SafeString(string) {
  112423. this.string = string;
  112424. }
  112425. SafeString.prototype.toString = SafeString.prototype.toHTML = function () {
  112426. return '' + this.string;
  112427. };
  112428. exports['default'] = SafeString;
  112429. module.exports = exports['default'];
  112430. /***/ }),
  112431. /* 22 */
  112432. /***/ (function(module, exports, __webpack_require__) {
  112433. 'use strict';
  112434. var _Object$seal = __webpack_require__(23)['default'];
  112435. var _interopRequireWildcard = __webpack_require__(3)['default'];
  112436. var _interopRequireDefault = __webpack_require__(1)['default'];
  112437. exports.__esModule = true;
  112438. exports.checkRevision = checkRevision;
  112439. exports.template = template;
  112440. exports.wrapProgram = wrapProgram;
  112441. exports.resolvePartial = resolvePartial;
  112442. exports.invokePartial = invokePartial;
  112443. exports.noop = noop;
  112444. var _utils = __webpack_require__(5);
  112445. var Utils = _interopRequireWildcard(_utils);
  112446. var _exception = __webpack_require__(6);
  112447. var _exception2 = _interopRequireDefault(_exception);
  112448. var _base = __webpack_require__(4);
  112449. function checkRevision(compilerInfo) {
  112450. var compilerRevision = compilerInfo && compilerInfo[0] || 1,
  112451. currentRevision = _base.COMPILER_REVISION;
  112452. if (compilerRevision !== currentRevision) {
  112453. if (compilerRevision < currentRevision) {
  112454. var runtimeVersions = _base.REVISION_CHANGES[currentRevision],
  112455. compilerVersions = _base.REVISION_CHANGES[compilerRevision];
  112456. throw new _exception2['default']('Template was precompiled with an older version of Handlebars than the current runtime. ' + 'Please update your precompiler to a newer version (' + runtimeVersions + ') or downgrade your runtime to an older version (' + compilerVersions + ').');
  112457. } else {
  112458. // Use the embedded version info since the runtime doesn't know about this revision yet
  112459. throw new _exception2['default']('Template was precompiled with a newer version of Handlebars than the current runtime. ' + 'Please update your runtime to a newer version (' + compilerInfo[1] + ').');
  112460. }
  112461. }
  112462. }
  112463. function template(templateSpec, env) {
  112464. /* istanbul ignore next */
  112465. if (!env) {
  112466. throw new _exception2['default']('No environment passed to template');
  112467. }
  112468. if (!templateSpec || !templateSpec.main) {
  112469. throw new _exception2['default']('Unknown template object: ' + typeof templateSpec);
  112470. }
  112471. templateSpec.main.decorator = templateSpec.main_d;
  112472. // Note: Using env.VM references rather than local var references throughout this section to allow
  112473. // for external users to override these as psuedo-supported APIs.
  112474. env.VM.checkRevision(templateSpec.compiler);
  112475. function invokePartialWrapper(partial, context, options) {
  112476. if (options.hash) {
  112477. context = Utils.extend({}, context, options.hash);
  112478. if (options.ids) {
  112479. options.ids[0] = true;
  112480. }
  112481. }
  112482. partial = env.VM.resolvePartial.call(this, partial, context, options);
  112483. var result = env.VM.invokePartial.call(this, partial, context, options);
  112484. if (result == null && env.compile) {
  112485. options.partials[options.name] = env.compile(partial, templateSpec.compilerOptions, env);
  112486. result = options.partials[options.name](context, options);
  112487. }
  112488. if (result != null) {
  112489. if (options.indent) {
  112490. var lines = result.split('\n');
  112491. for (var i = 0, l = lines.length; i < l; i++) {
  112492. if (!lines[i] && i + 1 === l) {
  112493. break;
  112494. }
  112495. lines[i] = options.indent + lines[i];
  112496. }
  112497. result = lines.join('\n');
  112498. }
  112499. return result;
  112500. } else {
  112501. throw new _exception2['default']('The partial ' + options.name + ' could not be compiled when running in runtime-only mode');
  112502. }
  112503. }
  112504. // Just add water
  112505. var container = {
  112506. strict: function strict(obj, name) {
  112507. if (!(name in obj)) {
  112508. throw new _exception2['default']('"' + name + '" not defined in ' + obj);
  112509. }
  112510. return obj[name];
  112511. },
  112512. lookup: function lookup(depths, name) {
  112513. var len = depths.length;
  112514. for (var i = 0; i < len; i++) {
  112515. if (depths[i] && depths[i][name] != null) {
  112516. return depths[i][name];
  112517. }
  112518. }
  112519. },
  112520. lambda: function lambda(current, context) {
  112521. return typeof current === 'function' ? current.call(context) : current;
  112522. },
  112523. escapeExpression: Utils.escapeExpression,
  112524. invokePartial: invokePartialWrapper,
  112525. fn: function fn(i) {
  112526. var ret = templateSpec[i];
  112527. ret.decorator = templateSpec[i + '_d'];
  112528. return ret;
  112529. },
  112530. programs: [],
  112531. program: function program(i, data, declaredBlockParams, blockParams, depths) {
  112532. var programWrapper = this.programs[i],
  112533. fn = this.fn(i);
  112534. if (data || depths || blockParams || declaredBlockParams) {
  112535. programWrapper = wrapProgram(this, i, fn, data, declaredBlockParams, blockParams, depths);
  112536. } else if (!programWrapper) {
  112537. programWrapper = this.programs[i] = wrapProgram(this, i, fn);
  112538. }
  112539. return programWrapper;
  112540. },
  112541. data: function data(value, depth) {
  112542. while (value && depth--) {
  112543. value = value._parent;
  112544. }
  112545. return value;
  112546. },
  112547. merge: function merge(param, common) {
  112548. var obj = param || common;
  112549. if (param && common && param !== common) {
  112550. obj = Utils.extend({}, common, param);
  112551. }
  112552. return obj;
  112553. },
  112554. // An empty object to use as replacement for null-contexts
  112555. nullContext: _Object$seal({}),
  112556. noop: env.VM.noop,
  112557. compilerInfo: templateSpec.compiler
  112558. };
  112559. function ret(context) {
  112560. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  112561. var data = options.data;
  112562. ret._setup(options);
  112563. if (!options.partial && templateSpec.useData) {
  112564. data = initData(context, data);
  112565. }
  112566. var depths = undefined,
  112567. blockParams = templateSpec.useBlockParams ? [] : undefined;
  112568. if (templateSpec.useDepths) {
  112569. if (options.depths) {
  112570. depths = context != options.depths[0] ? [context].concat(options.depths) : options.depths;
  112571. } else {
  112572. depths = [context];
  112573. }
  112574. }
  112575. function main(context /*, options*/) {
  112576. return '' + templateSpec.main(container, context, container.helpers, container.partials, data, blockParams, depths);
  112577. }
  112578. main = executeDecorators(templateSpec.main, main, container, options.depths || [], data, blockParams);
  112579. return main(context, options);
  112580. }
  112581. ret.isTop = true;
  112582. ret._setup = function (options) {
  112583. if (!options.partial) {
  112584. container.helpers = container.merge(options.helpers, env.helpers);
  112585. if (templateSpec.usePartial) {
  112586. container.partials = container.merge(options.partials, env.partials);
  112587. }
  112588. if (templateSpec.usePartial || templateSpec.useDecorators) {
  112589. container.decorators = container.merge(options.decorators, env.decorators);
  112590. }
  112591. } else {
  112592. container.helpers = options.helpers;
  112593. container.partials = options.partials;
  112594. container.decorators = options.decorators;
  112595. }
  112596. };
  112597. ret._child = function (i, data, blockParams, depths) {
  112598. if (templateSpec.useBlockParams && !blockParams) {
  112599. throw new _exception2['default']('must pass block params');
  112600. }
  112601. if (templateSpec.useDepths && !depths) {
  112602. throw new _exception2['default']('must pass parent depths');
  112603. }
  112604. return wrapProgram(container, i, templateSpec[i], data, 0, blockParams, depths);
  112605. };
  112606. return ret;
  112607. }
  112608. function wrapProgram(container, i, fn, data, declaredBlockParams, blockParams, depths) {
  112609. function prog(context) {
  112610. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  112611. var currentDepths = depths;
  112612. if (depths && context != depths[0] && !(context === container.nullContext && depths[0] === null)) {
  112613. currentDepths = [context].concat(depths);
  112614. }
  112615. return fn(container, context, container.helpers, container.partials, options.data || data, blockParams && [options.blockParams].concat(blockParams), currentDepths);
  112616. }
  112617. prog = executeDecorators(fn, prog, container, depths, data, blockParams);
  112618. prog.program = i;
  112619. prog.depth = depths ? depths.length : 0;
  112620. prog.blockParams = declaredBlockParams || 0;
  112621. return prog;
  112622. }
  112623. function resolvePartial(partial, context, options) {
  112624. if (!partial) {
  112625. if (options.name === '@partial-block') {
  112626. partial = options.data['partial-block'];
  112627. } else {
  112628. partial = options.partials[options.name];
  112629. }
  112630. } else if (!partial.call && !options.name) {
  112631. // This is a dynamic partial that returned a string
  112632. options.name = partial;
  112633. partial = options.partials[partial];
  112634. }
  112635. return partial;
  112636. }
  112637. function invokePartial(partial, context, options) {
  112638. // Use the current closure context to save the partial-block if this partial
  112639. var currentPartialBlock = options.data && options.data['partial-block'];
  112640. options.partial = true;
  112641. if (options.ids) {
  112642. options.data.contextPath = options.ids[0] || options.data.contextPath;
  112643. }
  112644. var partialBlock = undefined;
  112645. if (options.fn && options.fn !== noop) {
  112646. (function () {
  112647. options.data = _base.createFrame(options.data);
  112648. // Wrapper function to get access to currentPartialBlock from the closure
  112649. var fn = options.fn;
  112650. partialBlock = options.data['partial-block'] = function partialBlockWrapper(context) {
  112651. var options = arguments.length <= 1 || arguments[1] === undefined ? {} : arguments[1];
  112652. // Restore the partial-block from the closure for the execution of the block
  112653. // i.e. the part inside the block of the partial call.
  112654. options.data = _base.createFrame(options.data);
  112655. options.data['partial-block'] = currentPartialBlock;
  112656. return fn(context, options);
  112657. };
  112658. if (fn.partials) {
  112659. options.partials = Utils.extend({}, options.partials, fn.partials);
  112660. }
  112661. })();
  112662. }
  112663. if (partial === undefined && partialBlock) {
  112664. partial = partialBlock;
  112665. }
  112666. if (partial === undefined) {
  112667. throw new _exception2['default']('The partial ' + options.name + ' could not be found');
  112668. } else if (partial instanceof Function) {
  112669. return partial(context, options);
  112670. }
  112671. }
  112672. function noop() {
  112673. return '';
  112674. }
  112675. function initData(context, data) {
  112676. if (!data || !('root' in data)) {
  112677. data = data ? _base.createFrame(data) : {};
  112678. data.root = context;
  112679. }
  112680. return data;
  112681. }
  112682. function executeDecorators(fn, prog, container, depths, data, blockParams) {
  112683. if (fn.decorator) {
  112684. var props = {};
  112685. prog = fn.decorator(prog, props, container, depths && depths[0], data, blockParams, depths);
  112686. Utils.extend(prog, props);
  112687. }
  112688. return prog;
  112689. }
  112690. /***/ }),
  112691. /* 23 */
  112692. /***/ (function(module, exports, __webpack_require__) {
  112693. module.exports = { "default": __webpack_require__(24), __esModule: true };
  112694. /***/ }),
  112695. /* 24 */
  112696. /***/ (function(module, exports, __webpack_require__) {
  112697. __webpack_require__(25);
  112698. module.exports = __webpack_require__(30).Object.seal;
  112699. /***/ }),
  112700. /* 25 */
  112701. /***/ (function(module, exports, __webpack_require__) {
  112702. // 19.1.2.17 Object.seal(O)
  112703. var isObject = __webpack_require__(26);
  112704. __webpack_require__(27)('seal', function($seal){
  112705. return function seal(it){
  112706. return $seal && isObject(it) ? $seal(it) : it;
  112707. };
  112708. });
  112709. /***/ }),
  112710. /* 26 */
  112711. /***/ (function(module, exports) {
  112712. module.exports = function(it){
  112713. return typeof it === 'object' ? it !== null : typeof it === 'function';
  112714. };
  112715. /***/ }),
  112716. /* 27 */
  112717. /***/ (function(module, exports, __webpack_require__) {
  112718. // most Object methods by ES6 should accept primitives
  112719. var $export = __webpack_require__(28)
  112720. , core = __webpack_require__(30)
  112721. , fails = __webpack_require__(33);
  112722. module.exports = function(KEY, exec){
  112723. var fn = (core.Object || {})[KEY] || Object[KEY]
  112724. , exp = {};
  112725. exp[KEY] = exec(fn);
  112726. $export($export.S + $export.F * fails(function(){ fn(1); }), 'Object', exp);
  112727. };
  112728. /***/ }),
  112729. /* 28 */
  112730. /***/ (function(module, exports, __webpack_require__) {
  112731. var global = __webpack_require__(29)
  112732. , core = __webpack_require__(30)
  112733. , ctx = __webpack_require__(31)
  112734. , PROTOTYPE = 'prototype';
  112735. var $export = function(type, name, source){
  112736. var IS_FORCED = type & $export.F
  112737. , IS_GLOBAL = type & $export.G
  112738. , IS_STATIC = type & $export.S
  112739. , IS_PROTO = type & $export.P
  112740. , IS_BIND = type & $export.B
  112741. , IS_WRAP = type & $export.W
  112742. , exports = IS_GLOBAL ? core : core[name] || (core[name] = {})
  112743. , target = IS_GLOBAL ? global : IS_STATIC ? global[name] : (global[name] || {})[PROTOTYPE]
  112744. , key, own, out;
  112745. if(IS_GLOBAL)source = name;
  112746. for(key in source){
  112747. // contains in native
  112748. own = !IS_FORCED && target && key in target;
  112749. if(own && key in exports)continue;
  112750. // export native or passed
  112751. out = own ? target[key] : source[key];
  112752. // prevent global pollution for namespaces
  112753. exports[key] = IS_GLOBAL && typeof target[key] != 'function' ? source[key]
  112754. // bind timers to global for call from export context
  112755. : IS_BIND && own ? ctx(out, global)
  112756. // wrap global constructors for prevent change them in library
  112757. : IS_WRAP && target[key] == out ? (function(C){
  112758. var F = function(param){
  112759. return this instanceof C ? new C(param) : C(param);
  112760. };
  112761. F[PROTOTYPE] = C[PROTOTYPE];
  112762. return F;
  112763. // make static versions for prototype methods
  112764. })(out) : IS_PROTO && typeof out == 'function' ? ctx(Function.call, out) : out;
  112765. if(IS_PROTO)(exports[PROTOTYPE] || (exports[PROTOTYPE] = {}))[key] = out;
  112766. }
  112767. };
  112768. // type bitmap
  112769. $export.F = 1; // forced
  112770. $export.G = 2; // global
  112771. $export.S = 4; // static
  112772. $export.P = 8; // proto
  112773. $export.B = 16; // bind
  112774. $export.W = 32; // wrap
  112775. module.exports = $export;
  112776. /***/ }),
  112777. /* 29 */
  112778. /***/ (function(module, exports) {
  112779. // https://github.com/zloirock/core-js/issues/86#issuecomment-115759028
  112780. var global = module.exports = typeof window != 'undefined' && window.Math == Math
  112781. ? window : typeof self != 'undefined' && self.Math == Math ? self : Function('return this')();
  112782. if(typeof __g == 'number')__g = global; // eslint-disable-line no-undef
  112783. /***/ }),
  112784. /* 30 */
  112785. /***/ (function(module, exports) {
  112786. var core = module.exports = {version: '1.2.6'};
  112787. if(typeof __e == 'number')__e = core; // eslint-disable-line no-undef
  112788. /***/ }),
  112789. /* 31 */
  112790. /***/ (function(module, exports, __webpack_require__) {
  112791. // optional / simple context binding
  112792. var aFunction = __webpack_require__(32);
  112793. module.exports = function(fn, that, length){
  112794. aFunction(fn);
  112795. if(that === undefined)return fn;
  112796. switch(length){
  112797. case 1: return function(a){
  112798. return fn.call(that, a);
  112799. };
  112800. case 2: return function(a, b){
  112801. return fn.call(that, a, b);
  112802. };
  112803. case 3: return function(a, b, c){
  112804. return fn.call(that, a, b, c);
  112805. };
  112806. }
  112807. return function(/* ...args */){
  112808. return fn.apply(that, arguments);
  112809. };
  112810. };
  112811. /***/ }),
  112812. /* 32 */
  112813. /***/ (function(module, exports) {
  112814. module.exports = function(it){
  112815. if(typeof it != 'function')throw TypeError(it + ' is not a function!');
  112816. return it;
  112817. };
  112818. /***/ }),
  112819. /* 33 */
  112820. /***/ (function(module, exports) {
  112821. module.exports = function(exec){
  112822. try {
  112823. return !!exec();
  112824. } catch(e){
  112825. return true;
  112826. }
  112827. };
  112828. /***/ }),
  112829. /* 34 */
  112830. /***/ (function(module, exports) {
  112831. /* WEBPACK VAR INJECTION */(function(global) {/* global window */
  112832. 'use strict';
  112833. exports.__esModule = true;
  112834. exports['default'] = function (Handlebars) {
  112835. /* istanbul ignore next */
  112836. var root = typeof global !== 'undefined' ? global : window,
  112837. $Handlebars = root.Handlebars;
  112838. /* istanbul ignore next */
  112839. Handlebars.noConflict = function () {
  112840. if (root.Handlebars === Handlebars) {
  112841. root.Handlebars = $Handlebars;
  112842. }
  112843. return Handlebars;
  112844. };
  112845. };
  112846. module.exports = exports['default'];
  112847. /* WEBPACK VAR INJECTION */}.call(exports, (function() { return this; }())))
  112848. /***/ }),
  112849. /* 35 */
  112850. /***/ (function(module, exports) {
  112851. 'use strict';
  112852. exports.__esModule = true;
  112853. var AST = {
  112854. // Public API used to evaluate derived attributes regarding AST nodes
  112855. helpers: {
  112856. // a mustache is definitely a helper if:
  112857. // * it is an eligible helper, and
  112858. // * it has at least one parameter or hash segment
  112859. helperExpression: function helperExpression(node) {
  112860. return node.type === 'SubExpression' || (node.type === 'MustacheStatement' || node.type === 'BlockStatement') && !!(node.params && node.params.length || node.hash);
  112861. },
  112862. scopedId: function scopedId(path) {
  112863. return (/^\.|this\b/.test(path.original)
  112864. );
  112865. },
  112866. // an ID is simple if it only has one part, and that part is not
  112867. // `..` or `this`.
  112868. simpleId: function simpleId(path) {
  112869. return path.parts.length === 1 && !AST.helpers.scopedId(path) && !path.depth;
  112870. }
  112871. }
  112872. };
  112873. // Must be exported as an object rather than the root of the module as the jison lexer
  112874. // must modify the object to operate properly.
  112875. exports['default'] = AST;
  112876. module.exports = exports['default'];
  112877. /***/ }),
  112878. /* 36 */
  112879. /***/ (function(module, exports, __webpack_require__) {
  112880. 'use strict';
  112881. var _interopRequireDefault = __webpack_require__(1)['default'];
  112882. var _interopRequireWildcard = __webpack_require__(3)['default'];
  112883. exports.__esModule = true;
  112884. exports.parse = parse;
  112885. var _parser = __webpack_require__(37);
  112886. var _parser2 = _interopRequireDefault(_parser);
  112887. var _whitespaceControl = __webpack_require__(38);
  112888. var _whitespaceControl2 = _interopRequireDefault(_whitespaceControl);
  112889. var _helpers = __webpack_require__(40);
  112890. var Helpers = _interopRequireWildcard(_helpers);
  112891. var _utils = __webpack_require__(5);
  112892. exports.parser = _parser2['default'];
  112893. var yy = {};
  112894. _utils.extend(yy, Helpers);
  112895. function parse(input, options) {
  112896. // Just return if an already-compiled AST was passed in.
  112897. if (input.type === 'Program') {
  112898. return input;
  112899. }
  112900. _parser2['default'].yy = yy;
  112901. // Altering the shared object here, but this is ok as parser is a sync operation
  112902. yy.locInfo = function (locInfo) {
  112903. return new yy.SourceLocation(options && options.srcName, locInfo);
  112904. };
  112905. var strip = new _whitespaceControl2['default'](options);
  112906. return strip.accept(_parser2['default'].parse(input));
  112907. }
  112908. /***/ }),
  112909. /* 37 */
  112910. /***/ (function(module, exports) {
  112911. // File ignored in coverage tests via setting in .istanbul.yml
  112912. /* Jison generated parser */
  112913. "use strict";
  112914. exports.__esModule = true;
  112915. var handlebars = (function () {
  112916. var parser = { trace: function trace() {},
  112917. yy: {},
  112918. 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 },
  112919. 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" },
  112920. 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]],
  112921. performAction: function anonymous(yytext, yyleng, yylineno, yy, yystate, $$, _$
  112922. /**/) {
  112923. var $0 = $$.length - 1;
  112924. switch (yystate) {
  112925. case 1:
  112926. return $$[$0 - 1];
  112927. break;
  112928. case 2:
  112929. this.$ = yy.prepareProgram($$[$0]);
  112930. break;
  112931. case 3:
  112932. this.$ = $$[$0];
  112933. break;
  112934. case 4:
  112935. this.$ = $$[$0];
  112936. break;
  112937. case 5:
  112938. this.$ = $$[$0];
  112939. break;
  112940. case 6:
  112941. this.$ = $$[$0];
  112942. break;
  112943. case 7:
  112944. this.$ = $$[$0];
  112945. break;
  112946. case 8:
  112947. this.$ = $$[$0];
  112948. break;
  112949. case 9:
  112950. this.$ = {
  112951. type: 'CommentStatement',
  112952. value: yy.stripComment($$[$0]),
  112953. strip: yy.stripFlags($$[$0], $$[$0]),
  112954. loc: yy.locInfo(this._$)
  112955. };
  112956. break;
  112957. case 10:
  112958. this.$ = {
  112959. type: 'ContentStatement',
  112960. original: $$[$0],
  112961. value: $$[$0],
  112962. loc: yy.locInfo(this._$)
  112963. };
  112964. break;
  112965. case 11:
  112966. this.$ = yy.prepareRawBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  112967. break;
  112968. case 12:
  112969. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1] };
  112970. break;
  112971. case 13:
  112972. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], false, this._$);
  112973. break;
  112974. case 14:
  112975. this.$ = yy.prepareBlock($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0], true, this._$);
  112976. break;
  112977. case 15:
  112978. this.$ = { open: $$[$0 - 5], path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  112979. break;
  112980. case 16:
  112981. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  112982. break;
  112983. case 17:
  112984. this.$ = { path: $$[$0 - 4], params: $$[$0 - 3], hash: $$[$0 - 2], blockParams: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 5], $$[$0]) };
  112985. break;
  112986. case 18:
  112987. this.$ = { strip: yy.stripFlags($$[$0 - 1], $$[$0 - 1]), program: $$[$0] };
  112988. break;
  112989. case 19:
  112990. var inverse = yy.prepareBlock($$[$0 - 2], $$[$0 - 1], $$[$0], $$[$0], false, this._$),
  112991. program = yy.prepareProgram([inverse], $$[$0 - 1].loc);
  112992. program.chained = true;
  112993. this.$ = { strip: $$[$0 - 2].strip, program: program, chain: true };
  112994. break;
  112995. case 20:
  112996. this.$ = $$[$0];
  112997. break;
  112998. case 21:
  112999. this.$ = { path: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 2], $$[$0]) };
  113000. break;
  113001. case 22:
  113002. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  113003. break;
  113004. case 23:
  113005. this.$ = yy.prepareMustache($$[$0 - 3], $$[$0 - 2], $$[$0 - 1], $$[$0 - 4], yy.stripFlags($$[$0 - 4], $$[$0]), this._$);
  113006. break;
  113007. case 24:
  113008. this.$ = {
  113009. type: 'PartialStatement',
  113010. name: $$[$0 - 3],
  113011. params: $$[$0 - 2],
  113012. hash: $$[$0 - 1],
  113013. indent: '',
  113014. strip: yy.stripFlags($$[$0 - 4], $$[$0]),
  113015. loc: yy.locInfo(this._$)
  113016. };
  113017. break;
  113018. case 25:
  113019. this.$ = yy.preparePartialBlock($$[$0 - 2], $$[$0 - 1], $$[$0], this._$);
  113020. break;
  113021. case 26:
  113022. this.$ = { path: $$[$0 - 3], params: $$[$0 - 2], hash: $$[$0 - 1], strip: yy.stripFlags($$[$0 - 4], $$[$0]) };
  113023. break;
  113024. case 27:
  113025. this.$ = $$[$0];
  113026. break;
  113027. case 28:
  113028. this.$ = $$[$0];
  113029. break;
  113030. case 29:
  113031. this.$ = {
  113032. type: 'SubExpression',
  113033. path: $$[$0 - 3],
  113034. params: $$[$0 - 2],
  113035. hash: $$[$0 - 1],
  113036. loc: yy.locInfo(this._$)
  113037. };
  113038. break;
  113039. case 30:
  113040. this.$ = { type: 'Hash', pairs: $$[$0], loc: yy.locInfo(this._$) };
  113041. break;
  113042. case 31:
  113043. this.$ = { type: 'HashPair', key: yy.id($$[$0 - 2]), value: $$[$0], loc: yy.locInfo(this._$) };
  113044. break;
  113045. case 32:
  113046. this.$ = yy.id($$[$0 - 1]);
  113047. break;
  113048. case 33:
  113049. this.$ = $$[$0];
  113050. break;
  113051. case 34:
  113052. this.$ = $$[$0];
  113053. break;
  113054. case 35:
  113055. this.$ = { type: 'StringLiteral', value: $$[$0], original: $$[$0], loc: yy.locInfo(this._$) };
  113056. break;
  113057. case 36:
  113058. this.$ = { type: 'NumberLiteral', value: Number($$[$0]), original: Number($$[$0]), loc: yy.locInfo(this._$) };
  113059. break;
  113060. case 37:
  113061. this.$ = { type: 'BooleanLiteral', value: $$[$0] === 'true', original: $$[$0] === 'true', loc: yy.locInfo(this._$) };
  113062. break;
  113063. case 38:
  113064. this.$ = { type: 'UndefinedLiteral', original: undefined, value: undefined, loc: yy.locInfo(this._$) };
  113065. break;
  113066. case 39:
  113067. this.$ = { type: 'NullLiteral', original: null, value: null, loc: yy.locInfo(this._$) };
  113068. break;
  113069. case 40:
  113070. this.$ = $$[$0];
  113071. break;
  113072. case 41:
  113073. this.$ = $$[$0];
  113074. break;
  113075. case 42:
  113076. this.$ = yy.preparePath(true, $$[$0], this._$);
  113077. break;
  113078. case 43:
  113079. this.$ = yy.preparePath(false, $$[$0], this._$);
  113080. break;
  113081. case 44:
  113082. $$[$0 - 2].push({ part: yy.id($$[$0]), original: $$[$0], separator: $$[$0 - 1] });this.$ = $$[$0 - 2];
  113083. break;
  113084. case 45:
  113085. this.$ = [{ part: yy.id($$[$0]), original: $$[$0] }];
  113086. break;
  113087. case 46:
  113088. this.$ = [];
  113089. break;
  113090. case 47:
  113091. $$[$0 - 1].push($$[$0]);
  113092. break;
  113093. case 48:
  113094. this.$ = [$$[$0]];
  113095. break;
  113096. case 49:
  113097. $$[$0 - 1].push($$[$0]);
  113098. break;
  113099. case 50:
  113100. this.$ = [];
  113101. break;
  113102. case 51:
  113103. $$[$0 - 1].push($$[$0]);
  113104. break;
  113105. case 58:
  113106. this.$ = [];
  113107. break;
  113108. case 59:
  113109. $$[$0 - 1].push($$[$0]);
  113110. break;
  113111. case 64:
  113112. this.$ = [];
  113113. break;
  113114. case 65:
  113115. $$[$0 - 1].push($$[$0]);
  113116. break;
  113117. case 70:
  113118. this.$ = [];
  113119. break;
  113120. case 71:
  113121. $$[$0 - 1].push($$[$0]);
  113122. break;
  113123. case 78:
  113124. this.$ = [];
  113125. break;
  113126. case 79:
  113127. $$[$0 - 1].push($$[$0]);
  113128. break;
  113129. case 82:
  113130. this.$ = [];
  113131. break;
  113132. case 83:
  113133. $$[$0 - 1].push($$[$0]);
  113134. break;
  113135. case 86:
  113136. this.$ = [];
  113137. break;
  113138. case 87:
  113139. $$[$0 - 1].push($$[$0]);
  113140. break;
  113141. case 90:
  113142. this.$ = [];
  113143. break;
  113144. case 91:
  113145. $$[$0 - 1].push($$[$0]);
  113146. break;
  113147. case 94:
  113148. this.$ = [];
  113149. break;
  113150. case 95:
  113151. $$[$0 - 1].push($$[$0]);
  113152. break;
  113153. case 98:
  113154. this.$ = [$$[$0]];
  113155. break;
  113156. case 99:
  113157. $$[$0 - 1].push($$[$0]);
  113158. break;
  113159. case 100:
  113160. this.$ = [$$[$0]];
  113161. break;
  113162. case 101:
  113163. $$[$0 - 1].push($$[$0]);
  113164. break;
  113165. }
  113166. },
  113167. table: [{ 3: 1, 4: 2, 5: [2, 46], 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 1: [3] }, { 5: [1, 4] }, { 5: [2, 2], 7: 5, 8: 6, 9: 7, 10: 8, 11: 9, 12: 10, 13: 11, 14: [1, 12], 15: [1, 20], 16: 17, 19: [1, 23], 24: 15, 27: 16, 29: [1, 21], 34: [1, 22], 39: [2, 2], 44: [2, 2], 47: [2, 2], 48: [1, 13], 51: [1, 14], 55: [1, 18], 59: 19, 60: [1, 24] }, { 1: [2, 1] }, { 5: [2, 47], 14: [2, 47], 15: [2, 47], 19: [2, 47], 29: [2, 47], 34: [2, 47], 39: [2, 47], 44: [2, 47], 47: [2, 47], 48: [2, 47], 51: [2, 47], 55: [2, 47], 60: [2, 47] }, { 5: [2, 3], 14: [2, 3], 15: [2, 3], 19: [2, 3], 29: [2, 3], 34: [2, 3], 39: [2, 3], 44: [2, 3], 47: [2, 3], 48: [2, 3], 51: [2, 3], 55: [2, 3], 60: [2, 3] }, { 5: [2, 4], 14: [2, 4], 15: [2, 4], 19: [2, 4], 29: [2, 4], 34: [2, 4], 39: [2, 4], 44: [2, 4], 47: [2, 4], 48: [2, 4], 51: [2, 4], 55: [2, 4], 60: [2, 4] }, { 5: [2, 5], 14: [2, 5], 15: [2, 5], 19: [2, 5], 29: [2, 5], 34: [2, 5], 39: [2, 5], 44: [2, 5], 47: [2, 5], 48: [2, 5], 51: [2, 5], 55: [2, 5], 60: [2, 5] }, { 5: [2, 6], 14: [2, 6], 15: [2, 6], 19: [2, 6], 29: [2, 6], 34: [2, 6], 39: [2, 6], 44: [2, 6], 47: [2, 6], 48: [2, 6], 51: [2, 6], 55: [2, 6], 60: [2, 6] }, { 5: [2, 7], 14: [2, 7], 15: [2, 7], 19: [2, 7], 29: [2, 7], 34: [2, 7], 39: [2, 7], 44: [2, 7], 47: [2, 7], 48: [2, 7], 51: [2, 7], 55: [2, 7], 60: [2, 7] }, { 5: [2, 8], 14: [2, 8], 15: [2, 8], 19: [2, 8], 29: [2, 8], 34: [2, 8], 39: [2, 8], 44: [2, 8], 47: [2, 8], 48: [2, 8], 51: [2, 8], 55: [2, 8], 60: [2, 8] }, { 5: [2, 9], 14: [2, 9], 15: [2, 9], 19: [2, 9], 29: [2, 9], 34: [2, 9], 39: [2, 9], 44: [2, 9], 47: [2, 9], 48: [2, 9], 51: [2, 9], 55: [2, 9], 60: [2, 9] }, { 20: 25, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 36, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 37, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 4: 38, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 13: 40, 15: [1, 20], 17: 39 }, { 20: 42, 56: 41, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 45, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 5: [2, 10], 14: [2, 10], 15: [2, 10], 18: [2, 10], 19: [2, 10], 29: [2, 10], 34: [2, 10], 39: [2, 10], 44: [2, 10], 47: [2, 10], 48: [2, 10], 51: [2, 10], 55: [2, 10], 60: [2, 10] }, { 20: 46, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 47, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 48, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 42, 56: 49, 64: 43, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [2, 78], 49: 50, 65: [2, 78], 72: [2, 78], 80: [2, 78], 81: [2, 78], 82: [2, 78], 83: [2, 78], 84: [2, 78], 85: [2, 78] }, { 23: [2, 33], 33: [2, 33], 54: [2, 33], 65: [2, 33], 68: [2, 33], 72: [2, 33], 75: [2, 33], 80: [2, 33], 81: [2, 33], 82: [2, 33], 83: [2, 33], 84: [2, 33], 85: [2, 33] }, { 23: [2, 34], 33: [2, 34], 54: [2, 34], 65: [2, 34], 68: [2, 34], 72: [2, 34], 75: [2, 34], 80: [2, 34], 81: [2, 34], 82: [2, 34], 83: [2, 34], 84: [2, 34], 85: [2, 34] }, { 23: [2, 35], 33: [2, 35], 54: [2, 35], 65: [2, 35], 68: [2, 35], 72: [2, 35], 75: [2, 35], 80: [2, 35], 81: [2, 35], 82: [2, 35], 83: [2, 35], 84: [2, 35], 85: [2, 35] }, { 23: [2, 36], 33: [2, 36], 54: [2, 36], 65: [2, 36], 68: [2, 36], 72: [2, 36], 75: [2, 36], 80: [2, 36], 81: [2, 36], 82: [2, 36], 83: [2, 36], 84: [2, 36], 85: [2, 36] }, { 23: [2, 37], 33: [2, 37], 54: [2, 37], 65: [2, 37], 68: [2, 37], 72: [2, 37], 75: [2, 37], 80: [2, 37], 81: [2, 37], 82: [2, 37], 83: [2, 37], 84: [2, 37], 85: [2, 37] }, { 23: [2, 38], 33: [2, 38], 54: [2, 38], 65: [2, 38], 68: [2, 38], 72: [2, 38], 75: [2, 38], 80: [2, 38], 81: [2, 38], 82: [2, 38], 83: [2, 38], 84: [2, 38], 85: [2, 38] }, { 23: [2, 39], 33: [2, 39], 54: [2, 39], 65: [2, 39], 68: [2, 39], 72: [2, 39], 75: [2, 39], 80: [2, 39], 81: [2, 39], 82: [2, 39], 83: [2, 39], 84: [2, 39], 85: [2, 39] }, { 23: [2, 43], 33: [2, 43], 54: [2, 43], 65: [2, 43], 68: [2, 43], 72: [2, 43], 75: [2, 43], 80: [2, 43], 81: [2, 43], 82: [2, 43], 83: [2, 43], 84: [2, 43], 85: [2, 43], 87: [1, 51] }, { 72: [1, 35], 86: 52 }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 52: 53, 54: [2, 82], 65: [2, 82], 72: [2, 82], 80: [2, 82], 81: [2, 82], 82: [2, 82], 83: [2, 82], 84: [2, 82], 85: [2, 82] }, { 25: 54, 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 55, 47: [2, 54] }, { 28: 60, 43: 61, 44: [1, 59], 47: [2, 56] }, { 13: 63, 15: [1, 20], 18: [1, 62] }, { 15: [2, 48], 18: [2, 48] }, { 33: [2, 86], 57: 64, 65: [2, 86], 72: [2, 86], 80: [2, 86], 81: [2, 86], 82: [2, 86], 83: [2, 86], 84: [2, 86], 85: [2, 86] }, { 33: [2, 40], 65: [2, 40], 72: [2, 40], 80: [2, 40], 81: [2, 40], 82: [2, 40], 83: [2, 40], 84: [2, 40], 85: [2, 40] }, { 33: [2, 41], 65: [2, 41], 72: [2, 41], 80: [2, 41], 81: [2, 41], 82: [2, 41], 83: [2, 41], 84: [2, 41], 85: [2, 41] }, { 20: 65, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 66, 47: [1, 67] }, { 30: 68, 33: [2, 58], 65: [2, 58], 72: [2, 58], 75: [2, 58], 80: [2, 58], 81: [2, 58], 82: [2, 58], 83: [2, 58], 84: [2, 58], 85: [2, 58] }, { 33: [2, 64], 35: 69, 65: [2, 64], 72: [2, 64], 75: [2, 64], 80: [2, 64], 81: [2, 64], 82: [2, 64], 83: [2, 64], 84: [2, 64], 85: [2, 64] }, { 21: 70, 23: [2, 50], 65: [2, 50], 72: [2, 50], 80: [2, 50], 81: [2, 50], 82: [2, 50], 83: [2, 50], 84: [2, 50], 85: [2, 50] }, { 33: [2, 90], 61: 71, 65: [2, 90], 72: [2, 90], 80: [2, 90], 81: [2, 90], 82: [2, 90], 83: [2, 90], 84: [2, 90], 85: [2, 90] }, { 20: 75, 33: [2, 80], 50: 72, 63: 73, 64: 76, 65: [1, 44], 69: 74, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 72: [1, 80] }, { 23: [2, 42], 33: [2, 42], 54: [2, 42], 65: [2, 42], 68: [2, 42], 72: [2, 42], 75: [2, 42], 80: [2, 42], 81: [2, 42], 82: [2, 42], 83: [2, 42], 84: [2, 42], 85: [2, 42], 87: [1, 51] }, { 20: 75, 53: 81, 54: [2, 84], 63: 82, 64: 76, 65: [1, 44], 69: 83, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 26: 84, 47: [1, 67] }, { 47: [2, 55] }, { 4: 85, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 39: [2, 46], 44: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 47: [2, 20] }, { 20: 86, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 4: 87, 6: 3, 14: [2, 46], 15: [2, 46], 19: [2, 46], 29: [2, 46], 34: [2, 46], 47: [2, 46], 48: [2, 46], 51: [2, 46], 55: [2, 46], 60: [2, 46] }, { 26: 88, 47: [1, 67] }, { 47: [2, 57] }, { 5: [2, 11], 14: [2, 11], 15: [2, 11], 19: [2, 11], 29: [2, 11], 34: [2, 11], 39: [2, 11], 44: [2, 11], 47: [2, 11], 48: [2, 11], 51: [2, 11], 55: [2, 11], 60: [2, 11] }, { 15: [2, 49], 18: [2, 49] }, { 20: 75, 33: [2, 88], 58: 89, 63: 90, 64: 76, 65: [1, 44], 69: 91, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 65: [2, 94], 66: 92, 68: [2, 94], 72: [2, 94], 80: [2, 94], 81: [2, 94], 82: [2, 94], 83: [2, 94], 84: [2, 94], 85: [2, 94] }, { 5: [2, 25], 14: [2, 25], 15: [2, 25], 19: [2, 25], 29: [2, 25], 34: [2, 25], 39: [2, 25], 44: [2, 25], 47: [2, 25], 48: [2, 25], 51: [2, 25], 55: [2, 25], 60: [2, 25] }, { 20: 93, 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 31: 94, 33: [2, 60], 63: 95, 64: 76, 65: [1, 44], 69: 96, 70: 77, 71: 78, 72: [1, 79], 75: [2, 60], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 66], 36: 97, 63: 98, 64: 76, 65: [1, 44], 69: 99, 70: 77, 71: 78, 72: [1, 79], 75: [2, 66], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 22: 100, 23: [2, 52], 63: 101, 64: 76, 65: [1, 44], 69: 102, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 20: 75, 33: [2, 92], 62: 103, 63: 104, 64: 76, 65: [1, 44], 69: 105, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 106] }, { 33: [2, 79], 65: [2, 79], 72: [2, 79], 80: [2, 79], 81: [2, 79], 82: [2, 79], 83: [2, 79], 84: [2, 79], 85: [2, 79] }, { 33: [2, 81] }, { 23: [2, 27], 33: [2, 27], 54: [2, 27], 65: [2, 27], 68: [2, 27], 72: [2, 27], 75: [2, 27], 80: [2, 27], 81: [2, 27], 82: [2, 27], 83: [2, 27], 84: [2, 27], 85: [2, 27] }, { 23: [2, 28], 33: [2, 28], 54: [2, 28], 65: [2, 28], 68: [2, 28], 72: [2, 28], 75: [2, 28], 80: [2, 28], 81: [2, 28], 82: [2, 28], 83: [2, 28], 84: [2, 28], 85: [2, 28] }, { 23: [2, 30], 33: [2, 30], 54: [2, 30], 68: [2, 30], 71: 107, 72: [1, 108], 75: [2, 30] }, { 23: [2, 98], 33: [2, 98], 54: [2, 98], 68: [2, 98], 72: [2, 98], 75: [2, 98] }, { 23: [2, 45], 33: [2, 45], 54: [2, 45], 65: [2, 45], 68: [2, 45], 72: [2, 45], 73: [1, 109], 75: [2, 45], 80: [2, 45], 81: [2, 45], 82: [2, 45], 83: [2, 45], 84: [2, 45], 85: [2, 45], 87: [2, 45] }, { 23: [2, 44], 33: [2, 44], 54: [2, 44], 65: [2, 44], 68: [2, 44], 72: [2, 44], 75: [2, 44], 80: [2, 44], 81: [2, 44], 82: [2, 44], 83: [2, 44], 84: [2, 44], 85: [2, 44], 87: [2, 44] }, { 54: [1, 110] }, { 54: [2, 83], 65: [2, 83], 72: [2, 83], 80: [2, 83], 81: [2, 83], 82: [2, 83], 83: [2, 83], 84: [2, 83], 85: [2, 83] }, { 54: [2, 85] }, { 5: [2, 13], 14: [2, 13], 15: [2, 13], 19: [2, 13], 29: [2, 13], 34: [2, 13], 39: [2, 13], 44: [2, 13], 47: [2, 13], 48: [2, 13], 51: [2, 13], 55: [2, 13], 60: [2, 13] }, { 38: 56, 39: [1, 58], 43: 57, 44: [1, 59], 45: 112, 46: 111, 47: [2, 76] }, { 33: [2, 70], 40: 113, 65: [2, 70], 72: [2, 70], 75: [2, 70], 80: [2, 70], 81: [2, 70], 82: [2, 70], 83: [2, 70], 84: [2, 70], 85: [2, 70] }, { 47: [2, 18] }, { 5: [2, 14], 14: [2, 14], 15: [2, 14], 19: [2, 14], 29: [2, 14], 34: [2, 14], 39: [2, 14], 44: [2, 14], 47: [2, 14], 48: [2, 14], 51: [2, 14], 55: [2, 14], 60: [2, 14] }, { 33: [1, 114] }, { 33: [2, 87], 65: [2, 87], 72: [2, 87], 80: [2, 87], 81: [2, 87], 82: [2, 87], 83: [2, 87], 84: [2, 87], 85: [2, 87] }, { 33: [2, 89] }, { 20: 75, 63: 116, 64: 76, 65: [1, 44], 67: 115, 68: [2, 96], 69: 117, 70: 77, 71: 78, 72: [1, 79], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 33: [1, 118] }, { 32: 119, 33: [2, 62], 74: 120, 75: [1, 121] }, { 33: [2, 59], 65: [2, 59], 72: [2, 59], 75: [2, 59], 80: [2, 59], 81: [2, 59], 82: [2, 59], 83: [2, 59], 84: [2, 59], 85: [2, 59] }, { 33: [2, 61], 75: [2, 61] }, { 33: [2, 68], 37: 122, 74: 123, 75: [1, 121] }, { 33: [2, 65], 65: [2, 65], 72: [2, 65], 75: [2, 65], 80: [2, 65], 81: [2, 65], 82: [2, 65], 83: [2, 65], 84: [2, 65], 85: [2, 65] }, { 33: [2, 67], 75: [2, 67] }, { 23: [1, 124] }, { 23: [2, 51], 65: [2, 51], 72: [2, 51], 80: [2, 51], 81: [2, 51], 82: [2, 51], 83: [2, 51], 84: [2, 51], 85: [2, 51] }, { 23: [2, 53] }, { 33: [1, 125] }, { 33: [2, 91], 65: [2, 91], 72: [2, 91], 80: [2, 91], 81: [2, 91], 82: [2, 91], 83: [2, 91], 84: [2, 91], 85: [2, 91] }, { 33: [2, 93] }, { 5: [2, 22], 14: [2, 22], 15: [2, 22], 19: [2, 22], 29: [2, 22], 34: [2, 22], 39: [2, 22], 44: [2, 22], 47: [2, 22], 48: [2, 22], 51: [2, 22], 55: [2, 22], 60: [2, 22] }, { 23: [2, 99], 33: [2, 99], 54: [2, 99], 68: [2, 99], 72: [2, 99], 75: [2, 99] }, { 73: [1, 109] }, { 20: 75, 63: 126, 64: 76, 65: [1, 44], 72: [1, 35], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 23], 14: [2, 23], 15: [2, 23], 19: [2, 23], 29: [2, 23], 34: [2, 23], 39: [2, 23], 44: [2, 23], 47: [2, 23], 48: [2, 23], 51: [2, 23], 55: [2, 23], 60: [2, 23] }, { 47: [2, 19] }, { 47: [2, 77] }, { 20: 75, 33: [2, 72], 41: 127, 63: 128, 64: 76, 65: [1, 44], 69: 129, 70: 77, 71: 78, 72: [1, 79], 75: [2, 72], 78: 26, 79: 27, 80: [1, 28], 81: [1, 29], 82: [1, 30], 83: [1, 31], 84: [1, 32], 85: [1, 34], 86: 33 }, { 5: [2, 24], 14: [2, 24], 15: [2, 24], 19: [2, 24], 29: [2, 24], 34: [2, 24], 39: [2, 24], 44: [2, 24], 47: [2, 24], 48: [2, 24], 51: [2, 24], 55: [2, 24], 60: [2, 24] }, { 68: [1, 130] }, { 65: [2, 95], 68: [2, 95], 72: [2, 95], 80: [2, 95], 81: [2, 95], 82: [2, 95], 83: [2, 95], 84: [2, 95], 85: [2, 95] }, { 68: [2, 97] }, { 5: [2, 21], 14: [2, 21], 15: [2, 21], 19: [2, 21], 29: [2, 21], 34: [2, 21], 39: [2, 21], 44: [2, 21], 47: [2, 21], 48: [2, 21], 51: [2, 21], 55: [2, 21], 60: [2, 21] }, { 33: [1, 131] }, { 33: [2, 63] }, { 72: [1, 133], 76: 132 }, { 33: [1, 134] }, { 33: [2, 69] }, { 15: [2, 12] }, { 14: [2, 26], 15: [2, 26], 19: [2, 26], 29: [2, 26], 34: [2, 26], 47: [2, 26], 48: [2, 26], 51: [2, 26], 55: [2, 26], 60: [2, 26] }, { 23: [2, 31], 33: [2, 31], 54: [2, 31], 68: [2, 31], 72: [2, 31], 75: [2, 31] }, { 33: [2, 74], 42: 135, 74: 136, 75: [1, 121] }, { 33: [2, 71], 65: [2, 71], 72: [2, 71], 75: [2, 71], 80: [2, 71], 81: [2, 71], 82: [2, 71], 83: [2, 71], 84: [2, 71], 85: [2, 71] }, { 33: [2, 73], 75: [2, 73] }, { 23: [2, 29], 33: [2, 29], 54: [2, 29], 65: [2, 29], 68: [2, 29], 72: [2, 29], 75: [2, 29], 80: [2, 29], 81: [2, 29], 82: [2, 29], 83: [2, 29], 84: [2, 29], 85: [2, 29] }, { 14: [2, 15], 15: [2, 15], 19: [2, 15], 29: [2, 15], 34: [2, 15], 39: [2, 15], 44: [2, 15], 47: [2, 15], 48: [2, 15], 51: [2, 15], 55: [2, 15], 60: [2, 15] }, { 72: [1, 138], 77: [1, 137] }, { 72: [2, 100], 77: [2, 100] }, { 14: [2, 16], 15: [2, 16], 19: [2, 16], 29: [2, 16], 34: [2, 16], 44: [2, 16], 47: [2, 16], 48: [2, 16], 51: [2, 16], 55: [2, 16], 60: [2, 16] }, { 33: [1, 139] }, { 33: [2, 75] }, { 33: [2, 32] }, { 72: [2, 101], 77: [2, 101] }, { 14: [2, 17], 15: [2, 17], 19: [2, 17], 29: [2, 17], 34: [2, 17], 39: [2, 17], 44: [2, 17], 47: [2, 17], 48: [2, 17], 51: [2, 17], 55: [2, 17], 60: [2, 17] }],
  113168. 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] },
  113169. parseError: function parseError(str, hash) {
  113170. throw new Error(str);
  113171. },
  113172. parse: function parse(input) {
  113173. var self = this,
  113174. stack = [0],
  113175. vstack = [null],
  113176. lstack = [],
  113177. table = this.table,
  113178. yytext = "",
  113179. yylineno = 0,
  113180. yyleng = 0,
  113181. recovering = 0,
  113182. TERROR = 2,
  113183. EOF = 1;
  113184. this.lexer.setInput(input);
  113185. this.lexer.yy = this.yy;
  113186. this.yy.lexer = this.lexer;
  113187. this.yy.parser = this;
  113188. if (typeof this.lexer.yylloc == "undefined") this.lexer.yylloc = {};
  113189. var yyloc = this.lexer.yylloc;
  113190. lstack.push(yyloc);
  113191. var ranges = this.lexer.options && this.lexer.options.ranges;
  113192. if (typeof this.yy.parseError === "function") this.parseError = this.yy.parseError;
  113193. function popStack(n) {
  113194. stack.length = stack.length - 2 * n;
  113195. vstack.length = vstack.length - n;
  113196. lstack.length = lstack.length - n;
  113197. }
  113198. function lex() {
  113199. var token;
  113200. token = self.lexer.lex() || 1;
  113201. if (typeof token !== "number") {
  113202. token = self.symbols_[token] || token;
  113203. }
  113204. return token;
  113205. }
  113206. var symbol,
  113207. preErrorSymbol,
  113208. state,
  113209. action,
  113210. a,
  113211. r,
  113212. yyval = {},
  113213. p,
  113214. len,
  113215. newState,
  113216. expected;
  113217. while (true) {
  113218. state = stack[stack.length - 1];
  113219. if (this.defaultActions[state]) {
  113220. action = this.defaultActions[state];
  113221. } else {
  113222. if (symbol === null || typeof symbol == "undefined") {
  113223. symbol = lex();
  113224. }
  113225. action = table[state] && table[state][symbol];
  113226. }
  113227. if (typeof action === "undefined" || !action.length || !action[0]) {
  113228. var errStr = "";
  113229. if (!recovering) {
  113230. expected = [];
  113231. for (p in table[state]) if (this.terminals_[p] && p > 2) {
  113232. expected.push("'" + this.terminals_[p] + "'");
  113233. }
  113234. if (this.lexer.showPosition) {
  113235. errStr = "Parse error on line " + (yylineno + 1) + ":\n" + this.lexer.showPosition() + "\nExpecting " + expected.join(", ") + ", got '" + (this.terminals_[symbol] || symbol) + "'";
  113236. } else {
  113237. errStr = "Parse error on line " + (yylineno + 1) + ": Unexpected " + (symbol == 1 ? "end of input" : "'" + (this.terminals_[symbol] || symbol) + "'");
  113238. }
  113239. this.parseError(errStr, { text: this.lexer.match, token: this.terminals_[symbol] || symbol, line: this.lexer.yylineno, loc: yyloc, expected: expected });
  113240. }
  113241. }
  113242. if (action[0] instanceof Array && action.length > 1) {
  113243. throw new Error("Parse Error: multiple actions possible at state: " + state + ", token: " + symbol);
  113244. }
  113245. switch (action[0]) {
  113246. case 1:
  113247. stack.push(symbol);
  113248. vstack.push(this.lexer.yytext);
  113249. lstack.push(this.lexer.yylloc);
  113250. stack.push(action[1]);
  113251. symbol = null;
  113252. if (!preErrorSymbol) {
  113253. yyleng = this.lexer.yyleng;
  113254. yytext = this.lexer.yytext;
  113255. yylineno = this.lexer.yylineno;
  113256. yyloc = this.lexer.yylloc;
  113257. if (recovering > 0) recovering--;
  113258. } else {
  113259. symbol = preErrorSymbol;
  113260. preErrorSymbol = null;
  113261. }
  113262. break;
  113263. case 2:
  113264. len = this.productions_[action[1]][1];
  113265. yyval.$ = vstack[vstack.length - len];
  113266. yyval._$ = { first_line: lstack[lstack.length - (len || 1)].first_line, last_line: lstack[lstack.length - 1].last_line, first_column: lstack[lstack.length - (len || 1)].first_column, last_column: lstack[lstack.length - 1].last_column };
  113267. if (ranges) {
  113268. yyval._$.range = [lstack[lstack.length - (len || 1)].range[0], lstack[lstack.length - 1].range[1]];
  113269. }
  113270. r = this.performAction.call(yyval, yytext, yyleng, yylineno, this.yy, action[1], vstack, lstack);
  113271. if (typeof r !== "undefined") {
  113272. return r;
  113273. }
  113274. if (len) {
  113275. stack = stack.slice(0, -1 * len * 2);
  113276. vstack = vstack.slice(0, -1 * len);
  113277. lstack = lstack.slice(0, -1 * len);
  113278. }
  113279. stack.push(this.productions_[action[1]][0]);
  113280. vstack.push(yyval.$);
  113281. lstack.push(yyval._$);
  113282. newState = table[stack[stack.length - 2]][stack[stack.length - 1]];
  113283. stack.push(newState);
  113284. break;
  113285. case 3:
  113286. return true;
  113287. }
  113288. }
  113289. return true;
  113290. }
  113291. };
  113292. /* Jison generated lexer */
  113293. var lexer = (function () {
  113294. var lexer = { EOF: 1,
  113295. parseError: function parseError(str, hash) {
  113296. if (this.yy.parser) {
  113297. this.yy.parser.parseError(str, hash);
  113298. } else {
  113299. throw new Error(str);
  113300. }
  113301. },
  113302. setInput: function setInput(input) {
  113303. this._input = input;
  113304. this._more = this._less = this.done = false;
  113305. this.yylineno = this.yyleng = 0;
  113306. this.yytext = this.matched = this.match = '';
  113307. this.conditionStack = ['INITIAL'];
  113308. this.yylloc = { first_line: 1, first_column: 0, last_line: 1, last_column: 0 };
  113309. if (this.options.ranges) this.yylloc.range = [0, 0];
  113310. this.offset = 0;
  113311. return this;
  113312. },
  113313. input: function input() {
  113314. var ch = this._input[0];
  113315. this.yytext += ch;
  113316. this.yyleng++;
  113317. this.offset++;
  113318. this.match += ch;
  113319. this.matched += ch;
  113320. var lines = ch.match(/(?:\r\n?|\n).*/g);
  113321. if (lines) {
  113322. this.yylineno++;
  113323. this.yylloc.last_line++;
  113324. } else {
  113325. this.yylloc.last_column++;
  113326. }
  113327. if (this.options.ranges) this.yylloc.range[1]++;
  113328. this._input = this._input.slice(1);
  113329. return ch;
  113330. },
  113331. unput: function unput(ch) {
  113332. var len = ch.length;
  113333. var lines = ch.split(/(?:\r\n?|\n)/g);
  113334. this._input = ch + this._input;
  113335. this.yytext = this.yytext.substr(0, this.yytext.length - len - 1);
  113336. //this.yyleng -= len;
  113337. this.offset -= len;
  113338. var oldLines = this.match.split(/(?:\r\n?|\n)/g);
  113339. this.match = this.match.substr(0, this.match.length - 1);
  113340. this.matched = this.matched.substr(0, this.matched.length - 1);
  113341. if (lines.length - 1) this.yylineno -= lines.length - 1;
  113342. var r = this.yylloc.range;
  113343. this.yylloc = { first_line: this.yylloc.first_line,
  113344. last_line: this.yylineno + 1,
  113345. first_column: this.yylloc.first_column,
  113346. last_column: lines ? (lines.length === oldLines.length ? this.yylloc.first_column : 0) + oldLines[oldLines.length - lines.length].length - lines[0].length : this.yylloc.first_column - len
  113347. };
  113348. if (this.options.ranges) {
  113349. this.yylloc.range = [r[0], r[0] + this.yyleng - len];
  113350. }
  113351. return this;
  113352. },
  113353. more: function more() {
  113354. this._more = true;
  113355. return this;
  113356. },
  113357. less: function less(n) {
  113358. this.unput(this.match.slice(n));
  113359. },
  113360. pastInput: function pastInput() {
  113361. var past = this.matched.substr(0, this.matched.length - this.match.length);
  113362. return (past.length > 20 ? '...' : '') + past.substr(-20).replace(/\n/g, "");
  113363. },
  113364. upcomingInput: function upcomingInput() {
  113365. var next = this.match;
  113366. if (next.length < 20) {
  113367. next += this._input.substr(0, 20 - next.length);
  113368. }
  113369. return (next.substr(0, 20) + (next.length > 20 ? '...' : '')).replace(/\n/g, "");
  113370. },
  113371. showPosition: function showPosition() {
  113372. var pre = this.pastInput();
  113373. var c = new Array(pre.length + 1).join("-");
  113374. return pre + this.upcomingInput() + "\n" + c + "^";
  113375. },
  113376. next: function next() {
  113377. if (this.done) {
  113378. return this.EOF;
  113379. }
  113380. if (!this._input) this.done = true;
  113381. var token, match, tempMatch, index, col, lines;
  113382. if (!this._more) {
  113383. this.yytext = '';
  113384. this.match = '';
  113385. }
  113386. var rules = this._currentRules();
  113387. for (var i = 0; i < rules.length; i++) {
  113388. tempMatch = this._input.match(this.rules[rules[i]]);
  113389. if (tempMatch && (!match || tempMatch[0].length > match[0].length)) {
  113390. match = tempMatch;
  113391. index = i;
  113392. if (!this.options.flex) break;
  113393. }
  113394. }
  113395. if (match) {
  113396. lines = match[0].match(/(?:\r\n?|\n).*/g);
  113397. if (lines) this.yylineno += lines.length;
  113398. this.yylloc = { first_line: this.yylloc.last_line,
  113399. last_line: this.yylineno + 1,
  113400. first_column: this.yylloc.last_column,
  113401. last_column: lines ? lines[lines.length - 1].length - lines[lines.length - 1].match(/\r?\n?/)[0].length : this.yylloc.last_column + match[0].length };
  113402. this.yytext += match[0];
  113403. this.match += match[0];
  113404. this.matches = match;
  113405. this.yyleng = this.yytext.length;
  113406. if (this.options.ranges) {
  113407. this.yylloc.range = [this.offset, this.offset += this.yyleng];
  113408. }
  113409. this._more = false;
  113410. this._input = this._input.slice(match[0].length);
  113411. this.matched += match[0];
  113412. token = this.performAction.call(this, this.yy, this, rules[index], this.conditionStack[this.conditionStack.length - 1]);
  113413. if (this.done && this._input) this.done = false;
  113414. if (token) return token;else return;
  113415. }
  113416. if (this._input === "") {
  113417. return this.EOF;
  113418. } else {
  113419. return this.parseError('Lexical error on line ' + (this.yylineno + 1) + '. Unrecognized text.\n' + this.showPosition(), { text: "", token: null, line: this.yylineno });
  113420. }
  113421. },
  113422. lex: function lex() {
  113423. var r = this.next();
  113424. if (typeof r !== 'undefined') {
  113425. return r;
  113426. } else {
  113427. return this.lex();
  113428. }
  113429. },
  113430. begin: function begin(condition) {
  113431. this.conditionStack.push(condition);
  113432. },
  113433. popState: function popState() {
  113434. return this.conditionStack.pop();
  113435. },
  113436. _currentRules: function _currentRules() {
  113437. return this.conditions[this.conditionStack[this.conditionStack.length - 1]].rules;
  113438. },
  113439. topState: function topState() {
  113440. return this.conditionStack[this.conditionStack.length - 2];
  113441. },
  113442. pushState: function begin(condition) {
  113443. this.begin(condition);
  113444. } };
  113445. lexer.options = {};
  113446. lexer.performAction = function anonymous(yy, yy_, $avoiding_name_collisions, YY_START
  113447. /**/) {
  113448. function strip(start, end) {
  113449. return yy_.yytext = yy_.yytext.substr(start, yy_.yyleng - end);
  113450. }
  113451. var YYSTATE = YY_START;
  113452. switch ($avoiding_name_collisions) {
  113453. case 0:
  113454. if (yy_.yytext.slice(-2) === "\\\\") {
  113455. strip(0, 1);
  113456. this.begin("mu");
  113457. } else if (yy_.yytext.slice(-1) === "\\") {
  113458. strip(0, 1);
  113459. this.begin("emu");
  113460. } else {
  113461. this.begin("mu");
  113462. }
  113463. if (yy_.yytext) return 15;
  113464. break;
  113465. case 1:
  113466. return 15;
  113467. break;
  113468. case 2:
  113469. this.popState();
  113470. return 15;
  113471. break;
  113472. case 3:
  113473. this.begin('raw');return 15;
  113474. break;
  113475. case 4:
  113476. this.popState();
  113477. // Should be using `this.topState()` below, but it currently
  113478. // returns the second top instead of the first top. Opened an
  113479. // issue about it at https://github.com/zaach/jison/issues/291
  113480. if (this.conditionStack[this.conditionStack.length - 1] === 'raw') {
  113481. return 15;
  113482. } else {
  113483. yy_.yytext = yy_.yytext.substr(5, yy_.yyleng - 9);
  113484. return 'END_RAW_BLOCK';
  113485. }
  113486. break;
  113487. case 5:
  113488. return 15;
  113489. break;
  113490. case 6:
  113491. this.popState();
  113492. return 14;
  113493. break;
  113494. case 7:
  113495. return 65;
  113496. break;
  113497. case 8:
  113498. return 68;
  113499. break;
  113500. case 9:
  113501. return 19;
  113502. break;
  113503. case 10:
  113504. this.popState();
  113505. this.begin('raw');
  113506. return 23;
  113507. break;
  113508. case 11:
  113509. return 55;
  113510. break;
  113511. case 12:
  113512. return 60;
  113513. break;
  113514. case 13:
  113515. return 29;
  113516. break;
  113517. case 14:
  113518. return 47;
  113519. break;
  113520. case 15:
  113521. this.popState();return 44;
  113522. break;
  113523. case 16:
  113524. this.popState();return 44;
  113525. break;
  113526. case 17:
  113527. return 34;
  113528. break;
  113529. case 18:
  113530. return 39;
  113531. break;
  113532. case 19:
  113533. return 51;
  113534. break;
  113535. case 20:
  113536. return 48;
  113537. break;
  113538. case 21:
  113539. this.unput(yy_.yytext);
  113540. this.popState();
  113541. this.begin('com');
  113542. break;
  113543. case 22:
  113544. this.popState();
  113545. return 14;
  113546. break;
  113547. case 23:
  113548. return 48;
  113549. break;
  113550. case 24:
  113551. return 73;
  113552. break;
  113553. case 25:
  113554. return 72;
  113555. break;
  113556. case 26:
  113557. return 72;
  113558. break;
  113559. case 27:
  113560. return 87;
  113561. break;
  113562. case 28:
  113563. // ignore whitespace
  113564. break;
  113565. case 29:
  113566. this.popState();return 54;
  113567. break;
  113568. case 30:
  113569. this.popState();return 33;
  113570. break;
  113571. case 31:
  113572. yy_.yytext = strip(1, 2).replace(/\\"/g, '"');return 80;
  113573. break;
  113574. case 32:
  113575. yy_.yytext = strip(1, 2).replace(/\\'/g, "'");return 80;
  113576. break;
  113577. case 33:
  113578. return 85;
  113579. break;
  113580. case 34:
  113581. return 82;
  113582. break;
  113583. case 35:
  113584. return 82;
  113585. break;
  113586. case 36:
  113587. return 83;
  113588. break;
  113589. case 37:
  113590. return 84;
  113591. break;
  113592. case 38:
  113593. return 81;
  113594. break;
  113595. case 39:
  113596. return 75;
  113597. break;
  113598. case 40:
  113599. return 77;
  113600. break;
  113601. case 41:
  113602. return 72;
  113603. break;
  113604. case 42:
  113605. yy_.yytext = yy_.yytext.replace(/\\([\\\]])/g, '$1');return 72;
  113606. break;
  113607. case 43:
  113608. return 'INVALID';
  113609. break;
  113610. case 44:
  113611. return 5;
  113612. break;
  113613. }
  113614. };
  113615. lexer.rules = [/^(?:[^\x00]*?(?=(\{\{)))/, /^(?:[^\x00]+)/, /^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/, /^(?:\{\{\{\{(?=[^\/]))/, /^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/, /^(?:[^\x00]*?(?=(\{\{\{\{)))/, /^(?:[\s\S]*?--(~)?\}\})/, /^(?:\()/, /^(?:\))/, /^(?:\{\{\{\{)/, /^(?:\}\}\}\})/, /^(?:\{\{(~)?>)/, /^(?:\{\{(~)?#>)/, /^(?:\{\{(~)?#\*?)/, /^(?:\{\{(~)?\/)/, /^(?:\{\{(~)?\^\s*(~)?\}\})/, /^(?:\{\{(~)?\s*else\s*(~)?\}\})/, /^(?:\{\{(~)?\^)/, /^(?:\{\{(~)?\s*else\b)/, /^(?:\{\{(~)?\{)/, /^(?:\{\{(~)?&)/, /^(?:\{\{(~)?!--)/, /^(?:\{\{(~)?![\s\S]*?\}\})/, /^(?:\{\{(~)?\*?)/, /^(?:=)/, /^(?:\.\.)/, /^(?:\.(?=([=~}\s\/.)|])))/, /^(?:[\/.])/, /^(?:\s+)/, /^(?:\}(~)?\}\})/, /^(?:(~)?\}\})/, /^(?:"(\\["]|[^"])*")/, /^(?:'(\\[']|[^'])*')/, /^(?:@)/, /^(?:true(?=([~}\s)])))/, /^(?:false(?=([~}\s)])))/, /^(?:undefined(?=([~}\s)])))/, /^(?:null(?=([~}\s)])))/, /^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/, /^(?:as\s+\|)/, /^(?:\|)/, /^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/, /^(?:\[(\\\]|[^\]])*\])/, /^(?:.)/, /^(?:$)/];
  113616. lexer.conditions = { "mu": { "rules": [7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44], "inclusive": false }, "emu": { "rules": [2], "inclusive": false }, "com": { "rules": [6], "inclusive": false }, "raw": { "rules": [3, 4, 5], "inclusive": false }, "INITIAL": { "rules": [0, 1, 44], "inclusive": true } };
  113617. return lexer;
  113618. })();
  113619. parser.lexer = lexer;
  113620. function Parser() {
  113621. this.yy = {};
  113622. }Parser.prototype = parser;parser.Parser = Parser;
  113623. return new Parser();
  113624. })();exports["default"] = handlebars;
  113625. module.exports = exports["default"];
  113626. /***/ }),
  113627. /* 38 */
  113628. /***/ (function(module, exports, __webpack_require__) {
  113629. 'use strict';
  113630. var _interopRequireDefault = __webpack_require__(1)['default'];
  113631. exports.__esModule = true;
  113632. var _visitor = __webpack_require__(39);
  113633. var _visitor2 = _interopRequireDefault(_visitor);
  113634. function WhitespaceControl() {
  113635. var options = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0];
  113636. this.options = options;
  113637. }
  113638. WhitespaceControl.prototype = new _visitor2['default']();
  113639. WhitespaceControl.prototype.Program = function (program) {
  113640. var doStandalone = !this.options.ignoreStandalone;
  113641. var isRoot = !this.isRootSeen;
  113642. this.isRootSeen = true;
  113643. var body = program.body;
  113644. for (var i = 0, l = body.length; i < l; i++) {
  113645. var current = body[i],
  113646. strip = this.accept(current);
  113647. if (!strip) {
  113648. continue;
  113649. }
  113650. var _isPrevWhitespace = isPrevWhitespace(body, i, isRoot),
  113651. _isNextWhitespace = isNextWhitespace(body, i, isRoot),
  113652. openStandalone = strip.openStandalone && _isPrevWhitespace,
  113653. closeStandalone = strip.closeStandalone && _isNextWhitespace,
  113654. inlineStandalone = strip.inlineStandalone && _isPrevWhitespace && _isNextWhitespace;
  113655. if (strip.close) {
  113656. omitRight(body, i, true);
  113657. }
  113658. if (strip.open) {
  113659. omitLeft(body, i, true);
  113660. }
  113661. if (doStandalone && inlineStandalone) {
  113662. omitRight(body, i);
  113663. if (omitLeft(body, i)) {
  113664. // If we are on a standalone node, save the indent info for partials
  113665. if (current.type === 'PartialStatement') {
  113666. // Pull out the whitespace from the final line
  113667. current.indent = /([ \t]+$)/.exec(body[i - 1].original)[1];
  113668. }
  113669. }
  113670. }
  113671. if (doStandalone && openStandalone) {
  113672. omitRight((current.program || current.inverse).body);
  113673. // Strip out the previous content node if it's whitespace only
  113674. omitLeft(body, i);
  113675. }
  113676. if (doStandalone && closeStandalone) {
  113677. // Always strip the next node
  113678. omitRight(body, i);
  113679. omitLeft((current.inverse || current.program).body);
  113680. }
  113681. }
  113682. return program;
  113683. };
  113684. WhitespaceControl.prototype.BlockStatement = WhitespaceControl.prototype.DecoratorBlock = WhitespaceControl.prototype.PartialBlockStatement = function (block) {
  113685. this.accept(block.program);
  113686. this.accept(block.inverse);
  113687. // Find the inverse program that is involed with whitespace stripping.
  113688. var program = block.program || block.inverse,
  113689. inverse = block.program && block.inverse,
  113690. firstInverse = inverse,
  113691. lastInverse = inverse;
  113692. if (inverse && inverse.chained) {
  113693. firstInverse = inverse.body[0].program;
  113694. // Walk the inverse chain to find the last inverse that is actually in the chain.
  113695. while (lastInverse.chained) {
  113696. lastInverse = lastInverse.body[lastInverse.body.length - 1].program;
  113697. }
  113698. }
  113699. var strip = {
  113700. open: block.openStrip.open,
  113701. close: block.closeStrip.close,
  113702. // Determine the standalone candiacy. Basically flag our content as being possibly standalone
  113703. // so our parent can determine if we actually are standalone
  113704. openStandalone: isNextWhitespace(program.body),
  113705. closeStandalone: isPrevWhitespace((firstInverse || program).body)
  113706. };
  113707. if (block.openStrip.close) {
  113708. omitRight(program.body, null, true);
  113709. }
  113710. if (inverse) {
  113711. var inverseStrip = block.inverseStrip;
  113712. if (inverseStrip.open) {
  113713. omitLeft(program.body, null, true);
  113714. }
  113715. if (inverseStrip.close) {
  113716. omitRight(firstInverse.body, null, true);
  113717. }
  113718. if (block.closeStrip.open) {
  113719. omitLeft(lastInverse.body, null, true);
  113720. }
  113721. // Find standalone else statments
  113722. if (!this.options.ignoreStandalone && isPrevWhitespace(program.body) && isNextWhitespace(firstInverse.body)) {
  113723. omitLeft(program.body);
  113724. omitRight(firstInverse.body);
  113725. }
  113726. } else if (block.closeStrip.open) {
  113727. omitLeft(program.body, null, true);
  113728. }
  113729. return strip;
  113730. };
  113731. WhitespaceControl.prototype.Decorator = WhitespaceControl.prototype.MustacheStatement = function (mustache) {
  113732. return mustache.strip;
  113733. };
  113734. WhitespaceControl.prototype.PartialStatement = WhitespaceControl.prototype.CommentStatement = function (node) {
  113735. /* istanbul ignore next */
  113736. var strip = node.strip || {};
  113737. return {
  113738. inlineStandalone: true,
  113739. open: strip.open,
  113740. close: strip.close
  113741. };
  113742. };
  113743. function isPrevWhitespace(body, i, isRoot) {
  113744. if (i === undefined) {
  113745. i = body.length;
  113746. }
  113747. // Nodes that end with newlines are considered whitespace (but are special
  113748. // cased for strip operations)
  113749. var prev = body[i - 1],
  113750. sibling = body[i - 2];
  113751. if (!prev) {
  113752. return isRoot;
  113753. }
  113754. if (prev.type === 'ContentStatement') {
  113755. return (sibling || !isRoot ? /\r?\n\s*?$/ : /(^|\r?\n)\s*?$/).test(prev.original);
  113756. }
  113757. }
  113758. function isNextWhitespace(body, i, isRoot) {
  113759. if (i === undefined) {
  113760. i = -1;
  113761. }
  113762. var next = body[i + 1],
  113763. sibling = body[i + 2];
  113764. if (!next) {
  113765. return isRoot;
  113766. }
  113767. if (next.type === 'ContentStatement') {
  113768. return (sibling || !isRoot ? /^\s*?\r?\n/ : /^\s*?(\r?\n|$)/).test(next.original);
  113769. }
  113770. }
  113771. // Marks the node to the right of the position as omitted.
  113772. // I.e. {{foo}}' ' will mark the ' ' node as omitted.
  113773. //
  113774. // If i is undefined, then the first child will be marked as such.
  113775. //
  113776. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  113777. // content is met.
  113778. function omitRight(body, i, multiple) {
  113779. var current = body[i == null ? 0 : i + 1];
  113780. if (!current || current.type !== 'ContentStatement' || !multiple && current.rightStripped) {
  113781. return;
  113782. }
  113783. var original = current.value;
  113784. current.value = current.value.replace(multiple ? /^\s+/ : /^[ \t]*\r?\n?/, '');
  113785. current.rightStripped = current.value !== original;
  113786. }
  113787. // Marks the node to the left of the position as omitted.
  113788. // I.e. ' '{{foo}} will mark the ' ' node as omitted.
  113789. //
  113790. // If i is undefined then the last child will be marked as such.
  113791. //
  113792. // If mulitple is truthy then all whitespace will be stripped out until non-whitespace
  113793. // content is met.
  113794. function omitLeft(body, i, multiple) {
  113795. var current = body[i == null ? body.length - 1 : i - 1];
  113796. if (!current || current.type !== 'ContentStatement' || !multiple && current.leftStripped) {
  113797. return;
  113798. }
  113799. // We omit the last node if it's whitespace only and not preceeded by a non-content node.
  113800. var original = current.value;
  113801. current.value = current.value.replace(multiple ? /\s+$/ : /[ \t]+$/, '');
  113802. current.leftStripped = current.value !== original;
  113803. return current.leftStripped;
  113804. }
  113805. exports['default'] = WhitespaceControl;
  113806. module.exports = exports['default'];
  113807. /***/ }),
  113808. /* 39 */
  113809. /***/ (function(module, exports, __webpack_require__) {
  113810. 'use strict';
  113811. var _interopRequireDefault = __webpack_require__(1)['default'];
  113812. exports.__esModule = true;
  113813. var _exception = __webpack_require__(6);
  113814. var _exception2 = _interopRequireDefault(_exception);
  113815. function Visitor() {
  113816. this.parents = [];
  113817. }
  113818. Visitor.prototype = {
  113819. constructor: Visitor,
  113820. mutating: false,
  113821. // Visits a given value. If mutating, will replace the value if necessary.
  113822. acceptKey: function acceptKey(node, name) {
  113823. var value = this.accept(node[name]);
  113824. if (this.mutating) {
  113825. // Hacky sanity check: This may have a few false positives for type for the helper
  113826. // methods but will generally do the right thing without a lot of overhead.
  113827. if (value && !Visitor.prototype[value.type]) {
  113828. throw new _exception2['default']('Unexpected node type "' + value.type + '" found when accepting ' + name + ' on ' + node.type);
  113829. }
  113830. node[name] = value;
  113831. }
  113832. },
  113833. // Performs an accept operation with added sanity check to ensure
  113834. // required keys are not removed.
  113835. acceptRequired: function acceptRequired(node, name) {
  113836. this.acceptKey(node, name);
  113837. if (!node[name]) {
  113838. throw new _exception2['default'](node.type + ' requires ' + name);
  113839. }
  113840. },
  113841. // Traverses a given array. If mutating, empty respnses will be removed
  113842. // for child elements.
  113843. acceptArray: function acceptArray(array) {
  113844. for (var i = 0, l = array.length; i < l; i++) {
  113845. this.acceptKey(array, i);
  113846. if (!array[i]) {
  113847. array.splice(i, 1);
  113848. i--;
  113849. l--;
  113850. }
  113851. }
  113852. },
  113853. accept: function accept(object) {
  113854. if (!object) {
  113855. return;
  113856. }
  113857. /* istanbul ignore next: Sanity code */
  113858. if (!this[object.type]) {
  113859. throw new _exception2['default']('Unknown type: ' + object.type, object);
  113860. }
  113861. if (this.current) {
  113862. this.parents.unshift(this.current);
  113863. }
  113864. this.current = object;
  113865. var ret = this[object.type](object);
  113866. this.current = this.parents.shift();
  113867. if (!this.mutating || ret) {
  113868. return ret;
  113869. } else if (ret !== false) {
  113870. return object;
  113871. }
  113872. },
  113873. Program: function Program(program) {
  113874. this.acceptArray(program.body);
  113875. },
  113876. MustacheStatement: visitSubExpression,
  113877. Decorator: visitSubExpression,
  113878. BlockStatement: visitBlock,
  113879. DecoratorBlock: visitBlock,
  113880. PartialStatement: visitPartial,
  113881. PartialBlockStatement: function PartialBlockStatement(partial) {
  113882. visitPartial.call(this, partial);
  113883. this.acceptKey(partial, 'program');
  113884. },
  113885. ContentStatement: function ContentStatement() /* content */{},
  113886. CommentStatement: function CommentStatement() /* comment */{},
  113887. SubExpression: visitSubExpression,
  113888. PathExpression: function PathExpression() /* path */{},
  113889. StringLiteral: function StringLiteral() /* string */{},
  113890. NumberLiteral: function NumberLiteral() /* number */{},
  113891. BooleanLiteral: function BooleanLiteral() /* bool */{},
  113892. UndefinedLiteral: function UndefinedLiteral() /* literal */{},
  113893. NullLiteral: function NullLiteral() /* literal */{},
  113894. Hash: function Hash(hash) {
  113895. this.acceptArray(hash.pairs);
  113896. },
  113897. HashPair: function HashPair(pair) {
  113898. this.acceptRequired(pair, 'value');
  113899. }
  113900. };
  113901. function visitSubExpression(mustache) {
  113902. this.acceptRequired(mustache, 'path');
  113903. this.acceptArray(mustache.params);
  113904. this.acceptKey(mustache, 'hash');
  113905. }
  113906. function visitBlock(block) {
  113907. visitSubExpression.call(this, block);
  113908. this.acceptKey(block, 'program');
  113909. this.acceptKey(block, 'inverse');
  113910. }
  113911. function visitPartial(partial) {
  113912. this.acceptRequired(partial, 'name');
  113913. this.acceptArray(partial.params);
  113914. this.acceptKey(partial, 'hash');
  113915. }
  113916. exports['default'] = Visitor;
  113917. module.exports = exports['default'];
  113918. /***/ }),
  113919. /* 40 */
  113920. /***/ (function(module, exports, __webpack_require__) {
  113921. 'use strict';
  113922. var _interopRequireDefault = __webpack_require__(1)['default'];
  113923. exports.__esModule = true;
  113924. exports.SourceLocation = SourceLocation;
  113925. exports.id = id;
  113926. exports.stripFlags = stripFlags;
  113927. exports.stripComment = stripComment;
  113928. exports.preparePath = preparePath;
  113929. exports.prepareMustache = prepareMustache;
  113930. exports.prepareRawBlock = prepareRawBlock;
  113931. exports.prepareBlock = prepareBlock;
  113932. exports.prepareProgram = prepareProgram;
  113933. exports.preparePartialBlock = preparePartialBlock;
  113934. var _exception = __webpack_require__(6);
  113935. var _exception2 = _interopRequireDefault(_exception);
  113936. function validateClose(open, close) {
  113937. close = close.path ? close.path.original : close;
  113938. if (open.path.original !== close) {
  113939. var errorNode = { loc: open.path.loc };
  113940. throw new _exception2['default'](open.path.original + " doesn't match " + close, errorNode);
  113941. }
  113942. }
  113943. function SourceLocation(source, locInfo) {
  113944. this.source = source;
  113945. this.start = {
  113946. line: locInfo.first_line,
  113947. column: locInfo.first_column
  113948. };
  113949. this.end = {
  113950. line: locInfo.last_line,
  113951. column: locInfo.last_column
  113952. };
  113953. }
  113954. function id(token) {
  113955. if (/^\[.*\]$/.test(token)) {
  113956. return token.substr(1, token.length - 2);
  113957. } else {
  113958. return token;
  113959. }
  113960. }
  113961. function stripFlags(open, close) {
  113962. return {
  113963. open: open.charAt(2) === '~',
  113964. close: close.charAt(close.length - 3) === '~'
  113965. };
  113966. }
  113967. function stripComment(comment) {
  113968. return comment.replace(/^\{\{~?\!-?-?/, '').replace(/-?-?~?\}\}$/, '');
  113969. }
  113970. function preparePath(data, parts, loc) {
  113971. loc = this.locInfo(loc);
  113972. var original = data ? '@' : '',
  113973. dig = [],
  113974. depth = 0,
  113975. depthString = '';
  113976. for (var i = 0, l = parts.length; i < l; i++) {
  113977. var part = parts[i].part,
  113978. // If we have [] syntax then we do not treat path references as operators,
  113979. // i.e. foo.[this] resolves to approximately context.foo['this']
  113980. isLiteral = parts[i].original !== part;
  113981. original += (parts[i].separator || '') + part;
  113982. if (!isLiteral && (part === '..' || part === '.' || part === 'this')) {
  113983. if (dig.length > 0) {
  113984. throw new _exception2['default']('Invalid path: ' + original, { loc: loc });
  113985. } else if (part === '..') {
  113986. depth++;
  113987. depthString += '../';
  113988. }
  113989. } else {
  113990. dig.push(part);
  113991. }
  113992. }
  113993. return {
  113994. type: 'PathExpression',
  113995. data: data,
  113996. depth: depth,
  113997. parts: dig,
  113998. original: original,
  113999. loc: loc
  114000. };
  114001. }
  114002. function prepareMustache(path, params, hash, open, strip, locInfo) {
  114003. // Must use charAt to support IE pre-10
  114004. var escapeFlag = open.charAt(3) || open.charAt(2),
  114005. escaped = escapeFlag !== '{' && escapeFlag !== '&';
  114006. var decorator = /\*/.test(open);
  114007. return {
  114008. type: decorator ? 'Decorator' : 'MustacheStatement',
  114009. path: path,
  114010. params: params,
  114011. hash: hash,
  114012. escaped: escaped,
  114013. strip: strip,
  114014. loc: this.locInfo(locInfo)
  114015. };
  114016. }
  114017. function prepareRawBlock(openRawBlock, contents, close, locInfo) {
  114018. validateClose(openRawBlock, close);
  114019. locInfo = this.locInfo(locInfo);
  114020. var program = {
  114021. type: 'Program',
  114022. body: contents,
  114023. strip: {},
  114024. loc: locInfo
  114025. };
  114026. return {
  114027. type: 'BlockStatement',
  114028. path: openRawBlock.path,
  114029. params: openRawBlock.params,
  114030. hash: openRawBlock.hash,
  114031. program: program,
  114032. openStrip: {},
  114033. inverseStrip: {},
  114034. closeStrip: {},
  114035. loc: locInfo
  114036. };
  114037. }
  114038. function prepareBlock(openBlock, program, inverseAndProgram, close, inverted, locInfo) {
  114039. if (close && close.path) {
  114040. validateClose(openBlock, close);
  114041. }
  114042. var decorator = /\*/.test(openBlock.open);
  114043. program.blockParams = openBlock.blockParams;
  114044. var inverse = undefined,
  114045. inverseStrip = undefined;
  114046. if (inverseAndProgram) {
  114047. if (decorator) {
  114048. throw new _exception2['default']('Unexpected inverse block on decorator', inverseAndProgram);
  114049. }
  114050. if (inverseAndProgram.chain) {
  114051. inverseAndProgram.program.body[0].closeStrip = close.strip;
  114052. }
  114053. inverseStrip = inverseAndProgram.strip;
  114054. inverse = inverseAndProgram.program;
  114055. }
  114056. if (inverted) {
  114057. inverted = inverse;
  114058. inverse = program;
  114059. program = inverted;
  114060. }
  114061. return {
  114062. type: decorator ? 'DecoratorBlock' : 'BlockStatement',
  114063. path: openBlock.path,
  114064. params: openBlock.params,
  114065. hash: openBlock.hash,
  114066. program: program,
  114067. inverse: inverse,
  114068. openStrip: openBlock.strip,
  114069. inverseStrip: inverseStrip,
  114070. closeStrip: close && close.strip,
  114071. loc: this.locInfo(locInfo)
  114072. };
  114073. }
  114074. function prepareProgram(statements, loc) {
  114075. if (!loc && statements.length) {
  114076. var firstLoc = statements[0].loc,
  114077. lastLoc = statements[statements.length - 1].loc;
  114078. /* istanbul ignore else */
  114079. if (firstLoc && lastLoc) {
  114080. loc = {
  114081. source: firstLoc.source,
  114082. start: {
  114083. line: firstLoc.start.line,
  114084. column: firstLoc.start.column
  114085. },
  114086. end: {
  114087. line: lastLoc.end.line,
  114088. column: lastLoc.end.column
  114089. }
  114090. };
  114091. }
  114092. }
  114093. return {
  114094. type: 'Program',
  114095. body: statements,
  114096. strip: {},
  114097. loc: loc
  114098. };
  114099. }
  114100. function preparePartialBlock(open, program, close, locInfo) {
  114101. validateClose(open, close);
  114102. return {
  114103. type: 'PartialBlockStatement',
  114104. name: open.path,
  114105. params: open.params,
  114106. hash: open.hash,
  114107. program: program,
  114108. openStrip: open.strip,
  114109. closeStrip: close && close.strip,
  114110. loc: this.locInfo(locInfo)
  114111. };
  114112. }
  114113. /***/ }),
  114114. /* 41 */
  114115. /***/ (function(module, exports, __webpack_require__) {
  114116. /* eslint-disable new-cap */
  114117. 'use strict';
  114118. var _interopRequireDefault = __webpack_require__(1)['default'];
  114119. exports.__esModule = true;
  114120. exports.Compiler = Compiler;
  114121. exports.precompile = precompile;
  114122. exports.compile = compile;
  114123. var _exception = __webpack_require__(6);
  114124. var _exception2 = _interopRequireDefault(_exception);
  114125. var _utils = __webpack_require__(5);
  114126. var _ast = __webpack_require__(35);
  114127. var _ast2 = _interopRequireDefault(_ast);
  114128. var slice = [].slice;
  114129. function Compiler() {}
  114130. // the foundHelper register will disambiguate helper lookup from finding a
  114131. // function in a context. This is necessary for mustache compatibility, which
  114132. // requires that context functions in blocks are evaluated by blockHelperMissing,
  114133. // and then proceed as if the resulting value was provided to blockHelperMissing.
  114134. Compiler.prototype = {
  114135. compiler: Compiler,
  114136. equals: function equals(other) {
  114137. var len = this.opcodes.length;
  114138. if (other.opcodes.length !== len) {
  114139. return false;
  114140. }
  114141. for (var i = 0; i < len; i++) {
  114142. var opcode = this.opcodes[i],
  114143. otherOpcode = other.opcodes[i];
  114144. if (opcode.opcode !== otherOpcode.opcode || !argEquals(opcode.args, otherOpcode.args)) {
  114145. return false;
  114146. }
  114147. }
  114148. // We know that length is the same between the two arrays because they are directly tied
  114149. // to the opcode behavior above.
  114150. len = this.children.length;
  114151. for (var i = 0; i < len; i++) {
  114152. if (!this.children[i].equals(other.children[i])) {
  114153. return false;
  114154. }
  114155. }
  114156. return true;
  114157. },
  114158. guid: 0,
  114159. compile: function compile(program, options) {
  114160. this.sourceNode = [];
  114161. this.opcodes = [];
  114162. this.children = [];
  114163. this.options = options;
  114164. this.stringParams = options.stringParams;
  114165. this.trackIds = options.trackIds;
  114166. options.blockParams = options.blockParams || [];
  114167. // These changes will propagate to the other compiler components
  114168. var knownHelpers = options.knownHelpers;
  114169. options.knownHelpers = {
  114170. 'helperMissing': true,
  114171. 'blockHelperMissing': true,
  114172. 'each': true,
  114173. 'if': true,
  114174. 'unless': true,
  114175. 'with': true,
  114176. 'log': true,
  114177. 'lookup': true
  114178. };
  114179. if (knownHelpers) {
  114180. for (var _name in knownHelpers) {
  114181. /* istanbul ignore else */
  114182. if (_name in knownHelpers) {
  114183. this.options.knownHelpers[_name] = knownHelpers[_name];
  114184. }
  114185. }
  114186. }
  114187. return this.accept(program);
  114188. },
  114189. compileProgram: function compileProgram(program) {
  114190. var childCompiler = new this.compiler(),
  114191. // eslint-disable-line new-cap
  114192. result = childCompiler.compile(program, this.options),
  114193. guid = this.guid++;
  114194. this.usePartial = this.usePartial || result.usePartial;
  114195. this.children[guid] = result;
  114196. this.useDepths = this.useDepths || result.useDepths;
  114197. return guid;
  114198. },
  114199. accept: function accept(node) {
  114200. /* istanbul ignore next: Sanity code */
  114201. if (!this[node.type]) {
  114202. throw new _exception2['default']('Unknown type: ' + node.type, node);
  114203. }
  114204. this.sourceNode.unshift(node);
  114205. var ret = this[node.type](node);
  114206. this.sourceNode.shift();
  114207. return ret;
  114208. },
  114209. Program: function Program(program) {
  114210. this.options.blockParams.unshift(program.blockParams);
  114211. var body = program.body,
  114212. bodyLength = body.length;
  114213. for (var i = 0; i < bodyLength; i++) {
  114214. this.accept(body[i]);
  114215. }
  114216. this.options.blockParams.shift();
  114217. this.isSimple = bodyLength === 1;
  114218. this.blockParams = program.blockParams ? program.blockParams.length : 0;
  114219. return this;
  114220. },
  114221. BlockStatement: function BlockStatement(block) {
  114222. transformLiteralToPath(block);
  114223. var program = block.program,
  114224. inverse = block.inverse;
  114225. program = program && this.compileProgram(program);
  114226. inverse = inverse && this.compileProgram(inverse);
  114227. var type = this.classifySexpr(block);
  114228. if (type === 'helper') {
  114229. this.helperSexpr(block, program, inverse);
  114230. } else if (type === 'simple') {
  114231. this.simpleSexpr(block);
  114232. // now that the simple mustache is resolved, we need to
  114233. // evaluate it by executing `blockHelperMissing`
  114234. this.opcode('pushProgram', program);
  114235. this.opcode('pushProgram', inverse);
  114236. this.opcode('emptyHash');
  114237. this.opcode('blockValue', block.path.original);
  114238. } else {
  114239. this.ambiguousSexpr(block, program, inverse);
  114240. // now that the simple mustache is resolved, we need to
  114241. // evaluate it by executing `blockHelperMissing`
  114242. this.opcode('pushProgram', program);
  114243. this.opcode('pushProgram', inverse);
  114244. this.opcode('emptyHash');
  114245. this.opcode('ambiguousBlockValue');
  114246. }
  114247. this.opcode('append');
  114248. },
  114249. DecoratorBlock: function DecoratorBlock(decorator) {
  114250. var program = decorator.program && this.compileProgram(decorator.program);
  114251. var params = this.setupFullMustacheParams(decorator, program, undefined),
  114252. path = decorator.path;
  114253. this.useDecorators = true;
  114254. this.opcode('registerDecorator', params.length, path.original);
  114255. },
  114256. PartialStatement: function PartialStatement(partial) {
  114257. this.usePartial = true;
  114258. var program = partial.program;
  114259. if (program) {
  114260. program = this.compileProgram(partial.program);
  114261. }
  114262. var params = partial.params;
  114263. if (params.length > 1) {
  114264. throw new _exception2['default']('Unsupported number of partial arguments: ' + params.length, partial);
  114265. } else if (!params.length) {
  114266. if (this.options.explicitPartialContext) {
  114267. this.opcode('pushLiteral', 'undefined');
  114268. } else {
  114269. params.push({ type: 'PathExpression', parts: [], depth: 0 });
  114270. }
  114271. }
  114272. var partialName = partial.name.original,
  114273. isDynamic = partial.name.type === 'SubExpression';
  114274. if (isDynamic) {
  114275. this.accept(partial.name);
  114276. }
  114277. this.setupFullMustacheParams(partial, program, undefined, true);
  114278. var indent = partial.indent || '';
  114279. if (this.options.preventIndent && indent) {
  114280. this.opcode('appendContent', indent);
  114281. indent = '';
  114282. }
  114283. this.opcode('invokePartial', isDynamic, partialName, indent);
  114284. this.opcode('append');
  114285. },
  114286. PartialBlockStatement: function PartialBlockStatement(partialBlock) {
  114287. this.PartialStatement(partialBlock);
  114288. },
  114289. MustacheStatement: function MustacheStatement(mustache) {
  114290. this.SubExpression(mustache);
  114291. if (mustache.escaped && !this.options.noEscape) {
  114292. this.opcode('appendEscaped');
  114293. } else {
  114294. this.opcode('append');
  114295. }
  114296. },
  114297. Decorator: function Decorator(decorator) {
  114298. this.DecoratorBlock(decorator);
  114299. },
  114300. ContentStatement: function ContentStatement(content) {
  114301. if (content.value) {
  114302. this.opcode('appendContent', content.value);
  114303. }
  114304. },
  114305. CommentStatement: function CommentStatement() {},
  114306. SubExpression: function SubExpression(sexpr) {
  114307. transformLiteralToPath(sexpr);
  114308. var type = this.classifySexpr(sexpr);
  114309. if (type === 'simple') {
  114310. this.simpleSexpr(sexpr);
  114311. } else if (type === 'helper') {
  114312. this.helperSexpr(sexpr);
  114313. } else {
  114314. this.ambiguousSexpr(sexpr);
  114315. }
  114316. },
  114317. ambiguousSexpr: function ambiguousSexpr(sexpr, program, inverse) {
  114318. var path = sexpr.path,
  114319. name = path.parts[0],
  114320. isBlock = program != null || inverse != null;
  114321. this.opcode('getContext', path.depth);
  114322. this.opcode('pushProgram', program);
  114323. this.opcode('pushProgram', inverse);
  114324. path.strict = true;
  114325. this.accept(path);
  114326. this.opcode('invokeAmbiguous', name, isBlock);
  114327. },
  114328. simpleSexpr: function simpleSexpr(sexpr) {
  114329. var path = sexpr.path;
  114330. path.strict = true;
  114331. this.accept(path);
  114332. this.opcode('resolvePossibleLambda');
  114333. },
  114334. helperSexpr: function helperSexpr(sexpr, program, inverse) {
  114335. var params = this.setupFullMustacheParams(sexpr, program, inverse),
  114336. path = sexpr.path,
  114337. name = path.parts[0];
  114338. if (this.options.knownHelpers[name]) {
  114339. this.opcode('invokeKnownHelper', params.length, name);
  114340. } else if (this.options.knownHelpersOnly) {
  114341. throw new _exception2['default']('You specified knownHelpersOnly, but used the unknown helper ' + name, sexpr);
  114342. } else {
  114343. path.strict = true;
  114344. path.falsy = true;
  114345. this.accept(path);
  114346. this.opcode('invokeHelper', params.length, path.original, _ast2['default'].helpers.simpleId(path));
  114347. }
  114348. },
  114349. PathExpression: function PathExpression(path) {
  114350. this.addDepth(path.depth);
  114351. this.opcode('getContext', path.depth);
  114352. var name = path.parts[0],
  114353. scoped = _ast2['default'].helpers.scopedId(path),
  114354. blockParamId = !path.depth && !scoped && this.blockParamIndex(name);
  114355. if (blockParamId) {
  114356. this.opcode('lookupBlockParam', blockParamId, path.parts);
  114357. } else if (!name) {
  114358. // Context reference, i.e. `{{foo .}}` or `{{foo ..}}`
  114359. this.opcode('pushContext');
  114360. } else if (path.data) {
  114361. this.options.data = true;
  114362. this.opcode('lookupData', path.depth, path.parts, path.strict);
  114363. } else {
  114364. this.opcode('lookupOnContext', path.parts, path.falsy, path.strict, scoped);
  114365. }
  114366. },
  114367. StringLiteral: function StringLiteral(string) {
  114368. this.opcode('pushString', string.value);
  114369. },
  114370. NumberLiteral: function NumberLiteral(number) {
  114371. this.opcode('pushLiteral', number.value);
  114372. },
  114373. BooleanLiteral: function BooleanLiteral(bool) {
  114374. this.opcode('pushLiteral', bool.value);
  114375. },
  114376. UndefinedLiteral: function UndefinedLiteral() {
  114377. this.opcode('pushLiteral', 'undefined');
  114378. },
  114379. NullLiteral: function NullLiteral() {
  114380. this.opcode('pushLiteral', 'null');
  114381. },
  114382. Hash: function Hash(hash) {
  114383. var pairs = hash.pairs,
  114384. i = 0,
  114385. l = pairs.length;
  114386. this.opcode('pushHash');
  114387. for (; i < l; i++) {
  114388. this.pushParam(pairs[i].value);
  114389. }
  114390. while (i--) {
  114391. this.opcode('assignToHash', pairs[i].key);
  114392. }
  114393. this.opcode('popHash');
  114394. },
  114395. // HELPERS
  114396. opcode: function opcode(name) {
  114397. this.opcodes.push({ opcode: name, args: slice.call(arguments, 1), loc: this.sourceNode[0].loc });
  114398. },
  114399. addDepth: function addDepth(depth) {
  114400. if (!depth) {
  114401. return;
  114402. }
  114403. this.useDepths = true;
  114404. },
  114405. classifySexpr: function classifySexpr(sexpr) {
  114406. var isSimple = _ast2['default'].helpers.simpleId(sexpr.path);
  114407. var isBlockParam = isSimple && !!this.blockParamIndex(sexpr.path.parts[0]);
  114408. // a mustache is an eligible helper if:
  114409. // * its id is simple (a single part, not `this` or `..`)
  114410. var isHelper = !isBlockParam && _ast2['default'].helpers.helperExpression(sexpr);
  114411. // if a mustache is an eligible helper but not a definite
  114412. // helper, it is ambiguous, and will be resolved in a later
  114413. // pass or at runtime.
  114414. var isEligible = !isBlockParam && (isHelper || isSimple);
  114415. // if ambiguous, we can possibly resolve the ambiguity now
  114416. // An eligible helper is one that does not have a complex path, i.e. `this.foo`, `../foo` etc.
  114417. if (isEligible && !isHelper) {
  114418. var _name2 = sexpr.path.parts[0],
  114419. options = this.options;
  114420. if (options.knownHelpers[_name2]) {
  114421. isHelper = true;
  114422. } else if (options.knownHelpersOnly) {
  114423. isEligible = false;
  114424. }
  114425. }
  114426. if (isHelper) {
  114427. return 'helper';
  114428. } else if (isEligible) {
  114429. return 'ambiguous';
  114430. } else {
  114431. return 'simple';
  114432. }
  114433. },
  114434. pushParams: function pushParams(params) {
  114435. for (var i = 0, l = params.length; i < l; i++) {
  114436. this.pushParam(params[i]);
  114437. }
  114438. },
  114439. pushParam: function pushParam(val) {
  114440. var value = val.value != null ? val.value : val.original || '';
  114441. if (this.stringParams) {
  114442. if (value.replace) {
  114443. value = value.replace(/^(\.?\.\/)*/g, '').replace(/\//g, '.');
  114444. }
  114445. if (val.depth) {
  114446. this.addDepth(val.depth);
  114447. }
  114448. this.opcode('getContext', val.depth || 0);
  114449. this.opcode('pushStringParam', value, val.type);
  114450. if (val.type === 'SubExpression') {
  114451. // SubExpressions get evaluated and passed in
  114452. // in string params mode.
  114453. this.accept(val);
  114454. }
  114455. } else {
  114456. if (this.trackIds) {
  114457. var blockParamIndex = undefined;
  114458. if (val.parts && !_ast2['default'].helpers.scopedId(val) && !val.depth) {
  114459. blockParamIndex = this.blockParamIndex(val.parts[0]);
  114460. }
  114461. if (blockParamIndex) {
  114462. var blockParamChild = val.parts.slice(1).join('.');
  114463. this.opcode('pushId', 'BlockParam', blockParamIndex, blockParamChild);
  114464. } else {
  114465. value = val.original || value;
  114466. if (value.replace) {
  114467. value = value.replace(/^this(?:\.|$)/, '').replace(/^\.\//, '').replace(/^\.$/, '');
  114468. }
  114469. this.opcode('pushId', val.type, value);
  114470. }
  114471. }
  114472. this.accept(val);
  114473. }
  114474. },
  114475. setupFullMustacheParams: function setupFullMustacheParams(sexpr, program, inverse, omitEmpty) {
  114476. var params = sexpr.params;
  114477. this.pushParams(params);
  114478. this.opcode('pushProgram', program);
  114479. this.opcode('pushProgram', inverse);
  114480. if (sexpr.hash) {
  114481. this.accept(sexpr.hash);
  114482. } else {
  114483. this.opcode('emptyHash', omitEmpty);
  114484. }
  114485. return params;
  114486. },
  114487. blockParamIndex: function blockParamIndex(name) {
  114488. for (var depth = 0, len = this.options.blockParams.length; depth < len; depth++) {
  114489. var blockParams = this.options.blockParams[depth],
  114490. param = blockParams && _utils.indexOf(blockParams, name);
  114491. if (blockParams && param >= 0) {
  114492. return [depth, param];
  114493. }
  114494. }
  114495. }
  114496. };
  114497. function precompile(input, options, env) {
  114498. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  114499. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.precompile. You passed ' + input);
  114500. }
  114501. options = options || {};
  114502. if (!('data' in options)) {
  114503. options.data = true;
  114504. }
  114505. if (options.compat) {
  114506. options.useDepths = true;
  114507. }
  114508. var ast = env.parse(input, options),
  114509. environment = new env.Compiler().compile(ast, options);
  114510. return new env.JavaScriptCompiler().compile(environment, options);
  114511. }
  114512. function compile(input, options, env) {
  114513. if (options === undefined) options = {};
  114514. if (input == null || typeof input !== 'string' && input.type !== 'Program') {
  114515. throw new _exception2['default']('You must pass a string or Handlebars AST to Handlebars.compile. You passed ' + input);
  114516. }
  114517. options = _utils.extend({}, options);
  114518. if (!('data' in options)) {
  114519. options.data = true;
  114520. }
  114521. if (options.compat) {
  114522. options.useDepths = true;
  114523. }
  114524. var compiled = undefined;
  114525. function compileInput() {
  114526. var ast = env.parse(input, options),
  114527. environment = new env.Compiler().compile(ast, options),
  114528. templateSpec = new env.JavaScriptCompiler().compile(environment, options, undefined, true);
  114529. return env.template(templateSpec);
  114530. }
  114531. // Template is only compiled on first use and cached after that point.
  114532. function ret(context, execOptions) {
  114533. if (!compiled) {
  114534. compiled = compileInput();
  114535. }
  114536. return compiled.call(this, context, execOptions);
  114537. }
  114538. ret._setup = function (setupOptions) {
  114539. if (!compiled) {
  114540. compiled = compileInput();
  114541. }
  114542. return compiled._setup(setupOptions);
  114543. };
  114544. ret._child = function (i, data, blockParams, depths) {
  114545. if (!compiled) {
  114546. compiled = compileInput();
  114547. }
  114548. return compiled._child(i, data, blockParams, depths);
  114549. };
  114550. return ret;
  114551. }
  114552. function argEquals(a, b) {
  114553. if (a === b) {
  114554. return true;
  114555. }
  114556. if (_utils.isArray(a) && _utils.isArray(b) && a.length === b.length) {
  114557. for (var i = 0; i < a.length; i++) {
  114558. if (!argEquals(a[i], b[i])) {
  114559. return false;
  114560. }
  114561. }
  114562. return true;
  114563. }
  114564. }
  114565. function transformLiteralToPath(sexpr) {
  114566. if (!sexpr.path.parts) {
  114567. var literal = sexpr.path;
  114568. // Casting to string here to make false and 0 literal values play nicely with the rest
  114569. // of the system.
  114570. sexpr.path = {
  114571. type: 'PathExpression',
  114572. data: false,
  114573. depth: 0,
  114574. parts: [literal.original + ''],
  114575. original: literal.original + '',
  114576. loc: literal.loc
  114577. };
  114578. }
  114579. }
  114580. /***/ }),
  114581. /* 42 */
  114582. /***/ (function(module, exports, __webpack_require__) {
  114583. 'use strict';
  114584. var _interopRequireDefault = __webpack_require__(1)['default'];
  114585. exports.__esModule = true;
  114586. var _base = __webpack_require__(4);
  114587. var _exception = __webpack_require__(6);
  114588. var _exception2 = _interopRequireDefault(_exception);
  114589. var _utils = __webpack_require__(5);
  114590. var _codeGen = __webpack_require__(43);
  114591. var _codeGen2 = _interopRequireDefault(_codeGen);
  114592. function Literal(value) {
  114593. this.value = value;
  114594. }
  114595. function JavaScriptCompiler() {}
  114596. JavaScriptCompiler.prototype = {
  114597. // PUBLIC API: You can override these methods in a subclass to provide
  114598. // alternative compiled forms for name lookup and buffering semantics
  114599. nameLookup: function nameLookup(parent, name /* , type*/) {
  114600. if (JavaScriptCompiler.isValidJavaScriptVariableName(name)) {
  114601. return [parent, '.', name];
  114602. } else {
  114603. return [parent, '[', JSON.stringify(name), ']'];
  114604. }
  114605. },
  114606. depthedLookup: function depthedLookup(name) {
  114607. return [this.aliasable('container.lookup'), '(depths, "', name, '")'];
  114608. },
  114609. compilerInfo: function compilerInfo() {
  114610. var revision = _base.COMPILER_REVISION,
  114611. versions = _base.REVISION_CHANGES[revision];
  114612. return [revision, versions];
  114613. },
  114614. appendToBuffer: function appendToBuffer(source, location, explicit) {
  114615. // Force a source as this simplifies the merge logic.
  114616. if (!_utils.isArray(source)) {
  114617. source = [source];
  114618. }
  114619. source = this.source.wrap(source, location);
  114620. if (this.environment.isSimple) {
  114621. return ['return ', source, ';'];
  114622. } else if (explicit) {
  114623. // This is a case where the buffer operation occurs as a child of another
  114624. // construct, generally braces. We have to explicitly output these buffer
  114625. // operations to ensure that the emitted code goes in the correct location.
  114626. return ['buffer += ', source, ';'];
  114627. } else {
  114628. source.appendToBuffer = true;
  114629. return source;
  114630. }
  114631. },
  114632. initializeBuffer: function initializeBuffer() {
  114633. return this.quotedString('');
  114634. },
  114635. // END PUBLIC API
  114636. compile: function compile(environment, options, context, asObject) {
  114637. this.environment = environment;
  114638. this.options = options;
  114639. this.stringParams = this.options.stringParams;
  114640. this.trackIds = this.options.trackIds;
  114641. this.precompile = !asObject;
  114642. this.name = this.environment.name;
  114643. this.isChild = !!context;
  114644. this.context = context || {
  114645. decorators: [],
  114646. programs: [],
  114647. environments: []
  114648. };
  114649. this.preamble();
  114650. this.stackSlot = 0;
  114651. this.stackVars = [];
  114652. this.aliases = {};
  114653. this.registers = { list: [] };
  114654. this.hashes = [];
  114655. this.compileStack = [];
  114656. this.inlineStack = [];
  114657. this.blockParams = [];
  114658. this.compileChildren(environment, options);
  114659. this.useDepths = this.useDepths || environment.useDepths || environment.useDecorators || this.options.compat;
  114660. this.useBlockParams = this.useBlockParams || environment.useBlockParams;
  114661. var opcodes = environment.opcodes,
  114662. opcode = undefined,
  114663. firstLoc = undefined,
  114664. i = undefined,
  114665. l = undefined;
  114666. for (i = 0, l = opcodes.length; i < l; i++) {
  114667. opcode = opcodes[i];
  114668. this.source.currentLocation = opcode.loc;
  114669. firstLoc = firstLoc || opcode.loc;
  114670. this[opcode.opcode].apply(this, opcode.args);
  114671. }
  114672. // Flush any trailing content that might be pending.
  114673. this.source.currentLocation = firstLoc;
  114674. this.pushSource('');
  114675. /* istanbul ignore next */
  114676. if (this.stackSlot || this.inlineStack.length || this.compileStack.length) {
  114677. throw new _exception2['default']('Compile completed with content left on stack');
  114678. }
  114679. if (!this.decorators.isEmpty()) {
  114680. this.useDecorators = true;
  114681. this.decorators.prepend('var decorators = container.decorators;\n');
  114682. this.decorators.push('return fn;');
  114683. if (asObject) {
  114684. this.decorators = Function.apply(this, ['fn', 'props', 'container', 'depth0', 'data', 'blockParams', 'depths', this.decorators.merge()]);
  114685. } else {
  114686. this.decorators.prepend('function(fn, props, container, depth0, data, blockParams, depths) {\n');
  114687. this.decorators.push('}\n');
  114688. this.decorators = this.decorators.merge();
  114689. }
  114690. } else {
  114691. this.decorators = undefined;
  114692. }
  114693. var fn = this.createFunctionContext(asObject);
  114694. if (!this.isChild) {
  114695. var ret = {
  114696. compiler: this.compilerInfo(),
  114697. main: fn
  114698. };
  114699. if (this.decorators) {
  114700. ret.main_d = this.decorators; // eslint-disable-line camelcase
  114701. ret.useDecorators = true;
  114702. }
  114703. var _context = this.context;
  114704. var programs = _context.programs;
  114705. var decorators = _context.decorators;
  114706. for (i = 0, l = programs.length; i < l; i++) {
  114707. if (programs[i]) {
  114708. ret[i] = programs[i];
  114709. if (decorators[i]) {
  114710. ret[i + '_d'] = decorators[i];
  114711. ret.useDecorators = true;
  114712. }
  114713. }
  114714. }
  114715. if (this.environment.usePartial) {
  114716. ret.usePartial = true;
  114717. }
  114718. if (this.options.data) {
  114719. ret.useData = true;
  114720. }
  114721. if (this.useDepths) {
  114722. ret.useDepths = true;
  114723. }
  114724. if (this.useBlockParams) {
  114725. ret.useBlockParams = true;
  114726. }
  114727. if (this.options.compat) {
  114728. ret.compat = true;
  114729. }
  114730. if (!asObject) {
  114731. ret.compiler = JSON.stringify(ret.compiler);
  114732. this.source.currentLocation = { start: { line: 1, column: 0 } };
  114733. ret = this.objectLiteral(ret);
  114734. if (options.srcName) {
  114735. ret = ret.toStringWithSourceMap({ file: options.destName });
  114736. ret.map = ret.map && ret.map.toString();
  114737. } else {
  114738. ret = ret.toString();
  114739. }
  114740. } else {
  114741. ret.compilerOptions = this.options;
  114742. }
  114743. return ret;
  114744. } else {
  114745. return fn;
  114746. }
  114747. },
  114748. preamble: function preamble() {
  114749. // track the last context pushed into place to allow skipping the
  114750. // getContext opcode when it would be a noop
  114751. this.lastContext = 0;
  114752. this.source = new _codeGen2['default'](this.options.srcName);
  114753. this.decorators = new _codeGen2['default'](this.options.srcName);
  114754. },
  114755. createFunctionContext: function createFunctionContext(asObject) {
  114756. var varDeclarations = '';
  114757. var locals = this.stackVars.concat(this.registers.list);
  114758. if (locals.length > 0) {
  114759. varDeclarations += ', ' + locals.join(', ');
  114760. }
  114761. // Generate minimizer alias mappings
  114762. //
  114763. // When using true SourceNodes, this will update all references to the given alias
  114764. // as the source nodes are reused in situ. For the non-source node compilation mode,
  114765. // aliases will not be used, but this case is already being run on the client and
  114766. // we aren't concern about minimizing the template size.
  114767. var aliasCount = 0;
  114768. for (var alias in this.aliases) {
  114769. // eslint-disable-line guard-for-in
  114770. var node = this.aliases[alias];
  114771. if (this.aliases.hasOwnProperty(alias) && node.children && node.referenceCount > 1) {
  114772. varDeclarations += ', alias' + ++aliasCount + '=' + alias;
  114773. node.children[0] = 'alias' + aliasCount;
  114774. }
  114775. }
  114776. var params = ['container', 'depth0', 'helpers', 'partials', 'data'];
  114777. if (this.useBlockParams || this.useDepths) {
  114778. params.push('blockParams');
  114779. }
  114780. if (this.useDepths) {
  114781. params.push('depths');
  114782. }
  114783. // Perform a second pass over the output to merge content when possible
  114784. var source = this.mergeSource(varDeclarations);
  114785. if (asObject) {
  114786. params.push(source);
  114787. return Function.apply(this, params);
  114788. } else {
  114789. return this.source.wrap(['function(', params.join(','), ') {\n ', source, '}']);
  114790. }
  114791. },
  114792. mergeSource: function mergeSource(varDeclarations) {
  114793. var isSimple = this.environment.isSimple,
  114794. appendOnly = !this.forceBuffer,
  114795. appendFirst = undefined,
  114796. sourceSeen = undefined,
  114797. bufferStart = undefined,
  114798. bufferEnd = undefined;
  114799. this.source.each(function (line) {
  114800. if (line.appendToBuffer) {
  114801. if (bufferStart) {
  114802. line.prepend(' + ');
  114803. } else {
  114804. bufferStart = line;
  114805. }
  114806. bufferEnd = line;
  114807. } else {
  114808. if (bufferStart) {
  114809. if (!sourceSeen) {
  114810. appendFirst = true;
  114811. } else {
  114812. bufferStart.prepend('buffer += ');
  114813. }
  114814. bufferEnd.add(';');
  114815. bufferStart = bufferEnd = undefined;
  114816. }
  114817. sourceSeen = true;
  114818. if (!isSimple) {
  114819. appendOnly = false;
  114820. }
  114821. }
  114822. });
  114823. if (appendOnly) {
  114824. if (bufferStart) {
  114825. bufferStart.prepend('return ');
  114826. bufferEnd.add(';');
  114827. } else if (!sourceSeen) {
  114828. this.source.push('return "";');
  114829. }
  114830. } else {
  114831. varDeclarations += ', buffer = ' + (appendFirst ? '' : this.initializeBuffer());
  114832. if (bufferStart) {
  114833. bufferStart.prepend('return buffer + ');
  114834. bufferEnd.add(';');
  114835. } else {
  114836. this.source.push('return buffer;');
  114837. }
  114838. }
  114839. if (varDeclarations) {
  114840. this.source.prepend('var ' + varDeclarations.substring(2) + (appendFirst ? '' : ';\n'));
  114841. }
  114842. return this.source.merge();
  114843. },
  114844. // [blockValue]
  114845. //
  114846. // On stack, before: hash, inverse, program, value
  114847. // On stack, after: return value of blockHelperMissing
  114848. //
  114849. // The purpose of this opcode is to take a block of the form
  114850. // `{{#this.foo}}...{{/this.foo}}`, resolve the value of `foo`, and
  114851. // replace it on the stack with the result of properly
  114852. // invoking blockHelperMissing.
  114853. blockValue: function blockValue(name) {
  114854. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  114855. params = [this.contextName(0)];
  114856. this.setupHelperArgs(name, 0, params);
  114857. var blockName = this.popStack();
  114858. params.splice(1, 0, blockName);
  114859. this.push(this.source.functionCall(blockHelperMissing, 'call', params));
  114860. },
  114861. // [ambiguousBlockValue]
  114862. //
  114863. // On stack, before: hash, inverse, program, value
  114864. // Compiler value, before: lastHelper=value of last found helper, if any
  114865. // On stack, after, if no lastHelper: same as [blockValue]
  114866. // On stack, after, if lastHelper: value
  114867. ambiguousBlockValue: function ambiguousBlockValue() {
  114868. // We're being a bit cheeky and reusing the options value from the prior exec
  114869. var blockHelperMissing = this.aliasable('helpers.blockHelperMissing'),
  114870. params = [this.contextName(0)];
  114871. this.setupHelperArgs('', 0, params, true);
  114872. this.flushInline();
  114873. var current = this.topStack();
  114874. params.splice(1, 0, current);
  114875. this.pushSource(['if (!', this.lastHelper, ') { ', current, ' = ', this.source.functionCall(blockHelperMissing, 'call', params), '}']);
  114876. },
  114877. // [appendContent]
  114878. //
  114879. // On stack, before: ...
  114880. // On stack, after: ...
  114881. //
  114882. // Appends the string value of `content` to the current buffer
  114883. appendContent: function appendContent(content) {
  114884. if (this.pendingContent) {
  114885. content = this.pendingContent + content;
  114886. } else {
  114887. this.pendingLocation = this.source.currentLocation;
  114888. }
  114889. this.pendingContent = content;
  114890. },
  114891. // [append]
  114892. //
  114893. // On stack, before: value, ...
  114894. // On stack, after: ...
  114895. //
  114896. // Coerces `value` to a String and appends it to the current buffer.
  114897. //
  114898. // If `value` is truthy, or 0, it is coerced into a string and appended
  114899. // Otherwise, the empty string is appended
  114900. append: function append() {
  114901. if (this.isInline()) {
  114902. this.replaceStack(function (current) {
  114903. return [' != null ? ', current, ' : ""'];
  114904. });
  114905. this.pushSource(this.appendToBuffer(this.popStack()));
  114906. } else {
  114907. var local = this.popStack();
  114908. this.pushSource(['if (', local, ' != null) { ', this.appendToBuffer(local, undefined, true), ' }']);
  114909. if (this.environment.isSimple) {
  114910. this.pushSource(['else { ', this.appendToBuffer("''", undefined, true), ' }']);
  114911. }
  114912. }
  114913. },
  114914. // [appendEscaped]
  114915. //
  114916. // On stack, before: value, ...
  114917. // On stack, after: ...
  114918. //
  114919. // Escape `value` and append it to the buffer
  114920. appendEscaped: function appendEscaped() {
  114921. this.pushSource(this.appendToBuffer([this.aliasable('container.escapeExpression'), '(', this.popStack(), ')']));
  114922. },
  114923. // [getContext]
  114924. //
  114925. // On stack, before: ...
  114926. // On stack, after: ...
  114927. // Compiler value, after: lastContext=depth
  114928. //
  114929. // Set the value of the `lastContext` compiler value to the depth
  114930. getContext: function getContext(depth) {
  114931. this.lastContext = depth;
  114932. },
  114933. // [pushContext]
  114934. //
  114935. // On stack, before: ...
  114936. // On stack, after: currentContext, ...
  114937. //
  114938. // Pushes the value of the current context onto the stack.
  114939. pushContext: function pushContext() {
  114940. this.pushStackLiteral(this.contextName(this.lastContext));
  114941. },
  114942. // [lookupOnContext]
  114943. //
  114944. // On stack, before: ...
  114945. // On stack, after: currentContext[name], ...
  114946. //
  114947. // Looks up the value of `name` on the current context and pushes
  114948. // it onto the stack.
  114949. lookupOnContext: function lookupOnContext(parts, falsy, strict, scoped) {
  114950. var i = 0;
  114951. if (!scoped && this.options.compat && !this.lastContext) {
  114952. // The depthed query is expected to handle the undefined logic for the root level that
  114953. // is implemented below, so we evaluate that directly in compat mode
  114954. this.push(this.depthedLookup(parts[i++]));
  114955. } else {
  114956. this.pushContext();
  114957. }
  114958. this.resolvePath('context', parts, i, falsy, strict);
  114959. },
  114960. // [lookupBlockParam]
  114961. //
  114962. // On stack, before: ...
  114963. // On stack, after: blockParam[name], ...
  114964. //
  114965. // Looks up the value of `parts` on the given block param and pushes
  114966. // it onto the stack.
  114967. lookupBlockParam: function lookupBlockParam(blockParamId, parts) {
  114968. this.useBlockParams = true;
  114969. this.push(['blockParams[', blockParamId[0], '][', blockParamId[1], ']']);
  114970. this.resolvePath('context', parts, 1);
  114971. },
  114972. // [lookupData]
  114973. //
  114974. // On stack, before: ...
  114975. // On stack, after: data, ...
  114976. //
  114977. // Push the data lookup operator
  114978. lookupData: function lookupData(depth, parts, strict) {
  114979. if (!depth) {
  114980. this.pushStackLiteral('data');
  114981. } else {
  114982. this.pushStackLiteral('container.data(data, ' + depth + ')');
  114983. }
  114984. this.resolvePath('data', parts, 0, true, strict);
  114985. },
  114986. resolvePath: function resolvePath(type, parts, i, falsy, strict) {
  114987. // istanbul ignore next
  114988. var _this = this;
  114989. if (this.options.strict || this.options.assumeObjects) {
  114990. this.push(strictLookup(this.options.strict && strict, this, parts, type));
  114991. return;
  114992. }
  114993. var len = parts.length;
  114994. for (; i < len; i++) {
  114995. /* eslint-disable no-loop-func */
  114996. this.replaceStack(function (current) {
  114997. var lookup = _this.nameLookup(current, parts[i], type);
  114998. // We want to ensure that zero and false are handled properly if the context (falsy flag)
  114999. // needs to have the special handling for these values.
  115000. if (!falsy) {
  115001. return [' != null ? ', lookup, ' : ', current];
  115002. } else {
  115003. // Otherwise we can use generic falsy handling
  115004. return [' && ', lookup];
  115005. }
  115006. });
  115007. /* eslint-enable no-loop-func */
  115008. }
  115009. },
  115010. // [resolvePossibleLambda]
  115011. //
  115012. // On stack, before: value, ...
  115013. // On stack, after: resolved value, ...
  115014. //
  115015. // If the `value` is a lambda, replace it on the stack by
  115016. // the return value of the lambda
  115017. resolvePossibleLambda: function resolvePossibleLambda() {
  115018. this.push([this.aliasable('container.lambda'), '(', this.popStack(), ', ', this.contextName(0), ')']);
  115019. },
  115020. // [pushStringParam]
  115021. //
  115022. // On stack, before: ...
  115023. // On stack, after: string, currentContext, ...
  115024. //
  115025. // This opcode is designed for use in string mode, which
  115026. // provides the string value of a parameter along with its
  115027. // depth rather than resolving it immediately.
  115028. pushStringParam: function pushStringParam(string, type) {
  115029. this.pushContext();
  115030. this.pushString(type);
  115031. // If it's a subexpression, the string result
  115032. // will be pushed after this opcode.
  115033. if (type !== 'SubExpression') {
  115034. if (typeof string === 'string') {
  115035. this.pushString(string);
  115036. } else {
  115037. this.pushStackLiteral(string);
  115038. }
  115039. }
  115040. },
  115041. emptyHash: function emptyHash(omitEmpty) {
  115042. if (this.trackIds) {
  115043. this.push('{}'); // hashIds
  115044. }
  115045. if (this.stringParams) {
  115046. this.push('{}'); // hashContexts
  115047. this.push('{}'); // hashTypes
  115048. }
  115049. this.pushStackLiteral(omitEmpty ? 'undefined' : '{}');
  115050. },
  115051. pushHash: function pushHash() {
  115052. if (this.hash) {
  115053. this.hashes.push(this.hash);
  115054. }
  115055. this.hash = { values: [], types: [], contexts: [], ids: [] };
  115056. },
  115057. popHash: function popHash() {
  115058. var hash = this.hash;
  115059. this.hash = this.hashes.pop();
  115060. if (this.trackIds) {
  115061. this.push(this.objectLiteral(hash.ids));
  115062. }
  115063. if (this.stringParams) {
  115064. this.push(this.objectLiteral(hash.contexts));
  115065. this.push(this.objectLiteral(hash.types));
  115066. }
  115067. this.push(this.objectLiteral(hash.values));
  115068. },
  115069. // [pushString]
  115070. //
  115071. // On stack, before: ...
  115072. // On stack, after: quotedString(string), ...
  115073. //
  115074. // Push a quoted version of `string` onto the stack
  115075. pushString: function pushString(string) {
  115076. this.pushStackLiteral(this.quotedString(string));
  115077. },
  115078. // [pushLiteral]
  115079. //
  115080. // On stack, before: ...
  115081. // On stack, after: value, ...
  115082. //
  115083. // Pushes a value onto the stack. This operation prevents
  115084. // the compiler from creating a temporary variable to hold
  115085. // it.
  115086. pushLiteral: function pushLiteral(value) {
  115087. this.pushStackLiteral(value);
  115088. },
  115089. // [pushProgram]
  115090. //
  115091. // On stack, before: ...
  115092. // On stack, after: program(guid), ...
  115093. //
  115094. // Push a program expression onto the stack. This takes
  115095. // a compile-time guid and converts it into a runtime-accessible
  115096. // expression.
  115097. pushProgram: function pushProgram(guid) {
  115098. if (guid != null) {
  115099. this.pushStackLiteral(this.programExpression(guid));
  115100. } else {
  115101. this.pushStackLiteral(null);
  115102. }
  115103. },
  115104. // [registerDecorator]
  115105. //
  115106. // On stack, before: hash, program, params..., ...
  115107. // On stack, after: ...
  115108. //
  115109. // Pops off the decorator's parameters, invokes the decorator,
  115110. // and inserts the decorator into the decorators list.
  115111. registerDecorator: function registerDecorator(paramSize, name) {
  115112. var foundDecorator = this.nameLookup('decorators', name, 'decorator'),
  115113. options = this.setupHelperArgs(name, paramSize);
  115114. this.decorators.push(['fn = ', this.decorators.functionCall(foundDecorator, '', ['fn', 'props', 'container', options]), ' || fn;']);
  115115. },
  115116. // [invokeHelper]
  115117. //
  115118. // On stack, before: hash, inverse, program, params..., ...
  115119. // On stack, after: result of helper invocation
  115120. //
  115121. // Pops off the helper's parameters, invokes the helper,
  115122. // and pushes the helper's return value onto the stack.
  115123. //
  115124. // If the helper is not found, `helperMissing` is called.
  115125. invokeHelper: function invokeHelper(paramSize, name, isSimple) {
  115126. var nonHelper = this.popStack(),
  115127. helper = this.setupHelper(paramSize, name),
  115128. simple = isSimple ? [helper.name, ' || '] : '';
  115129. var lookup = ['('].concat(simple, nonHelper);
  115130. if (!this.options.strict) {
  115131. lookup.push(' || ', this.aliasable('helpers.helperMissing'));
  115132. }
  115133. lookup.push(')');
  115134. this.push(this.source.functionCall(lookup, 'call', helper.callParams));
  115135. },
  115136. // [invokeKnownHelper]
  115137. //
  115138. // On stack, before: hash, inverse, program, params..., ...
  115139. // On stack, after: result of helper invocation
  115140. //
  115141. // This operation is used when the helper is known to exist,
  115142. // so a `helperMissing` fallback is not required.
  115143. invokeKnownHelper: function invokeKnownHelper(paramSize, name) {
  115144. var helper = this.setupHelper(paramSize, name);
  115145. this.push(this.source.functionCall(helper.name, 'call', helper.callParams));
  115146. },
  115147. // [invokeAmbiguous]
  115148. //
  115149. // On stack, before: hash, inverse, program, params..., ...
  115150. // On stack, after: result of disambiguation
  115151. //
  115152. // This operation is used when an expression like `{{foo}}`
  115153. // is provided, but we don't know at compile-time whether it
  115154. // is a helper or a path.
  115155. //
  115156. // This operation emits more code than the other options,
  115157. // and can be avoided by passing the `knownHelpers` and
  115158. // `knownHelpersOnly` flags at compile-time.
  115159. invokeAmbiguous: function invokeAmbiguous(name, helperCall) {
  115160. this.useRegister('helper');
  115161. var nonHelper = this.popStack();
  115162. this.emptyHash();
  115163. var helper = this.setupHelper(0, name, helperCall);
  115164. var helperName = this.lastHelper = this.nameLookup('helpers', name, 'helper');
  115165. var lookup = ['(', '(helper = ', helperName, ' || ', nonHelper, ')'];
  115166. if (!this.options.strict) {
  115167. lookup[0] = '(helper = ';
  115168. lookup.push(' != null ? helper : ', this.aliasable('helpers.helperMissing'));
  115169. }
  115170. this.push(['(', lookup, helper.paramsInit ? ['),(', helper.paramsInit] : [], '),', '(typeof helper === ', this.aliasable('"function"'), ' ? ', this.source.functionCall('helper', 'call', helper.callParams), ' : helper))']);
  115171. },
  115172. // [invokePartial]
  115173. //
  115174. // On stack, before: context, ...
  115175. // On stack after: result of partial invocation
  115176. //
  115177. // This operation pops off a context, invokes a partial with that context,
  115178. // and pushes the result of the invocation back.
  115179. invokePartial: function invokePartial(isDynamic, name, indent) {
  115180. var params = [],
  115181. options = this.setupParams(name, 1, params);
  115182. if (isDynamic) {
  115183. name = this.popStack();
  115184. delete options.name;
  115185. }
  115186. if (indent) {
  115187. options.indent = JSON.stringify(indent);
  115188. }
  115189. options.helpers = 'helpers';
  115190. options.partials = 'partials';
  115191. options.decorators = 'container.decorators';
  115192. if (!isDynamic) {
  115193. params.unshift(this.nameLookup('partials', name, 'partial'));
  115194. } else {
  115195. params.unshift(name);
  115196. }
  115197. if (this.options.compat) {
  115198. options.depths = 'depths';
  115199. }
  115200. options = this.objectLiteral(options);
  115201. params.push(options);
  115202. this.push(this.source.functionCall('container.invokePartial', '', params));
  115203. },
  115204. // [assignToHash]
  115205. //
  115206. // On stack, before: value, ..., hash, ...
  115207. // On stack, after: ..., hash, ...
  115208. //
  115209. // Pops a value off the stack and assigns it to the current hash
  115210. assignToHash: function assignToHash(key) {
  115211. var value = this.popStack(),
  115212. context = undefined,
  115213. type = undefined,
  115214. id = undefined;
  115215. if (this.trackIds) {
  115216. id = this.popStack();
  115217. }
  115218. if (this.stringParams) {
  115219. type = this.popStack();
  115220. context = this.popStack();
  115221. }
  115222. var hash = this.hash;
  115223. if (context) {
  115224. hash.contexts[key] = context;
  115225. }
  115226. if (type) {
  115227. hash.types[key] = type;
  115228. }
  115229. if (id) {
  115230. hash.ids[key] = id;
  115231. }
  115232. hash.values[key] = value;
  115233. },
  115234. pushId: function pushId(type, name, child) {
  115235. if (type === 'BlockParam') {
  115236. this.pushStackLiteral('blockParams[' + name[0] + '].path[' + name[1] + ']' + (child ? ' + ' + JSON.stringify('.' + child) : ''));
  115237. } else if (type === 'PathExpression') {
  115238. this.pushString(name);
  115239. } else if (type === 'SubExpression') {
  115240. this.pushStackLiteral('true');
  115241. } else {
  115242. this.pushStackLiteral('null');
  115243. }
  115244. },
  115245. // HELPERS
  115246. compiler: JavaScriptCompiler,
  115247. compileChildren: function compileChildren(environment, options) {
  115248. var children = environment.children,
  115249. child = undefined,
  115250. compiler = undefined;
  115251. for (var i = 0, l = children.length; i < l; i++) {
  115252. child = children[i];
  115253. compiler = new this.compiler(); // eslint-disable-line new-cap
  115254. var existing = this.matchExistingProgram(child);
  115255. if (existing == null) {
  115256. this.context.programs.push(''); // Placeholder to prevent name conflicts for nested children
  115257. var index = this.context.programs.length;
  115258. child.index = index;
  115259. child.name = 'program' + index;
  115260. this.context.programs[index] = compiler.compile(child, options, this.context, !this.precompile);
  115261. this.context.decorators[index] = compiler.decorators;
  115262. this.context.environments[index] = child;
  115263. this.useDepths = this.useDepths || compiler.useDepths;
  115264. this.useBlockParams = this.useBlockParams || compiler.useBlockParams;
  115265. child.useDepths = this.useDepths;
  115266. child.useBlockParams = this.useBlockParams;
  115267. } else {
  115268. child.index = existing.index;
  115269. child.name = 'program' + existing.index;
  115270. this.useDepths = this.useDepths || existing.useDepths;
  115271. this.useBlockParams = this.useBlockParams || existing.useBlockParams;
  115272. }
  115273. }
  115274. },
  115275. matchExistingProgram: function matchExistingProgram(child) {
  115276. for (var i = 0, len = this.context.environments.length; i < len; i++) {
  115277. var environment = this.context.environments[i];
  115278. if (environment && environment.equals(child)) {
  115279. return environment;
  115280. }
  115281. }
  115282. },
  115283. programExpression: function programExpression(guid) {
  115284. var child = this.environment.children[guid],
  115285. programParams = [child.index, 'data', child.blockParams];
  115286. if (this.useBlockParams || this.useDepths) {
  115287. programParams.push('blockParams');
  115288. }
  115289. if (this.useDepths) {
  115290. programParams.push('depths');
  115291. }
  115292. return 'container.program(' + programParams.join(', ') + ')';
  115293. },
  115294. useRegister: function useRegister(name) {
  115295. if (!this.registers[name]) {
  115296. this.registers[name] = true;
  115297. this.registers.list.push(name);
  115298. }
  115299. },
  115300. push: function push(expr) {
  115301. if (!(expr instanceof Literal)) {
  115302. expr = this.source.wrap(expr);
  115303. }
  115304. this.inlineStack.push(expr);
  115305. return expr;
  115306. },
  115307. pushStackLiteral: function pushStackLiteral(item) {
  115308. this.push(new Literal(item));
  115309. },
  115310. pushSource: function pushSource(source) {
  115311. if (this.pendingContent) {
  115312. this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent), this.pendingLocation));
  115313. this.pendingContent = undefined;
  115314. }
  115315. if (source) {
  115316. this.source.push(source);
  115317. }
  115318. },
  115319. replaceStack: function replaceStack(callback) {
  115320. var prefix = ['('],
  115321. stack = undefined,
  115322. createdStack = undefined,
  115323. usedLiteral = undefined;
  115324. /* istanbul ignore next */
  115325. if (!this.isInline()) {
  115326. throw new _exception2['default']('replaceStack on non-inline');
  115327. }
  115328. // We want to merge the inline statement into the replacement statement via ','
  115329. var top = this.popStack(true);
  115330. if (top instanceof Literal) {
  115331. // Literals do not need to be inlined
  115332. stack = [top.value];
  115333. prefix = ['(', stack];
  115334. usedLiteral = true;
  115335. } else {
  115336. // Get or create the current stack name for use by the inline
  115337. createdStack = true;
  115338. var _name = this.incrStack();
  115339. prefix = ['((', this.push(_name), ' = ', top, ')'];
  115340. stack = this.topStack();
  115341. }
  115342. var item = callback.call(this, stack);
  115343. if (!usedLiteral) {
  115344. this.popStack();
  115345. }
  115346. if (createdStack) {
  115347. this.stackSlot--;
  115348. }
  115349. this.push(prefix.concat(item, ')'));
  115350. },
  115351. incrStack: function incrStack() {
  115352. this.stackSlot++;
  115353. if (this.stackSlot > this.stackVars.length) {
  115354. this.stackVars.push('stack' + this.stackSlot);
  115355. }
  115356. return this.topStackName();
  115357. },
  115358. topStackName: function topStackName() {
  115359. return 'stack' + this.stackSlot;
  115360. },
  115361. flushInline: function flushInline() {
  115362. var inlineStack = this.inlineStack;
  115363. this.inlineStack = [];
  115364. for (var i = 0, len = inlineStack.length; i < len; i++) {
  115365. var entry = inlineStack[i];
  115366. /* istanbul ignore if */
  115367. if (entry instanceof Literal) {
  115368. this.compileStack.push(entry);
  115369. } else {
  115370. var stack = this.incrStack();
  115371. this.pushSource([stack, ' = ', entry, ';']);
  115372. this.compileStack.push(stack);
  115373. }
  115374. }
  115375. },
  115376. isInline: function isInline() {
  115377. return this.inlineStack.length;
  115378. },
  115379. popStack: function popStack(wrapped) {
  115380. var inline = this.isInline(),
  115381. item = (inline ? this.inlineStack : this.compileStack).pop();
  115382. if (!wrapped && item instanceof Literal) {
  115383. return item.value;
  115384. } else {
  115385. if (!inline) {
  115386. /* istanbul ignore next */
  115387. if (!this.stackSlot) {
  115388. throw new _exception2['default']('Invalid stack pop');
  115389. }
  115390. this.stackSlot--;
  115391. }
  115392. return item;
  115393. }
  115394. },
  115395. topStack: function topStack() {
  115396. var stack = this.isInline() ? this.inlineStack : this.compileStack,
  115397. item = stack[stack.length - 1];
  115398. /* istanbul ignore if */
  115399. if (item instanceof Literal) {
  115400. return item.value;
  115401. } else {
  115402. return item;
  115403. }
  115404. },
  115405. contextName: function contextName(context) {
  115406. if (this.useDepths && context) {
  115407. return 'depths[' + context + ']';
  115408. } else {
  115409. return 'depth' + context;
  115410. }
  115411. },
  115412. quotedString: function quotedString(str) {
  115413. return this.source.quotedString(str);
  115414. },
  115415. objectLiteral: function objectLiteral(obj) {
  115416. return this.source.objectLiteral(obj);
  115417. },
  115418. aliasable: function aliasable(name) {
  115419. var ret = this.aliases[name];
  115420. if (ret) {
  115421. ret.referenceCount++;
  115422. return ret;
  115423. }
  115424. ret = this.aliases[name] = this.source.wrap(name);
  115425. ret.aliasable = true;
  115426. ret.referenceCount = 1;
  115427. return ret;
  115428. },
  115429. setupHelper: function setupHelper(paramSize, name, blockHelper) {
  115430. var params = [],
  115431. paramsInit = this.setupHelperArgs(name, paramSize, params, blockHelper);
  115432. var foundHelper = this.nameLookup('helpers', name, 'helper'),
  115433. callContext = this.aliasable(this.contextName(0) + ' != null ? ' + this.contextName(0) + ' : (container.nullContext || {})');
  115434. return {
  115435. params: params,
  115436. paramsInit: paramsInit,
  115437. name: foundHelper,
  115438. callParams: [callContext].concat(params)
  115439. };
  115440. },
  115441. setupParams: function setupParams(helper, paramSize, params) {
  115442. var options = {},
  115443. contexts = [],
  115444. types = [],
  115445. ids = [],
  115446. objectArgs = !params,
  115447. param = undefined;
  115448. if (objectArgs) {
  115449. params = [];
  115450. }
  115451. options.name = this.quotedString(helper);
  115452. options.hash = this.popStack();
  115453. if (this.trackIds) {
  115454. options.hashIds = this.popStack();
  115455. }
  115456. if (this.stringParams) {
  115457. options.hashTypes = this.popStack();
  115458. options.hashContexts = this.popStack();
  115459. }
  115460. var inverse = this.popStack(),
  115461. program = this.popStack();
  115462. // Avoid setting fn and inverse if neither are set. This allows
  115463. // helpers to do a check for `if (options.fn)`
  115464. if (program || inverse) {
  115465. options.fn = program || 'container.noop';
  115466. options.inverse = inverse || 'container.noop';
  115467. }
  115468. // The parameters go on to the stack in order (making sure that they are evaluated in order)
  115469. // so we need to pop them off the stack in reverse order
  115470. var i = paramSize;
  115471. while (i--) {
  115472. param = this.popStack();
  115473. params[i] = param;
  115474. if (this.trackIds) {
  115475. ids[i] = this.popStack();
  115476. }
  115477. if (this.stringParams) {
  115478. types[i] = this.popStack();
  115479. contexts[i] = this.popStack();
  115480. }
  115481. }
  115482. if (objectArgs) {
  115483. options.args = this.source.generateArray(params);
  115484. }
  115485. if (this.trackIds) {
  115486. options.ids = this.source.generateArray(ids);
  115487. }
  115488. if (this.stringParams) {
  115489. options.types = this.source.generateArray(types);
  115490. options.contexts = this.source.generateArray(contexts);
  115491. }
  115492. if (this.options.data) {
  115493. options.data = 'data';
  115494. }
  115495. if (this.useBlockParams) {
  115496. options.blockParams = 'blockParams';
  115497. }
  115498. return options;
  115499. },
  115500. setupHelperArgs: function setupHelperArgs(helper, paramSize, params, useRegister) {
  115501. var options = this.setupParams(helper, paramSize, params);
  115502. options = this.objectLiteral(options);
  115503. if (useRegister) {
  115504. this.useRegister('options');
  115505. params.push('options');
  115506. return ['options=', options];
  115507. } else if (params) {
  115508. params.push(options);
  115509. return '';
  115510. } else {
  115511. return options;
  115512. }
  115513. }
  115514. };
  115515. (function () {
  115516. var reservedWords = ('break else new var' + ' case finally return void' + ' catch for switch while' + ' continue function this with' + ' default if throw' + ' delete in try' + ' do instanceof typeof' + ' abstract enum int short' + ' boolean export interface static' + ' byte extends long super' + ' char final native synchronized' + ' class float package throws' + ' const goto private transient' + ' debugger implements protected volatile' + ' double import public let yield await' + ' null true false').split(' ');
  115517. var compilerWords = JavaScriptCompiler.RESERVED_WORDS = {};
  115518. for (var i = 0, l = reservedWords.length; i < l; i++) {
  115519. compilerWords[reservedWords[i]] = true;
  115520. }
  115521. })();
  115522. JavaScriptCompiler.isValidJavaScriptVariableName = function (name) {
  115523. return !JavaScriptCompiler.RESERVED_WORDS[name] && /^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(name);
  115524. };
  115525. function strictLookup(requireTerminal, compiler, parts, type) {
  115526. var stack = compiler.popStack(),
  115527. i = 0,
  115528. len = parts.length;
  115529. if (requireTerminal) {
  115530. len--;
  115531. }
  115532. for (; i < len; i++) {
  115533. stack = compiler.nameLookup(stack, parts[i], type);
  115534. }
  115535. if (requireTerminal) {
  115536. return [compiler.aliasable('container.strict'), '(', stack, ', ', compiler.quotedString(parts[i]), ')'];
  115537. } else {
  115538. return stack;
  115539. }
  115540. }
  115541. exports['default'] = JavaScriptCompiler;
  115542. module.exports = exports['default'];
  115543. /***/ }),
  115544. /* 43 */
  115545. /***/ (function(module, exports, __webpack_require__) {
  115546. /* global define */
  115547. 'use strict';
  115548. exports.__esModule = true;
  115549. var _utils = __webpack_require__(5);
  115550. var SourceNode = undefined;
  115551. try {
  115552. /* istanbul ignore next */
  115553. if (false) {
  115554. // We don't support this in AMD environments. For these environments, we asusme that
  115555. // they are running on the browser and thus have no need for the source-map library.
  115556. var SourceMap = require('source-map');
  115557. SourceNode = SourceMap.SourceNode;
  115558. }
  115559. } catch (err) {}
  115560. /* NOP */
  115561. /* istanbul ignore if: tested but not covered in istanbul due to dist build */
  115562. if (!SourceNode) {
  115563. SourceNode = function (line, column, srcFile, chunks) {
  115564. this.src = '';
  115565. if (chunks) {
  115566. this.add(chunks);
  115567. }
  115568. };
  115569. /* istanbul ignore next */
  115570. SourceNode.prototype = {
  115571. add: function add(chunks) {
  115572. if (_utils.isArray(chunks)) {
  115573. chunks = chunks.join('');
  115574. }
  115575. this.src += chunks;
  115576. },
  115577. prepend: function prepend(chunks) {
  115578. if (_utils.isArray(chunks)) {
  115579. chunks = chunks.join('');
  115580. }
  115581. this.src = chunks + this.src;
  115582. },
  115583. toStringWithSourceMap: function toStringWithSourceMap() {
  115584. return { code: this.toString() };
  115585. },
  115586. toString: function toString() {
  115587. return this.src;
  115588. }
  115589. };
  115590. }
  115591. function castChunk(chunk, codeGen, loc) {
  115592. if (_utils.isArray(chunk)) {
  115593. var ret = [];
  115594. for (var i = 0, len = chunk.length; i < len; i++) {
  115595. ret.push(codeGen.wrap(chunk[i], loc));
  115596. }
  115597. return ret;
  115598. } else if (typeof chunk === 'boolean' || typeof chunk === 'number') {
  115599. // Handle primitives that the SourceNode will throw up on
  115600. return chunk + '';
  115601. }
  115602. return chunk;
  115603. }
  115604. function CodeGen(srcFile) {
  115605. this.srcFile = srcFile;
  115606. this.source = [];
  115607. }
  115608. CodeGen.prototype = {
  115609. isEmpty: function isEmpty() {
  115610. return !this.source.length;
  115611. },
  115612. prepend: function prepend(source, loc) {
  115613. this.source.unshift(this.wrap(source, loc));
  115614. },
  115615. push: function push(source, loc) {
  115616. this.source.push(this.wrap(source, loc));
  115617. },
  115618. merge: function merge() {
  115619. var source = this.empty();
  115620. this.each(function (line) {
  115621. source.add([' ', line, '\n']);
  115622. });
  115623. return source;
  115624. },
  115625. each: function each(iter) {
  115626. for (var i = 0, len = this.source.length; i < len; i++) {
  115627. iter(this.source[i]);
  115628. }
  115629. },
  115630. empty: function empty() {
  115631. var loc = this.currentLocation || { start: {} };
  115632. return new SourceNode(loc.start.line, loc.start.column, this.srcFile);
  115633. },
  115634. wrap: function wrap(chunk) {
  115635. var loc = arguments.length <= 1 || arguments[1] === undefined ? this.currentLocation || { start: {} } : arguments[1];
  115636. if (chunk instanceof SourceNode) {
  115637. return chunk;
  115638. }
  115639. chunk = castChunk(chunk, this, loc);
  115640. return new SourceNode(loc.start.line, loc.start.column, this.srcFile, chunk);
  115641. },
  115642. functionCall: function functionCall(fn, type, params) {
  115643. params = this.generateList(params);
  115644. return this.wrap([fn, type ? '.' + type + '(' : '(', params, ')']);
  115645. },
  115646. quotedString: function quotedString(str) {
  115647. return '"' + (str + '').replace(/\\/g, '\\\\').replace(/"/g, '\\"').replace(/\n/g, '\\n').replace(/\r/g, '\\r').replace(/\u2028/g, '\\u2028') // Per Ecma-262 7.3 + 7.8.4
  115648. .replace(/\u2029/g, '\\u2029') + '"';
  115649. },
  115650. objectLiteral: function objectLiteral(obj) {
  115651. var pairs = [];
  115652. for (var key in obj) {
  115653. if (obj.hasOwnProperty(key)) {
  115654. var value = castChunk(obj[key], this);
  115655. if (value !== 'undefined') {
  115656. pairs.push([this.quotedString(key), ':', value]);
  115657. }
  115658. }
  115659. }
  115660. var ret = this.generateList(pairs);
  115661. ret.prepend('{');
  115662. ret.add('}');
  115663. return ret;
  115664. },
  115665. generateList: function generateList(entries) {
  115666. var ret = this.empty();
  115667. for (var i = 0, len = entries.length; i < len; i++) {
  115668. if (i) {
  115669. ret.add(',');
  115670. }
  115671. ret.add(castChunk(entries[i], this));
  115672. }
  115673. return ret;
  115674. },
  115675. generateArray: function generateArray(entries) {
  115676. var ret = this.generateList(entries);
  115677. ret.prepend('[');
  115678. ret.add(']');
  115679. return ret;
  115680. }
  115681. };
  115682. exports['default'] = CodeGen;
  115683. module.exports = exports['default'];
  115684. /***/ })
  115685. /******/ ])
  115686. });
  115687. ;
  115688. /***/ }),
  115689. /* 16 */
  115690. /***/ (function(module, exports, __webpack_require__) {
  115691. module.exports = __webpack_require__(17);
  115692. /***/ }),
  115693. /* 17 */
  115694. /***/ (function(module, exports, __webpack_require__) {
  115695. "use strict";
  115696. function __export(m) {
  115697. for (var p in m) if (!exports.hasOwnProperty(p)) exports[p] = m[p];
  115698. }
  115699. Object.defineProperty(exports, "__esModule", { value: true });
  115700. var mappers_1 = __webpack_require__(3);
  115701. exports.mapperManager = mappers_1.mapperManager;
  115702. var globals_1 = __webpack_require__(4);
  115703. exports.viewerGlobals = globals_1.viewerGlobals;
  115704. var viewerManager_1 = __webpack_require__(7);
  115705. exports.viewerManager = viewerManager_1.viewerManager;
  115706. var defaultViewer_1 = __webpack_require__(8);
  115707. exports.DefaultViewer = defaultViewer_1.DefaultViewer;
  115708. var viewer_1 = __webpack_require__(9);
  115709. exports.AbstractViewer = viewer_1.AbstractViewer;
  115710. var telemetryManager_1 = __webpack_require__(6);
  115711. exports.telemetryManager = telemetryManager_1.telemetryManager;
  115712. var modelLoader_1 = __webpack_require__(13);
  115713. exports.ModelLoader = modelLoader_1.ModelLoader;
  115714. var viewerModel_1 = __webpack_require__(5);
  115715. exports.ViewerModel = viewerModel_1.ViewerModel;
  115716. exports.ModelState = viewerModel_1.ModelState;
  115717. /**
  115718. * BabylonJS Viewer
  115719. *
  115720. * An HTML-Based viewer for 3D models, based on BabylonJS and its extensions.
  115721. */
  115722. var BABYLON = __webpack_require__(0);
  115723. exports.BABYLON = BABYLON;
  115724. // load needed modules.
  115725. __webpack_require__(14);
  115726. __webpack_require__(66);
  115727. var initializer_1 = __webpack_require__(67);
  115728. exports.InitTags = initializer_1.InitTags;
  115729. // promise polyfill, if needed!
  115730. BABYLON.PromisePolyfill.Apply();
  115731. initializer_1.initListeners();
  115732. //deprectaed, here for backwards compatibility
  115733. var disableInit = globals_1.viewerGlobals.disableInit;
  115734. exports.disableInit = disableInit;
  115735. /**
  115736. * Dispose all viewers currently registered
  115737. */
  115738. function disposeAll() {
  115739. viewerManager_1.viewerManager.dispose();
  115740. mappers_1.mapperManager.dispose();
  115741. telemetryManager_1.telemetryManager.dispose();
  115742. }
  115743. exports.disposeAll = disposeAll;
  115744. var Version = globals_1.viewerGlobals.version;
  115745. exports.Version = Version;
  115746. console.log("Babylon.js viewer (v" + Version + ")");
  115747. // export publicliy all configuration interfaces
  115748. __export(__webpack_require__(10));
  115749. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7Ozs7QUFBQSxtREFBd0Q7QUE4Q3lFLHdCQTlDeEgsdUJBQWEsQ0E4Q3dIO0FBN0M5SSxtREFBd0Q7QUE2Q1ksd0JBN0MzRCx1QkFBYSxDQTZDMkQ7QUE1Q2pGLHdEQUF1RDtBQTRDMkQsd0JBNUN6Ryw2QkFBYSxDQTRDeUc7QUEzQy9ILHdEQUF1RDtBQTJDbEIsd0JBM0M1Qiw2QkFBYSxDQTJDNEI7QUExQ2xELDBDQUFpRDtBQTBDRyx5QkExQzNDLHVCQUFjLENBMEMyQztBQXpDbEUsZ0VBQStEO0FBeUNvQiwyQkF6QzFFLG1DQUFnQixDQXlDMEU7QUF4Q25HLG9EQUFtRDtBQXdDeUcsc0JBeENuSix5QkFBVyxDQXdDbUo7QUF2Q3ZLLG1EQUE4RDtBQXVDMkcsc0JBdkNoSyx5QkFBVyxDQXVDZ0s7QUFBcUMscUJBdkNuTSx3QkFBVSxDQXVDbU07QUFuQ25POzs7O0dBSUc7QUFFSCxtQ0FBcUM7QUE2QjVCLDBCQUFPO0FBM0JoQix1QkFBdUI7QUFDdkIsNkJBQTJCO0FBQzNCLGlCQUFlO0FBRWYsNkNBQXdEO0FBdUI3QixtQkF2Qkgsc0JBQVEsQ0F1Qkc7QUFyQm5DLCtCQUErQjtBQUMvQixPQUFPLENBQUMsZUFBZSxDQUFDLEtBQUssRUFBRSxDQUFDO0FBQ2hDLDJCQUFhLEVBQUUsQ0FBQztBQUVoQiw4Q0FBOEM7QUFDOUMsSUFBSSxXQUFXLEdBQVksdUJBQWEsQ0FBQyxXQUFXLENBQUM7QUFnQmdELGtDQUFXO0FBZGhIOztHQUVHO0FBQ0g7SUFDSSw2QkFBYSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ3hCLHVCQUFhLENBQUMsT0FBTyxFQUFFLENBQUM7SUFDeEIsbUNBQWdCLENBQUMsT0FBTyxFQUFFLENBQUM7QUFDL0IsQ0FBQztBQU8rSSxnQ0FBVTtBQUwxSixJQUFNLE9BQU8sR0FBRyx1QkFBYSxDQUFDLE9BQU8sQ0FBQztBQUtwQiwwQkFBTztBQUh6QixPQUFPLENBQUMsR0FBRyxDQUFDLHNCQUFzQixHQUFHLE9BQU8sR0FBRyxHQUFHLENBQUMsQ0FBQztBQUlwRCxnREFBZ0Q7QUFDaEQscUNBQWdDIn0=
  115750. /***/ }),
  115751. /* 18 */
  115752. /***/ (function(module, exports) {
  115753. var g;
  115754. // This works in non-strict mode
  115755. g = (function() {
  115756. return this;
  115757. })();
  115758. try {
  115759. // This works if eval is allowed (see CSP)
  115760. g = g || Function("return this")() || (1,eval)("this");
  115761. } catch(e) {
  115762. // This works if the window reference is available
  115763. if(typeof window === "object")
  115764. g = window;
  115765. }
  115766. // g can still be undefined, but nothing to do about it...
  115767. // We return undefined, instead of nothing here, so it's
  115768. // easier to handle this case. if(!global) { ...}
  115769. module.exports = g;
  115770. /***/ }),
  115771. /* 19 */
  115772. /***/ (function(module, exports) {
  115773. if(typeof CANNON === 'undefined') {var e = new Error("Cannot find module \"CANNON\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  115774. module.exports = CANNON;
  115775. /***/ }),
  115776. /* 20 */
  115777. /***/ (function(module, exports) {
  115778. if(typeof OIMO === 'undefined') {var e = new Error("Cannot find module \"OIMO\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  115779. module.exports = OIMO;
  115780. /***/ }),
  115781. /* 21 */
  115782. /***/ (function(module, exports) {
  115783. if(typeof earcut === 'undefined') {var e = new Error("Cannot find module \"earcut\""); e.code = 'MODULE_NOT_FOUND'; throw e;}
  115784. module.exports = earcut;
  115785. /***/ }),
  115786. /* 22 */
  115787. /***/ (function(module, __webpack_exports__, __webpack_require__) {
  115788. "use strict";
  115789. Object.defineProperty(__webpack_exports__, "__esModule", { value: true });
  115790. var isMergeableObject = function isMergeableObject(value) {
  115791. return isNonNullObject(value)
  115792. && !isSpecial(value)
  115793. };
  115794. function isNonNullObject(value) {
  115795. return !!value && typeof value === 'object'
  115796. }
  115797. function isSpecial(value) {
  115798. var stringValue = Object.prototype.toString.call(value);
  115799. return stringValue === '[object RegExp]'
  115800. || stringValue === '[object Date]'
  115801. || isReactElement(value)
  115802. }
  115803. // see https://github.com/facebook/react/blob/b5ac963fb791d1298e7f396236383bc955f916c1/src/isomorphic/classic/element/ReactElement.js#L21-L25
  115804. var canUseSymbol = typeof Symbol === 'function' && Symbol.for;
  115805. var REACT_ELEMENT_TYPE = canUseSymbol ? Symbol.for('react.element') : 0xeac7;
  115806. function isReactElement(value) {
  115807. return value.$$typeof === REACT_ELEMENT_TYPE
  115808. }
  115809. function emptyTarget(val) {
  115810. return Array.isArray(val) ? [] : {}
  115811. }
  115812. function cloneUnlessOtherwiseSpecified(value, options) {
  115813. return (options.clone !== false && options.isMergeableObject(value))
  115814. ? deepmerge(emptyTarget(value), value, options)
  115815. : value
  115816. }
  115817. function defaultArrayMerge(target, source, options) {
  115818. return target.concat(source).map(function(element) {
  115819. return cloneUnlessOtherwiseSpecified(element, options)
  115820. })
  115821. }
  115822. function mergeObject(target, source, options) {
  115823. var destination = {};
  115824. if (options.isMergeableObject(target)) {
  115825. Object.keys(target).forEach(function(key) {
  115826. destination[key] = cloneUnlessOtherwiseSpecified(target[key], options);
  115827. });
  115828. }
  115829. Object.keys(source).forEach(function(key) {
  115830. if (!options.isMergeableObject(source[key]) || !target[key]) {
  115831. destination[key] = cloneUnlessOtherwiseSpecified(source[key], options);
  115832. } else {
  115833. destination[key] = deepmerge(target[key], source[key], options);
  115834. }
  115835. });
  115836. return destination
  115837. }
  115838. function deepmerge(target, source, options) {
  115839. options = options || {};
  115840. options.arrayMerge = options.arrayMerge || defaultArrayMerge;
  115841. options.isMergeableObject = options.isMergeableObject || isMergeableObject;
  115842. var sourceIsArray = Array.isArray(source);
  115843. var targetIsArray = Array.isArray(target);
  115844. var sourceAndTargetTypesMatch = sourceIsArray === targetIsArray;
  115845. if (!sourceAndTargetTypesMatch) {
  115846. return cloneUnlessOtherwiseSpecified(source, options)
  115847. } else if (sourceIsArray) {
  115848. return options.arrayMerge(target, source, options)
  115849. } else {
  115850. return mergeObject(target, source, options)
  115851. }
  115852. }
  115853. deepmerge.all = function deepmergeAll(array, options) {
  115854. if (!Array.isArray(array)) {
  115855. throw new Error('first argument should be an array')
  115856. }
  115857. return array.reduce(function(prev, next) {
  115858. return deepmerge(prev, next, options)
  115859. }, {})
  115860. };
  115861. var deepmerge_1 = deepmerge;
  115862. /* harmony default export */ __webpack_exports__["default"] = (deepmerge_1);
  115863. /***/ }),
  115864. /* 23 */
  115865. /***/ (function(module, exports, __webpack_require__) {
  115866. "use strict";
  115867. Object.defineProperty(exports, "__esModule", { value: true });
  115868. var babylonjs_1 = __webpack_require__(0);
  115869. var configuration_1 = __webpack_require__(10);
  115870. var viewerModel_1 = __webpack_require__(5);
  115871. var helper_1 = __webpack_require__(1);
  115872. var viewerLabs_1 = __webpack_require__(25);
  115873. var _1 = __webpack_require__(27);
  115874. var SceneManager = /** @class */ (function () {
  115875. function SceneManager(_engine, _configurationContainer, _observablesManager) {
  115876. var _this = this;
  115877. this._engine = _engine;
  115878. this._configurationContainer = _configurationContainer;
  115879. this._observablesManager = _observablesManager;
  115880. this._animationBlendingEnabled = true;
  115881. this._white = babylonjs_1.Color3.White();
  115882. this._forceShadowUpdate = false;
  115883. this._processShadows = true;
  115884. this._groundEnabled = true;
  115885. this._groundMirrorEnabled = true;
  115886. this._defaultRenderingPipelineEnabled = false;
  115887. this._globalConfiguration = {};
  115888. this._defaultRenderingPipelineShouldBuild = true;
  115889. // default from rendering pipeline
  115890. this._bloomEnabled = false;
  115891. // default from rendering pipeline
  115892. this._fxaaEnabled = false;
  115893. this._focusOnModel = function (model) {
  115894. var boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  115895. var sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  115896. var halfSizeVec = sizeVec.scale(0.5);
  115897. var center = boundingInfo.min.add(halfSizeVec);
  115898. _this.camera.setTarget(center);
  115899. _this.camera.alpha = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.alpha) || _this.camera.alpha;
  115900. _this.camera.beta = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.beta) || _this.camera.beta;
  115901. _this.camera.radius = (_this._globalConfiguration.camera && _this._globalConfiguration.camera.radius) || _this.camera.radius;
  115902. var sceneDiagonalLenght = sizeVec.length();
  115903. if (isFinite(sceneDiagonalLenght))
  115904. _this.camera.upperRadiusLimit = sceneDiagonalLenght * 4;
  115905. if (_this._configurationContainer.configuration)
  115906. _this._configureEnvironment(_this._configurationContainer.configuration.skybox, _this._configurationContainer.configuration.ground);
  115907. /*this.scene.lights.filter(light => light instanceof ShadowLight).forEach(light => {
  115908. // casting ais safe, due to the constraints tested before
  115909. (<ShadowLight>light).setDirectionToTarget(center);
  115910. });*/
  115911. };
  115912. this._cameraBehaviorMapping = {};
  115913. this.models = [];
  115914. this.onCameraConfiguredObservable = new babylonjs_1.Observable();
  115915. this.onLightsConfiguredObservable = new babylonjs_1.Observable();
  115916. this.onModelsConfiguredObservable = new babylonjs_1.Observable();
  115917. this.onSceneConfiguredObservable = new babylonjs_1.Observable();
  115918. this.onSceneInitObservable = new babylonjs_1.Observable();
  115919. this.onSceneOptimizerConfiguredObservable = new babylonjs_1.Observable();
  115920. this.onEnvironmentConfiguredObservable = new babylonjs_1.Observable();
  115921. this.onVRConfiguredObservable = new babylonjs_1.Observable();
  115922. //this._viewer.onEngineInitObservable.add(() => {
  115923. this._handleHardwareLimitations();
  115924. //});
  115925. this.onSceneInitObservable.add(function (scene) {
  115926. _this.scene.animationPropertiesOverride = _this.scene.animationPropertiesOverride || new babylonjs_1.AnimationPropertiesOverride();
  115927. _this.labs = new viewerLabs_1.ViewerLabs(scene);
  115928. var updateShadows = function () {
  115929. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  115930. var light = _a[_i];
  115931. var generator = light.getShadowGenerator();
  115932. if (generator) {
  115933. // Processing shadows if animates
  115934. var shadowMap = generator.getShadowMap();
  115935. if (shadowMap) {
  115936. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  115937. }
  115938. }
  115939. }
  115940. };
  115941. scene.registerBeforeRender(function () {
  115942. if (_this._forceShadowUpdate || (scene.animatables && scene.animatables.length > 0)) {
  115943. // make sure all models are loaded
  115944. updateShadows();
  115945. _this._forceShadowUpdate = false;
  115946. }
  115947. else if (!(_this.models.every(function (model) {
  115948. if (!model.shadowsRenderedAfterLoad) {
  115949. model.shadowsRenderedAfterLoad = true;
  115950. return false;
  115951. }
  115952. return model.state === viewerModel_1.ModelState.COMPLETE && !model.currentAnimation;
  115953. }))) {
  115954. updateShadows();
  115955. }
  115956. });
  115957. return _this._observablesManager && _this._observablesManager.onSceneInitObservable.notifyObserversWithPromise(_this.scene);
  115958. });
  115959. if (this._observablesManager) {
  115960. this._observablesManager.onModelLoadedObservable.add(function (model) {
  115961. for (var _i = 0, _a = _this.scene.lights; _i < _a.length; _i++) {
  115962. var light = _a[_i];
  115963. var generator = light.getShadowGenerator();
  115964. if (generator) {
  115965. // Processing shadows if animates
  115966. var shadowMap = generator.getShadowMap();
  115967. if (shadowMap) {
  115968. shadowMap.refreshRate = babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  115969. }
  115970. }
  115971. }
  115972. _this._focusOnModel(model);
  115973. });
  115974. this._observablesManager.onModelAddedObservable.add(function (model) {
  115975. _this.models.push(model);
  115976. });
  115977. this._observablesManager.onModelRemovedObservable.add(function (model) {
  115978. _this.models.splice(_this.models.indexOf(model), 1);
  115979. });
  115980. }
  115981. }
  115982. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipeline", {
  115983. get: function () {
  115984. return this._defaultRenderingPipeline;
  115985. },
  115986. enumerable: true,
  115987. configurable: true
  115988. });
  115989. Object.defineProperty(SceneManager.prototype, "vrHelper", {
  115990. get: function () {
  115991. return this._vrHelper;
  115992. },
  115993. enumerable: true,
  115994. configurable: true
  115995. });
  115996. Object.defineProperty(SceneManager.prototype, "isHdrSupported", {
  115997. /**
  115998. * Returns a boolean representing HDR support
  115999. */
  116000. get: function () {
  116001. return this._hdrSupport;
  116002. },
  116003. enumerable: true,
  116004. configurable: true
  116005. });
  116006. Object.defineProperty(SceneManager.prototype, "mainColor", {
  116007. /**
  116008. * Return the main color defined in the configuration.
  116009. */
  116010. get: function () {
  116011. return this._configurationContainer.mainColor;
  116012. },
  116013. enumerable: true,
  116014. configurable: true
  116015. });
  116016. Object.defineProperty(SceneManager.prototype, "reflectionColor", {
  116017. get: function () {
  116018. return this._configurationContainer.reflectionColor;
  116019. },
  116020. enumerable: true,
  116021. configurable: true
  116022. });
  116023. Object.defineProperty(SceneManager.prototype, "animationBlendingEnabled", {
  116024. get: function () {
  116025. return this.scene && this.scene.animationPropertiesOverride.enableBlending;
  116026. },
  116027. set: function (value) {
  116028. this.scene.animationPropertiesOverride.enableBlending = value;
  116029. },
  116030. enumerable: true,
  116031. configurable: true
  116032. });
  116033. Object.defineProperty(SceneManager.prototype, "observablesManager", {
  116034. get: function () {
  116035. return this._observablesManager;
  116036. },
  116037. enumerable: true,
  116038. configurable: true
  116039. });
  116040. Object.defineProperty(SceneManager.prototype, "processShadows", {
  116041. /**
  116042. * The flag defining whether shadows are rendered constantly or once.
  116043. */
  116044. get: function () {
  116045. return this._processShadows;
  116046. },
  116047. /**
  116048. * Should shadows be rendered every frame, or only once and stop.
  116049. * This can be used to optimize a scene.
  116050. *
  116051. * Not that the shadows will NOT disapear but will remain in place.
  116052. * @param process if true shadows will be updated once every frame. if false they will stop being updated.
  116053. */
  116054. set: function (process) {
  116055. var refreshType = process ? babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONEVERYFRAME : babylonjs_1.RenderTargetTexture.REFRESHRATE_RENDER_ONCE;
  116056. for (var _i = 0, _a = this.scene.lights; _i < _a.length; _i++) {
  116057. var light = _a[_i];
  116058. var generator = light.getShadowGenerator();
  116059. if (generator) {
  116060. var shadowMap = generator.getShadowMap();
  116061. if (shadowMap) {
  116062. shadowMap.refreshRate = refreshType;
  116063. }
  116064. }
  116065. }
  116066. this._processShadows = process;
  116067. },
  116068. enumerable: true,
  116069. configurable: true
  116070. });
  116071. Object.defineProperty(SceneManager.prototype, "groundEnabled", {
  116072. get: function () {
  116073. return this._groundEnabled;
  116074. },
  116075. set: function (newValue) {
  116076. if (newValue === this._groundEnabled)
  116077. return;
  116078. this._groundEnabled = newValue;
  116079. if (this.environmentHelper && this.environmentHelper.ground) {
  116080. this.environmentHelper.ground.setEnabled(this._groundEnabled);
  116081. }
  116082. },
  116083. enumerable: true,
  116084. configurable: true
  116085. });
  116086. Object.defineProperty(SceneManager.prototype, "groundMirrorEnabled", {
  116087. /**
  116088. * gets wether the reflection is disabled.
  116089. */
  116090. get: function () {
  116091. return this._groundMirrorEnabled;
  116092. },
  116093. /**
  116094. * sets wether the reflection is disabled.
  116095. */
  116096. set: function (value) {
  116097. if (this._groundMirrorEnabled === value) {
  116098. return;
  116099. }
  116100. this._groundMirrorEnabled = value;
  116101. if (this.environmentHelper && this.environmentHelper.groundMaterial && this.environmentHelper.groundMirror) {
  116102. if (!value) {
  116103. this.environmentHelper.groundMaterial.reflectionTexture = null;
  116104. }
  116105. else {
  116106. this.environmentHelper.groundMaterial.reflectionTexture = this.environmentHelper.groundMirror;
  116107. }
  116108. }
  116109. },
  116110. enumerable: true,
  116111. configurable: true
  116112. });
  116113. Object.defineProperty(SceneManager.prototype, "defaultRenderingPipelineEnabled", {
  116114. get: function () {
  116115. return this._defaultRenderingPipelineEnabled;
  116116. },
  116117. set: function (value) {
  116118. if (value === this._defaultRenderingPipelineEnabled) {
  116119. return;
  116120. }
  116121. this._defaultRenderingPipelineEnabled = value;
  116122. this._rebuildPostprocesses();
  116123. if (this._defaultRenderingPipeline) {
  116124. this._defaultRenderingPipelineShouldBuild = false;
  116125. this._defaultRenderingPipeline.prepare();
  116126. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116127. }
  116128. },
  116129. enumerable: true,
  116130. configurable: true
  116131. });
  116132. /**
  116133. * Sets the engine flags to unlock all babylon features.
  116134. * Can also be configured using the scene.flags configuration object
  116135. */
  116136. SceneManager.prototype.unlockBabylonFeatures = function () {
  116137. this.scene.shadowsEnabled = true;
  116138. this.scene.particlesEnabled = true;
  116139. this.scene.postProcessesEnabled = true;
  116140. this.scene.collisionsEnabled = true;
  116141. this.scene.lightsEnabled = true;
  116142. this.scene.texturesEnabled = true;
  116143. this.scene.lensFlaresEnabled = true;
  116144. this.scene.proceduralTexturesEnabled = true;
  116145. this.scene.renderTargetsEnabled = true;
  116146. this.scene.spritesEnabled = true;
  116147. this.scene.skeletonsEnabled = true;
  116148. this.scene.audioEnabled = true;
  116149. };
  116150. /**
  116151. * initialize the scene. Calling this function again will dispose the old scene, if exists.
  116152. */
  116153. SceneManager.prototype.initScene = function (sceneConfiguration, optimizerConfiguration) {
  116154. if (sceneConfiguration === void 0) { sceneConfiguration = {}; }
  116155. // if the scen exists, dispose it.
  116156. if (this.scene) {
  116157. this.scene.dispose();
  116158. }
  116159. // create a new scene
  116160. this.scene = new babylonjs_1.Scene(this._engine);
  116161. this._configurationContainer.scene = this.scene;
  116162. // set a default PBR material
  116163. if (!sceneConfiguration.defaultMaterial) {
  116164. var defaultMaterial = new BABYLON.PBRMaterial('defaultMaterial', this.scene);
  116165. defaultMaterial.reflectivityColor = new BABYLON.Color3(0.1, 0.1, 0.1);
  116166. defaultMaterial.microSurface = 0.6;
  116167. if (this.scene.defaultMaterial) {
  116168. this.scene.defaultMaterial.dispose();
  116169. }
  116170. this.scene.defaultMaterial = defaultMaterial;
  116171. }
  116172. this.scene.animationPropertiesOverride = new babylonjs_1.AnimationPropertiesOverride();
  116173. babylonjs_1.Animation.AllowMatricesInterpolation = true;
  116174. /*if (sceneConfiguration.glow) {
  116175. let options: Partial<IGlowLayerOptions> = {
  116176. mainTextureFixedSize: 512
  116177. };
  116178. if (typeof sceneConfiguration.glow === 'object') {
  116179. options = sceneConfiguration.glow
  116180. }
  116181. var gl = new BABYLON.GlowLayer("glow", this.scene, options);
  116182. }*/
  116183. return this.onSceneInitObservable.notifyObserversWithPromise(this.scene);
  116184. };
  116185. SceneManager.prototype.clearScene = function (clearModels, clearLights) {
  116186. if (clearModels === void 0) { clearModels = true; }
  116187. if (clearLights === void 0) { clearLights = false; }
  116188. if (clearModels) {
  116189. this.models.forEach(function (m) { return m.dispose(); });
  116190. this.models.length = 0;
  116191. }
  116192. if (clearLights) {
  116193. this.scene.lights.forEach(function (l) { return l.dispose(); });
  116194. }
  116195. };
  116196. /**
  116197. * This will update the scene's configuration, including camera, lights, environment.
  116198. * @param newConfiguration the delta that should be configured. This includes only the changes
  116199. * @param globalConfiguration The global configuration object, after the new configuration was merged into it
  116200. */
  116201. SceneManager.prototype.updateConfiguration = function (newConfiguration) {
  116202. var _this = this;
  116203. if (this._configurationContainer) {
  116204. this._globalConfiguration = this._configurationContainer.configuration;
  116205. }
  116206. else {
  116207. this._globalConfiguration = newConfiguration;
  116208. }
  116209. if (newConfiguration.lab) {
  116210. if (newConfiguration.lab.assetsRootURL) {
  116211. this.labs.assetsRootURL = newConfiguration.lab.assetsRootURL;
  116212. }
  116213. }
  116214. // update scene configuration
  116215. if (newConfiguration.scene) {
  116216. this._configureScene(newConfiguration.scene);
  116217. }
  116218. // optimizer
  116219. if (newConfiguration.optimizer !== undefined) {
  116220. this._configureOptimizer(newConfiguration.optimizer);
  116221. }
  116222. // configure model
  116223. /*if (newConfiguration.model && typeof newConfiguration.model === 'object') {
  116224. this._configureModel(newConfiguration.model);
  116225. }*/
  116226. // lights
  116227. this._configureLights(newConfiguration.lights);
  116228. // environment
  116229. if (newConfiguration.skybox !== undefined || newConfiguration.ground !== undefined) {
  116230. this._configureEnvironment(newConfiguration.skybox, newConfiguration.ground);
  116231. }
  116232. // camera
  116233. this._configureCamera(newConfiguration.camera);
  116234. if (newConfiguration.vr !== undefined) {
  116235. this._configureVR(newConfiguration.vr);
  116236. }
  116237. if (newConfiguration.lab) {
  116238. if (newConfiguration.lab.environmentMap) {
  116239. var rot_1 = newConfiguration.lab.environmentMap.rotationY;
  116240. this.labs.loadEnvironment(newConfiguration.lab.environmentMap.texture, function () {
  116241. _this.labs.applyEnvironmentMapConfiguration(rot_1);
  116242. });
  116243. if (!newConfiguration.lab.environmentMap.texture && newConfiguration.lab.environmentMap.rotationY) {
  116244. this.labs.applyEnvironmentMapConfiguration(newConfiguration.lab.environmentMap.rotationY);
  116245. }
  116246. }
  116247. // rendering piplines
  116248. if (newConfiguration.lab.defaultRenderingPipelines) {
  116249. var pipelineConfig = newConfiguration.lab.defaultRenderingPipelines;
  116250. if (typeof pipelineConfig === 'boolean') {
  116251. this.defaultRenderingPipelineEnabled = pipelineConfig;
  116252. }
  116253. else {
  116254. this.defaultRenderingPipelineEnabled = true;
  116255. }
  116256. }
  116257. if (this.environmentHelper && newConfiguration.lab.environmentMainColor) {
  116258. var mainColor = new babylonjs_1.Color3().copyFrom(newConfiguration.lab.environmentMainColor);
  116259. this.environmentHelper.setMainColor(mainColor);
  116260. }
  116261. if (newConfiguration.lab.globalLightRotation !== undefined) {
  116262. // rotate all lights that are shadow lights
  116263. this.scene.lights.filter(function (light) { return light instanceof babylonjs_1.ShadowLight; }).forEach(function (light) {
  116264. // casting and '!' are safe, due to the constraints tested before
  116265. _this.labs.rotateShadowLight(light, newConfiguration.lab.globalLightRotation);
  116266. });
  116267. this._forceShadowUpdate = true;
  116268. }
  116269. }
  116270. if (this._defaultRenderingPipeline && this._defaultRenderingPipeline.imageProcessing) {
  116271. this._defaultRenderingPipeline.imageProcessing.fromLinearSpace = true;
  116272. }
  116273. if (this._defaultRenderingPipelineShouldBuild && this._defaultRenderingPipeline) {
  116274. this._defaultRenderingPipelineShouldBuild = false;
  116275. this._defaultRenderingPipeline.prepare();
  116276. }
  116277. };
  116278. SceneManager.prototype._rebuildPostprocesses = function (configuration) {
  116279. if (!this._defaultRenderingPipelineEnabled || !configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", this._globalConfiguration)) {
  116280. if (this._defaultRenderingPipeline) {
  116281. this._defaultRenderingPipeline.dispose();
  116282. this._defaultRenderingPipeline = null;
  116283. this.scene.autoClearDepthAndStencil = true;
  116284. this.scene.autoClear = true;
  116285. this.scene.imageProcessingConfiguration.applyByPostProcess = false;
  116286. }
  116287. return;
  116288. }
  116289. var pipelineConfig = configuration || (this._globalConfiguration.lab && this._globalConfiguration.lab.defaultRenderingPipelines);
  116290. if (pipelineConfig) {
  116291. if (!this._defaultRenderingPipeline) {
  116292. // Create pipeline in manual mode to avoid triggering multiple shader compilations
  116293. this._defaultRenderingPipeline = new babylonjs_1.DefaultRenderingPipeline("default rendering pipeline", this._hdrSupport, this.scene, [this.camera], false);
  116294. }
  116295. this.scene.autoClear = false;
  116296. this.scene.autoClearDepthAndStencil = false;
  116297. this._defaultRenderingPipelineShouldBuild = true;
  116298. var bloomEnabled = this._bloomEnabled;
  116299. if (typeof pipelineConfig !== 'boolean') {
  116300. helper_1.extendClassWithConfig(this._defaultRenderingPipeline, pipelineConfig);
  116301. this._bloomEnabled = !!pipelineConfig.bloomEnabled;
  116302. this._fxaaEnabled = !!pipelineConfig.fxaaEnabled;
  116303. bloomEnabled = this._bloomEnabled && pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight > 0;
  116304. this._defaultRenderingPipeline.bloomWeight = (pipelineConfig.bloomWeight !== undefined && pipelineConfig.bloomWeight) || (this._defaultRenderingPipeline.bloomWeight);
  116305. }
  116306. this._defaultRenderingPipeline.bloomEnabled = bloomEnabled;
  116307. this._defaultRenderingPipeline.fxaaEnabled = this.fxaaEnabled;
  116308. }
  116309. };
  116310. Object.defineProperty(SceneManager.prototype, "bloomEnabled", {
  116311. get: function () {
  116312. return this._bloomEnabled;
  116313. },
  116314. set: function (value) {
  116315. if (this._bloomEnabled === value) {
  116316. return;
  116317. }
  116318. this._bloomEnabled = value;
  116319. this._rebuildPostprocesses();
  116320. if (this._defaultRenderingPipeline) {
  116321. this._defaultRenderingPipelineShouldBuild = false;
  116322. this._defaultRenderingPipeline.prepare();
  116323. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116324. }
  116325. },
  116326. enumerable: true,
  116327. configurable: true
  116328. });
  116329. Object.defineProperty(SceneManager.prototype, "fxaaEnabled", {
  116330. get: function () {
  116331. return this._fxaaEnabled;
  116332. },
  116333. set: function (value) {
  116334. if (this._fxaaEnabled === value) {
  116335. return;
  116336. }
  116337. this._fxaaEnabled = value;
  116338. this._rebuildPostprocesses();
  116339. if (this._defaultRenderingPipeline) {
  116340. this._defaultRenderingPipelineShouldBuild = false;
  116341. this._defaultRenderingPipeline.prepare();
  116342. this.scene.imageProcessingConfiguration.applyByPostProcess = true;
  116343. }
  116344. },
  116345. enumerable: true,
  116346. configurable: true
  116347. });
  116348. /**
  116349. * internally configure the scene using the provided configuration.
  116350. * The scene will not be recreated, but just updated.
  116351. * @param sceneConfig the (new) scene configuration
  116352. */
  116353. SceneManager.prototype._configureScene = function (sceneConfig) {
  116354. // sanity check!
  116355. if (!this.scene) {
  116356. return;
  116357. }
  116358. var cc = sceneConfig.clearColor;
  116359. var oldcc = this.scene.clearColor;
  116360. if (cc) {
  116361. if (cc.r !== undefined) {
  116362. oldcc.r = cc.r;
  116363. }
  116364. if (cc.g !== undefined) {
  116365. oldcc.g = cc.g;
  116366. }
  116367. if (cc.b !== undefined) {
  116368. oldcc.b = cc.b;
  116369. }
  116370. if (cc.a !== undefined) {
  116371. oldcc.a = cc.a;
  116372. }
  116373. }
  116374. // image processing configuration - optional.
  116375. if (sceneConfig.imageProcessingConfiguration) {
  116376. helper_1.extendClassWithConfig(this.scene.imageProcessingConfiguration, sceneConfig.imageProcessingConfiguration);
  116377. }
  116378. //animation properties override
  116379. if (sceneConfig.animationPropertiesOverride) {
  116380. helper_1.extendClassWithConfig(this.scene.animationPropertiesOverride, sceneConfig.animationPropertiesOverride);
  116381. }
  116382. if (sceneConfig.environmentTexture) {
  116383. if (!(this.scene.environmentTexture && this.scene.environmentTexture.url === sceneConfig.environmentTexture)) {
  116384. if (this.scene.environmentTexture && this.scene.environmentTexture.dispose) {
  116385. this.scene.environmentTexture.dispose();
  116386. }
  116387. var environmentTexture = babylonjs_1.CubeTexture.CreateFromPrefilteredData(sceneConfig.environmentTexture, this.scene);
  116388. this.scene.environmentTexture = environmentTexture;
  116389. }
  116390. }
  116391. if (sceneConfig.debug === true) {
  116392. this.scene.debugLayer.show();
  116393. }
  116394. else if (sceneConfig.debug === false) {
  116395. if (this.scene.debugLayer.isVisible()) {
  116396. this.scene.debugLayer.hide();
  116397. }
  116398. }
  116399. if (sceneConfig.disableHdr) {
  116400. this._handleHardwareLimitations(false);
  116401. }
  116402. else {
  116403. this._handleHardwareLimitations(true);
  116404. }
  116405. if (sceneConfig.renderInBackground !== undefined) {
  116406. this._engine.renderEvenInBackground = !!sceneConfig.renderInBackground;
  116407. }
  116408. var canvas = this._engine.getRenderingCanvas();
  116409. if (canvas) {
  116410. if (this.camera && sceneConfig.disableCameraControl) {
  116411. this.camera.detachControl(canvas);
  116412. }
  116413. else if (this.camera && sceneConfig.disableCameraControl === false) {
  116414. this.camera.attachControl(canvas);
  116415. }
  116416. }
  116417. // process mainColor changes:
  116418. if (sceneConfig.mainColor) {
  116419. this._configurationContainer.mainColor = this.mainColor || babylonjs_1.Color3.White();
  116420. var mc = sceneConfig.mainColor;
  116421. if (mc.r !== undefined) {
  116422. this.mainColor.r = mc.r;
  116423. }
  116424. if (mc.g !== undefined) {
  116425. this.mainColor.g = mc.g;
  116426. }
  116427. if (mc.b !== undefined) {
  116428. this.mainColor.b = mc.b;
  116429. }
  116430. this.reflectionColor.copyFrom(this.mainColor);
  116431. var environmentTint = configuration_1.getConfigurationKey("lab.environmentMap.tintLevel", this._globalConfiguration) || 0;
  116432. // reflection color
  116433. this.reflectionColor.toLinearSpaceToRef(this.reflectionColor);
  116434. this.reflectionColor.scaleToRef(1 / this.scene.imageProcessingConfiguration.exposure, this.reflectionColor);
  116435. var tmpColor3 = babylonjs_1.Color3.Lerp(this._white, this.reflectionColor, environmentTint);
  116436. this.reflectionColor.copyFrom(tmpColor3);
  116437. //update the environment, if exists
  116438. if (this.environmentHelper) {
  116439. if (this.environmentHelper.groundMaterial) {
  116440. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  116441. }
  116442. if (this.environmentHelper.skyboxMaterial) {
  116443. this.environmentHelper.skyboxMaterial._perceptualColor = this.mainColor;
  116444. }
  116445. }
  116446. }
  116447. if (sceneConfig.defaultMaterial) {
  116448. var conf = sceneConfig.defaultMaterial;
  116449. if ((conf.materialType === 'standard' && this.scene.defaultMaterial.getClassName() !== 'StandardMaterial') ||
  116450. (conf.materialType === 'pbr' && this.scene.defaultMaterial.getClassName() !== 'PBRMaterial')) {
  116451. this.scene.defaultMaterial.dispose();
  116452. if (conf.materialType === 'standard') {
  116453. this.scene.defaultMaterial = new babylonjs_1.StandardMaterial("defaultMaterial", this.scene);
  116454. }
  116455. else {
  116456. this.scene.defaultMaterial = new babylonjs_1.PBRMaterial("defaultMaterial", this.scene);
  116457. }
  116458. }
  116459. helper_1.extendClassWithConfig(this.scene.defaultMaterial, conf);
  116460. }
  116461. if (sceneConfig.flags) {
  116462. helper_1.extendClassWithConfig(this.scene, sceneConfig.flags);
  116463. }
  116464. this.onSceneConfiguredObservable.notifyObservers({
  116465. sceneManager: this,
  116466. object: this.scene,
  116467. newConfiguration: sceneConfig
  116468. });
  116469. };
  116470. /**
  116471. * Configure the scene optimizer.
  116472. * The existing scene optimizer will be disposed and a new one will be created.
  116473. * @param optimizerConfig the (new) optimizer configuration
  116474. */
  116475. SceneManager.prototype._configureOptimizer = function (optimizerConfig) {
  116476. var _this = this;
  116477. if (typeof optimizerConfig === 'boolean') {
  116478. if (this.sceneOptimizer) {
  116479. this.sceneOptimizer.stop();
  116480. this.sceneOptimizer.dispose();
  116481. delete this.sceneOptimizer;
  116482. }
  116483. if (optimizerConfig) {
  116484. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene);
  116485. this.sceneOptimizer.start();
  116486. }
  116487. }
  116488. else {
  116489. var optimizerOptions = new babylonjs_1.SceneOptimizerOptions(optimizerConfig.targetFrameRate, optimizerConfig.trackerDuration);
  116490. // check for degradation
  116491. if (optimizerConfig.degradation) {
  116492. switch (optimizerConfig.degradation) {
  116493. case "low":
  116494. optimizerOptions = babylonjs_1.SceneOptimizerOptions.LowDegradationAllowed(optimizerConfig.targetFrameRate);
  116495. break;
  116496. case "moderate":
  116497. optimizerOptions = babylonjs_1.SceneOptimizerOptions.ModerateDegradationAllowed(optimizerConfig.targetFrameRate);
  116498. break;
  116499. case "hight":
  116500. optimizerOptions = babylonjs_1.SceneOptimizerOptions.HighDegradationAllowed(optimizerConfig.targetFrameRate);
  116501. break;
  116502. }
  116503. }
  116504. if (this.sceneOptimizer) {
  116505. this.sceneOptimizer.stop();
  116506. this.sceneOptimizer.dispose();
  116507. }
  116508. if (optimizerConfig.custom) {
  116509. var customOptimizer_1 = _1.getCustomOptimizerByName(optimizerConfig.custom, optimizerConfig.improvementMode);
  116510. if (customOptimizer_1) {
  116511. optimizerOptions.addCustomOptimization(function () {
  116512. return customOptimizer_1(_this);
  116513. }, function () {
  116514. return "Babylon Viewer " + optimizerConfig.custom + " custom optimization";
  116515. });
  116516. }
  116517. }
  116518. this.sceneOptimizer = new babylonjs_1.SceneOptimizer(this.scene, optimizerOptions, optimizerConfig.autoGeneratePriorities, optimizerConfig.improvementMode);
  116519. this.sceneOptimizer.start();
  116520. }
  116521. this.onSceneOptimizerConfiguredObservable.notifyObservers({
  116522. sceneManager: this,
  116523. object: this.sceneOptimizer,
  116524. newConfiguration: optimizerConfig
  116525. });
  116526. };
  116527. /**
  116528. * configure all models using the configuration.
  116529. * @param modelConfiguration the configuration to use to reconfigure the models
  116530. */
  116531. /*protected _configureModel(modelConfiguration: Partial<IModelConfiguration>) {
  116532. this.models.forEach(model => {
  116533. model.updateConfiguration(modelConfiguration);
  116534. });
  116535. this.onModelsConfiguredObservable.notifyObservers({
  116536. sceneManager: this,
  116537. object: this.models,
  116538. newConfiguration: modelConfiguration
  116539. });
  116540. }*/
  116541. SceneManager.prototype._configureVR = function (vrConfig) {
  116542. var _this = this;
  116543. if (vrConfig.disabled) {
  116544. if (this._vrHelper) {
  116545. if (this._vrHelper.isInVRMode) {
  116546. this._vrHelper.exitVR();
  116547. }
  116548. this._vrHelper.dispose();
  116549. this._vrHelper = undefined;
  116550. }
  116551. return;
  116552. }
  116553. var vrOptions = vrConfig.vrOptions || {
  116554. useCustomVRButton: true,
  116555. createDeviceOrientationCamera: false,
  116556. trackPosition: true
  116557. };
  116558. this._vrHelper = this.scene.createDefaultVRExperience(vrOptions);
  116559. if (!vrConfig.disableInteractions) {
  116560. this._vrHelper.enableInteractions();
  116561. }
  116562. if (!vrConfig.disableTeleportation) {
  116563. var floorMeshName = vrConfig.overrideFloorMeshName || "BackgroundPlane";
  116564. this._vrHelper.enableTeleportation({
  116565. floorMeshName: floorMeshName
  116566. });
  116567. }
  116568. var rotationOffset;
  116569. this._vrHelper.onControllerMeshLoadedObservable.add(function (controller) {
  116570. controller.onTriggerStateChangedObservable.add(function (data) {
  116571. if (controller.mesh && controller.mesh.rotationQuaternion) {
  116572. if (data.pressed) {
  116573. if (!rotationOffset) {
  116574. _this.models[0].rootMesh.rotationQuaternion = _this.models[0].rootMesh.rotationQuaternion || new babylonjs_1.Quaternion();
  116575. rotationOffset = controller.mesh.rotationQuaternion.conjugate().multiply(_this.models[0].rootMesh.rotationQuaternion);
  116576. }
  116577. }
  116578. else {
  116579. rotationOffset = null;
  116580. }
  116581. }
  116582. });
  116583. _this.scene.registerBeforeRender(function () {
  116584. if (_this.models[0]) {
  116585. if (rotationOffset && controller.mesh && controller.mesh.rotationQuaternion) {
  116586. _this.models[0].rootMesh.rotationQuaternion.copyFrom(controller.mesh.rotationQuaternion).multiplyInPlace(rotationOffset);
  116587. }
  116588. else {
  116589. _this.models[0].rootMesh.rotationQuaternion = null;
  116590. }
  116591. }
  116592. });
  116593. });
  116594. this.onVRConfiguredObservable.notifyObservers({
  116595. sceneManager: this,
  116596. object: this._vrHelper,
  116597. newConfiguration: vrConfig
  116598. });
  116599. };
  116600. /**
  116601. * (Re) configure the camera. The camera will only be created once and from this point will only be reconfigured.
  116602. * @param cameraConfig the new camera configuration
  116603. * @param model optionally use the model to configure the camera.
  116604. */
  116605. SceneManager.prototype._configureCamera = function (cameraConfig) {
  116606. var _this = this;
  116607. if (cameraConfig === void 0) { cameraConfig = {}; }
  116608. if (!this.scene.activeCamera) {
  116609. var attachControl = true;
  116610. if (this._globalConfiguration.scene && this._globalConfiguration.scene.disableCameraControl) {
  116611. attachControl = false;
  116612. }
  116613. this.scene.createDefaultCamera(true, true, attachControl);
  116614. this.camera = this.scene.activeCamera;
  116615. this.camera.setTarget(babylonjs_1.Vector3.Zero());
  116616. }
  116617. if (!this.camera) {
  116618. this.camera = this.scene.activeCamera;
  116619. }
  116620. if (cameraConfig.position) {
  116621. var newPosition = this.camera.position.clone();
  116622. helper_1.extendClassWithConfig(newPosition, cameraConfig.position);
  116623. this.camera.setPosition(newPosition);
  116624. }
  116625. if (cameraConfig.target) {
  116626. var newTarget = this.camera.target.clone();
  116627. helper_1.extendClassWithConfig(newTarget, cameraConfig.target);
  116628. this.camera.setTarget(newTarget);
  116629. } /*else if (this.models.length && !cameraConfig.disableAutoFocus) {
  116630. this._focusOnModel(this.models[0]);
  116631. }*/
  116632. if (cameraConfig.rotation) {
  116633. this.camera.rotationQuaternion = new babylonjs_1.Quaternion(cameraConfig.rotation.x || 0, cameraConfig.rotation.y || 0, cameraConfig.rotation.z || 0, cameraConfig.rotation.w || 0);
  116634. }
  116635. if (cameraConfig.behaviors) {
  116636. for (var name_1 in cameraConfig.behaviors) {
  116637. if (cameraConfig.behaviors[name_1] !== undefined) {
  116638. this._setCameraBehavior(name_1, cameraConfig.behaviors[name_1]);
  116639. }
  116640. }
  116641. }
  116642. ;
  116643. var sceneExtends = this.scene.getWorldExtends(function (mesh) {
  116644. return !_this.environmentHelper || (mesh !== _this.environmentHelper.ground && mesh !== _this.environmentHelper.rootMesh && mesh !== _this.environmentHelper.skybox);
  116645. });
  116646. var sceneDiagonal = sceneExtends.max.subtract(sceneExtends.min);
  116647. var sceneDiagonalLength = sceneDiagonal.length();
  116648. if (isFinite(sceneDiagonalLength)) {
  116649. this.camera.upperRadiusLimit = sceneDiagonalLength * 4;
  116650. }
  116651. // sanity check!
  116652. if (this.scene.imageProcessingConfiguration) {
  116653. this.scene.imageProcessingConfiguration.colorCurvesEnabled = true;
  116654. this.scene.imageProcessingConfiguration.vignetteEnabled = true;
  116655. this.scene.imageProcessingConfiguration.toneMappingEnabled = !!configuration_1.getConfigurationKey("camera.toneMappingEnabled", this._globalConfiguration);
  116656. }
  116657. helper_1.extendClassWithConfig(this.camera, cameraConfig);
  116658. this.onCameraConfiguredObservable.notifyObservers({
  116659. sceneManager: this,
  116660. object: this.camera,
  116661. newConfiguration: cameraConfig
  116662. });
  116663. };
  116664. SceneManager.prototype._configureEnvironment = function (skyboxConifguration, groundConfiguration) {
  116665. var _this = this;
  116666. if (!skyboxConifguration && !groundConfiguration) {
  116667. if (this.environmentHelper) {
  116668. this.environmentHelper.dispose();
  116669. this.environmentHelper = undefined;
  116670. }
  116671. ;
  116672. }
  116673. else {
  116674. var options = {
  116675. createGround: !!groundConfiguration && this._groundEnabled,
  116676. createSkybox: !!skyboxConifguration,
  116677. setupImageProcessing: false,
  116678. };
  116679. // will that cause problems with model ground configuration?
  116680. /*if (model) {
  116681. const boundingInfo = model.rootMesh.getHierarchyBoundingVectors(true);
  116682. const sizeVec = boundingInfo.max.subtract(boundingInfo.min);
  116683. const halfSizeVec = sizeVec.scale(0.5);
  116684. const center = boundingInfo.min.add(halfSizeVec);
  116685. options.groundYBias = -center.y;
  116686. }*/
  116687. if (groundConfiguration) {
  116688. var groundConfig_1 = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  116689. var groundSize = groundConfig_1.size || (typeof skyboxConifguration === 'object' && skyboxConifguration.scale);
  116690. if (groundSize) {
  116691. options.groundSize = groundSize;
  116692. }
  116693. options.enableGroundShadow = groundConfig_1 === true || groundConfig_1.receiveShadows;
  116694. if (groundConfig_1.shadowLevel !== undefined) {
  116695. options.groundShadowLevel = groundConfig_1.shadowLevel;
  116696. }
  116697. options.enableGroundMirror = !!groundConfig_1.mirror && this.groundMirrorEnabled;
  116698. if (groundConfig_1.texture) {
  116699. options.groundTexture = this.labs.getAssetUrl(groundConfig_1.texture);
  116700. }
  116701. if (groundConfig_1.color) {
  116702. options.groundColor = new babylonjs_1.Color3(groundConfig_1.color.r, groundConfig_1.color.g, groundConfig_1.color.b);
  116703. }
  116704. if (groundConfig_1.opacity !== undefined) {
  116705. options.groundOpacity = groundConfig_1.opacity;
  116706. }
  116707. if (groundConfig_1.mirror) {
  116708. options.enableGroundMirror = true;
  116709. // to prevent undefines
  116710. if (typeof groundConfig_1.mirror === "object") {
  116711. if (groundConfig_1.mirror.amount !== undefined)
  116712. options.groundMirrorAmount = groundConfig_1.mirror.amount;
  116713. if (groundConfig_1.mirror.sizeRatio !== undefined)
  116714. options.groundMirrorSizeRatio = groundConfig_1.mirror.sizeRatio;
  116715. if (groundConfig_1.mirror.blurKernel !== undefined)
  116716. options.groundMirrorBlurKernel = groundConfig_1.mirror.blurKernel;
  116717. if (groundConfig_1.mirror.fresnelWeight !== undefined)
  116718. options.groundMirrorFresnelWeight = groundConfig_1.mirror.fresnelWeight;
  116719. if (groundConfig_1.mirror.fallOffDistance !== undefined)
  116720. options.groundMirrorFallOffDistance = groundConfig_1.mirror.fallOffDistance;
  116721. if (this._defaultPipelineTextureType !== undefined)
  116722. options.groundMirrorTextureType = this._defaultPipelineTextureType;
  116723. }
  116724. }
  116725. }
  116726. var postInitSkyboxMaterial = false;
  116727. if (skyboxConifguration) {
  116728. var conf = skyboxConifguration === true ? {} : skyboxConifguration;
  116729. if (conf.material && conf.material.imageProcessingConfiguration) {
  116730. options.setupImageProcessing = false; // will be configured later manually.
  116731. }
  116732. var skyboxSize = conf.scale;
  116733. if (skyboxSize) {
  116734. options.skyboxSize = skyboxSize;
  116735. }
  116736. options.sizeAuto = !options.skyboxSize;
  116737. if (conf.color) {
  116738. options.skyboxColor = new babylonjs_1.Color3(conf.color.r, conf.color.g, conf.color.b);
  116739. }
  116740. if (conf.cubeTexture && conf.cubeTexture.url) {
  116741. if (typeof conf.cubeTexture.url === "string") {
  116742. options.skyboxTexture = this.labs.getAssetUrl(conf.cubeTexture.url);
  116743. }
  116744. else {
  116745. // init later!
  116746. postInitSkyboxMaterial = true;
  116747. }
  116748. }
  116749. if (conf.material) {
  116750. postInitSkyboxMaterial = true;
  116751. }
  116752. }
  116753. options.setupImageProcessing = false; // TMP
  116754. if (!this.environmentHelper) {
  116755. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  116756. }
  116757. else {
  116758. // unlikely, but there might be a new scene! we need to dispose.
  116759. // get the scene used by the envHelper
  116760. var scene = this.environmentHelper.rootMesh.getScene();
  116761. // is it a different scene? Oh no!
  116762. if (scene !== this.scene) {
  116763. this.environmentHelper.dispose();
  116764. this.environmentHelper = this.scene.createDefaultEnvironment(options);
  116765. }
  116766. else {
  116767. // recreate the ground
  116768. if (this.environmentHelper.ground) {
  116769. this.environmentHelper.ground.dispose();
  116770. }
  116771. // recreate the skybox
  116772. if (this.environmentHelper.skybox) {
  116773. this.environmentHelper.skybox.dispose();
  116774. }
  116775. this.environmentHelper.updateOptions(options);
  116776. // update doesn't change the size of the skybox and ground, so we have to recreate!
  116777. //this.environmentHelper.dispose();
  116778. //this.environmentHelper = this.scene.createDefaultEnvironment(options)!;
  116779. }
  116780. }
  116781. if (this.environmentHelper.rootMesh && this._globalConfiguration.scene && this._globalConfiguration.scene.environmentRotationY !== undefined) {
  116782. this.environmentHelper.rootMesh.rotation.y = this._globalConfiguration.scene.environmentRotationY;
  116783. }
  116784. var groundConfig = (typeof groundConfiguration === 'boolean') ? {} : groundConfiguration;
  116785. if (this.environmentHelper.groundMaterial && groundConfig) {
  116786. this.environmentHelper.groundMaterial._perceptualColor = this.mainColor;
  116787. if (groundConfig.material) {
  116788. helper_1.extendClassWithConfig(this.environmentHelper.groundMaterial, groundConfig.material);
  116789. }
  116790. if (this.environmentHelper.groundMirror) {
  116791. var mirrorClearColor = this.environmentHelper.groundMaterial._perceptualColor.toLinearSpace();
  116792. // TODO user camera exposure value to set the mirror clear color
  116793. var exposure = Math.pow(2.0, -this.scene.imageProcessingConfiguration.exposure) * Math.PI;
  116794. mirrorClearColor.scaleToRef(1 / exposure, mirrorClearColor);
  116795. this.environmentHelper.groundMirror.clearColor.r = babylonjs_1.Scalar.Clamp(mirrorClearColor.r);
  116796. this.environmentHelper.groundMirror.clearColor.g = babylonjs_1.Scalar.Clamp(mirrorClearColor.g);
  116797. this.environmentHelper.groundMirror.clearColor.b = babylonjs_1.Scalar.Clamp(mirrorClearColor.b);
  116798. this.environmentHelper.groundMirror.clearColor.a = 1;
  116799. if (!this.groundMirrorEnabled) {
  116800. this.environmentHelper.groundMaterial.reflectionTexture = null;
  116801. }
  116802. }
  116803. }
  116804. var skyboxMaterial = this.environmentHelper.skyboxMaterial;
  116805. if (skyboxMaterial) {
  116806. skyboxMaterial._perceptualColor = this.mainColor;
  116807. if (postInitSkyboxMaterial) {
  116808. if (typeof skyboxConifguration === 'object' && skyboxConifguration.material) {
  116809. helper_1.extendClassWithConfig(skyboxMaterial, skyboxConifguration.material);
  116810. }
  116811. }
  116812. }
  116813. }
  116814. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  116815. _this._updateGroundMirrorRenderList(model);
  116816. });
  116817. this.onEnvironmentConfiguredObservable.notifyObservers({
  116818. sceneManager: this,
  116819. object: this.environmentHelper,
  116820. newConfiguration: {
  116821. skybox: skyboxConifguration,
  116822. ground: groundConfiguration
  116823. }
  116824. });
  116825. };
  116826. /**
  116827. * configure the lights.
  116828. *
  116829. * @param lightsConfiguration the (new) light(s) configuration
  116830. * @param model optionally use the model to configure the camera.
  116831. */
  116832. SceneManager.prototype._configureLights = function (lightsConfiguration) {
  116833. var _this = this;
  116834. if (lightsConfiguration === void 0) { lightsConfiguration = {}; }
  116835. // sanity check!
  116836. var lightKeys = Object.keys(lightsConfiguration).filter(function (name) { return name !== 'globalRotation'; });
  116837. if (!lightKeys.length) {
  116838. if (!this.scene.lights.length)
  116839. this.scene.createDefaultLight(true);
  116840. }
  116841. else {
  116842. var lightsAvailable_1 = this.scene.lights.map(function (light) { return light.name; });
  116843. // compare to the global (!) configuration object and dispose unneeded:
  116844. var lightsToConfigure_1 = Object.keys(this._globalConfiguration.lights || []);
  116845. if (Object.keys(lightsToConfigure_1).length !== lightsAvailable_1.length) {
  116846. lightsAvailable_1.forEach(function (lName) {
  116847. if (lightsToConfigure_1.indexOf(lName) === -1) {
  116848. _this.scene.getLightByName(lName).dispose();
  116849. }
  116850. });
  116851. }
  116852. lightKeys.forEach(function (name, idx) {
  116853. var lightConfig = { type: 0 };
  116854. if (typeof lightsConfiguration[name] === 'object') {
  116855. lightConfig = lightsConfiguration[name];
  116856. }
  116857. if (typeof lightsConfiguration[name] === 'number') {
  116858. lightConfig.type = lightsConfiguration[name];
  116859. }
  116860. lightConfig.name = name;
  116861. var light;
  116862. // light is not already available
  116863. if (lightsAvailable_1.indexOf(name) === -1) {
  116864. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  116865. if (!constructor)
  116866. return;
  116867. light = constructor();
  116868. }
  116869. else {
  116870. // available? get it from the scene
  116871. light = _this.scene.getLightByName(name);
  116872. if (typeof lightsConfiguration[name] === 'boolean') {
  116873. lightConfig.type = light.getTypeID();
  116874. }
  116875. lightsAvailable_1 = lightsAvailable_1.filter(function (ln) { return ln !== name; });
  116876. if (lightConfig.type !== undefined && light.getTypeID() !== lightConfig.type) {
  116877. light.dispose();
  116878. var constructor = babylonjs_1.Light.GetConstructorFromName(lightConfig.type, lightConfig.name, _this.scene);
  116879. if (!constructor)
  116880. return;
  116881. light = constructor();
  116882. }
  116883. }
  116884. // if config set the light to false, dispose it.
  116885. if (lightsConfiguration[name] === false) {
  116886. light.dispose();
  116887. return;
  116888. }
  116889. //enabled
  116890. var enabled = lightConfig.enabled !== undefined ? lightConfig.enabled : !lightConfig.disabled;
  116891. light.setEnabled(enabled);
  116892. helper_1.extendClassWithConfig(light, lightConfig);
  116893. //position. Some lights don't support shadows
  116894. if (light instanceof babylonjs_1.ShadowLight) {
  116895. // set default values
  116896. light.shadowMinZ = light.shadowMinZ || 0.2;
  116897. light.shadowMaxZ = Math.min(10, light.shadowMaxZ || 10); //large far clips reduce shadow depth precision
  116898. if (lightConfig.target) {
  116899. if (light.setDirectionToTarget) {
  116900. var target = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.target);
  116901. light.setDirectionToTarget(target);
  116902. }
  116903. }
  116904. else if (lightConfig.direction) {
  116905. var direction = babylonjs_1.Vector3.Zero().copyFrom(lightConfig.direction);
  116906. light.direction = direction;
  116907. }
  116908. var isShadowEnabled = false;
  116909. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  116910. light.shadowFrustumSize = lightConfig.shadowFrustumSize || 2;
  116911. isShadowEnabled = true;
  116912. }
  116913. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  116914. var spotLight = light;
  116915. if (lightConfig.spotAngle !== undefined) {
  116916. spotLight.angle = lightConfig.spotAngle * Math.PI / 180;
  116917. }
  116918. if (spotLight.angle && lightConfig.shadowFieldOfView) {
  116919. spotLight.shadowAngleScale = lightConfig.shadowFieldOfView / spotLight.angle;
  116920. }
  116921. isShadowEnabled = true;
  116922. }
  116923. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  116924. if (lightConfig.shadowFieldOfView) {
  116925. light.shadowAngle = lightConfig.shadowFieldOfView * Math.PI / 180;
  116926. }
  116927. isShadowEnabled = true;
  116928. }
  116929. var shadowGenerator_1 = light.getShadowGenerator();
  116930. if (isShadowEnabled && lightConfig.shadowEnabled && _this._maxShadows) {
  116931. var bufferSize = lightConfig.shadowBufferSize || 256;
  116932. if (!shadowGenerator_1) {
  116933. shadowGenerator_1 = new babylonjs_1.ShadowGenerator(bufferSize, light);
  116934. }
  116935. var blurKernel = _this.getBlurKernel(light, bufferSize);
  116936. shadowGenerator_1.bias = _this._shadowGeneratorBias;
  116937. shadowGenerator_1.blurKernel = blurKernel;
  116938. //override defaults
  116939. helper_1.extendClassWithConfig(shadowGenerator_1, lightConfig.shadowConfig || {});
  116940. // add the focues meshes to the shadow list
  116941. _this._observablesManager && _this._observablesManager.onModelLoadedObservable.add(function (model) {
  116942. _this._updateShadowRenderList(shadowGenerator_1, model);
  116943. });
  116944. //if (model) {
  116945. _this._updateShadowRenderList(shadowGenerator_1);
  116946. //}
  116947. }
  116948. else if (shadowGenerator_1) {
  116949. shadowGenerator_1.dispose();
  116950. }
  116951. }
  116952. });
  116953. // render priority
  116954. var globalLightsConfiguration_1 = this._globalConfiguration.lights || {};
  116955. Object.keys(globalLightsConfiguration_1).sort().forEach(function (name, idx) {
  116956. var configuration = globalLightsConfiguration_1[name];
  116957. var light = _this.scene.getLightByName(name);
  116958. // sanity check
  116959. if (!light)
  116960. return;
  116961. light.renderPriority = -idx;
  116962. });
  116963. }
  116964. this.onLightsConfiguredObservable.notifyObservers({
  116965. sceneManager: this,
  116966. object: this.scene.lights,
  116967. newConfiguration: lightsConfiguration
  116968. });
  116969. };
  116970. SceneManager.prototype._updateShadowRenderList = function (shadowGenerator, model, resetList) {
  116971. var focusMeshes = model ? model.meshes : this.scene.meshes;
  116972. // add the focues meshes to the shadow list
  116973. var shadownMap = shadowGenerator.getShadowMap();
  116974. if (!shadownMap)
  116975. return;
  116976. if (resetList && shadownMap.renderList) {
  116977. shadownMap.renderList.length = 0;
  116978. }
  116979. else {
  116980. shadownMap.renderList = shadownMap.renderList || [];
  116981. }
  116982. for (var index = 0; index < focusMeshes.length; index++) {
  116983. var mesh = focusMeshes[index];
  116984. if (babylonjs_1.Tags.MatchesQuery(mesh, 'castShadow') && shadownMap.renderList.indexOf(mesh) === -1) {
  116985. shadownMap.renderList.push(mesh);
  116986. }
  116987. }
  116988. if (!this._shadowGroundPlane) {
  116989. if (shadowGenerator.useBlurCloseExponentialShadowMap) {
  116990. var shadowGroundPlane = babylonjs_1.Mesh.CreatePlane("shadowGroundPlane", 100, this.scene, false);
  116991. shadowGroundPlane.useVertexColors = false;
  116992. //material isn't ever used in rendering, just used to set back face culling
  116993. shadowGroundPlane.material = new babylonjs_1.StandardMaterial('shadowGroundPlaneMaterial', this.scene);
  116994. shadowGroundPlane.material.backFaceCulling = false;
  116995. shadowGroundPlane.rotation.x = Math.PI * 0.5;
  116996. shadowGroundPlane.freezeWorldMatrix();
  116997. this._shadowGroundPlane = shadowGroundPlane;
  116998. this.scene.removeMesh(shadowGroundPlane);
  116999. }
  117000. }
  117001. else {
  117002. if (!shadowGenerator.useBlurCloseExponentialShadowMap) {
  117003. this._shadowGroundPlane.dispose();
  117004. this._shadowGroundPlane = null;
  117005. }
  117006. }
  117007. if (this._shadowGroundPlane && shadownMap.renderList.indexOf(this._shadowGroundPlane) === -1) {
  117008. shadownMap.renderList.push(this._shadowGroundPlane);
  117009. }
  117010. };
  117011. SceneManager.prototype._updateGroundMirrorRenderList = function (model, resetList) {
  117012. if (this.environmentHelper && this.environmentHelper.groundMirror && this.environmentHelper.groundMirror.renderList) {
  117013. var focusMeshes = model ? model.meshes : this.scene.meshes;
  117014. var renderList = this.environmentHelper.groundMirror.renderList;
  117015. if (resetList) {
  117016. renderList.length = 0;
  117017. }
  117018. for (var index = 0; index < focusMeshes.length; index++) {
  117019. var mesh = focusMeshes[index];
  117020. if (renderList.indexOf(mesh) === -1) {
  117021. renderList.push(mesh);
  117022. }
  117023. }
  117024. }
  117025. };
  117026. /**
  117027. * Gets the shadow map blur kernel according to the light configuration.
  117028. * @param light The light used to generate the shadows
  117029. * @param bufferSize The size of the shadow map
  117030. * @return the kernel blur size
  117031. */
  117032. SceneManager.prototype.getBlurKernel = function (light, bufferSize) {
  117033. var normalizedBlurKernel = 0.05; // TODO Should come from the config.
  117034. if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_DIRECTIONALLIGHT) {
  117035. normalizedBlurKernel = normalizedBlurKernel / light.shadowFrustumSize;
  117036. }
  117037. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_POINTLIGHT) {
  117038. normalizedBlurKernel = normalizedBlurKernel / light.shadowAngle;
  117039. }
  117040. else if (light.getTypeID() === BABYLON.Light.LIGHTTYPEID_SPOTLIGHT) {
  117041. normalizedBlurKernel = normalizedBlurKernel / (light.angle * light.shadowAngleScale);
  117042. }
  117043. var minimumBlurKernel = 5 / (bufferSize / 256); //magic number that aims to keep away sawtooth shadows
  117044. var blurKernel = Math.max(bufferSize * normalizedBlurKernel, minimumBlurKernel);
  117045. return blurKernel;
  117046. };
  117047. /**
  117048. * Alters render settings to reduce features based on hardware feature limitations
  117049. * @param enableHDR Allows the viewer to run in HDR mode.
  117050. */
  117051. SceneManager.prototype._handleHardwareLimitations = function (enableHDR) {
  117052. if (enableHDR === void 0) { enableHDR = true; }
  117053. //flip rendering settings switches based on hardware support
  117054. var maxVaryingRows = this._engine.getCaps().maxVaryingVectors;
  117055. var maxFragmentSamplers = this._engine.getCaps().maxTexturesImageUnits;
  117056. //shadows are disabled if there's not enough varyings for a single shadow
  117057. if ((maxVaryingRows < 8) || (maxFragmentSamplers < 8)) {
  117058. this._maxShadows = 0;
  117059. }
  117060. else {
  117061. this._maxShadows = 3;
  117062. }
  117063. //can we render to any >= 16-bit targets (required for HDR)
  117064. var caps = this._engine.getCaps();
  117065. var linearHalfFloatTargets = caps.textureHalfFloatRender && caps.textureHalfFloatLinearFiltering;
  117066. var linearFloatTargets = caps.textureFloatRender && caps.textureFloatLinearFiltering;
  117067. this._hdrSupport = enableHDR && !!(linearFloatTargets || linearHalfFloatTargets);
  117068. if (linearHalfFloatTargets) {
  117069. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_HALF_FLOAT;
  117070. this._shadowGeneratorBias = 0.002;
  117071. }
  117072. else if (linearFloatTargets) {
  117073. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_FLOAT;
  117074. this._shadowGeneratorBias = 0.001;
  117075. }
  117076. else {
  117077. this._defaultHighpTextureType = babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  117078. this._shadowGeneratorBias = 0.001;
  117079. }
  117080. this._defaultPipelineTextureType = this._hdrSupport ? this._defaultHighpTextureType : babylonjs_1.Engine.TEXTURETYPE_UNSIGNED_INT;
  117081. };
  117082. /**
  117083. * Dispoe the entire viewer including the scene and the engine
  117084. */
  117085. SceneManager.prototype.dispose = function () {
  117086. // this.onCameraConfiguredObservable.clear();
  117087. this.onEnvironmentConfiguredObservable.clear();
  117088. this.onLightsConfiguredObservable.clear();
  117089. this.onModelsConfiguredObservable.clear();
  117090. this.onSceneConfiguredObservable.clear();
  117091. this.onSceneInitObservable.clear();
  117092. this.onSceneOptimizerConfiguredObservable.clear();
  117093. this.onVRConfiguredObservable.clear();
  117094. if (this.sceneOptimizer) {
  117095. this.sceneOptimizer.stop();
  117096. this.sceneOptimizer.dispose();
  117097. }
  117098. if (this.environmentHelper) {
  117099. this.environmentHelper.dispose();
  117100. }
  117101. this.models.forEach(function (model) {
  117102. model.dispose();
  117103. });
  117104. if (this._defaultRenderingPipeline) {
  117105. this._defaultRenderingPipeline.dispose();
  117106. }
  117107. this.models.length = 0;
  117108. if (this.scene) {
  117109. this.scene.dispose();
  117110. }
  117111. };
  117112. SceneManager.prototype._setCameraBehavior = function (name, behaviorConfig, payload) {
  117113. var behavior;
  117114. var type;
  117115. if (typeof behaviorConfig === 'object') {
  117116. type = behaviorConfig.type;
  117117. }
  117118. else if (typeof behaviorConfig === 'number') {
  117119. type = behaviorConfig;
  117120. }
  117121. else {
  117122. type = this._cameraBehaviorMapping[name];
  117123. }
  117124. if (type === undefined)
  117125. return;
  117126. var config = (typeof behaviorConfig === "object") ? behaviorConfig : {};
  117127. var enabled = true;
  117128. if (typeof behaviorConfig === 'boolean') {
  117129. enabled = behaviorConfig;
  117130. }
  117131. // constructing behavior
  117132. switch (type) {
  117133. case 0 /* AUTOROTATION */:
  117134. this.camera.useAutoRotationBehavior = enabled;
  117135. behavior = this.camera.autoRotationBehavior;
  117136. break;
  117137. case 1 /* BOUNCING */:
  117138. this.camera.useBouncingBehavior = enabled;
  117139. behavior = this.camera.bouncingBehavior;
  117140. break;
  117141. case 2 /* FRAMING */:
  117142. this.camera.useFramingBehavior = enabled;
  117143. behavior = this.camera.framingBehavior;
  117144. break;
  117145. default:
  117146. behavior = null;
  117147. break;
  117148. }
  117149. if (behavior) {
  117150. this._cameraBehaviorMapping[name] = type;
  117151. if (typeof behaviorConfig === "object") {
  117152. helper_1.extendClassWithConfig(behavior, behaviorConfig);
  117153. }
  117154. }
  117155. // post attach configuration. Some functionalities require the attached camera.
  117156. switch (type) {
  117157. case 0 /* AUTOROTATION */:
  117158. break;
  117159. case 1 /* BOUNCING */:
  117160. break;
  117161. case 2 /* FRAMING */:
  117162. this._observablesManager && this._observablesManager.onModelLoadedObservable.add(function (model) {
  117163. if (config.zoomOnBoundingInfo) {
  117164. behavior.zoomOnMeshHierarchy(model.rootMesh);
  117165. }
  117166. });
  117167. break;
  117168. }
  117169. };
  117170. return SceneManager;
  117171. }());
  117172. exports.SceneManager = SceneManager;
  117173. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2NlbmVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL3NjZW5lTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4bUI7QUFDOW1CLGtEQUFxUztBQUNyUyxvREFBK0Q7QUFDL0Qsb0NBQWtEO0FBRWxELGlEQUFnRDtBQUNoRCx5Q0FBZ0U7QUFnQmhFO0lBa0dJLHNCQUFvQixPQUFlLEVBQVUsdUJBQStDLEVBQVUsbUJBQXdDO1FBQTlJLGlCQTBFQztRQTFFbUIsWUFBTyxHQUFQLE9BQU8sQ0FBUTtRQUFVLDRCQUF1QixHQUF2Qix1QkFBdUIsQ0FBd0I7UUFBVSx3QkFBbUIsR0FBbkIsbUJBQW1CLENBQXFCO1FBeEN0SSw4QkFBeUIsR0FBWSxJQUFJLENBQUM7UUFpQmpDLFdBQU0sR0FBRyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBRWpDLHVCQUFrQixHQUFZLEtBQUssQ0FBQztRQStIcEMsb0JBQWUsR0FBWSxJQUFJLENBQUM7UUFrQ2hDLG1CQUFjLEdBQVksSUFBSSxDQUFDO1FBZ0IvQix5QkFBb0IsR0FBRyxJQUFJLENBQUM7UUF5QjVCLHFDQUFnQyxHQUFZLEtBQUssQ0FBQztRQThGbEQseUJBQW9CLEdBQXdCLEVBQUUsQ0FBQztRQWtHL0MseUNBQW9DLEdBQVksSUFBSSxDQUFDO1FBMkM3RCxrQ0FBa0M7UUFDMUIsa0JBQWEsR0FBWSxLQUFLLENBQUM7UUFvQnZDLGtDQUFrQztRQUMxQixpQkFBWSxHQUFZLEtBQUssQ0FBQztRQXFXOUIsa0JBQWEsR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TUFBTSxDQUFDLGVBQWUsQ0FBQztnQkFDdkMsTUFBTTtZQUNWO2dCQUNJLFFBQVEsR0FBRyxJQUFJLENBQUM7Z0JBQ2hCLE1BQU07U0FDYjtRQUVELElBQUksUUFBUSxFQUFFO1lBQ1YsSUFBSSxDQUFDLHNCQUFzQixDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksQ0FBQztZQUV6QyxJQUFJLE9BQU8sY0FBYyxLQUFLLFFBQVEsRUFBRTtnQkFDcEMsOEJBQXFCLENBQUMsUUFBUSxFQUFFLGNBQWMsQ0FBQyxDQUFDO2FBQ25EO1NBQ0o7UUFFRCwrRUFBK0U7UUFDL0UsUUFBUSxJQUFJLEVBQUU7WUFDVjtnQkFDSSxNQUFNO1lBQ1Y7Z0JBQ0ksTUFBTTtZQUNWO2dCQUNJLElBQUksQ0FBQyxtQkFBbUIsSUFBSSxJQUFJLENBQUMsbUJBQW1CLENBQUMsdUJBQXVCLENBQUMsR0FBRyxDQUFDLFVBQUMsS0FBSztvQkFDbkYsSUFBSSxNQUFNLENBQUMsa0JBQWtCLEVBQUU7d0JBQ1QsUUFBUyxDQUFDLG1CQUFtQixDQUFDLEtBQUssQ0FBQyxRQUFRLENBQUMsQ0FBQztxQkFDbkU7Z0JBQ0wsQ0FBQyxDQUFDLENBQUM7Z0JBQ0gsTUFBTTtTQUNiO0lBQ0wsQ0FBQztJQUNMLG1CQUFDO0FBQUQsQ0FBQyxBQTE4Q0QsSUEwOENDO0FBMThDWSxvQ0FBWSJ9
  117174. /***/ }),
  117175. /* 24 */
  117176. /***/ (function(module, exports, __webpack_require__) {
  117177. "use strict";
  117178. Object.defineProperty(exports, "__esModule", { value: true });
  117179. /**
  117180. * The GroupModelAnimation is an implementation of the IModelAnimation interface using BABYLON's
  117181. * native GroupAnimation class.
  117182. */
  117183. var GroupModelAnimation = /** @class */ (function () {
  117184. /**
  117185. * Create a new GroupModelAnimation object using an AnimationGroup object
  117186. * @param _animationGroup The aniamtion group to base the class on
  117187. */
  117188. function GroupModelAnimation(_animationGroup) {
  117189. var _this = this;
  117190. this._animationGroup = _animationGroup;
  117191. this._state = 0 /* INIT */;
  117192. this._playMode = 1 /* LOOP */;
  117193. this._animationGroup.onAnimationEndObservable.add(function () {
  117194. _this.stop();
  117195. _this._state = 4 /* ENDED */;
  117196. });
  117197. }
  117198. Object.defineProperty(GroupModelAnimation.prototype, "name", {
  117199. /**
  117200. * Get the animation's name
  117201. */
  117202. get: function () {
  117203. return this._animationGroup.name;
  117204. },
  117205. enumerable: true,
  117206. configurable: true
  117207. });
  117208. Object.defineProperty(GroupModelAnimation.prototype, "state", {
  117209. /**
  117210. * Get the current animation's state
  117211. */
  117212. get: function () {
  117213. return this._state;
  117214. },
  117215. enumerable: true,
  117216. configurable: true
  117217. });
  117218. Object.defineProperty(GroupModelAnimation.prototype, "speedRatio", {
  117219. /**
  117220. * Gets the speed ratio to use for all animations
  117221. */
  117222. get: function () {
  117223. return this._animationGroup.speedRatio;
  117224. },
  117225. /**
  117226. * Sets the speed ratio to use for all animations
  117227. */
  117228. set: function (value) {
  117229. this._animationGroup.speedRatio = value;
  117230. },
  117231. enumerable: true,
  117232. configurable: true
  117233. });
  117234. Object.defineProperty(GroupModelAnimation.prototype, "frames", {
  117235. /**
  117236. * Get the max numbers of frame available in the animation group
  117237. *
  117238. * In correlation to an arry, this would be ".length"
  117239. */
  117240. get: function () {
  117241. return this._animationGroup.to - this._animationGroup.from;
  117242. },
  117243. enumerable: true,
  117244. configurable: true
  117245. });
  117246. Object.defineProperty(GroupModelAnimation.prototype, "currentFrame", {
  117247. /**
  117248. * Get the current frame playing right now.
  117249. * This can be used to poll the frame currently playing (and, for exmaple, display a progress bar with the data)
  117250. *
  117251. * In correlation to an array, this would be the current index
  117252. */
  117253. get: function () {
  117254. if (this._animationGroup.targetedAnimations[0] && this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0]) {
  117255. return this._animationGroup.targetedAnimations[0].animation.runtimeAnimations[0].currentFrame - this._animationGroup.from;
  117256. }
  117257. else {
  117258. return 0;
  117259. }
  117260. },
  117261. enumerable: true,
  117262. configurable: true
  117263. });
  117264. Object.defineProperty(GroupModelAnimation.prototype, "fps", {
  117265. /**
  117266. * Get the FPS value of this animation
  117267. */
  117268. get: function () {
  117269. // get the first currentFrame found
  117270. for (var i = 0; i < this._animationGroup.animatables.length; ++i) {
  117271. var animatable = this._animationGroup.animatables[i];
  117272. var animations = animatable.getAnimations();
  117273. if (!animations || !animations.length) {
  117274. continue;
  117275. }
  117276. for (var idx = 0; idx < animations.length; ++idx) {
  117277. if (animations[idx].animation && animations[idx].animation.framePerSecond) {
  117278. return animations[idx].animation.framePerSecond;
  117279. }
  117280. }
  117281. }
  117282. return 0;
  117283. },
  117284. enumerable: true,
  117285. configurable: true
  117286. });
  117287. Object.defineProperty(GroupModelAnimation.prototype, "playMode", {
  117288. /**
  117289. * What is the animation'S play mode (looping or played once)
  117290. */
  117291. get: function () {
  117292. return this._playMode;
  117293. },
  117294. /**
  117295. * Set the play mode.
  117296. * If the animation is played, it will continue playing at least once more, depending on the new play mode set.
  117297. * If the animation is not set, the will be initialized and will wait for the user to start playing it.
  117298. */
  117299. set: function (value) {
  117300. if (value === this._playMode) {
  117301. return;
  117302. }
  117303. this._playMode = value;
  117304. if (this.state === 1 /* PLAYING */) {
  117305. this._animationGroup.play(this._playMode === 1 /* LOOP */);
  117306. }
  117307. else {
  117308. this._animationGroup.reset();
  117309. this._state = 0 /* INIT */;
  117310. }
  117311. },
  117312. enumerable: true,
  117313. configurable: true
  117314. });
  117315. /**
  117316. * Reset the animation group
  117317. */
  117318. GroupModelAnimation.prototype.reset = function () {
  117319. this._animationGroup.reset();
  117320. };
  117321. /**
  117322. * Restart the animation group
  117323. */
  117324. GroupModelAnimation.prototype.restart = function () {
  117325. if (this.state === 2 /* PAUSED */)
  117326. this._animationGroup.restart();
  117327. else
  117328. this.start();
  117329. };
  117330. /**
  117331. *
  117332. * @param frameNumber Go to a specific frame in the animation
  117333. */
  117334. GroupModelAnimation.prototype.goToFrame = function (frameNumber) {
  117335. this._animationGroup.goToFrame(frameNumber + this._animationGroup.from);
  117336. };
  117337. /**
  117338. * Start playing the animation.
  117339. */
  117340. GroupModelAnimation.prototype.start = function () {
  117341. this._animationGroup.start(this.playMode === 1 /* LOOP */, this.speedRatio);
  117342. if (this._animationGroup.isStarted) {
  117343. this._state = 1 /* PLAYING */;
  117344. }
  117345. };
  117346. /**
  117347. * Pause the animation
  117348. */
  117349. GroupModelAnimation.prototype.pause = function () {
  117350. this._animationGroup.pause();
  117351. this._state = 2 /* PAUSED */;
  117352. };
  117353. /**
  117354. * Stop the animation.
  117355. * This will fail silently if the animation group is already stopped.
  117356. */
  117357. GroupModelAnimation.prototype.stop = function () {
  117358. this._animationGroup.stop();
  117359. if (!this._animationGroup.isStarted) {
  117360. this._state = 3 /* STOPPED */;
  117361. }
  117362. };
  117363. /**
  117364. * Dispose this animation object.
  117365. */
  117366. GroupModelAnimation.prototype.dispose = function () {
  117367. this._animationGroup.dispose();
  117368. };
  117369. return GroupModelAnimation;
  117370. }());
  117371. exports.GroupModelAnimation = GroupModelAnimation;
  117372. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibW9kZWxBbmltYXRpb24uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvbW9kZWwvbW9kZWxBbmltYXRpb24udHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUF3SUE7OztHQUdHO0FBQ0g7SUFLSTs7O09BR0c7SUFDSCw2QkFBb0IsZUFBK0I7UUFBbkQsaUJBUUM7UUFSbUIsb0JBQWUsR0FBZixlQUFlLENBQWdCO1FBQy9DLElBQUksQ0FBQyxNQUFNLGVBQXNCLENBQUM7UUFDbEMsSUFBSSxDQUFDLFNBQVMsZUFBeUIsQ0FBQztRQUV4QyxJQUFJLENBQUMsZUFBZSxDQUFDLHdCQUF3QixD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Q0ksbUNBQUssR0FBWjtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxDQUFDLElBQUksQ0FBQyxRQUFRLGlCQUEyQixFQUFFLElBQUksQ0FBQyxVQUFVLENBQUMsQ0FBQztRQUN0RixJQUFJLElBQUksQ0FBQyxlQUFlLENBQUMsU0FBUyxFQUFFO1lBQ2hDLElBQUksQ0FBQyxNQUFNLGtCQUF5QixDQUFDO1NBQ3hDO0lBQ0wsQ0FBQztJQUVEOztPQUVHO0lBQ0gsbUNBQUssR0FBTDtRQUNJLElBQUksQ0FBQyxlQUFlLENBQUMsS0FBSyxFQUFFLENBQUM7UUFDN0IsSUFBSSxDQUFDLE1BQU0saUJBQXdCLENBQUM7SUFDeEMsQ0FBQztJQUVEOzs7T0FHRztJQUNJLGtDQUFJLEdBQVg7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQzVCLElBQUksQ0FBQyxJQUFJLENBQUMsZUFBZSxDQUFDLFNBQVMsRUFBRTtZQUNqQyxJQUFJLENBQUMsTUFBTSxrQkFBeUIsQ0FBQztTQUN4QztJQUNMLENBQUM7SUFFRDs7T0FFRztJQUNJLHFDQUFPLEdBQWQ7UUFDSSxJQUFJLENBQUMsZUFBZSxDQUFDLE9BQU8sRUFBRSxDQUFDO0lBQ25DLENBQUM7SUFDTCwwQkFBQztBQUFELENBQUMsQUFqTEQsSUFpTEM7QUFqTFksa0RBQW1CIn0=
  117373. /***/ }),
  117374. /* 25 */
  117375. /***/ (function(module, exports, __webpack_require__) {
  117376. "use strict";
  117377. Object.defineProperty(exports, "__esModule", { value: true });
  117378. var environmentSerializer_1 = __webpack_require__(26);
  117379. var babylonjs_1 = __webpack_require__(0);
  117380. var texture_1 = __webpack_require__(12);
  117381. /**
  117382. * The ViewerLabs class will hold functions that are not (!) backwards compatible.
  117383. * The APIs in all labs-related classes and configuration might change.
  117384. * Once stable, lab features will be moved to the publis API and configuration object.
  117385. */
  117386. var ViewerLabs = /** @class */ (function () {
  117387. function ViewerLabs(_scene) {
  117388. this._scene = _scene;
  117389. this.environment = {
  117390. //irradiance
  117391. irradiancePolynomialCoefficients: {
  117392. x: new babylonjs_1.Vector3(0, 0, 0),
  117393. y: new babylonjs_1.Vector3(0, 0, 0),
  117394. z: new babylonjs_1.Vector3(0, 0, 0),
  117395. xx: new babylonjs_1.Vector3(0, 0, 0),
  117396. yy: new babylonjs_1.Vector3(0, 0, 0),
  117397. zz: new babylonjs_1.Vector3(0, 0, 0),
  117398. yz: new babylonjs_1.Vector3(0, 0, 0),
  117399. zx: new babylonjs_1.Vector3(0, 0, 0),
  117400. xy: new babylonjs_1.Vector3(0, 0, 0)
  117401. },
  117402. textureIntensityScale: 1.0
  117403. };
  117404. }
  117405. ViewerLabs.prototype.loadEnvironment = function (data, onSuccess, onProgress, onError) {
  117406. var _this = this;
  117407. //@! todo: should loadEnvironment cancel any currently loading environments?
  117408. if (data instanceof ArrayBuffer) {
  117409. this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(data);
  117410. if (onSuccess)
  117411. onSuccess(this.environment);
  117412. }
  117413. else if (typeof data === 'string') {
  117414. var url = this.getAssetUrl(data);
  117415. this._scene._loadFile(url, function (arrayBuffer) {
  117416. _this.environment = environmentSerializer_1.EnvironmentDeserializer.Parse(arrayBuffer);
  117417. if (onSuccess)
  117418. onSuccess(_this.environment);
  117419. }, function (progressEvent) { if (onProgress)
  117420. onProgress(progressEvent.loaded, progressEvent.total); }, false, true, function (r, e) {
  117421. if (onError) {
  117422. onError(e);
  117423. }
  117424. });
  117425. }
  117426. else {
  117427. //data assumed to be PBREnvironment object
  117428. this.environment = data;
  117429. if (onSuccess)
  117430. onSuccess(data);
  117431. }
  117432. };
  117433. /**
  117434. * Applies an `EnvironmentMapConfiguration` to the scene
  117435. * @param environmentMapConfiguration Environment map configuration to apply
  117436. */
  117437. ViewerLabs.prototype.applyEnvironmentMapConfiguration = function (rotationY) {
  117438. if (!this.environment)
  117439. return;
  117440. //set orientation
  117441. var rotatquatRotationionY = babylonjs_1.Quaternion.RotationAxis(babylonjs_1.Axis.Y, rotationY || 0);
  117442. // Add env texture to the scene.
  117443. if (this.environment.specularTexture) {
  117444. // IE crashes when disposing the old texture and setting a new one
  117445. if (!this._scene.environmentTexture) {
  117446. this._scene.environmentTexture = texture_1.TextureUtils.GetBabylonCubeTexture(this._scene, this.environment.specularTexture, false, true);
  117447. }
  117448. if (this._scene.environmentTexture) {
  117449. this._scene.environmentTexture.level = this.environment.textureIntensityScale;
  117450. this._scene.environmentTexture.invertZ = true;
  117451. this._scene.environmentTexture.lodLevelInAlpha = true;
  117452. var poly = this._scene.environmentTexture.sphericalPolynomial || new babylonjs_1.SphericalPolynomial();
  117453. poly.x = this.environment.irradiancePolynomialCoefficients.x;
  117454. poly.y = this.environment.irradiancePolynomialCoefficients.y;
  117455. poly.z = this.environment.irradiancePolynomialCoefficients.z;
  117456. poly.xx = this.environment.irradiancePolynomialCoefficients.xx;
  117457. poly.xy = this.environment.irradiancePolynomialCoefficients.xy;
  117458. poly.yy = this.environment.irradiancePolynomialCoefficients.yy;
  117459. poly.yz = this.environment.irradiancePolynomialCoefficients.yz;
  117460. poly.zx = this.environment.irradiancePolynomialCoefficients.zx;
  117461. poly.zz = this.environment.irradiancePolynomialCoefficients.zz;
  117462. this._scene.environmentTexture.sphericalPolynomial = poly;
  117463. //set orientation
  117464. babylonjs_1.Matrix.FromQuaternionToRef(rotatquatRotationionY, this._scene.environmentTexture.getReflectionTextureMatrix());
  117465. }
  117466. }
  117467. };
  117468. /**
  117469. * Get an environment asset url by using the configuration if the path is not absolute.
  117470. * @param url Asset url
  117471. * @returns The Asset url using the `environmentAssetsRootURL` if the url is not an absolute path.
  117472. */
  117473. ViewerLabs.prototype.getAssetUrl = function (url) {
  117474. var returnUrl = url;
  117475. if (url && url.toLowerCase().indexOf("//") === -1) {
  117476. if (!this.assetsRootURL) {
  117477. // Tools.Warn("Please, specify the root url of your assets before loading the configuration (labs.environmentAssetsRootURL) or disable the background through the viewer options.");
  117478. return url;
  117479. }
  117480. returnUrl = this.assetsRootURL + returnUrl;
  117481. }
  117482. return returnUrl;
  117483. };
  117484. ViewerLabs.prototype.rotateShadowLight = function (shadowLight, amount, point, axis, target) {
  117485. if (point === void 0) { point = babylonjs_1.Vector3.Zero(); }
  117486. if (axis === void 0) { axis = babylonjs_1.Axis.Y; }
  117487. if (target === void 0) { target = babylonjs_1.Vector3.Zero(); }
  117488. axis.normalize();
  117489. point.subtractToRef(shadowLight.position, babylonjs_1.Tmp.Vector3[0]);
  117490. babylonjs_1.Matrix.TranslationToRef(babylonjs_1.Tmp.Vector3[0].x, babylonjs_1.Tmp.Vector3[0].y, babylonjs_1.Tmp.Vector3[0].z, babylonjs_1.Tmp.Matrix[0]);
  117491. babylonjs_1.Tmp.Matrix[0].invertToRef(babylonjs_1.Tmp.Matrix[2]);
  117492. babylonjs_1.Matrix.RotationAxisToRef(axis, amount, babylonjs_1.Tmp.Matrix[1]);
  117493. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[1], babylonjs_1.Tmp.Matrix[2]);
  117494. babylonjs_1.Tmp.Matrix[2].multiplyToRef(babylonjs_1.Tmp.Matrix[0], babylonjs_1.Tmp.Matrix[2]);
  117495. babylonjs_1.Tmp.Matrix[2].decompose(babylonjs_1.Tmp.Vector3[0], babylonjs_1.Tmp.Quaternion[0], babylonjs_1.Tmp.Vector3[1]);
  117496. shadowLight.position.addInPlace(babylonjs_1.Tmp.Vector3[1]);
  117497. shadowLight.setDirectionToTarget(target);
  117498. };
  117499. return ViewerLabs;
  117500. }());
  117501. exports.ViewerLabs = ViewerLabs;
  117502. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyTGFicy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9sYWJzL3ZpZXdlckxhYnMudH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QUFDLFVBQVUsQ0FBQyxlQUFHLENBQUMsT0FBTyxDQUFDLENBQUMsQ0FBQyxDQUFDLENBQUM7UUFFaEQsV0FBVyxDQUFDLG9CQUFvQixDQUFDLE1BQU0sQ0FBQyxDQUFDO0lBQzdDLENBQUM7SUFFTCxpQkFBQztBQUFELENBQUMsQUFySkQsSUFxSkM7QUFySlksZ0NBQVUifQ==
  117503. /***/ }),
  117504. /* 26 */
  117505. /***/ (function(module, exports, __webpack_require__) {
  117506. "use strict";
  117507. Object.defineProperty(exports, "__esModule", { value: true });
  117508. var babylonjs_1 = __webpack_require__(0);
  117509. var texture_1 = __webpack_require__(12);
  117510. /**
  117511. * A static class proving methods to aid parsing Spectre environment files
  117512. */
  117513. var EnvironmentDeserializer = /** @class */ (function () {
  117514. function EnvironmentDeserializer() {
  117515. }
  117516. /**
  117517. * Parses an arraybuffer into a new PBREnvironment object
  117518. * @param arrayBuffer The arraybuffer of the Spectre environment file
  117519. * @return a PBREnvironment object
  117520. */
  117521. EnvironmentDeserializer.Parse = function (arrayBuffer) {
  117522. var environment = {
  117523. //irradiance
  117524. irradiancePolynomialCoefficients: {
  117525. x: new babylonjs_1.Vector3(0, 0, 0),
  117526. y: new babylonjs_1.Vector3(0, 0, 0),
  117527. z: new babylonjs_1.Vector3(0, 0, 0),
  117528. xx: new babylonjs_1.Vector3(0, 0, 0),
  117529. yy: new babylonjs_1.Vector3(0, 0, 0),
  117530. zz: new babylonjs_1.Vector3(0, 0, 0),
  117531. yz: new babylonjs_1.Vector3(0, 0, 0),
  117532. zx: new babylonjs_1.Vector3(0, 0, 0),
  117533. xy: new babylonjs_1.Vector3(0, 0, 0)
  117534. },
  117535. //specular
  117536. textureIntensityScale: 1.0,
  117537. };
  117538. //read .env
  117539. var littleEndian = false;
  117540. var magicBytes = [0x86, 0x16, 0x87, 0x96, 0xf6, 0xd6, 0x96, 0x36];
  117541. var dataView = new DataView(arrayBuffer);
  117542. var pos = 0;
  117543. for (var i = 0; i < magicBytes.length; i++) {
  117544. if (dataView.getUint8(pos++) !== magicBytes[i]) {
  117545. babylonjs_1.Tools.Error('Not a Spectre environment map');
  117546. }
  117547. }
  117548. var version = dataView.getUint16(pos, littleEndian);
  117549. pos += 2;
  117550. if (version !== 1) {
  117551. babylonjs_1.Tools.Warn('Unsupported Spectre environment map version "' + version + '"');
  117552. }
  117553. //read json descriptor - collect characters up to null terminator
  117554. var descriptorString = '';
  117555. var charCode = 0x00;
  117556. while ((charCode = dataView.getUint8(pos++))) {
  117557. descriptorString += String.fromCharCode(charCode);
  117558. }
  117559. var descriptor = JSON.parse(descriptorString);
  117560. var payloadPos = pos;
  117561. //irradiance
  117562. switch (descriptor.irradiance.type) {
  117563. case 'irradiance_sh_coefficients_9':
  117564. //irradiance
  117565. var harmonics = descriptor.irradiance;
  117566. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance(harmonics);
  117567. //harmonics now represent radiance
  117568. EnvironmentDeserializer._ConvertSHToSP(harmonics, environment.irradiancePolynomialCoefficients);
  117569. break;
  117570. default:
  117571. babylonjs_1.Tools.Error('Unhandled MapType descriptor.irradiance.type (' + descriptor.irradiance.type + ')');
  117572. }
  117573. //specular
  117574. switch (descriptor.specular.type) {
  117575. case 'cubemap_faces':
  117576. var specularDescriptor = descriptor.specular;
  117577. var specularTexture = environment.specularTexture = new texture_1.TextureCube(6408 /* RGBA */, 5121 /* UNSIGNED_BYTE */);
  117578. environment.textureIntensityScale = specularDescriptor.multiplier != null ? specularDescriptor.multiplier : 1.0;
  117579. var mipmaps = specularDescriptor.mipmaps;
  117580. var imageType = specularDescriptor.imageType;
  117581. for (var l = 0; l < mipmaps.length; l++) {
  117582. var faceRanges = mipmaps[l];
  117583. specularTexture.source[l] = [];
  117584. for (var i = 0; i < 6; i++) {
  117585. var range = faceRanges[i];
  117586. var bytes = new Uint8Array(arrayBuffer, payloadPos + range.pos, range.length);
  117587. switch (imageType) {
  117588. case 'png':
  117589. //construct image element from bytes
  117590. var image = new Image();
  117591. var src = URL.createObjectURL(new Blob([bytes], { type: 'image/png' }));
  117592. image.src = src;
  117593. specularTexture.source[l][i] = image;
  117594. break;
  117595. default:
  117596. babylonjs_1.Tools.Error('Unhandled ImageType descriptor.specular.imageType (' + imageType + ')');
  117597. }
  117598. }
  117599. }
  117600. break;
  117601. default:
  117602. babylonjs_1.Tools.Error('Unhandled MapType descriptor.specular.type (' + descriptor.specular.type + ')');
  117603. }
  117604. return environment;
  117605. };
  117606. /**
  117607. * Convert from irradiance to outgoing radiance for Lambertian BDRF, suitable for efficient shader evaluation.
  117608. * L = (1/pi) * E * rho
  117609. *
  117610. * This is done by an additional scale by 1/pi, so is a fairly trivial operation but important conceptually.
  117611. * @param harmonics Spherical harmonic coefficients (9)
  117612. */
  117613. EnvironmentDeserializer._ConvertSHIrradianceToLambertianRadiance = function (harmonics) {
  117614. EnvironmentDeserializer._ScaleSH(harmonics, 1 / Math.PI);
  117615. // The resultant SH now represents outgoing radiance, so includes the Lambert 1/pi normalisation factor but without albedo (rho) applied
  117616. // (The pixel shader must apply albedo after texture fetches, etc).
  117617. };
  117618. /**
  117619. * Convert spherical harmonics to spherical polynomial coefficients
  117620. * @param harmonics Spherical harmonic coefficients (9)
  117621. * @param outPolynomialCoefficents Polynomial coefficients (9) object to store result
  117622. */
  117623. EnvironmentDeserializer._ConvertSHToSP = function (harmonics, outPolynomialCoefficents) {
  117624. var rPi = 1 / Math.PI;
  117625. //x
  117626. outPolynomialCoefficents.x.x = 1.02333 * harmonics.l11[0] * rPi;
  117627. outPolynomialCoefficents.x.y = 1.02333 * harmonics.l11[1] * rPi;
  117628. outPolynomialCoefficents.x.z = 1.02333 * harmonics.l11[2] * rPi;
  117629. outPolynomialCoefficents.y.x = 1.02333 * harmonics.l1_1[0] * rPi;
  117630. outPolynomialCoefficents.y.y = 1.02333 * harmonics.l1_1[1] * rPi;
  117631. outPolynomialCoefficents.y.z = 1.02333 * harmonics.l1_1[2] * rPi;
  117632. outPolynomialCoefficents.z.x = 1.02333 * harmonics.l10[0] * rPi;
  117633. outPolynomialCoefficents.z.y = 1.02333 * harmonics.l10[1] * rPi;
  117634. outPolynomialCoefficents.z.z = 1.02333 * harmonics.l10[2] * rPi;
  117635. //xx
  117636. outPolynomialCoefficents.xx.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] + 0.429043 * harmonics.l22[0]) * rPi;
  117637. outPolynomialCoefficents.xx.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] + 0.429043 * harmonics.l22[1]) * rPi;
  117638. outPolynomialCoefficents.xx.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] + 0.429043 * harmonics.l22[2]) * rPi;
  117639. outPolynomialCoefficents.yy.x = (0.886277 * harmonics.l00[0] - 0.247708 * harmonics.l20[0] - 0.429043 * harmonics.l22[0]) * rPi;
  117640. outPolynomialCoefficents.yy.y = (0.886277 * harmonics.l00[1] - 0.247708 * harmonics.l20[1] - 0.429043 * harmonics.l22[1]) * rPi;
  117641. outPolynomialCoefficents.yy.z = (0.886277 * harmonics.l00[2] - 0.247708 * harmonics.l20[2] - 0.429043 * harmonics.l22[2]) * rPi;
  117642. outPolynomialCoefficents.zz.x = (0.886277 * harmonics.l00[0] + 0.495417 * harmonics.l20[0]) * rPi;
  117643. outPolynomialCoefficents.zz.y = (0.886277 * harmonics.l00[1] + 0.495417 * harmonics.l20[1]) * rPi;
  117644. outPolynomialCoefficents.zz.z = (0.886277 * harmonics.l00[2] + 0.495417 * harmonics.l20[2]) * rPi;
  117645. //yz
  117646. outPolynomialCoefficents.yz.x = 0.858086 * harmonics.l2_1[0] * rPi;
  117647. outPolynomialCoefficents.yz.y = 0.858086 * harmonics.l2_1[1] * rPi;
  117648. outPolynomialCoefficents.yz.z = 0.858086 * harmonics.l2_1[2] * rPi;
  117649. outPolynomialCoefficents.zx.x = 0.858086 * harmonics.l21[0] * rPi;
  117650. outPolynomialCoefficents.zx.y = 0.858086 * harmonics.l21[1] * rPi;
  117651. outPolynomialCoefficents.zx.z = 0.858086 * harmonics.l21[2] * rPi;
  117652. outPolynomialCoefficents.xy.x = 0.858086 * harmonics.l2_2[0] * rPi;
  117653. outPolynomialCoefficents.xy.y = 0.858086 * harmonics.l2_2[1] * rPi;
  117654. outPolynomialCoefficents.xy.z = 0.858086 * harmonics.l2_2[2] * rPi;
  117655. };
  117656. /**
  117657. * Multiplies harmonic coefficients in place
  117658. * @param harmonics Spherical harmonic coefficients (9)
  117659. * @param scaleFactor Value to multiply by
  117660. */
  117661. EnvironmentDeserializer._ScaleSH = function (harmonics, scaleFactor) {
  117662. harmonics.l00[0] *= scaleFactor;
  117663. harmonics.l00[1] *= scaleFactor;
  117664. harmonics.l00[2] *= scaleFactor;
  117665. harmonics.l1_1[0] *= scaleFactor;
  117666. harmonics.l1_1[1] *= scaleFactor;
  117667. harmonics.l1_1[2] *= scaleFactor;
  117668. harmonics.l10[0] *= scaleFactor;
  117669. harmonics.l10[1] *= scaleFactor;
  117670. harmonics.l10[2] *= scaleFactor;
  117671. harmonics.l11[0] *= scaleFactor;
  117672. harmonics.l11[1] *= scaleFactor;
  117673. harmonics.l11[2] *= scaleFactor;
  117674. harmonics.l2_2[0] *= scaleFactor;
  117675. harmonics.l2_2[1] *= scaleFactor;
  117676. harmonics.l2_2[2] *= scaleFactor;
  117677. harmonics.l2_1[0] *= scaleFactor;
  117678. harmonics.l2_1[1] *= scaleFactor;
  117679. harmonics.l2_1[2] *= scaleFactor;
  117680. harmonics.l20[0] *= scaleFactor;
  117681. harmonics.l20[1] *= scaleFactor;
  117682. harmonics.l20[2] *= scaleFactor;
  117683. harmonics.l21[0] *= scaleFactor;
  117684. harmonics.l21[1] *= scaleFactor;
  117685. harmonics.l21[2] *= scaleFactor;
  117686. harmonics.l22[0] *= scaleFactor;
  117687. harmonics.l22[1] *= scaleFactor;
  117688. harmonics.l22[2] *= scaleFactor;
  117689. };
  117690. return EnvironmentDeserializer;
  117691. }());
  117692. exports.EnvironmentDeserializ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BRyxDQUFDLENBQUMsQ0FBQyxJQUFJLFdBQVcsQ0FBQztJQUNwQyxDQUFDO0lBQ0wsOEJBQUM7QUFBRCxDQUFDLEFBck5ELElBcU5DO0FBck5ZLDBEQUF1QiJ9
  117694. /***/ }),
  117695. /* 27 */
  117696. /***/ (function(module, exports, __webpack_require__) {
  117697. "use strict";
  117698. Object.defineProperty(exports, "__esModule", { value: true });
  117699. var extended_1 = __webpack_require__(28);
  117700. var cache = {};
  117701. /**
  117702. *
  117703. * @param name the name of the custom optimizer configuration
  117704. * @param upgrade set to true if you want to upgrade optimizer and false if you want to degrade
  117705. */
  117706. function getCustomOptimizerByName(name, upgrade) {
  117707. if (!cache[name]) {
  117708. switch (name) {
  117709. case 'extended':
  117710. if (upgrade) {
  117711. return extended_1.extendedUpgrade;
  117712. }
  117713. else {
  117714. return extended_1.extendedDegrade;
  117715. }
  117716. }
  117717. }
  117718. return cache[name];
  117719. }
  117720. exports.getCustomOptimizerByName = getCustomOptimizerByName;
  117721. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE4RDtBQUc5RCxJQUFNLEtBQUssR0FBK0QsRUFBRSxDQUFDO0FBRTdFOzs7O0dBSUc7QUFDSCxrQ0FBeUMsSUFBWSxFQUFFLE9BQWlCO0lBQ3BFLElBQUksQ0FBQyxLQUFLLENBQUMsSUFBSSxDQUFDLEVBQUU7UUFDZCxRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssVUFBVTtnQkFDWCxJQUFJLE9BQU8sRUFBRTtvQkFDVCxPQUFPLDBCQUFlLENBQUM7aUJBQzFCO3FCQUNJO29CQUNELE9BQU8sMEJBQWUsQ0FBQztpQkFDMUI7U0FDUjtLQUNKO0lBRUQsT0FBTyxLQUFLLENBQUMsSUFBSSxDQUFDLENBQUM7QUFDdkIsQ0FBQztBQWRELDREQWNDIn0=
  117722. /***/ }),
  117723. /* 28 */
  117724. /***/ (function(module, exports, __webpack_require__) {
  117725. "use strict";
  117726. Object.defineProperty(exports, "__esModule", { value: true });
  117727. var babylonjs_1 = __webpack_require__(0);
  117728. /**
  117729. * A custom upgrade-oriented function configuration for the scene optimizer.
  117730. *
  117731. * @param viewer the viewer to optimize
  117732. */
  117733. function extendedUpgrade(sceneManager) {
  117734. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  117735. // if (!this.Scene.BackgroundHelper) {
  117736. // this.Scene.EngineScene.autoClear = false;
  117737. // this.Scene.BackgroundHelper = true;
  117738. // Would require a dedicated clear color;
  117739. // return false;
  117740. // }
  117741. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > 1) {
  117742. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, 1);
  117743. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  117744. return false;
  117745. }
  117746. if (!sceneManager.scene.postProcessesEnabled) {
  117747. sceneManager.scene.postProcessesEnabled = true;
  117748. return false;
  117749. }
  117750. if (!sceneManager.groundEnabled) {
  117751. sceneManager.groundEnabled = true;
  117752. return false;
  117753. }
  117754. if (defaultPipeline && !sceneManager.fxaaEnabled) {
  117755. sceneManager.fxaaEnabled = true;
  117756. return false;
  117757. }
  117758. var hardwareScalingLevel = Math.max(1 / 2, 1 / (window.devicePixelRatio || 2));
  117759. if (sceneManager.scene.getEngine().getHardwareScalingLevel() > hardwareScalingLevel) {
  117760. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() - 0.25, 0, hardwareScalingLevel);
  117761. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  117762. return false;
  117763. }
  117764. if (!sceneManager.processShadows) {
  117765. sceneManager.processShadows = true;
  117766. return false;
  117767. }
  117768. if (defaultPipeline && !sceneManager.bloomEnabled) {
  117769. sceneManager.bloomEnabled = true;
  117770. return false;
  117771. }
  117772. if (!sceneManager.groundMirrorEnabled) {
  117773. sceneManager.groundMirrorEnabled = true;
  117774. return false;
  117775. }
  117776. return true;
  117777. }
  117778. exports.extendedUpgrade = extendedUpgrade;
  117779. /**
  117780. * A custom degrade-oriented function configuration for the scene optimizer.
  117781. *
  117782. * @param viewer the viewer to optimize
  117783. */
  117784. function extendedDegrade(sceneManager) {
  117785. var defaultPipeline = sceneManager.defaultRenderingPipeline;
  117786. if (sceneManager.groundMirrorEnabled) {
  117787. sceneManager.groundMirrorEnabled = false;
  117788. return false;
  117789. }
  117790. if (defaultPipeline && sceneManager.bloomEnabled) {
  117791. sceneManager.bloomEnabled = false;
  117792. return false;
  117793. }
  117794. if (sceneManager.processShadows) {
  117795. sceneManager.processShadows = false;
  117796. return false;
  117797. }
  117798. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1) {
  117799. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1);
  117800. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  117801. return false;
  117802. }
  117803. if (defaultPipeline && sceneManager.fxaaEnabled) {
  117804. sceneManager.fxaaEnabled = false;
  117805. return false;
  117806. }
  117807. if (sceneManager.groundEnabled) {
  117808. sceneManager.groundEnabled = false;
  117809. return false;
  117810. }
  117811. if (sceneManager.scene.postProcessesEnabled) {
  117812. sceneManager.scene.postProcessesEnabled = false;
  117813. return false;
  117814. }
  117815. if (sceneManager.scene.getEngine().getHardwareScalingLevel() < 1.25) {
  117816. var scaling = babylonjs_1.Scalar.Clamp(sceneManager.scene.getEngine().getHardwareScalingLevel() + 0.25, 0, 1.25);
  117817. sceneManager.scene.getEngine().setHardwareScalingLevel(scaling);
  117818. return false;
  117819. }
  117820. // if (this.Scene.BackgroundHelper) {
  117821. // this.Scene.EngineScene.autoClear = true;
  117822. // this.Scene.BackgroundHelper = false;
  117823. // Would require a dedicated clear color;
  117824. // return false;
  117825. // }
  117826. return true;
  117827. }
  117828. exports.extendedDegrade = extendedDegrade;
  117829. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvb3B0aW1pemVyL2N1c3RvbS9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUFvRTtBQUdwRTs7OztHQUlHO0FBQ0gseUJBQWdDLFlBQTBCO0lBQ3RELElBQUksZUFBZSxHQUE2QixZQUFZLENBQUMsd0JBQXdCLENBQUM7SUFDdEYsc0NBQXNDO0lBQ3RDLDZDQUE2QztJQUM3QyxzQ0FBc0M7SUFDdEMseUNBQXlDO0lBQ3pDLGdCQUFnQjtJQUNoQixJQUFJO0lBQ0osSUFBSSxZQUFZLENBQUMsS0FBSyxDQUFDLFNBQVMsRUFBRSxDQUFDLHVCQUF1QixFQUFFLEdBQUcsQ0FBQyxFQUFFO1FBQzlELElBQUksT0FBTyxHQUFHLGtCQUFNLENBQUMsS0FBSyxDQUFDLFlBQVksQ0FBQyxLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsdUJBQXVCLEVBQUUsR0FBRyxJQUFJLEVBQUUsQ0FBQyxFQUFFLENBQUMsQ0FBQyxDQUFDO1FBQ2xHLFlBQVksQ0FBQyxLQUFLLENBQUMsU0FBUyxFQUFFLENBQUMsdUJBQXVCLENBQUMsT0FBTyxDQUFDLENBQUM7UUFDaEUsT0FBTyxLQUFLLENBQUM7S0FDaEI7SUFDRCxJQUFJLENBQUMsWUFBWSxDQUFDLEtBQUssQ0FBQyxvQkFBb0IsRUFBRTtRQUMxQyxZQUFZLENBQUMsS0FBSyxDQUFDLG9CQUFvQixHQUFHLElBQUksQ0FBQztRQ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0lBQ0osT0FBTyxJQUFJLENBQUM7QUFDaEIsQ0FBQztBQTVDRCwwQ0E0Q0MifQ==
  117830. /***/ }),
  117831. /* 29 */
  117832. /***/ (function(module, exports, __webpack_require__) {
  117833. "use strict";
  117834. Object.defineProperty(exports, "__esModule", { value: true });
  117835. var mappers_1 = __webpack_require__(3);
  117836. var types_1 = __webpack_require__(30);
  117837. var configurationCompatibility_1 = __webpack_require__(54);
  117838. var _1 = __webpack_require__(1);
  117839. var babylonjs_1 = __webpack_require__(0);
  117840. /**
  117841. * The configuration loader will load the configuration object from any source and will use the defined mapper to
  117842. * parse the object and return a conform ViewerConfiguration.
  117843. * It is a private member of the scene.
  117844. */
  117845. var ConfigurationLoader = /** @class */ (function () {
  117846. function ConfigurationLoader(_enableCache) {
  117847. if (_enableCache === void 0) { _enableCache = false; }
  117848. this._enableCache = _enableCache;
  117849. this._configurationCache = {};
  117850. this._loadRequests = [];
  117851. }
  117852. /**
  117853. * load a configuration object that is defined in the initial configuration provided.
  117854. * The viewer configuration can extend different types of configuration objects and have an extra configuration defined.
  117855. *
  117856. * @param initConfig the initial configuration that has the definitions of further configuration to load.
  117857. * @param callback an optional callback that will be called sync, if noconfiguration needs to be loaded or configuration is payload-only
  117858. * @returns A promise that delivers the extended viewer configuration, when done.
  117859. */
  117860. ConfigurationLoader.prototype.loadConfiguration = function (initConfig, callback) {
  117861. var _this = this;
  117862. if (initConfig === void 0) { initConfig = {}; }
  117863. var loadedConfig = _1.deepmerge({}, initConfig);
  117864. var extendedConfiguration = types_1.getConfigurationType(loadedConfig.extends || "");
  117865. if (loadedConfig.configuration) {
  117866. var mapperType_1 = "json";
  117867. return Promise.resolve().then(function () {
  117868. if (typeof loadedConfig.configuration === "string" || (loadedConfig.configuration && loadedConfig.configuration.url)) {
  117869. // a file to load
  117870. var url = '';
  117871. if (typeof loadedConfig.configuration === "string") {
  117872. url = loadedConfig.configuration;
  117873. }
  117874. // if configuration is an object
  117875. if (typeof loadedConfig.configuration === "object" && loadedConfig.configuration.url) {
  117876. url = loadedConfig.configuration.url;
  117877. var type = loadedConfig.configuration.mapper;
  117878. // empty string?
  117879. if (!type) {
  117880. // load mapper type from filename / url
  117881. type = loadedConfig.configuration.url.split('.').pop();
  117882. }
  117883. mapperType_1 = type || mapperType_1;
  117884. }
  117885. return _this._loadFile(url);
  117886. }
  117887. else {
  117888. if (typeof loadedConfig.configuration === "object") {
  117889. mapperType_1 = loadedConfig.configuration.mapper || mapperType_1;
  117890. return loadedConfig.configuration.payload || {};
  117891. }
  117892. return {};
  117893. }
  117894. }).then(function (data) {
  117895. var mapper = mappers_1.mapperManager.getMapper(mapperType_1);
  117896. var parsed = _1.deepmerge(mapper.map(data), loadedConfig);
  117897. var merged = _1.deepmerge(extendedConfiguration, parsed);
  117898. configurationCompatibility_1.processConfigurationCompatibility(merged);
  117899. if (callback)
  117900. callback(merged);
  117901. return merged;
  117902. });
  117903. }
  117904. else {
  117905. loadedConfig = _1.deepmerge(extendedConfiguration, loadedConfig);
  117906. configurationCompatibility_1.processConfigurationCompatibility(loadedConfig);
  117907. if (callback)
  117908. callback(loadedConfig);
  117909. return Promise.resolve(loadedConfig);
  117910. }
  117911. };
  117912. /**
  117913. * Dispose the configuration loader. This will cancel file requests, if active.
  117914. */
  117915. ConfigurationLoader.prototype.dispose = function () {
  117916. this._loadRequests.forEach(function (request) {
  117917. request.abort();
  117918. });
  117919. this._loadRequests.length = 0;
  117920. };
  117921. ConfigurationLoader.prototype._loadFile = function (url) {
  117922. var _this = this;
  117923. var cacheReference = this._configurationCache;
  117924. if (this._enableCache && cacheReference[url]) {
  117925. return Promise.resolve(cacheReference[url]);
  117926. }
  117927. return new Promise(function (resolve, reject) {
  117928. var fileRequest = babylonjs_1.Tools.LoadFile(url, function (result) {
  117929. var idx = _this._loadRequests.indexOf(fileRequest);
  117930. if (idx !== -1)
  117931. _this._loadRequests.splice(idx, 1);
  117932. if (_this._enableCache)
  117933. cacheReference[url] = result;
  117934. resolve(result);
  117935. }, undefined, undefined, false, function (request, error) {
  117936. var idx = _this._loadRequests.indexOf(fileRequest);
  117937. if (idx !== -1)
  117938. _this._loadRequests.splice(idx, 1);
  117939. reject(error);
  117940. });
  117941. _this._loadRequests.push(fileRequest);
  117942. });
  117943. };
  117944. return ConfigurationLoader;
  117945. }());
  117946. exports.ConfigurationLoader = ConfigurationLoader;
  117947. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibG9hZGVyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2NvbmZpZ3VyYXRpb24vbG9hZGVyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQUEscUNBQTBDO0FBRTFDLGlDQUErQztBQUMvQywyRUFBaUY7QUFFakYsK0JBQXVDO0FBQ3ZDLHVDQUFnRDtBQUVoRDs7OztHQUlHO0FBQ0g7SUFNSSw2QkFBb0IsWUFBNkI7UUFBN0IsNkJBQUEsRUFBQSxvQkFBNkI7UUFBN0IsaUJBQVksR0FBWixZQUFZLENBQWlCO1FBQzdDLElBQUksQ0FBQyxtQkFBbUIsR0FBRyxFQUFFLENBQUM7UUFDOUIsSUFBSSxDQUFDLGFBQWEsR0FBRyxFQUFFLENBQUM7SUFDNUIsQ0FBQztJQUVEOzs7Ozs7O09BT0c7SUFDSSwrQ0FBaUIsR0FBeEIsVUFBeUIsVUFBb0MsRUFBRSxRQUFnRDtRQUEvRyxpQkFvREM7UUFwRHdCLDJCQUFBLEVBQUEsZUFBb0M7UUFFekQsSUFBSSxZQUFZLEdBQXdCLFlBQVMsQ0FBQyxFQUFFLEVBQUUsVUFBVSxDQUFDLENBQUM7UUFFbEUsSUFBSSxxQkFBcUIsR0FBRyw0QkFBb0IsQ0FBQyxZQUFZLENBQUMsT0FBTyxJQUFJLEVBQUUsQ0FBQyxDQUFDO1FBRTdFLElBQUksWUFBWSxDQUFDLGFBQWEsRUFBRTtZQUU1Q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oRCxJQUFJLEdBQUcsR0FBRyxLQUFJLENBQUMsYUFBYSxDQUFDLE9BQU8sQ0FBQyxXQUFXLENBQUMsQ0FBQztnQkFDbEQsSUFBSSxHQUFHLEtBQUssQ0FBQyxDQUFDO29CQUNWLEtBQUksQ0FBQyxhQUFhLENBQUMsTUFBTSxDQUFDLEdBQUcsRUFBRSxDQUFDLENBQUMsQ0FBQztnQkFDdEMsTUFBTSxDQUFDLEtBQUssQ0FBQyxDQUFDO1lBQ2xCLENBQUMsQ0FBQyxDQUFDO1lBQ0gsS0FBSSxDQUFDLGFBQWEsQ0FBQyxJQUFJLENBQUMsV0FBVyxDQUFDLENBQUM7UUFDekMsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUwsMEJBQUM7QUFBRCxDQUFDLEFBMUdELElBMEdDO0FBMUdZLGtEQUFtQiJ9
  117948. /***/ }),
  117949. /* 30 */
  117950. /***/ (function(module, exports, __webpack_require__) {
  117951. "use strict";
  117952. Object.defineProperty(exports, "__esModule", { value: true });
  117953. var minimal_1 = __webpack_require__(31);
  117954. exports.minimalConfiguration = minimal_1.minimalConfiguration;
  117955. var default_1 = __webpack_require__(50);
  117956. exports.defaultConfiguration = default_1.defaultConfiguration;
  117957. var extended_1 = __webpack_require__(51);
  117958. var shadowLight_1 = __webpack_require__(52);
  117959. var environmentMap_1 = __webpack_require__(53);
  117960. var _1 = __webpack_require__(1);
  117961. /**
  117962. * Get the configuration type you need to use as the base for your viewer.
  117963. * The types can either be a single string, or comma separated types that will extend each other. for example:
  117964. *
  117965. * "default, environmentMap" will first load the default configuration and will extend it using the environmentMap configuration.
  117966. *
  117967. * @param types a comma-separated string of the type(s) or configuration to load.
  117968. */
  117969. var getConfigurationType = function (types) {
  117970. var config = {};
  117971. var typesSeparated = types.split(",");
  117972. typesSeparated.forEach(function (type) {
  117973. switch (type.trim()) {
  117974. case 'environmentMap':
  117975. config = _1.deepmerge(config, environmentMap_1.environmentMapConfiguration);
  117976. break;
  117977. case 'shadowDirectionalLight':
  117978. config = _1.deepmerge(config, shadowLight_1.shadowDirectionalLightConfiguration);
  117979. break;
  117980. case 'shadowSpotLight':
  117981. config = _1.deepmerge(config, shadowLight_1.shadowSpotlLightConfiguration);
  117982. break;
  117983. case 'extended':
  117984. config = _1.deepmerge(config, extended_1.extendedConfiguration);
  117985. break;
  117986. case 'minimal':
  117987. config = _1.deepmerge(config, minimal_1.minimalConfiguration);
  117988. break;
  117989. case 'none':
  117990. break;
  117991. case 'default':
  117992. default:
  117993. config = _1.deepmerge(config, default_1.defaultConfiguration);
  117994. break;
  117995. }
  117996. if (config.extends) {
  117997. config = _1.deepmerge(config, getConfigurationType(config.extends));
  117998. }
  117999. });
  118000. return config;
  118001. };
  118002. exports.getConfigurationType = getConfigurationType;
  118003. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHFDQUFpRDtBQW9ESSwrQkFwRDVDLDhCQUFvQixDQW9ENEM7QUFuRHpFLHFDQUFpRDtBQW1EbEIsK0JBbkR0Qiw4QkFBb0IsQ0FtRHNCO0FBbERuRCx1Q0FBbUQ7QUFFbkQsNkNBQW1HO0FBQ25HLG1EQUErRDtBQUMvRCxrQ0FBMEM7QUFFMUM7Ozs7Ozs7R0FPRztBQUNILElBQUksb0JBQW9CLEdBQUcsVUFBVSxLQUFhO0lBQzlDLElBQUksTUFBTSxHQUF3QixFQUFFLENBQUM7SUFDckMsSUFBSSxjQUFjLEdBQUcsS0FBSyxDQUFDLEtBQUssQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN0QyxjQUFjLENBQUMsT0FBTyxDQUFDLFVBQUEsSUFBSTtRQUN2QixRQUFRLElBQUksQ0FBQy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object.defineProperty(exports, "__esModule", { value: true });
  118009. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  118010. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  118011. /**
  118012. * The minimal configuration needed to make the viewer work.
  118013. * Some functionalities might not work correctly (like fill-screen)
  118014. */
  118015. exports.minimalConfiguration = {
  118016. version: "0.1",
  118017. templates: {
  118018. main: {
  118019. html: babylonjs_viewer_assets_1.defaultTemplate
  118020. },
  118021. fillContainer: {
  118022. html: babylonjs_viewer_assets_1.fillContainer,
  118023. params: {
  118024. disable: false
  118025. }
  118026. },
  118027. loadingScreen: {
  118028. html: babylonjs_viewer_assets_1.loadingScreen,
  118029. params: {
  118030. backgroundColor: "#000000",
  118031. loadingImage: babylonjs_viewer_assets_2.loading
  118032. }
  118033. },
  118034. viewer: {
  118035. html: babylonjs_viewer_assets_1.defaultViewer,
  118036. },
  118037. overlay: {
  118038. html: babylonjs_viewer_assets_1.overlay,
  118039. params: {
  118040. closeImage: babylonjs_viewer_assets_2.close,
  118041. closeText: 'Close'
  118042. }
  118043. },
  118044. error: {
  118045. html: babylonjs_viewer_assets_1.error
  118046. }
  118047. },
  118048. engine: {
  118049. antialiasing: true
  118050. }
  118051. };
  118052. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibWluaW1hbC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL21pbmltYWwudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBdUg7QUFDdkgsbUVBQXlEO0FBRXpEOzs7R0FHRztBQUNRLFFBQUEsb0JBQW9CLEdBQXdCO0lBQ25ELE9BQU8sRUFBRSxLQUFLO0lBQ2QsU0FBUyxFQUFFO1FBQ1AsSUFBSSxFQUFFO1lBQ0YsSUFBSSxFQUFFLHlDQUFlO1NBQ3hCO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixPQUFPLEVBQUUsS0FBSzthQUNqQjtTQUNKO1FBQ0QsYUFBYSxFQUFFO1lBQ1gsSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixlQUFlLEVBQUUsU0FBUztnQkFDMUIsWUFBWSxFQUFFLGlDQUFPO2FBQ3hCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsdUNBQWE7U0FDdEI7UUFDRCxPQUFPLEVBQUU7WUFDTCxJQUFJLEVBQUUsaUNBQU87WUFDYixNQUFNLEVBQUU7Z0JBQ0osVUFBVSxFQUFFLCtCQUFLO2dCQUNqQixTQUFTLEVBQUUsT0FBTzthQUNyQjtTQUNKO1FBQ0QsS0FBSyxFQUFFO1lBQ0gsSUFBSSxFQUFFLCtCQUFLO1NBQ2Q7S0FFSjtJQUNELE1BQU0sRUFBRTtRQUNKLFlBQVksRUFBRSxJQUFJO0tBQ3JCO0NBQ0osQ0FBQSJ9
  118053. /***/ }),
  118054. /* 32 */
  118055. /***/ (function(module, exports, __webpack_require__) {
  118056. "use strict";
  118057. Object.defineProperty(exports, "__esModule", { value: true });
  118058. exports.babylonFont = __webpack_require__(33);
  118059. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZm9udC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9hc3NldHMvZm9udC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFhLFFBQUEsV0FBVyxHQUFHLE9BQU8sQ0FBQywyQkFBMkIsQ0FBQyxDQUFDIn0=
  118060. /***/ }),
  118061. /* 33 */
  118062. /***/ (function(module, exports) {
  118063. module.exports = "data:application/font-woff;charset=utf-8;base64,d09GRgABAAAAABTkAA8AAAAAJEwAAAA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tsCP+a/jHwPWkfez9DwA2xTIinBIYGpGNiw2yHC71birmEKinqAZ9ZYN8eUE6cKtHAXlHt2kq0Feu0UaYpawMamIdkAzinpFdSrxqStDPGQWbgrrVNPIv0Z0HcJXUWc3Z0h1YjiqPrRE4ZoVUXV2thqQvmKcl4lsPgX3W1pHMKNgmcB1Svdl5bv4OZnyczUDSLNdUpgXVxzWqfKWonkE1Fc5curD3a5ITOgf552HFCR74ui9jbGP5vbefsKTFNQGZojh11LpnN6qIMOu9Px3WtNwOYSZuLI3/dW4D8ba4pSGrKXNNb+azZE4emSlJftF/brFpc0ZtVkSVG23Wz40HNnN7kf57R9qtW+M7M2bs3RPkq4/xgvCOqdNvb+RdZ0AR35z/h1P9ay0PfZPoqH7oH79Gr0Wb0fvRu9DasVw4xFWB/B/QeUd2KNsrg++CbkFE3d0DTQLyYjfgbYLuFq3jaY2BmAIP/fgzlDFgAACkqAcgAeNrbwKDNsImRk0mbcRMXiNzO1ZobaqvKwKG9nTs12EFPBsTiifCw0JAEsXidzbXlhUEsPh0VGREeEItfTkKYjwPEEuDj4WRnAbEEwQDEEtowoSDAAMhi2M4IN5oJbjQz3GgWuNGscKPZ5CShRrPDjeaAG80JN3qTMCO79gYGBdfaTAkXAMQBKBoAAAA="
  118064. /***/ }),
  118065. /* 34 */
  118066. /***/ (function(module, exports, __webpack_require__) {
  118067. "use strict";
  118068. Object.defineProperty(exports, "__esModule", { value: true });
  118069. exports.babylonLogo = __webpack_require__(35);
  118070. exports.close = __webpack_require__(36);
  118071. exports.fullscreen = __webpack_require__(37);
  118072. exports.helpCircle = __webpack_require__(38);
  118073. exports.loading = __webpack_require__(39);
  118074. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW1nLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy9pbWcudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLFdBQVcsR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUNuRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsNEJBQTRCLENBQUMsQ0FBQztBQUM5QyxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsaUNBQWlDLENBQUMsQ0FBQztBQUN4RCxRQUFBLFVBQVUsR0FBRyxPQUFPLENBQUMsa0NBQWtDLENBQUMsQ0FBQztBQUN6RCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsOEJBQThCLENBQUMsQ0FBQyJ9
  118075. /***/ }),
  118076. /* 35 */
  118077. /***/ (function(module, exports) {
  118078. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAB7MAAAgHCAYAAABZmyd0AAAACXBIWXMAAC4jAAAuIwF4pT92AAAgAElEQVR42uzd7XEb6Zm24Wtc+5/IgO0IyDcCtiMQNwLBEYgTgaAIhhOBpQhMRSAwghEjWCoCixHw/fE0DIKiKAIE+vM4qlDi1I531/fYRDdOPHf/dn9/HwAAAAAmb5bkNMnSKAAAgD74HyMAAAAAmJwqJVyfJqmbP4+a/9m3JIskH40JAADo0m9OZgMAAACM2ukTr6MX/OtEbQAAoFNiNgAAAMB41FkH6yrJ2R7+d4raAABAJ8RsAAAAgOFZPd+6znpl+MmB/2+K2gAAQKvEbAAAAIB+q/LjmvDjDv//EbUBAIBWiNkAAAAA/bFaD746df3S51t3QdQGAAAOSswGAAAA6Mbj09ZnA/33IWoDAAAHIWYDAAAAHF6dzXB9MsJ/j6I2AACwV2I2AAAAwP7MsrkivOvnW3dB1AYAAPZCzAYAAADYTZV1sK6bvz42lv8StQEAgFcRswEAAAB+bRWtq6xPXR8Zy4uI2gAAwE7EbAAAAIBNddbh+jTJmZHshagNAABsRcwGAAAApmr1fOuHrxNjOThRGwAAeBExGwAAAJiCVbiusw7Xnm/dLVEbAAB4lpgNAAAAjE2VdbCu4/nWfSdqAwAATxKzAQAAgC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AslNkAABzLJKWcPRXFg7YphX+T5EYcAAAAAIyNMhsAgGOaphTaJ6L47iqlwF6KAgAAAIAxU2YDAHBs75J8GXkGVtgAAAAA8C/KbAAA+uAiyecRPvd1yruwrbABAAAA4F+U2QAA9MUyye8jeM5dygJ7HitsAAAAAPghZTYAAH0xSXl/9mmlz3ed/SlxAAAAAOAXlNkAAPTJNKXQPqnkeaywAQAAAOCZlNkAAPTNLMnlwJ9hk1JgNz5OAAAAAHgeZTYAAH00T/JhYL/mXcp7v+dJ1j5CAAAAAHgZZTYAAH21SvJ2AL/O+xX2Msmtjw0AAAAA2qHMBgCgryYpC+fXPfy1WWEDAAAAQMeU2QAA9Nk0ZaF90pNfzzb7d2FbYQMAAABAh5TZAAD03SzJ5ZF/DYuUAnvl4wAAAACAw1BmAwAwBE2S8wP/f1phAwAAAMARKbMBABiKdZLTA/z/WGEDAAAAQA8oswEAGIpJkpt08/7sbUqBPY8VNgAAAAD0gjIbAIAhmSb51uL/3lVKib0ULQAAAAD0izIbAIChmSW5fMHff7/CblKW3gAAAABADymzAQAYoibJ+RP/HitsAAAAABgQZTYAAEO1TnL6i79ml/27sG9EBgAAAADDocwGAGCo3qQU2icP/HfX2Z8SBwAAAAAGSJkNAMCQnSX5evefrbABAAAAoCLKbAAAhu5dkkmssAEAAACgKv8F3qtfY+YVvDIAAAAASUVORK5CYII="
  118079. /***/ }),
  118080. /* 36 */
  118081. /***/ (function(module, exports) {
  118082. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAAt0lEQVR42u2WAQbDQBBFQ9IbRtDcrrqK3LBbXrEH6OuHEPMBjPd2xHyZKtdNpcLMg11Pr7y4/YdvwIdd4jtw4BU0Rjrbz9mNzkjzgpU3wNhCvH5M3i1fKzzeK3K8V+R4r8jxTpHjlULhc0WOd8fU6e4I8y3y13tFjHel4GswwAvFSR/ZN6Zv2gjvmzbGhwqPzxUenys83is8Pld4vFac/9sy8/SVNrbgYJl8WGhsvkpoA1+pVK6ZLyLNXm2txsT5AAAAAElFTkSuQmCC"
  118083. /***/ }),
  118084. /* 37 */
  118085. /***/ (function(module, exports) {
  118086. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwAQAAAAB/ecQqAAAAAnRSTlMAAHaTzTgAAAAeSURBVHgBY6ASsP/A/wcXZQNGhCkyAfE24HUndQAAXlkXcQ24P7gAAAAASUVORK5CYII="
  118087. /***/ }),
  118088. /* 38 */
  118089. /***/ (function(module, exports) {
  118090. module.exports = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAQAAAD9CzEMAAAB/ElEQVR42u3Xs4JdQRzH8X9sqYrNNnbqtPELxKgWD7AsI71B7BcI21W9rNa+d27zjSac/5kzZ2J8yqPfGUn++xMwis2UcpsGuilQoJt6blHCJkbKt2I+FbSRpJVy5kos5nAVQxrDJWbFfP4wXYTqYL9kwRiuk9VFRksYJvKEGA+ZEPb3+udrOcNaJjGJtZyhTo8IKIVaOXmOMfKrrnsCo1WU+HFE/fxu9dk9asR+f8fswnU08fmTuDo8nZarat2P/DjobtFPP3dY8bGi6jNUE/MxuM58vNsFVvfHiHNqleqjmwo0a+zdW3zutr26Dk2ZPqW1oZli7/fzuT57dQqaFmUaZDNZ9HoDYIMbUEoWt+xb69EVuwG3CdfNcvtWNbqbbkB9ePVgK4DFDKGrcwO6CNPHJvvGdGpI0uEGGELk2WGfn8or33OxAUc/TulP8cnHVVENI5Vhp+mIa+TT9tm9pKkN7ab6tHEDRVo3LUGjTxuNpClyAzaRSiwGSbPeDRhJC99Ls7rno5zvpUw0zMMQQV1wdFzmezgvSZhJR1Aj+3QyW5Jx8JsD9okfV74p4ELIceNudMAjRodtfh8T4yETg7fvEf3pAqMlCw7QQah29kl2zOIiedLkOc9MicVcymkhSQtlzJVvxUg2UMxNaunCYOiihpsUsZ6R8t8f4DUz8hFGPnrb0AAAAABJRU5ErkJggg=="
  118091. /***/ }),
  118092. /* 39 */
  118093. /***/ (function(module, exports) {
  118094. 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/M6AoqIUojapgWzgauBTEfiP6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ggg=="
  118095. /***/ }),
  118096. /* 40 */
  118097. /***/ (function(module, exports, __webpack_require__) {
  118098. "use strict";
  118099. Object.defineProperty(exports, "__esModule", { value: true });
  118100. exports.defaultTemplate = __webpack_require__(41);
  118101. exports.defaultViewer = __webpack_require__(42);
  118102. exports.error = __webpack_require__(43);
  118103. exports.fillContainer = __webpack_require__(44);
  118104. exports.help = __webpack_require__(45);
  118105. exports.loadingScreen = __webpack_require__(46);
  118106. exports.navbar = __webpack_require__(47);
  118107. exports.overlay = __webpack_require__(48);
  118108. exports.share = __webpack_require__(49);
  118109. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVzLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL2Fzc2V0cy90ZW1wbGF0ZXMudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBYSxRQUFBLGVBQWUsR0FBRyxPQUFPLENBQUMscURBQXFELENBQUMsQ0FBQztBQUNqRixRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQztBQUM3RCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLElBQUksR0FBRyxPQUFPLENBQUMsMENBQTBDLENBQUMsQ0FBQztBQUMzRCxRQUFBLGFBQWEsR0FBRyxPQUFPLENBQUMsbURBQW1ELENBQUMsQ0FBQztBQUM3RSxRQUFBLE1BQU0sR0FBRyxPQUFPLENBQUMsNENBQTRDLENBQUMsQ0FBQztBQUMvRCxRQUFBLE9BQU8sR0FBRyxPQUFPLENBQUMsNkNBQTZDLENBQUMsQ0FBQztBQUNqRSxRQUFBLEtBQUssR0FBRyxPQUFPLENBQUMsMkNBQTJDLENBQUMsQ0FBQyJ9
  118110. /***/ }),
  118111. /* 41 */
  118112. /***/ (function(module, exports) {
  118113. module.exports = "<style>@font-face{font-family:babylon;src:url({{babylonFont}}) format('woff');font-weight:400;font-style:normal}.icon{font-family:babylon}</style> {{#if fillScreen}} <style>body,html{width:100%;height:100%;margin:0;padding:0}</style> {{/if}} <fill-container></fill-container>";
  118114. /***/ }),
  118115. /* 42 */
  118116. /***/ (function(module, exports) {
  118117. module.exports = "<style>viewer{position:relative;overflow:hidden;z-index:1;justify-content:center;align-items:center;width:100%;height:100%}.babylonjs-canvas{flex:1;width:100%;height:100%;touch-action:none}</style> <canvas class=babylonjs-canvas touch-action=none> </canvas> <nav-bar></nav-bar>";
  118118. /***/ }),
  118119. /* 43 */
  118120. /***/ (function(module, exports) {
  118121. module.exports = "Error loading the model";
  118122. /***/ }),
  118123. /* 44 */
  118124. /***/ (function(module, exports) {
  118125. module.exports = "<style>fill-container{display:flex}fill-container>*{touch-action:none}</style> {{#unless disable}} <style>fill-container{width:100%;height:100%;justify-content:flex-start;align-items:stretch;align-content:stretch}fill-container>*{flex:1 1 auto;flex-direction:row;justify-content:flex-start;align-items:stretch;align-content:stretch}</style> {{/unless}} <viewer></viewer> <loading-screen></loading-screen> <overlay></overlay>";
  118126. /***/ }),
  118127. /* 45 */
  118128. /***/ (function(module, exports) {
  118129. module.exports = "HELP";
  118130. /***/ }),
  118131. /* 46 */
  118132. /***/ (function(module, exports) {
  118133. module.exports = "<style>loading-screen{position:absolute;left:0;z-index:100;opacity:1;pointer-events:none;display:flex;justify-content:center;align-items:center;-webkit-transition:opacity 1s ease;-moz-transition:opacity 1s ease;transition:opacity 1s ease}img.loading-image{-webkit-animation:spin 2s linear infinite;animation:spin 2s linear infinite}@-webkit-keyframes spin{0%{-webkit-transform:rotate(0)}100%{-webkit-transform:rotate(360deg)}}@keyframes spin{0%{transform:rotate(0)}100%{transform:rotate(360deg)}}</style> <img class=loading-image src={{loadingImage}}>";
  118134. /***/ }),
  118135. /* 47 */
  118136. /***/ (function(module, exports) {
  118137. module.exports = "<style>nav-bar{position:absolute;height:48px;width:100%;bottom:10px;display:flex;justify-content:center}nav-bar .nav-container{display:flex;flex-direction:row;margin:0 10px;height:100%;width:100%;justify-content:center}nav-bar .animation-control{background-color:rgba(91,93,107,.75);display:flex;flex-direction:row;height:100%;width:100%;max-width:1280px;justify-content:center}nav-bar .flex-container{display:flex;flex-direction:row;justify-content:center;height:100%;width:100%}nav-bar button{background:0 0;border:none;color:#fff;margin:0;padding:0;height:100%;min-width:48px;cursor:pointer}nav-bar button:active,nav-bar button:focus,nav-bar button:hover{background:0 0;border:none;outline:0}nav-bar button:hover{background-color:rgba(22,24,26,.2)}nav-bar .control-text{font-family:\"Segoe UI\";font-size:12px;font-weight:400;pointer-events:none}nav-bar .icon,nav-bar img{pointer-events:none}.logo-button{display:flex;align-items:center;flex-direction:row;justify-content:center;background-color:rgba(91,93,107,.75);height:48px;min-width:48px;margin-right:4px}.logo-button img{height:20px;width:20px}.types{display:flex;flex-direction:column;width:48px}.speed .flex-container,.types .flex-container{align-items:center}.menu-options{position:absolute;bottom:48px;width:48px;background-color:rgba(22,24,26,.9)}.animation-label,.help,.logo-button,.speed,.types-icon{display:none}.types-icon:after{font-size:16px;content:\"\\F6BE\"}.up-icon:after{line-height:16px;font-size:12px;content:\"\\E70E\"}.play-icon:after{font-size:16px;content:\"\\E768\"}.pause-icon:after{font-size:16px;content:\"\\E769\"}.fullscreen-icon:after{font-size:16px;content:\"\\E740\"}viewer.in-fullscreen .fullscreen-icon:after{content:\"\\E73F\"}.help-icon:after{font-size:16px;content:\"\\EF4E\"}viewer.in-vr .vr-icon:after{font-size:16px;content:\"\\E7F4\"}.vr-icon:after{font-size:16px;content:\"\\F119\"}.progress-control{display:flex;flex:1;position:relative;overflow:hidden;cursor:pointer;align-items:center}.animation-number{margin:0 6px}.speed-text{margin-right:6px}.progress-circle{width:12px;height:12px;border:2px solid #fff;border-radius:50%;background-color:#5b5d6b;cursor:pointer;position:relative;bottom:10px;pointer-events:none}.default-control{display:flex;flex-direction:row;height:100%;background-color:rgba(91,93,107,.75)}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button{width:100%;height:48px;color:#8e939b}.menu-options button:hover{background-color:transparent;color:#fff}.menu-options .animation-number{margin:0 18px 0 6px}.menu-options .speed-text{margin-right:18px}.menu-options{visibility:hidden}.open .menu-options{visibility:visible}.types .menu-options{width:144px}.types .menu-options button{padding:0 8px;justify-content:left}.types .menu-options button>*{display:flex;margin:8px}.types .menu-options button span.animation-number{display:none}.fullscreen{display:none}@media screen and (min-width:540px){.help,.speed,.types-icon{display:inline-block}.logo-button{display:flex}.types{width:84px}.progress-bar-container{margin:0 12px}.speed{width:64px}.speed .menu-options{width:64px}.fullscreen{display:block}}@media screen and (min-width:1024px){.animation-label{display:block;margin-left:6px;text-overflow:ellipsis;overflow:hidden}nav-bar button.animation-buttons{padding:0 8px;justify-content:left}.icon.up-icon{margin-left:8px}nav-bar button.animation-buttons>div{display:flex;pointer-events:none}.animation-number{display:none}.progress-bar-container{margin:0 12px}.types{width:144px}}.progress-wrapper{-webkit-appearance:none;cursor:pointer;width:100%;outline:0;margin:0 12px;height:30px;background-color:transparent}.progress-wrapper::-webkit-slider-thumb{-webkit-appearance:none;width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:-10px}.progress-wrapper::-webkit-slider-runnable-track{height:2px;-webkit-appearance:none;background-color:#fff}.progress-wrapper::-moz-range-progress{background-color:#fff;height:2px}.progress-wrapper::-moz-range-thumb{width:20px;height:20px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1)}.progress-wrapper::-moz-range-track{background:#fff;height:2px}.progress-wrapper::-ms-track{height:2px;background:0 0;border-color:transparent;border-width:10px 0;color:transparent}.progress-wrapper::-ms-fill-lower{background:#fff;border-radius:5px}.progress-wrapper::-ms-fill-upper{background:#fff;border-radius:5px}.progress-wrapper::-ms-thumb{width:16px;height:16px;border:2px solid #fff;border-radius:50%;background:rgba(91,93,107,1);margin-top:0}span{display:inline-block}</style> {{#if (or (not animations) hideAnimations)}} {{#if hideLogo}} <style>nav-bar .nav-container{justify-content:flex-end}</style> {{else}} <style>nav-bar .nav-container{justify-content:space-between}</style> {{/if}} {{/if}} {{#if disableOnFullscreen}} <style>viewer.in-fullscreen nav-bar{display:none}</style> {{/if}} <div class=\"nav-container navbar-control\"> {{#unless hideLogo}} <div class=logo-button title={{logoText}}> {{#if logoLink}} <a href={{logoLink}} target=_blank> <img src={{logoImage}}> </a> {{else}} <img src={{logoImage}}> {{/if}} </div> {{/unless}}{{#unless (or (not animations) hideAnimations)}} <div class=animation-control> <div class=types> <button class=\"flex-container types-button animation-buttons\"> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{selectedAnimationName}}</span> <span class=\"control-text animation-number\">{{selectedAnimation}}</span> {{#if (gt (count animations) 1)}} <span class=\"icon up-icon\"></span> {{/if}} </button> <div class=menu-options> {{#each animations}} {{#unless (eq ../selectedAnimation (add @index 1))}} <button class=\"flex-container label-option-button animation-buttons\" data-value={{this.value}}> <span class=\"icon types-icon\"></span> <span class=\"control-text animation-label\">{{this.label}}</span> <span class=\"control-text animation-number\">{{add @index 1}}</span> </button> {{/unless}} {{/each}} </div> </div> <div class=progress-control> <button class=\"play-pause play-pause-button\"> {{#if paused}} <span class=\"icon play-icon\"></span> {{else}} <span class=\"icon pause-icon\"></span> {{/if}} </button> <input class=progress-wrapper type=range min=0 max=100 step=0.01> </div> <div class=speed> <button class=\"flex-container speed-button\"> <span class=\"control-text speed-text\">{{selectedSpeed}}</span> <span class=\"icon up-icon\"></span> </button> <div class=menu-options> {{#eachInMap speedList}} {{#unless (eq ../selectedSpeed id)}} <button class=\"flex-container speed-option-button\" data-value={{value}}> <span class=\"control-text speed-text\">{{id}}</span> </button> {{/unless}} {{/eachInMap}} </div> </div> </div> {{/unless}} <div class=default-control> {{#unless hideVr}} <button class=\"vr vr-button\" title={{text.vrButton}}> <span class=\"icon vr-icon\"></span> </button> {{/unless}}{{#unless hideHelp}} <button class=\"help help-button\" title={{text.helpButton}}> <span class=\"icon help-icon\"></span> </button> {{/unless}} {{#unless hideFullScreen}} <button class=\"fullscreen fullscreen-button\" title={{text.fullscreenButton}}> <span class=\"icon fullscreen-icon\"></span> </button> {{/unless}} </div> </div>";
  118138. /***/ }),
  118139. /* 48 */
  118140. /***/ (function(module, exports) {
  118141. module.exports = "<style>overlay{position:absolute;z-index:99;opacity:0;display:none;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>";
  118142. /***/ }),
  118143. /* 49 */
  118144. /***/ (function(module, exports) {
  118145. module.exports = "SHARE";
  118146. /***/ }),
  118147. /* 50 */
  118148. /***/ (function(module, exports, __webpack_require__) {
  118149. "use strict";
  118150. Object.defineProperty(exports, "__esModule", { value: true });
  118151. var babylonjs_viewer_assets_1 = __webpack_require__(2);
  118152. var babylonjs_viewer_assets_2 = __webpack_require__(2);
  118153. var images = __webpack_require__(2);
  118154. /**
  118155. * The default configuration of the viewer, including templates (canvas, overly, loading screen)
  118156. * This configuration doesn't hold specific parameters, and only defines objects that are needed for the viewer to fully work correctly.
  118157. */
  118158. exports.defaultConfiguration = {
  118159. version: "3.2.0-alpha4",
  118160. templates: {
  118161. main: {
  118162. html: babylonjs_viewer_assets_1.defaultTemplate,
  118163. params: {
  118164. babylonFont: babylonjs_viewer_assets_2.babylonFont,
  118165. noEscape: true
  118166. }
  118167. },
  118168. fillContainer: {
  118169. html: babylonjs_viewer_assets_1.fillContainer,
  118170. params: {
  118171. disable: false
  118172. }
  118173. },
  118174. loadingScreen: {
  118175. html: babylonjs_viewer_assets_1.loadingScreen,
  118176. params: {
  118177. backgroundColor: "#000000",
  118178. loadingImage: images.loading
  118179. }
  118180. },
  118181. viewer: {
  118182. html: babylonjs_viewer_assets_1.defaultViewer,
  118183. params: {
  118184. enableDragAndDrop: false
  118185. }
  118186. },
  118187. navBar: {
  118188. html: babylonjs_viewer_assets_1.navbar,
  118189. params: {
  118190. speedList: {
  118191. "0.5x": "0.5",
  118192. "1.0x": "1.0",
  118193. "1.5x": "1.5",
  118194. "2.0x": "2.0",
  118195. },
  118196. logoImage: images.babylonLogo,
  118197. logoText: 'BabylonJS',
  118198. logoLink: 'https://babylonjs.com',
  118199. hideHelp: true,
  118200. hideHd: true,
  118201. hideVr: true,
  118202. disableOnFullscreen: false,
  118203. text: {
  118204. hdButton: "Toggle HD",
  118205. fullscreenButton: "Fullscreen",
  118206. helpButton: "Help",
  118207. vrButton: "Toggle VR"
  118208. }
  118209. },
  118210. events: {
  118211. pointerdown: {
  118212. '.navbar-control': true,
  118213. '.help-button': true
  118214. },
  118215. input: {
  118216. '.progress-wrapper': true
  118217. },
  118218. pointerup: {
  118219. '.progress-wrapper': true
  118220. }
  118221. }
  118222. },
  118223. overlay: {
  118224. html: babylonjs_viewer_assets_1.overlay,
  118225. params: {
  118226. closeImage: images.close,
  118227. closeText: 'Close'
  118228. }
  118229. },
  118230. help: {
  118231. html: babylonjs_viewer_assets_1.help
  118232. },
  118233. share: {
  118234. html: babylonjs_viewer_assets_1.share
  118235. },
  118236. error: {
  118237. html: babylonjs_viewer_assets_1.error
  118238. }
  118239. },
  118240. camera: {
  118241. behaviors: {
  118242. autoRotate: {
  118243. type: 0
  118244. },
  118245. framing: {
  118246. type: 2,
  118247. zoomOnBoundingInfo: true,
  118248. zoomStopsAnimation: false
  118249. },
  118250. bouncing: {
  118251. type: 1
  118252. }
  118253. }
  118254. },
  118255. skybox: {},
  118256. ground: {
  118257. receiveShadows: true
  118258. },
  118259. engine: {
  118260. antialiasing: true
  118261. },
  118262. scene: {}
  118263. };
  118264. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZGVmYXVsdC5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL3R5cGVzL2RlZmF1bHQudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSxtRUFBNEk7QUFDNUksbUVBQXNEO0FBQ3RELGdEQUFrRDtBQUVsRDs7O0dBR0c7QUFDUSxRQUFBLG9CQUFvQixHQUF3QjtJQUNuRCxPQUFPLEVBQUUsY0FBYztJQUN2QixTQUFTLEVBQUU7UUFDUCxJQUFJLEVBQUU7WUFDRixJQUFJLEVBQUUseUNBQWU7WUFDckIsTUFBTSxFQUFFO2dCQUNKLFdBQVcsRUFBRSxxQ0FBVztnQkFDeEIsUUFBUSxFQUFFLElBQUk7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osT0FBTyxFQUFFLEtBQUs7YUFDakI7U0FDSjtRQUNELGFBQWEsRUFBRTtZQUNYLElBQUksRUFBRSx1Q0FBYTtZQUNuQixNQUFNLEVBQUU7Z0JBQ0osZUFBZSxFQUFFLFNBQVM7Z0JBQzFCLFlBQVksRUFBRSxNQUFNLENBQUMsT0FBTzthQUMvQjtTQUNKO1FBQ0QsTUFBTSxFQUFFO1lBQ0osSUFBSSxFQUFFLHVDQUFhO1lBQ25CLE1BQU0sRUFBRTtnQkFDSixpQkFBaUIsRUFBRSxLQUFLO2FBQzNCO1NBQ0o7UUFDRCxNQUFNLEVBQUU7WUFDSixJQUFJLEVBQUUsZ0NBQU07WUFDWixNQUFNLEVBQUU7Z0JBQ0osU0FBUyxFQUFFO29CQUNQLE1BQU0sRUFBRSxLQU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DtLQUVKO0lBQ0QsTUFBTSxFQUFFO1FBQ0osU0FBUyxFQUFFO1lBQ1AsVUFBVSxFQUFFO2dCQUNSLElBQUksRUFBRSxDQUFDO2FBQ1Y7WUFDRCxPQUFPLEVBQUU7Z0JBQ0wsSUFBSSxFQUFFLENBQUM7Z0JBQ1Asa0JBQWtCLEVBQUUsSUFBSTtnQkFDeEIsa0JBQWtCLEVBQUUsS0FBSzthQUM1QjtZQUNELFFBQVEsRUFBRTtnQkFDTixJQUFJLEVBQUUsQ0FBQzthQUNWO1NBQ0o7S0FDSjtJQUNELE1BQU0sRUFBRSxFQUNQO0lBQ0QsTUFBTSxFQUFFO1FBQ0osY0FBYyxFQUFFLElBQUk7S0FDdkI7SUFDRCxNQUFNLEVBQUU7UUFDSixZQUFZLEVBQUUsSUFBSTtLQUNyQjtJQUNELEtBQUssRUFBRSxFQUNOO0NBQ0osQ0FBQSJ9
  118265. /***/ }),
  118266. /* 51 */
  118267. /***/ (function(module, exports, __webpack_require__) {
  118268. "use strict";
  118269. Object.defineProperty(exports, "__esModule", { value: true });
  118270. var babylonjs_1 = __webpack_require__(0);
  118271. /**
  118272. * The viewer's "extended" configuration.
  118273. * This configuration defines specific obejcts and parameters that we think make any model look good.
  118274. */
  118275. exports.extendedConfiguration = {
  118276. version: "3.2.0",
  118277. extends: "default",
  118278. camera: {
  118279. exposure: 3.034578,
  118280. fov: 0.7853981633974483,
  118281. contrast: 1.6,
  118282. toneMappingEnabled: true,
  118283. upperBetaLimit: 1.3962634015954636 + Math.PI / 2,
  118284. lowerBetaLimit: -1.4835298641951802 + Math.PI / 2,
  118285. behaviors: {
  118286. framing: {
  118287. type: 2,
  118288. mode: 0,
  118289. positionScale: 0.5,
  118290. defaultElevation: 0.2617993877991494,
  118291. elevationReturnWaitTime: 3000,
  118292. elevationReturnTime: 2000,
  118293. framingTime: 500,
  118294. zoomStopsAnimation: false,
  118295. radiusScale: 0.866
  118296. },
  118297. autoRotate: {
  118298. type: 0,
  118299. idleRotationWaitTime: 4000,
  118300. idleRotationSpeed: 0.17453292519943295,
  118301. idleRotationSpinupTime: 2500,
  118302. zoomStopsAnimation: false
  118303. },
  118304. bouncing: {
  118305. type: 1,
  118306. lowerRadiusTransitionRange: 0.05,
  118307. upperRadiusTransitionRange: -0.2
  118308. }
  118309. },
  118310. upperRadiusLimit: 5,
  118311. lowerRadiusLimit: 0.5,
  118312. frameOnModelLoad: true,
  118313. framingElevation: 0.2617993877991494,
  118314. framingRotation: 1.5707963267948966,
  118315. radius: 2,
  118316. alpha: 1.5708,
  118317. beta: Math.PI * 0.5 - 0.2618,
  118318. wheelPrecision: 300,
  118319. minZ: 0.1,
  118320. maxZ: 50,
  118321. fovMode: 0,
  118322. pinchPrecision: 1500,
  118323. panningSensibility: 3000
  118324. },
  118325. lights: {
  118326. light0: {
  118327. type: 0,
  118328. frustumEdgeFalloff: 0,
  118329. intensity: 7,
  118330. intensityMode: 0,
  118331. radius: 0.6,
  118332. range: 0.6,
  118333. spotAngle: 60,
  118334. diffuse: {
  118335. r: 1,
  118336. g: 1,
  118337. b: 1
  118338. },
  118339. position: {
  118340. x: -2,
  118341. y: 2.5,
  118342. z: 2
  118343. },
  118344. target: {
  118345. x: 0,
  118346. y: 0,
  118347. z: 0
  118348. },
  118349. enabled: true,
  118350. shadowEnabled: true,
  118351. shadowBufferSize: 512,
  118352. shadowMinZ: 1,
  118353. shadowMaxZ: 10,
  118354. shadowFieldOfView: 60,
  118355. shadowFrustumSize: 2,
  118356. shadowConfig: {
  118357. useBlurCloseExponentialShadowMap: true,
  118358. useKernelBlur: true,
  118359. blurScale: 1.0,
  118360. bias: 0.001,
  118361. depthScale: 50 * (10 - 1),
  118362. frustumEdgeFalloff: 0
  118363. }
  118364. },
  118365. light1: {
  118366. type: 0,
  118367. frustumEdgeFalloff: 0,
  118368. intensity: 7,
  118369. intensityMode: 0,
  118370. radius: 0.4,
  118371. range: 0.4,
  118372. spotAngle: 57,
  118373. diffuse: {
  118374. r: 1,
  118375. g: 1,
  118376. b: 1
  118377. },
  118378. position: {
  118379. x: 4,
  118380. y: 3,
  118381. z: -0.5
  118382. },
  118383. target: {
  118384. x: 0,
  118385. y: 0,
  118386. z: 0
  118387. },
  118388. enabled: true,
  118389. shadowEnabled: false,
  118390. shadowBufferSize: 512,
  118391. shadowMinZ: 0.2,
  118392. shadowMaxZ: 10,
  118393. shadowFieldOfView: 28,
  118394. shadowFrustumSize: 2
  118395. },
  118396. light2: {
  118397. type: 0,
  118398. frustumEdgeFalloff: 0,
  118399. intensity: 1,
  118400. intensityMode: 0,
  118401. radius: 0.5,
  118402. range: 0.5,
  118403. spotAngle: 42.85,
  118404. diffuse: {
  118405. r: 0.8,
  118406. g: 0.8,
  118407. b: 0.8
  118408. },
  118409. position: {
  118410. x: -1,
  118411. y: 3,
  118412. z: -3
  118413. },
  118414. target: {
  118415. x: 0,
  118416. y: 0,
  118417. z: 0
  118418. },
  118419. enabled: true,
  118420. shadowEnabled: false,
  118421. shadowBufferSize: 512,
  118422. shadowMinZ: 0.2,
  118423. shadowMaxZ: 10,
  118424. shadowFieldOfView: 45,
  118425. shadowFrustumSize: 2
  118426. }
  118427. },
  118428. ground: {
  118429. shadowLevel: 0.9,
  118430. texture: "Ground_2.0-1024.png",
  118431. material: {
  118432. primaryColorHighlightLevel: 0.035,
  118433. primaryColorShadowLevel: 0,
  118434. enableNoise: true,
  118435. useRGBColor: false,
  118436. maxSimultaneousLights: 1,
  118437. diffuseTexture: {
  118438. gammaSpace: true
  118439. }
  118440. },
  118441. opacity: 1,
  118442. mirror: false,
  118443. receiveShadows: true,
  118444. size: 5
  118445. },
  118446. skybox: {
  118447. scale: 11,
  118448. cubeTexture: {
  118449. url: "Skybox_2.0-256.dds"
  118450. },
  118451. material: {
  118452. primaryColorHighlightLevel: 0.03,
  118453. primaryColorShadowLevel: 0.03,
  118454. enableNoise: true,
  118455. useRGBColor: false,
  118456. reflectionTexture: {
  118457. gammaSpace: true
  118458. }
  118459. }
  118460. },
  118461. engine: {
  118462. renderInBackground: true
  118463. },
  118464. scene: {
  118465. flags: {
  118466. shadowsEnabled: true,
  118467. particlesEnabled: false,
  118468. collisionsEnabled: false,
  118469. lightsEnabled: true,
  118470. texturesEnabled: true,
  118471. lensFlaresEnabled: false,
  118472. proceduralTexturesEnabled: false,
  118473. renderTargetsEnabled: true,
  118474. spritesEnabled: false,
  118475. skeletonsEnabled: true,
  118476. audioEnabled: false,
  118477. },
  118478. defaultMaterial: {
  118479. materialType: 'pbr',
  118480. reflectivityColor: {
  118481. r: 0.1,
  118482. g: 0.1,
  118483. b: 0.1
  118484. },
  118485. microSurface: 0.6
  118486. },
  118487. clearColor: {
  118488. r: 0.9,
  118489. g: 0.9,
  118490. b: 0.9,
  118491. a: 1.0
  118492. },
  118493. imageProcessingConfiguration: {
  118494. vignetteCentreX: 0,
  118495. vignetteCentreY: 0,
  118496. vignetteColor: {
  118497. r: 0.086,
  118498. g: 0.184,
  118499. b: 0.259,
  118500. a: 1
  118501. },
  118502. vignetteWeight: 0.855,
  118503. vignetteStretch: 0.5,
  118504. vignetteBlendMode: 0,
  118505. vignetteCameraFov: 0.7853981633974483,
  118506. isEnabled: true,
  118507. colorCurves: {
  118508. shadowsHue: 0,
  118509. shadowsDensity: 0,
  118510. shadowsSaturation: 0,
  118511. shadowsExposure: 0,
  118512. midtonesHue: 0,
  118513. midtonesDensity: 0,
  118514. midtonesExposure: 0,
  118515. midtonesSaturation: 0,
  118516. highlightsHue: 0,
  118517. highlightsDensity: 0,
  118518. highlightsExposure: 0,
  118519. highlightsSaturation: 0
  118520. }
  118521. },
  118522. mainColor: {
  118523. r: 0.8823529411764706,
  118524. g: 0.8823529411764706,
  118525. b: 0.8823529411764706
  118526. }
  118527. },
  118528. loaderPlugins: {
  118529. extendedMaterial: true,
  118530. applyMaterialConfig: true,
  118531. msftLod: true,
  118532. telemetry: true
  118533. },
  118534. model: {
  118535. rotationOffsetAxis: {
  118536. x: 0,
  118537. y: -1,
  118538. z: 0
  118539. },
  118540. rotationOffsetAngle: babylonjs_1.Tools.ToRadians(210),
  118541. material: {
  118542. directEnabled: true,
  118543. directIntensity: 0.884,
  118544. emissiveIntensity: 1.04,
  118545. environmentIntensity: 0.6
  118546. },
  118547. entryAnimation: {
  118548. scaling: {
  118549. x: 0,
  118550. y: 0,
  118551. z: 0
  118552. },
  118553. time: 0.5,
  118554. easingFunction: 4,
  118555. easingMode: 1
  118556. },
  118557. exitAnimation: {
  118558. scaling: {
  118559. x: 0,
  118560. y: 0,
  118561. z: 0
  118562. },
  118563. time: 0.5,
  118564. easingFunction: 4,
  118565. easingMode: 1
  118566. },
  118567. normalize: true,
  118568. castShadow: true,
  118569. receiveShadows: true
  118570. },
  118571. lab: {
  118572. assetsRootURL: 'https://viewer.babylonjs.com/assets/environment/',
  118573. environmentMap: {
  118574. texture: "EnvMap_2.0-256.env",
  118575. rotationY: 3,
  118576. tintLevel: 0.4
  118577. },
  118578. defaultRenderingPipelines: {
  118579. bloomEnabled: true,
  118580. bloomThreshold: 1.0,
  118581. fxaaEnabled: true,
  118582. bloomWeight: 0.05
  118583. }
  118584. }
  118585. };
  118586. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9leHRlbmRlZC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVDQUFrQztBQUVsQzs7O0dBR0c7QUFDUSxRQUFBLHFCQUFxQixHQUF3QjtJQUNwRCxPQUFPLEVBQUUsT0FBTztJQUNoQixPQUFPLEVBQUUsU0FBUztJQUNsQixNQUFNLEVBQUU7UUFDSixRQUFRLEVBQUUsUUFBUTtRQUNsQixHQUFHLEVBQUUsa0JBQWtCO1FBQ3ZCLFFBQVEsRUFBRSxHQUFHO1FBQ2Isa0JBQWtCLEVBQUU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DRCxhQUFhLEVBQUUsa0RBQWtEO1FBQ2pFLGNBQWMsRUFBRTtZQUNaLE9BQU8sRUFBRSxvQkFBb0I7WUFDN0IsU0FBUyxFQUFFLENBQUM7WUFDWixTQUFTLEVBQUUsR0FBRztTQUNqQjtRQUNELHlCQUF5QixFQUFFO1lBQ3ZCLFlBQVksRUFBRSxJQUFJO1lBQ2xCLGNBQWMsRUFBRSxHQUFHO1lBQ25CLFdBQVcsRUFBRSxJQUFJO1lBQ2pCLFdBQVcsRUFBRSxJQUFJO1NBQ3BCO0tBQ0o7Q0FDSixDQUFBIn0=
  118587. /***/ }),
  118588. /* 52 */
  118589. /***/ (function(module, exports, __webpack_require__) {
  118590. "use strict";
  118591. Object.defineProperty(exports, "__esModule", { value: true });
  118592. /**
  118593. * Defines a default directional shadow light for normalized objects (!)
  118594. */
  118595. exports.shadowDirectionalLightConfiguration = {
  118596. model: {
  118597. receiveShadows: true,
  118598. castShadow: true
  118599. },
  118600. ground: {
  118601. receiveShadows: true
  118602. },
  118603. lights: {
  118604. shadowDirectionalLight: {
  118605. type: 1,
  118606. shadowEnabled: true,
  118607. target: { x: 0, y: 0, z: 0.5 },
  118608. position: { x: 1.49, y: 2.39, z: -1.33 },
  118609. diffuse: { r: 0.867, g: 0.816, b: 0.788 },
  118610. intensity: 4.887,
  118611. intensityMode: 0,
  118612. shadowBufferSize: 1024,
  118613. shadowFrustumSize: 6.0,
  118614. shadowFieldOfView: 50.977,
  118615. shadowMinZ: 0.1,
  118616. shadowMaxZ: 10.0,
  118617. shadowConfig: {
  118618. blurKernel: 32,
  118619. useBlurCloseExponentialShadowMap: true
  118620. }
  118621. }
  118622. }
  118623. };
  118624. /**
  118625. * Defines a default shadow-enabled spot light for normalized objects.
  118626. */
  118627. exports.shadowSpotlLightConfiguration = {
  118628. model: {
  118629. receiveShadows: true,
  118630. castShadow: true
  118631. },
  118632. ground: {
  118633. receiveShadows: true
  118634. },
  118635. lights: {
  118636. shadowSpotLight: {
  118637. type: 2,
  118638. intensity: 2,
  118639. shadowEnabled: true,
  118640. target: { x: 0, y: 0, z: 0.5 },
  118641. position: { x: 0, y: 3.5, z: 3.7 },
  118642. angle: 1,
  118643. shadowOrthoScale: 0.5,
  118644. shadowBufferSize: 1024,
  118645. shadowMinZ: 0.1,
  118646. shadowMaxZ: 50.0,
  118647. shadowConfig: {
  118648. frustumEdgeFalloff: 0.5,
  118649. blurKernel: 32,
  118650. useBlurExponentialShadowMap: true
  118651. }
  118652. }
  118653. }
  118654. };
  118655. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoic2hhZG93TGlnaHQuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9zaGFkb3dMaWdodC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSxtQ0FBbUMsR0FBd0I7SUFDcEUsS0FBSyxFQUFFO1FBQ0gsY0FBYyxFQUFFLElBQUk7UUFDcEIsVUFBVSxFQUFFLElBQUk7S0FDbkI7SUFDRCxNQUFNLEVBQUU7UUFDSixjQUFjLEVBQUUsSUFBSTtLQUN2QjtJQUNELE1BQU0sRUFBRTtRQUNKLHNCQUFzQixFQUFFO1lBQ3BCLElBQUksRUFBRSxDQUFDO1lBQ1AsYUFBYSxFQUFFLElBQUk7WUFDbkIsTUFBTSxFQUFFLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxDQUFDLEVBQUUsQ0FBQyxFQUFFLENBQUMsRUFBRSxHQUFHLEVBQUU7WUFDOUIsUUFBUSxFQUFFLEVBQUUsQ0FBQyxFQUFFLElBQUksRUFBRSxDQUFDLEVBQUUsSUFBSSxFQUFFLENBQUMsRUFBRSxDQUFDLElBQUksRUFBRTtZQUN4QyxPQUFPLEVBQUUsRUFBRSxDQUFDLEVBQUUsS0FBSyxFQUFFLENBQUMs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UFZLEVBQUU7Z0JBQ1Ysa0JBQWtCLEVBQUUsR0FBRztnQkFDdkIsVUFBVSxFQUFFLEVBQUU7Z0JBQ2QsMkJBQTJCLEVBQUUsSUFBSTthQUNwQztTQUNKO0tBQ0o7Q0FDSixDQUFBIn0=
  118656. /***/ }),
  118657. /* 53 */
  118658. /***/ (function(module, exports, __webpack_require__) {
  118659. "use strict";
  118660. Object.defineProperty(exports, "__esModule", { value: true });
  118661. /**
  118662. * Lab-oriented default .env support
  118663. */
  118664. exports.environmentMapConfiguration = {
  118665. lab: {
  118666. assetsRootURL: '/assets/environment/',
  118667. environmentMap: {
  118668. texture: 'EnvMap_2.0-256.env',
  118669. rotationY: 0,
  118670. tintLevel: 0.4
  118671. }
  118672. }
  118673. };
  118674. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZW52aXJvbm1lbnRNYXAuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi90eXBlcy9lbnZpcm9ubWVudE1hcC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUVBOztHQUVHO0FBQ1UsUUFBQSwyQkFBMkIsR0FBd0I7SUFDNUQsR0FBRyxFQUFFO1FBQ0QsYUFBYSxFQUFFLHNCQUFzQjtRQUNyQyxjQUFjLEVBQUU7WUFDWixPQUFPLEVBQUUsb0JBQW9CO1lBQzdCLFNBQVMsRUFBRSxDQUFDO1lBQ1osU0FBUyxFQUFFLEdBQUc7U0FDakI7S0FDSjtDQUNKLENBQUEifQ==
  118675. /***/ }),
  118676. /* 54 */
  118677. /***/ (function(module, exports, __webpack_require__) {
  118678. "use strict";
  118679. Object.defineProperty(exports, "__esModule", { value: true });
  118680. var configuration_1 = __webpack_require__(11);
  118681. /**
  118682. * This function will make sure the configuration file is taking deprecated fields into account
  118683. * and is setting them to the correct keys and values.
  118684. *
  118685. * @param configuration The configuration to process. Mutable!
  118686. */
  118687. function processConfigurationCompatibility(configuration) {
  118688. if (configuration.camera) {
  118689. // camera contrast -> image processing contrast
  118690. if (configuration.camera.contrast !== undefined) {
  118691. setKeyInObject(configuration, "scene.imageProcessingConfiguration.contrast", configuration.camera.contrast);
  118692. }
  118693. // camera exposure -> image processing exposure
  118694. if (configuration.camera.exposure !== undefined) {
  118695. setKeyInObject(configuration, "scene.imageProcessingConfiguration.exposure", configuration.camera.exposure);
  118696. }
  118697. }
  118698. if (configuration.scene) {
  118699. //glow
  118700. if (configuration.scene.glow) {
  118701. setKeyInObject(configuration, "lab.defaultRenderingPipelines.glowLayerEnabled", true);
  118702. var enabledProcessing = configuration_1.getConfigurationKey("scene.imageProcessingConfiguration.isEnabled", configuration);
  118703. if (enabledProcessing !== false) {
  118704. setKeyInObject(configuration, "scene.imageProcessingConfiguration.isEnabled", true);
  118705. }
  118706. }
  118707. }
  118708. }
  118709. exports.processConfigurationCompatibility = processConfigurationCompatibility;
  118710. function setKeyInObject(object, keys, value, shouldOverwrite) {
  118711. var keySplit = keys.split(".");
  118712. if (keySplit.length === 0)
  118713. return;
  118714. var lastKey = keySplit.pop();
  118715. if (!lastKey)
  118716. return;
  118717. var curObj = object;
  118718. keySplit.forEach(function (key) {
  118719. curObj[key] = curObj[key] || {};
  118720. curObj = curObj[key];
  118721. });
  118722. if (curObj[lastKey] !== undefined && !shouldOverwrite)
  118723. return;
  118724. curObj[lastKey] = value;
  118725. }
  118726. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbXBhdGliaWxpdHkuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvY29uZmlndXJhdGlvbi9jb25maWd1cmF0aW9uQ29tcGF0aWJpbGl0eS50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLGlEQUEwRTtBQUMxRTs7Ozs7R0FLRztBQU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UssQ0FBQztRQUFFLE9BQU87SUFDbEMsSUFBSSxPQUFPLEdBQUcsUUFBUSxDQUFDLEdBQUcsRUFBRSxDQUFDO0lBQzdCLElBQUksQ0FBQyxPQUFPO1FBQUUsT0FBTztJQUNyQixJQUFJLE1BQU0sR0FBRyxNQUFNLENBQUM7SUFDcEIsUUFBUSxDQUFDLE9BQU8sQ0FBQyxVQUFBLEdBQUc7UUFDaEIsTUFBTSxDQUFDLEdBQUcsQ0FBQyxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsSUFBSSxFQUFFLENBQUM7UUFDaEMsTUFBTSxHQUFHLE1BQU0sQ0FBQyxHQUFHLENBQUMsQ0FBQztJQUN6QixDQUFDLENBQUMsQ0FBQztJQUNILElBQUksTUFBTSxDQUFDLE9BQU8sQ0FBQyxLQUFLLFNBQVMsSUFBSSxDQUFDLGVBQWU7UUFBRSxPQUFPO0lBQzlELE1BQU0sQ0FBQyxPQUFPLENBQUMsR0FBRyxLQUFLLENBQUM7QUFDNUIsQ0FBQyJ9
  118727. /***/ }),
  118728. /* 55 */
  118729. /***/ (function(module, exports, __webpack_require__) {
  118730. "use strict";
  118731. Object.defineProperty(exports, "__esModule", { value: true });
  118732. var telemetryLoaderPlugin_1 = __webpack_require__(56);
  118733. exports.TelemetryLoaderPlugin = telemetryLoaderPlugin_1.TelemetryLoaderPlugin;
  118734. var msftLodLoaderPlugin_1 = __webpack_require__(57);
  118735. exports.MSFTLodLoaderPlugin = msftLodLoaderPlugin_1.MSFTLodLoaderPlugin;
  118736. var applyMaterialConfig_1 = __webpack_require__(58);
  118737. exports.ApplyMaterialConfigPlugin = applyMaterialConfig_1.ApplyMaterialConfigPlugin;
  118738. var extendedMaterialLoaderPlugin_1 = __webpack_require__(59);
  118739. exports.ExtendedMaterialLoaderPlugin = extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin;
  118740. var babylonjs_1 = __webpack_require__(0);
  118741. var pluginCache = {};
  118742. /**
  118743. * Get a loader plugin according to its name.
  118744. * The plugin will be cached and will be reused if called for again.
  118745. *
  118746. * @param name the name of the plugin
  118747. */
  118748. function getLoaderPluginByName(name) {
  118749. if (!pluginCache[name]) {
  118750. switch (name) {
  118751. case 'telemetry':
  118752. pluginCache[name] = new telemetryLoaderPlugin_1.TelemetryLoaderPlugin();
  118753. break;
  118754. case 'msftLod':
  118755. pluginCache[name] = new msftLodLoaderPlugin_1.MSFTLodLoaderPlugin();
  118756. break;
  118757. case 'applyMaterialConfig':
  118758. pluginCache[name] = new applyMaterialConfig_1.ApplyMaterialConfigPlugin();
  118759. break;
  118760. case 'extendedMaterial':
  118761. pluginCache[name] = new extendedMaterialLoaderPlugin_1.ExtendedMaterialLoaderPlugin();
  118762. break;
  118763. }
  118764. }
  118765. return pluginCache[name];
  118766. }
  118767. exports.getLoaderPluginByName = getLoaderPluginByName;
  118768. /**
  118769. *
  118770. */
  118771. function addLoaderPlugin(name, plugin) {
  118772. if (pluginCache[name]) {
  118773. babylonjs_1.Tools.Warn("Overwriting plugin with the same name - " + name);
  118774. }
  118775. pluginCache[name] = plugin;
  118776. }
  118777. exports.addLoaderPlugin = addLoaderPlugin;
  118778. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvbG9hZGVyL3BsdWdpbnMvaW5kZXgudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSxpRUFBZ0U7QUFTdkQsZ0NBVEEsNkNBQXFCLENBU0E7QUFQOUIsNkRBQTREO0FBT2IsOEJBUHRDLHlDQUFtQixDQU9zQztBQU5sRSw2REFBa0U7QUFNRSxvQ0FOM0QsK0NBQXlCLENBTTJEO0FBTDdGLCtFQUE4RTtBQUtpQix1Q0FMdEYsMkRBQTRCLENBS3NGO0FBSjNILHVDQUFrQztBQUVsQyxJQUFNLFdBQVcsR0FBcUMsRUFBRSxDQUFDO0FBSXpEOzs7OztHQUtHO0FBQ0gsK0JBQXNDLElBQVk7SUFDOUMsSUFBSSxDQUFDLFdBQVcsQ0FBQyxJQUFJLENBQUMsRUFBRTtRQUNwQixRQUFRLElBQUksRUFBRTtZQUNWLEtBQUssV0FBVztnQkFDWixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSw2Q0FBcUIsRUFBRSxDQUFDO2dCQUNoRCxNQUFNO1lBQ1YsS0FBSyxTQUFTO2dCQUNWLFdBQVcsQ0FBQyxJQUFJLENBQUMsR0FBRyxJQUFJLHlDQUFtQixFQUFFLENBQUM7Z0JBQzlDLE1BQU07WUFDVixLQUFLLHFCQUFxQjtnQkFDdEIsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLElBQUksK0NBQXlCLEVBQUUsQ0FBQztnQkFDcEQsTUFBTTtZQUNWLEtBQUssa0JBQWtCO2dCQUNuQixXQUFXLENBQUMsSUFBSSxDQUFDLEdBQUcsSUFBSSwyREFBNEIsRUFBRSxDQUFDO2dCQUN2RCxNQUFNO1NBQ2I7S0FDSjtJQUVELE9BQU8sV0FBVyxDQUFDLElBQUksQ0FBQyxDQUFDO0FBQzdCLENBQUM7QUFuQkQsc0RBbUJDO0FBRUQ7O0dBRUc7QUFDSCx5QkFBZ0MsSUFBWSxFQUFFLE1BQXFCO0lBQy9ELElBQUksV0FBVyxDQUFDLElBQUksQ0FBQyxFQUFFO1FBQ25CLGlCQUFLLENBQUMsSUFBSSxDQUFDLDBDQUEwQyxHQUFHLElBQUksQ0FBQyxDQUFDO0tBQ2pFO0lBQ0QsV0FBVyxDQUFDLElBQUksQ0FBQyxHQUFHLE1BQU0sQ0FBQztBQUMvQixDQUFDO0FBTEQsMENBS0MifQ==
  118779. /***/ }),
  118780. /* 56 */
  118781. /***/ (function(module, exports, __webpack_require__) {
  118782. "use strict";
  118783. Object.defineProperty(exports, "__esModule", { value: true });
  118784. var telemetryManager_1 = __webpack_require__(6);
  118785. var babylonjs_1 = __webpack_require__(0);
  118786. var TelemetryLoaderPlugin = /** @class */ (function () {
  118787. function TelemetryLoaderPlugin() {
  118788. }
  118789. TelemetryLoaderPlugin.prototype.onInit = function (loader, model) {
  118790. this._model = model;
  118791. this._loadStart = babylonjs_1.Tools.Now;
  118792. };
  118793. TelemetryLoaderPlugin.prototype.onLoaded = function (model) {
  118794. telemetryManager_1.telemetryManager.broadcast("Model Loaded", model.getViewerId(), {
  118795. model: model,
  118796. loadTime: babylonjs_1.Tools.Now - this._loadStart
  118797. });
  118798. telemetryManager_1.telemetryManager.flushWebGLErrors(model.rootMesh.getEngine(), model.getViewerId());
  118799. };
  118800. TelemetryLoaderPlugin.prototype.onError = function (message, exception) {
  118801. this._loadEnd = babylonjs_1.Tools.Now;
  118802. telemetryManager_1.telemetryManager.broadcast("Load Error", this._model.getViewerId(), {
  118803. model: this._model,
  118804. loadTime: this._loadEnd - this._loadStart
  118805. });
  118806. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118807. };
  118808. TelemetryLoaderPlugin.prototype.onComplete = function () {
  118809. this._loadEnd = babylonjs_1.Tools.Now;
  118810. telemetryManager_1.telemetryManager.broadcast("Load Complete", this._model.getViewerId(), {
  118811. model: this._model,
  118812. loadTime: this._loadEnd - this._loadStart
  118813. });
  118814. telemetryManager_1.telemetryManager.flushWebGLErrors(this._model.rootMesh.getEngine(), this._model.getViewerId());
  118815. };
  118816. return TelemetryLoaderPlugin;
  118817. }());
  118818. exports.TelemetryLoaderPlugin = TelemetryLoaderPlugin;
  118819. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVsZW1ldHJ5TG9hZGVyUGx1Z2luLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vLi4vc3JjL2xvYWRlci9wbHVnaW5zL3RlbGVtZXRyeUxvYWRlclBsdWdpbi50cyJdLCJ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ENBQUMsTUFBTSxDQUFDLFFBQVEsQ0FBQyxTQUFTLEVBQUUsRUFBRSxJQUFJLENBQUMsTUFBTSxDQUFDLFdBQVcsRUFBRSxDQUFDLENBQUM7SUFDbkcsQ0FBQztJQUVNLDBDQUFVLEdBQWpCO1FBQ0ksSUFBSSxDQUFDLFFBQVEsR0FBRyxpQkFBSyxDQUFDLEdBQUcsQ0FBQztRQUMxQixtQ0FBZ0IsQ0FBQyxTQUFTLENBQUMsZUFBZSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLEVBQUU7WUFDbkUsS0FBSyxFQUFFLElBQUksQ0FBQyxNQUFNO1lBQ2xCLFFBQVEsRUFBRSxJQUFJLENBQUMsUUFBUSxHQUFHLElBQUksQ0FBQyxVQUFVO1NBQzVDLENBQUMsQ0FBQztRQUVILG1DQUFnQixDQUFDLGdCQUFnQixDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsUUFBUSxDQUFDLFNBQVMsRUFBRSxFQUFFLElBQUksQ0FBQyxNQUFNLENBQUMsV0FBVyxFQUFFLENBQUMsQ0FBQztJQUNuRyxDQUFDO0lBQ0wsNEJBQUM7QUFBRCxDQUFDLEFBdkNELElBdUNDO0FBdkNZLHNEQUFxQiJ9
  118820. /***/ }),
  118821. /* 57 */
  118822. /***/ (function(module, exports, __webpack_require__) {
  118823. "use strict";
  118824. Object.defineProperty(exports, "__esModule", { value: true });
  118825. /**
  118826. * A loder plugin to use MSFT_lod extension correctly (glTF)
  118827. */
  118828. var MSFTLodLoaderPlugin = /** @class */ (function () {
  118829. function MSFTLodLoaderPlugin() {
  118830. }
  118831. MSFTLodLoaderPlugin.prototype.onInit = function (loader, model) {
  118832. this._model = model;
  118833. };
  118834. MSFTLodLoaderPlugin.prototype.onExtensionLoaded = function (extension) {
  118835. if (extension.name === "MSFT_lod" && this._model.configuration.loaderConfiguration) {
  118836. var MSFT_lod = extension;
  118837. MSFT_lod.enabled = !!this._model.configuration.loaderConfiguration.progressiveLoading;
  118838. MSFT_lod.maxLODsToLoad = this._model.configuration.loaderConfiguration.maxLODsToLoad || Number.MAX_VALUE;
  118839. }
  118840. };
  118841. return MSFTLodLoaderPlugin;
  118842. }());
  118843. exports.MSFTLodLoaderPlugin = MSFTLodLoaderPlugin;
  118844. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoibXNmdExvZExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9tc2Z0TG9kTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBZUEsQ0FBQztJQVhVLG9DQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSwrQ0FBaUIsR0FBeEIsVUFBeUIsU0FBK0I7UUFDcEQsSUFBSSxTQUFTLENBQUMsSUFBSSxLQUFLLFVBQVUsSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxtQkFBbUIsRUFBRTtZQUNoRixJQUFNLFFBQVEsR0FBRyxTQUFzQyxDQUFDO1lBQ3hELFFBQVEsQ0FBQyxPQUFPLEdBQUcsQ0FBQyxDQUFDLElBQUksQ0FBQyxNQUFNLENBQUMsYUFBYSxDQUFDLG1CQUFtQixDQUFDLGtCQUFrQixDQUFDO1lBQ3RGLFFBQVEsQ0FBQyxhQUFhLEdBQUcsSUFBSSxDQUFDLE1BQU0sQ0FBQyxhQUFhLENBQUMsbUJBQW1CLENBQUMsYUFBYSxJQUFJLE1BQU0sQ0FBQyxTQUFTLENBQUM7U0FDNUc7SUFDTCxDQUFDO0lBQ0wsMEJBQUM7QUFBRCxDQUFDLEFBZkQsSUFlQztBQWZZLGtEQUFtQiJ9
  118845. /***/ }),
  118846. /* 58 */
  118847. /***/ (function(module, exports, __webpack_require__) {
  118848. "use strict";
  118849. Object.defineProperty(exports, "__esModule", { value: true });
  118850. /**
  118851. * Force-apply material configuration right after a material was loaded.
  118852. */
  118853. var ApplyMaterialConfigPlugin = /** @class */ (function () {
  118854. function ApplyMaterialConfigPlugin() {
  118855. }
  118856. ApplyMaterialConfigPlugin.prototype.onInit = function (loader, model) {
  118857. this._model = model;
  118858. };
  118859. ApplyMaterialConfigPlugin.prototype.onMaterialLoaded = function (material) {
  118860. this._model && this._model._applyModelMaterialConfiguration(material);
  118861. };
  118862. return ApplyMaterialConfigPlugin;
  118863. }());
  118864. exports.ApplyMaterialConfigPlugin = ApplyMaterialConfigPlugin;
  118865. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiYXBwbHlNYXRlcmlhbENvbmZpZy5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9hcHBseU1hdGVyaWFsQ29uZmlnLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBS0E7O0dBRUc7QUFDSDtJQUFBO0lBV0EsQ0FBQztJQVBVLDBDQUFNLEdBQWIsVUFBYyxNQUFvRCxFQUFFLEtBQWtCO1FBQ2xGLElBQUksQ0FBQyxNQUFNLEdBQUcsS0FBSyxDQUFDO0lBQ3hCLENBQUM7SUFFTSxvREFBZ0IsR0FBdkIsVUFBd0IsUUFBa0I7UUFDdEMsSUFBSSxDQUFDLE1BQU0sSUFBSSxJQUFJLENBQUMsTUFBTSxDQUFDLGdDQUFnQyxDQUFDLFFBQVEsQ0FBQyxDQUFDO0lBQzFFLENBQUM7SUFDTCxnQ0FBQztBQUFELENBQUMsQUFYRCxJQVdDO0FBWFksOERBQXlCIn0=
  118866. /***/ }),
  118867. /* 59 */
  118868. /***/ (function(module, exports, __webpack_require__) {
  118869. "use strict";
  118870. Object.defineProperty(exports, "__esModule", { value: true });
  118871. var babylonjs_1 = __webpack_require__(0);
  118872. /**
  118873. * A (PBR) material will be extended using this function.
  118874. * This function will hold extra default configuration for the viewer, if not implemented in Babylon itself.
  118875. */
  118876. var ExtendedMaterialLoaderPlugin = /** @class */ (function () {
  118877. function ExtendedMaterialLoaderPlugin() {
  118878. }
  118879. ExtendedMaterialLoaderPlugin.prototype.onMaterialLoaded = function (baseMaterial) {
  118880. var material = baseMaterial;
  118881. material.alphaMode = babylonjs_1.Engine.ALPHA_PREMULTIPLIED_PORTERDUFF;
  118882. };
  118883. return ExtendedMaterialLoaderPlugin;
  118884. }());
  118885. exports.ExtendedMaterialLoaderPlugin = ExtendedMaterialLoaderPlugin;
  118886. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXh0ZW5kZWRNYXRlcmlhbExvYWRlclBsdWdpbi5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uLy4uL3NyYy9sb2FkZXIvcGx1Z2lucy9leHRlbmRlZE1hdGVyaWFsTG9hZGVyUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBRUEsdUNBQTRJO0FBRTVJOzs7R0FHRztBQUNIO0lBQUE7SUFNQSxDQUFDO0lBSlUsdURBQWdCLEdBQXZCLFVBQXdCLFlBQXNCO1FBQzFDLElBQUksUUFBUSxHQUFHLFlBQTJCLENBQUM7UUFDM0MsUUFBUSxDQUFDLFNBQVMsR0FBRyxrQkFBTSxDQUFDLDhCQUE4QixDQUFDO0lBQy9ELENBQUM7SUFDTCxtQ0FBQztBQUFELENBQUMsQUFORCxJQU1DO0FBTlksb0VBQTRCIn0=
  118887. /***/ }),
  118888. /* 60 */
  118889. /***/ (function(module, exports, __webpack_require__) {
  118890. "use strict";
  118891. Object.defineProperty(exports, "__esModule", { value: true });
  118892. var babylonjs_1 = __webpack_require__(0);
  118893. var ObservablesManager = /** @class */ (function () {
  118894. function ObservablesManager() {
  118895. this.onSceneInitObservable = new babylonjs_1.Observable();
  118896. this.onEngineInitObservable = new babylonjs_1.Observable();
  118897. this.onModelLoadedObservable = new babylonjs_1.Observable();
  118898. this.onModelLoadProgressObservable = new babylonjs_1.Observable();
  118899. this.onModelLoadErrorObservable = new babylonjs_1.Observable();
  118900. this.onModelAddedObservable = new babylonjs_1.Observable();
  118901. this.onModelRemovedObservable = new babylonjs_1.Observable();
  118902. this.onViewerInitDoneObservable = new babylonjs_1.Observable();
  118903. this.onLoaderInitObservable = new babylonjs_1.Observable();
  118904. this.onFrameRenderedObservable = new babylonjs_1.Observable();
  118905. }
  118906. ObservablesManager.prototype.dispose = function () {
  118907. this.onSceneInitObservable.clear();
  118908. this.onEngineInitObservable.clear();
  118909. this.onModelLoadedObservable.clear();
  118910. this.onModelLoadProgressObservable.clear();
  118911. this.onModelLoadErrorObservable.clear();
  118912. this.onModelAddedObservable.clear();
  118913. this.onModelRemovedObservable.clear();
  118914. this.onViewerInitDoneObservable.clear();
  118915. this.onLoaderInitObservable.clear();
  118916. this.onFrameRenderedObservable.clear();
  118917. };
  118918. return ObservablesManager;
  118919. }());
  118920. exports.ObservablesManager = ObservablesManager;
  118921. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoib2JzZXJ2YWJsZXNNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL21hbmFnZXJzL29ic2VydmFibGVzTWFuYWdlci50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUFBLHVDQUE2SDtBQUc3SDtJQStDSTtRQUNJLElBQUksQ0FBQyxxQkFBcUIsR0FBRyxJQUFJLHNCQUFVLEVBQUUsQ0FBQztRQUM5QyxJQUFJLENBQUMsc0JBQXNCLEdBQU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MsSUFBSSxDQUFDLHNCQUFzQixDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ3BDLElBQUksQ0FBQyx5QkFBeUIsQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUMzQyxDQUFDO0lBRUwseUJBQUM7QUFBRCxDQUFDLEFBekVELElBeUVDO0FBekVZLGdEQUFrQiJ9
  118922. /***/ }),
  118923. /* 61 */
  118924. /***/ (function(module, exports, __webpack_require__) {
  118925. "use strict";
  118926. Object.defineProperty(exports, "__esModule", { value: true });
  118927. var babylonjs_1 = __webpack_require__(0);
  118928. var ConfigurationContainer = /** @class */ (function () {
  118929. function ConfigurationContainer() {
  118930. this.mainColor = babylonjs_1.Color3.White();
  118931. this.reflectionColor = babylonjs_1.Color3.White();
  118932. }
  118933. return ConfigurationContainer;
  118934. }());
  118935. exports.ConfigurationContainer = ConfigurationContainer;
  118936. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiY29uZmlndXJhdGlvbkNvbnRhaW5lci5qcyIsInNvdXJjZVJvb3QiOiIiLCJzb3VyY2VzIjpbIi4uLy4uLy4uLy4uL3NyYy9jb25maWd1cmF0aW9uL2NvbmZpZ3VyYXRpb25Db250YWluZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFDQSx1Q0FBMEM7QUFFMUM7SUFBQTtRQU1XLGNBQVMsR0FBVyxrQkFBTSxDQUFDLEtBQUssRUFBRSxDQUFDO1FBQ25DLG9CQUFlLEdBQVcsa0JBQU0sQ0FBQyxLQUFLLEVBQUUsQ0FBQztJQUVwRCxDQUFDO0lBQUQsNkJBQUM7QUFBRCxDQUFDLEFBVEQsSUFTQztBQVRZLHdEQUFzQiJ9
  118937. /***/ }),
  118938. /* 62 */
  118939. /***/ (function(module, exports, __webpack_require__) {
  118940. "use strict";
  118941. Object.defineProperty(exports, "__esModule", { value: true });
  118942. var babylonjs_1 = __webpack_require__(0);
  118943. var helper_1 = __webpack_require__(1);
  118944. var Handlebars = __webpack_require__(15);
  118945. var eventManager_1 = __webpack_require__(63);
  118946. var _1 = __webpack_require__(1);
  118947. /**
  118948. * The template manager, a member of the viewer class, will manage the viewer's templates and generate the HTML.
  118949. * The template manager managers a single viewer and can be seen as the collection of all sub-templates of the viewer.
  118950. */
  118951. var TemplateManager = /** @class */ (function () {
  118952. function TemplateManager(containerElement) {
  118953. this.containerElement = containerElement;
  118954. this.templates = {};
  118955. this.onTemplateInit = new babylonjs_1.Observable();
  118956. this.onTemplateLoaded = new babylonjs_1.Observable();
  118957. this.onTemplateStateChange = new babylonjs_1.Observable();
  118958. this.onAllLoaded = new babylonjs_1.Observable();
  118959. this.onEventTriggered = new babylonjs_1.Observable();
  118960. this.eventManager = new eventManager_1.EventManager(this);
  118961. }
  118962. /**
  118963. * Initialize the template(s) for the viewer. Called bay the Viewer class
  118964. * @param templates the templates to be used to initialize the main template
  118965. */
  118966. TemplateManager.prototype.initTemplate = function (templates) {
  118967. var _this = this;
  118968. var internalInit = function (dependencyMap, name, parentTemplate) {
  118969. //init template
  118970. var template = _this.templates[name];
  118971. var childrenTemplates = Object.keys(dependencyMap).map(function (childName) {
  118972. return internalInit(dependencyMap[childName], childName, template);
  118973. });
  118974. // register the observers
  118975. //template.onLoaded.add(() => {
  118976. var addToParent = function () {
  118977. var containingElement = parentTemplate && parentTemplate.parent.querySelector(helper_1.camelToKebab(name)) || _this.containerElement;
  118978. template.appendTo(containingElement);
  118979. _this._checkLoadedState();
  118980. };
  118981. if (parentTemplate && !parentTemplate.parent) {
  118982. parentTemplate.onAppended.add(function () {
  118983. addToParent();
  118984. });
  118985. }
  118986. else {
  118987. addToParent();
  118988. }
  118989. //});
  118990. return template;
  118991. };
  118992. //build the html tree
  118993. return this._buildHTMLTree(templates).then(function (htmlTree) {
  118994. if (_this.templates['main']) {
  118995. internalInit(htmlTree, 'main');
  118996. }
  118997. else {
  118998. _this._checkLoadedState();
  118999. }
  119000. return;
  119001. });
  119002. };
  119003. /**
  119004. *
  119005. * This function will create a simple map with child-dependencies of the template html tree.
  119006. * It will compile each template, check if its children exist in the configuration and will add them if they do.
  119007. * It is expected that the main template will be called main!
  119008. *
  119009. * @param templates
  119010. */
  119011. TemplateManager.prototype._buildHTMLTree = function (templates) {
  119012. var _this = this;
  119013. var promises = Object.keys(templates).map(function (name) {
  119014. // if the template was overridden
  119015. if (!templates[name])
  119016. return Promise.resolve(false);
  119017. // else - we have a template, let's do our job!
  119018. var template = new Template(name, templates[name]);
  119019. template.onLoaded.add(function () {
  119020. _this.onTemplateLoaded.notifyObservers(template);
  119021. });
  119022. template.onStateChange.add(function () {
  119023. _this.onTemplateStateChange.notifyObservers(template);
  119024. });
  119025. _this.onTemplateInit.notifyObservers(template);
  119026. // make sure the global onEventTriggered is called as well
  119027. template.onEventTriggered.add(function (eventData) { return _this.onEventTriggered.notifyObservers(eventData); });
  119028. _this.templates[name] = template;
  119029. return template.initPromise;
  119030. });
  119031. return Promise.all(promises).then(function () {
  119032. var templateStructure = {};
  119033. // now iterate through all templates and check for children:
  119034. var buildTree = function (parentObject, name) {
  119035. _this.templates[name].isInHtmlTree = true;
  119036. var childNodes = _this.templates[name].getChildElements().filter(function (n) { return !!_this.templates[n]; });
  119037. childNodes.forEach(function (element) {
  119038. parentObject[element] = {};
  119039. buildTree(parentObject[element], element);
  119040. });
  119041. };
  119042. if (_this.templates['main']) {
  119043. buildTree(templateStructure, "main");
  119044. }
  119045. return templateStructure;
  119046. });
  119047. };
  119048. /**
  119049. * Get the canvas in the template tree.
  119050. * There must be one and only one canvas inthe template.
  119051. */
  119052. TemplateManager.prototype.getCanvas = function () {
  119053. return this.containerElement.querySelector('canvas');
  119054. };
  119055. /**
  119056. * Get a specific template from the template tree
  119057. * @param name the name of the template to load
  119058. */
  119059. TemplateManager.prototype.getTemplate = function (name) {
  119060. return this.templates[name];
  119061. };
  119062. TemplateManager.prototype._checkLoadedState = function () {
  119063. var _this = this;
  119064. var done = Object.keys(this.templates).length === 0 || Object.keys(this.templates).every(function (key) {
  119065. return (_this.templates[key].isLoaded && !!_this.templates[key].parent) || !_this.templates[key].isInHtmlTree;
  119066. });
  119067. if (done) {
  119068. this.onAllLoaded.notifyObservers(this);
  119069. }
  119070. };
  119071. /**
  119072. * Dispose the template manager
  119073. */
  119074. TemplateManager.prototype.dispose = function () {
  119075. var _this = this;
  119076. // dispose all templates
  119077. Object.keys(this.templates).forEach(function (template) {
  119078. _this.templates[template].dispose();
  119079. });
  119080. this.templates = {};
  119081. this.eventManager.dispose();
  119082. this.onTemplateInit.clear();
  119083. this.onAllLoaded.clear();
  119084. this.onEventTriggered.clear();
  119085. this.onTemplateLoaded.clear();
  119086. this.onTemplateStateChange.clear();
  119087. };
  119088. return TemplateManager;
  119089. }());
  119090. exports.TemplateManager = TemplateManager;
  119091. // register a new helper. modified https://stackoverflow.com/questions/9838925/is-there-any-method-to-iterate-a-map-with-handlebars-js
  119092. Handlebars.registerHelper('eachInMap', function (map, block) {
  119093. var out = '';
  119094. Object.keys(map).map(function (prop) {
  119095. var data = map[prop];
  119096. if (typeof data === 'object') {
  119097. data.id = data.id || prop;
  119098. out += block.fn(data);
  119099. }
  119100. else {
  119101. out += block.fn({ id: prop, value: data });
  119102. }
  119103. });
  119104. return out;
  119105. });
  119106. Handlebars.registerHelper('add', function (a, b) {
  119107. var out = a + b;
  119108. return out;
  119109. });
  119110. Handlebars.registerHelper('eq', function (a, b) {
  119111. var out = (a == b);
  119112. return out;
  119113. });
  119114. Handlebars.registerHelper('or', function (a, b) {
  119115. var out = a || b;
  119116. return out;
  119117. });
  119118. Handlebars.registerHelper('not', function (a) {
  119119. var out = !a;
  119120. return out;
  119121. });
  119122. Handlebars.registerHelper('count', function (map) {
  119123. return map.length;
  119124. });
  119125. Handlebars.registerHelper('gt', function (a, b) {
  119126. var out = a > b;
  119127. return out;
  119128. });
  119129. /**
  119130. * This class represents a single template in the viewer's template tree.
  119131. * An example for a template is a single canvas, an overlay (containing sub-templates) or the navigation bar.
  119132. * A template is injected using the template manager in the correct position.
  119133. * The template is rendered using Handlebars and can use Handlebars' features (such as parameter injection)
  119134. *
  119135. * For further information please refer to the documentation page, https://doc.babylonjs.com
  119136. */
  119137. var Template = /** @class */ (function () {
  119138. function Template(name, _configuration) {
  119139. var _this = this;
  119140. this.name = name;
  119141. this._configuration = _configuration;
  119142. this.onLoaded = new babylonjs_1.Observable();
  119143. this.onAppended = new babylonjs_1.Observable();
  119144. this.onStateChange = new babylonjs_1.Observable();
  119145. this.onEventTriggered = new babylonjs_1.Observable();
  119146. this.onParamsUpdated = new babylonjs_1.Observable();
  119147. this.onHTMLRendered = new babylonjs_1.Observable();
  119148. this.loadRequests = [];
  119149. this.isLoaded = false;
  119150. this.isShown = false;
  119151. this.isInHtmlTree = false;
  119152. var htmlContentPromise = this._getTemplateAsHtml(_configuration);
  119153. this.initPromise = htmlContentPromise.then(function (htmlTemplate) {
  119154. if (htmlTemplate) {
  119155. _this._htmlTemplate = htmlTemplate;
  119156. var compiledTemplate = Handlebars.compile(htmlTemplate, { noEscape: (_this._configuration.params && !!_this._configuration.params.noEscape) });
  119157. var config = _this._configuration.params || {};
  119158. _this._rawHtml = compiledTemplate(config);
  119159. try {
  119160. _this._fragment = document.createRange().createContextualFragment(_this._rawHtml);
  119161. }
  119162. catch (e) {
  119163. var test = document.createElement(_this.name);
  119164. test.innerHTML = _this._rawHtml;
  119165. _this._fragment = test;
  119166. }
  119167. _this.isLoaded = true;
  119168. _this.isShown = true;
  119169. _this.onLoaded.notifyObservers(_this);
  119170. }
  119171. return _this;
  119172. });
  119173. }
  119174. /**
  119175. * Some templates have parameters (like background color for example).
  119176. * The parameters are provided to Handlebars which in turn generates the template.
  119177. * This function will update the template with the new parameters
  119178. *
  119179. * Note that when updating parameters the events will be registered again (after being cleared).
  119180. *
  119181. * @param params the new template parameters
  119182. */
  119183. Template.prototype.updateParams = function (params, append) {
  119184. if (append === void 0) { append = true; }
  119185. if (append) {
  119186. this._configuration.params = _1.deepmerge(this._configuration.params, params);
  119187. }
  119188. else {
  119189. this._configuration.params = params;
  119190. }
  119191. // update the template
  119192. if (this.isLoaded) {
  119193. // this.dispose();
  119194. }
  119195. var compiledTemplate = Handlebars.compile(this._htmlTemplate);
  119196. var config = this._configuration.params || {};
  119197. this._rawHtml = compiledTemplate(config);
  119198. try {
  119199. this._fragment = document.createRange().createContextualFragment(this._rawHtml);
  119200. }
  119201. catch (e) {
  119202. var test = document.createElement(this.name);
  119203. test.innerHTML = this._rawHtml;
  119204. this._fragment = test;
  119205. }
  119206. if (this.parent) {
  119207. this.appendTo(this.parent, true);
  119208. }
  119209. };
  119210. Object.defineProperty(Template.prototype, "configuration", {
  119211. /**
  119212. * Get the template'S configuration
  119213. */
  119214. get: function () {
  119215. return this._configuration;
  119216. },
  119217. enumerable: true,
  119218. configurable: true
  119219. });
  119220. /**
  119221. * A template can be a parent element for other templates or HTML elements.
  119222. * This function will deliver all child HTML elements of this template.
  119223. */
  119224. Template.prototype.getChildElements = function () {
  119225. var childrenArray = [];
  119226. //Edge and IE don't support frage,ent.children
  119227. var children = this._fragment && this._fragment.children;
  119228. if (!this._fragment) {
  119229. var fragment = this.parent.querySelector(this.name);
  119230. if (fragment) {
  119231. children = fragment.querySelectorAll('*');
  119232. }
  119233. }
  119234. if (!children) {
  119235. // casting to HTMLCollection, as both NodeListOf and HTMLCollection have 'item()' and 'length'.
  119236. children = this._fragment.querySelectorAll('*');
  119237. }
  119238. for (var i = 0; i < children.length; ++i) {
  119239. childrenArray.push(helper_1.kebabToCamel(children.item(i).nodeName.toLowerCase()));
  119240. }
  119241. return childrenArray;
  119242. };
  119243. /**
  119244. * Appending the template to a parent HTML element.
  119245. * If a parent is already set and you wish to replace the old HTML with new one, forceRemove should be true.
  119246. * @param parent the parent to which the template is added
  119247. * @param forceRemove if the parent already exists, shoud the template be removed from it?
  119248. */
  119249. Template.prototype.appendTo = function (parent, forceRemove) {
  119250. var _this = this;
  119251. if (this.parent) {
  119252. if (forceRemove && this._addedFragment) {
  119253. /*let fragement = this.parent.querySelector(this.name)
  119254. if (fragement)
  119255. this.parent.removeChild(fragement);*/
  119256. this.parent.innerHTML = '';
  119257. }
  119258. else {
  119259. return;
  119260. }
  119261. }
  119262. this.parent = parent;
  119263. if (this._configuration.id) {
  119264. this.parent.id = this._configuration.id;
  119265. }
  119266. if (this._fragment) {
  119267. this.parent.appendChild(this._fragment);
  119268. this._addedFragment = this._fragment;
  119269. }
  119270. else {
  119271. this.parent.insertAdjacentHTML("beforeend", this._rawHtml);
  119272. }
  119273. this.onHTMLRendered.notifyObservers(this);
  119274. // appended only one frame after.
  119275. setTimeout(function () {
  119276. _this._registerEvents();
  119277. _this.onAppended.notifyObservers(_this);
  119278. });
  119279. };
  119280. /**
  119281. * Show the template using the provided visibilityFunction, or natively using display: flex.
  119282. * The provided function returns a promise that should be fullfilled when the element is shown.
  119283. * Since it is a promise async operations are more than possible.
  119284. * See the default viewer for an opacity example.
  119285. * @param visibilityFunction The function to execute to show the template.
  119286. */
  119287. Template.prototype.show = function (visibilityFunction) {
  119288. var _this = this;
  119289. if (this._isHiding)
  119290. return Promise.resolve(this);
  119291. return Promise.resolve().then(function () {
  119292. _this._isShowing = true;
  119293. if (visibilityFunction) {
  119294. return visibilityFunction(_this);
  119295. }
  119296. else {
  119297. // flex? box? should this be configurable easier than the visibilityFunction?
  119298. _this.parent.style.display = 'flex';
  119299. // support old browsers with no flex:
  119300. if (_this.parent.style.display !== 'flex') {
  119301. _this.parent.style.display = '';
  119302. }
  119303. return _this;
  119304. }
  119305. }).then(function () {
  119306. _this.isShown = true;
  119307. _this._isShowing = false;
  119308. _this.onStateChange.notifyObservers(_this);
  119309. return _this;
  119310. });
  119311. };
  119312. /**
  119313. * Hide the template using the provided visibilityFunction, or natively using display: none.
  119314. * The provided function returns a promise that should be fullfilled when the element is hidden.
  119315. * Since it is a promise async operations are more than possible.
  119316. * See the default viewer for an opacity example.
  119317. * @param visibilityFunction The function to execute to show the template.
  119318. */
  119319. Template.prototype.hide = function (visibilityFunction) {
  119320. var _this = this;
  119321. if (this._isShowing)
  119322. return Promise.resolve(this);
  119323. return Promise.resolve().then(function () {
  119324. _this._isHiding = true;
  119325. if (visibilityFunction) {
  119326. return visibilityFunction(_this);
  119327. }
  119328. else {
  119329. // flex? box? should this be configurable easier than the visibilityFunction?
  119330. _this.parent.style.display = 'none';
  119331. return _this;
  119332. }
  119333. }).then(function () {
  119334. _this.isShown = false;
  119335. _this._isHiding = false;
  119336. _this.onStateChange.notifyObservers(_this);
  119337. return _this;
  119338. });
  119339. };
  119340. /**
  119341. * Dispose this template
  119342. */
  119343. Template.prototype.dispose = function () {
  119344. this.onAppended.clear();
  119345. this.onEventTriggered.clear();
  119346. this.onLoaded.clear();
  119347. this.onStateChange.clear();
  119348. this.isLoaded = false;
  119349. // remove from parent
  119350. try {
  119351. this.parent.removeChild(this._fragment);
  119352. }
  119353. catch (e) {
  119354. //noop
  119355. }
  119356. this.loadRequests.forEach(function (request) {
  119357. request.abort();
  119358. });
  119359. if (this._registeredEvents) {
  119360. this._registeredEvents.forEach(function (evt) {
  119361. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  119362. });
  119363. }
  119364. delete this._fragment;
  119365. };
  119366. Template.prototype._getTemplateAsHtml = function (templateConfig) {
  119367. var _this = this;
  119368. if (!templateConfig) {
  119369. return Promise.reject('No templateConfig provided');
  119370. }
  119371. else if (templateConfig.html) {
  119372. return Promise.resolve(templateConfig.html);
  119373. }
  119374. else {
  119375. var location_1 = this._getTemplateLocation(templateConfig);
  119376. if (helper_1.isUrl(location_1)) {
  119377. return new Promise(function (resolve, reject) {
  119378. var fileRequest = babylonjs_1.Tools.LoadFile(location_1, function (data) {
  119379. resolve(data);
  119380. }, undefined, undefined, false, function (request, error) {
  119381. reject(error);
  119382. });
  119383. _this.loadRequests.push(fileRequest);
  119384. });
  119385. }
  119386. else {
  119387. location_1 = location_1.replace('#', '');
  119388. var element = document.getElementById(location_1);
  119389. if (element) {
  119390. return Promise.resolve(element.innerHTML);
  119391. }
  119392. else {
  119393. return Promise.reject('Template ID not found');
  119394. }
  119395. }
  119396. }
  119397. };
  119398. Template.prototype._registerEvents = function () {
  119399. var _this = this;
  119400. this._registeredEvents = this._registeredEvents || [];
  119401. if (this._registeredEvents.length) {
  119402. // first remove the registered events
  119403. this._registeredEvents.forEach(function (evt) {
  119404. evt.htmlElement.removeEventListener(evt.eventName, evt.function);
  119405. });
  119406. }
  119407. if (this._configuration.events) {
  119408. var _loop_1 = function (eventName) {
  119409. if (this_1._configuration.events && this_1._configuration.events[eventName]) {
  119410. var functionToFire_1 = function (selector, event) {
  119411. _this.onEventTriggered.notifyObservers({ event: event, template: _this, selector: selector });
  119412. };
  119413. // if boolean, set the parent as the event listener
  119414. if (typeof this_1._configuration.events[eventName] === 'boolean') {
  119415. var selector = this_1.parent.id;
  119416. if (selector) {
  119417. selector = '#' + selector;
  119418. }
  119419. else {
  119420. selector = this_1.parent.tagName;
  119421. }
  119422. var binding = functionToFire_1.bind(this_1, selector);
  119423. this_1.parent.addEventListener(eventName, functionToFire_1.bind(this_1, selector), false);
  119424. this_1._registeredEvents.push({
  119425. htmlElement: this_1.parent,
  119426. eventName: eventName,
  119427. function: binding
  119428. });
  119429. }
  119430. else if (typeof this_1._configuration.events[eventName] === 'object') {
  119431. var selectorsArray = Object.keys(this_1._configuration.events[eventName] || {});
  119432. // strict null checl is working incorrectly, must override:
  119433. var event_1 = this_1._configuration.events[eventName] || {};
  119434. selectorsArray.filter(function (selector) { return event_1[selector]; }).forEach(function (selector) {
  119435. var htmlElement = _this.parent.querySelector(selector);
  119436. if (!htmlElement) {
  119437. // backcompat, fallback to id
  119438. if (selector && selector.indexOf('#') !== 0) {
  119439. selector = '#' + selector;
  119440. }
  119441. try {
  119442. htmlElement = _this.parent.querySelector(selector);
  119443. }
  119444. catch (e) { }
  119445. }
  119446. if (htmlElement) {
  119447. var binding = functionToFire_1.bind(_this, selector);
  119448. htmlElement.addEventListener(eventName, binding, false);
  119449. _this._registeredEvents.push({
  119450. htmlElement: htmlElement,
  119451. eventName: eventName,
  119452. function: binding
  119453. });
  119454. }
  119455. });
  119456. }
  119457. }
  119458. };
  119459. var this_1 = this;
  119460. for (var eventName in this._configuration.events) {
  119461. _loop_1(eventName);
  119462. }
  119463. }
  119464. };
  119465. Template.prototype._getTemplateLocation = function (templateConfig) {
  119466. if (!templateConfig || typeof templateConfig === 'string') {
  119467. return templateConfig;
  119468. }
  119469. else {
  119470. return templateConfig.location;
  119471. }
  119472. };
  119473. return Template;
  119474. }());
  119475. exports.Template = Template;
  119476. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidGVtcGxhdGVNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvdGVtcGxhdGVNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBQ0EsdUNBQTREO0FBQzVELG9DQUE4RDtBQUU5RCx1REFBeUQ7QUFDekQsK0NBQThDO0FBRTlDLCtCQUF1QztBQVl2Qzs7O0dBR0c7QUFDSDtJQThCSSx5QkFBbUIsZ0JBQTZCO1FBQTdCLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBYTtRQUM1QyxJQUFJLENBQUMsU0FBUyxHQUFHLEVBQUUsQ0FBQztRQUVwQixJQUFJLENBQUMsY0FBYyxHQUFHLElBQUksc0JBQVUsRUFBWSxDQUFDO1FBQ2pELElBQUksQ0FBQyxnQkFBZ0IsR0FBRyxJQUFJLHNCQUFVLEVBQVksQ0FBQztRQUNuRCxJQUFJLENBQUMscUJBQXFCLEdBQUcsSUFBSSxzQkFBVSxFQUFZLENBQUM7UUFDeEQsSUFBSSxDQUFDLFdBQVcsR0FBRyxJQUFJLHNCQUFVLEVBQW1CLENBQUM7UUFDckQsSUFBSSxDQUFDLGdCQUFnQixHQUFHLElBQUksc0JBQ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DQUFDOzZCQUNOO3dCQUNMLENBQUMsQ0FBQyxDQUFDO3FCQUNOO2lCQUNKO1lBQ0wsQ0FBQzs7WUFoREQsS0FBSyxJQUFJLFNBQVMsSUFBSSxJQUFJLENBQUMsY0FBYyxDQUFDLE1BQU07d0JBQXZDLFNBQVM7YUFnRGpCO1NBQ0o7SUFDTCxDQUFDO0lBRU8sdUNBQW9CLEdBQTVCLFVBQTZCLGNBQWM7UUFDdkMsSUFBSSxDQUFDLGNBQWMsSUFBSSxPQUFPLGNBQWMsS0FBSyxRQUFRLEVBQUU7WUFDdkQsT0FBTyxjQUFjLENBQUM7U0FDekI7YUFBTTtZQUNILE9BQU8sY0FBYyxDQUFDLFFBQVEsQ0FBQztTQUNsQztJQUNMLENBQUM7SUFDTCxlQUFDO0FBQUQsQ0FBQyxBQTlYRCxJQThYQztBQTlYWSw0QkFBUSJ9
  119477. /***/ }),
  119478. /* 63 */
  119479. /***/ (function(module, exports, __webpack_require__) {
  119480. "use strict";
  119481. Object.defineProperty(exports, "__esModule", { value: true });
  119482. /**
  119483. * The EventManager is in charge of registering user interctions with the viewer.
  119484. * It is used in the TemplateManager
  119485. */
  119486. var EventManager = /** @class */ (function () {
  119487. function EventManager(_templateManager) {
  119488. var _this = this;
  119489. this._templateManager = _templateManager;
  119490. this._callbacksContainer = {};
  119491. this._templateManager.onEventTriggered.add(function (eventData) {
  119492. _this._eventTriggered(eventData);
  119493. });
  119494. }
  119495. /**
  119496. * Register a new callback to a specific template.
  119497. * The best example for the usage can be found in the DefaultViewer
  119498. *
  119499. * @param templateName the templateName to register the event to
  119500. * @param callback The callback to be executed
  119501. * @param eventType the type of event to register
  119502. * @param selector an optional selector. if not defined the parent object in the template will be selected
  119503. */
  119504. EventManager.prototype.registerCallback = function (templateName, callback, eventType, selector) {
  119505. if (!this._callbacksContainer[templateName]) {
  119506. this._callbacksContainer[templateName] = [];
  119507. }
  119508. this._callbacksContainer[templateName].push({
  119509. eventType: eventType,
  119510. callback: callback,
  119511. selector: selector
  119512. });
  119513. };
  119514. /**
  119515. * This will remove a registered event from the defined template.
  119516. * Each one of the variables apart from the template name are optional, but one must be provided.
  119517. *
  119518. * @param templateName the templateName
  119519. * @param callback the callback to remove (optional)
  119520. * @param eventType the event type to remove (optional)
  119521. * @param selector the selector from which to remove the event (optional)
  119522. */
  119523. EventManager.prototype.unregisterCallback = function (templateName, callback, eventType, selector) {
  119524. var callbackDefs = this._callbacksContainer[templateName] || [];
  119525. this._callbacksContainer[templateName] = callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); });
  119526. };
  119527. EventManager.prototype._eventTriggered = function (data) {
  119528. var templateName = data.template.name;
  119529. var eventType = data.event.type;
  119530. var selector = data.selector;
  119531. var callbackDefs = this._callbacksContainer[templateName] || [];
  119532. callbackDefs.filter(function (callbackDef) { return (!callbackDef.eventType || callbackDef.eventType === eventType) && (!callbackDef.selector || callbackDef.selector === selector); }).forEach(function (callbackDef) {
  119533. callbackDef.callback(data);
  119534. });
  119535. };
  119536. /**
  119537. * Dispose the event manager
  119538. */
  119539. EventManager.prototype.dispose = function () {
  119540. this._callbacksContainer = {};
  119541. };
  119542. return EventManager;
  119543. }());
  119544. exports.EventManager = EventManager;
  119545. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZXZlbnRNYW5hZ2VyLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vLi4vLi4vLi4vc3JjL3RlbXBsYXRpbmcvZXZlbnRNYW5hZ2VyLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7O0FBR0E7OztHQUdHO0FBQ0g7SUFJSSxzQkFBb0IsZ0JBQWlDO1FBQXJELGlCQUtDO1FBTG1CLHFCQUFnQixHQUFoQixnQkFBZ0IsQ0FBaUI7UUFDakQsSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztRQ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yxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQztJQUNqTixDQUFDO0lBRU8sc0NBQWUsR0FBdkIsVUFBd0IsSUFBbUI7UUFDdkMsSUFBSSxZQUFZLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQyxJQUFJLENBQUM7UUFDdEMsSUFBSSxTQUFTLEdBQUcsSUFBSSxDQUFDLEtBQUssQ0FBQyxJQUFJLENBQUM7UUFDaEMsSUFBSSxRQUFRLEdBQUcsSUFBSSxDQUFDLFFBQVEsQ0FBQztRQUU3QixJQUFJLFlBQVksR0FBRyxJQUFJLENBQUMsbUJBQW1CLENBQUMsWUFBWSxDQUFDLElBQUksRUFBRSxDQUFDO1FBQ2hFLFlBQVksQ0FBQyxNQUFNLENBQUMsVUFBQSxXQUFXLElBQUksT0FBQSxDQUFDLENBQUMsV0FBVyxDQUFDLFNBQVMsSUFBSSxXQUFXLENBQUMsU0FBUyxLQUFLLFNBQVMsQ0FBQyxJQUFJLENBQUMsQ0FBQyxXQUFXLENBQUMsUUFBUSxJQUFJLFdBQVcsQ0FBQyxRQUFRLEtBQUssUUFBUSxDQUFDLEVBQS9ILENBQStILENBQUMsQ0FBQyxPQUFPLENBQUMsVUFBQSxXQUFXO1lBQ25MLFdBQVcsQ0FBQyxRQUFRLENBQUMsSUFBSSxDQUFDLENBQUM7UUFDL0IsQ0FBQyxDQUFDLENBQUM7SUFDUCxDQUFDO0lBRUQ7O09BRUc7SUFDSSw4QkFBTyxHQUFkO1FBQ0ksSUFBSSxDQUFDLG1CQUFtQixHQUFHLEVBQUUsQ0FBQztJQUNsQyxDQUFDO0lBQ0wsbUJBQUM7QUFBRCxDQUFDLEFBOURELElBOERDO0FBOURZLG9DQUFZIn0=
  119546. /***/ }),
  119547. /* 64 */
  119548. /***/ (function(module, exports, __webpack_require__) {
  119549. "use strict";
  119550. var __extends = (this && this.__extends) || (function () {
  119551. var extendStatics = Object.setPrototypeOf ||
  119552. ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
  119553. function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
  119554. return function (d, b) {
  119555. extendStatics(d, b);
  119556. function __() { this.constructor = d; }
  119557. d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
  119558. };
  119559. })();
  119560. Object.defineProperty(exports, "__esModule", { value: true });
  119561. var viewerTemplatePlugin_1 = __webpack_require__(65);
  119562. var HDButtonPlugin = /** @class */ (function (_super) {
  119563. __extends(HDButtonPlugin, _super);
  119564. function HDButtonPlugin(_viewer) {
  119565. var _this = _super.call(this) || this;
  119566. _this._viewer = _viewer;
  119567. _this._buttonClass = "hd-button";
  119568. _this._htmlTemplate = "\n{{#unless hideHd}}\n<style>\n.hd-icon:after {\n font-size: 16px;\n content: \"\\F765\";\n}\n\n.hd-toggled span.hd-icon:after {\n content: \"\\F766\";\n}\n</style>\n<button class=\"hd-button\" title=\"{{text.hdButton}}\">\n <span class=\"icon hd-icon\"></span>\n </button>\n {{/unless}}\n";
  119569. return _this;
  119570. }
  119571. HDButtonPlugin.prototype.onEvent = function (event) {
  119572. var button = event.template.parent.querySelector(".hd-button");
  119573. if (button) {
  119574. button.classList.contains("hd-toggled") ? button.classList.remove("hd-toggled") : button.classList.add("hd-toggled");
  119575. }
  119576. this._viewer.toggleHD();
  119577. };
  119578. return HDButtonPlugin;
  119579. }(viewerTemplatePlugin_1.AbstractViewerNavbarButton));
  119580. exports.HDButtonPlugin = HDButtonPlugin;
  119581. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaGRCdXR0b25QbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy9wbHVnaW5zL2hkQnV0dG9uUGx1Z2luLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiI7Ozs7Ozs7Ozs7OztBQUFBLGdFQUFxRTtBQUlyRTtJQUFvQyxrQ0FBMEI7SUFJMUQsd0JBQW9CLE9BQXNCO1FBQTFDLFlBQ0ksaUJBQU8sU0FDVjtRQUZtQixhQUFPLEdBQVAsT0FBTyxDQUFlO1FBRmhDLGtCQUFZLEdBQUcsV0FBVyxDQUFDO1FBYzNCLG1CQUFhLEdBQVcsZ1RBZ0JyQyxDQUFDOztJQTFCRSxDQUFDO0lBRUQsZ0NBQU8sR0FBUCxVQUFRLEtBQW9CO1FBQ3hCLElBQUksTUFBTSxHQUFHLEtBQUssQ0FBQyxRQUFRLENBQUMsTUFBTSxDQUFDLGFBQWEsQ0FBQyxZQUFZLENBQUMsQ0FBQztRQUMvRCxJQUFJLE1BQU0sRUFBRTtZQUNSLE1BQU0sQ0FBQyxTQUFTLENBQUMsUUFBUSxDQUFDLFlBQVksQ0FBQyxDQUFDLENBQUMsQ0FBQyxNQUFNLENBQUMsU0FBUyxDQUFDLE1BQU0sQ0FBQyxZQUFZLENBQUMsQ0FBQyxDQUFDLENBQUMsTUFBTSxDQUFDLFNBQVMsQ0FBQyxHQUFHLENBQUMsWUFBWSxDQUFDLENBQUM7U0FDeEg7UUFDRCxJQUFJLENBQUMsT0FBTyxDQUFDLFFBQVEsRUFBRSxDQUFDO0lBQzVCLENBQUM7SUFtQkwscUJBQUM7QUFBRCxDQUFDLEFBakNELENBQW9DLGlEQUEwQixHQWlDN0Q7QUFqQ1ksd0NBQWMifQ==
  119582. /***/ }),
  119583. /* 65 */
  119584. /***/ (function(module, exports, __webpack_require__) {
  119585. "use strict";
  119586. Object.defineProperty(exports, "__esModule", { value: true });
  119587. var Handlebars = __webpack_require__(15);
  119588. var AbstractViewerNavbarButton = /** @class */ (function () {
  119589. function AbstractViewerNavbarButton() {
  119590. this.templateName = "navBar";
  119591. this.eventsToAttach = ['pointerdown'];
  119592. this._prepend = true;
  119593. }
  119594. AbstractViewerNavbarButton.prototype.interactionPredicate = function (event) {
  119595. var pointerDown = event.event;
  119596. if (pointerDown.button !== 0)
  119597. return false;
  119598. var element = event.event.target;
  119599. if (!element) {
  119600. return false;
  119601. }
  119602. var elementClasses = element.classList;
  119603. for (var i = 0; i < elementClasses.length; ++i) {
  119604. var className = elementClasses[i];
  119605. if (className.indexOf(this._buttonClass) !== -1) {
  119606. return true;
  119607. }
  119608. }
  119609. return false;
  119610. };
  119611. AbstractViewerNavbarButton.prototype.addHTMLTemplate = function (template) {
  119612. var element = this._generateHTMLElement(template);
  119613. var container = template.parent.querySelector("div.default-control");
  119614. if (container) {
  119615. if (this._prepend) {
  119616. container.insertBefore(element, container.firstChild);
  119617. }
  119618. else {
  119619. container.appendChild(element);
  119620. }
  119621. }
  119622. };
  119623. AbstractViewerNavbarButton.prototype._generateHTMLElement = function (template) {
  119624. var compiledTemplate = Handlebars.compile(this._htmlTemplate, { noEscape: (template.configuration.params && !!template.configuration.params.noEscape) });
  119625. var config = template.configuration.params || {};
  119626. var rawHtml = compiledTemplate(config);
  119627. var fragment;
  119628. try {
  119629. fragment = document.createRange().createContextualFragment(rawHtml);
  119630. }
  119631. catch (e) {
  119632. var test = document.createElement(this._buttonClass);
  119633. test.innerHTML = rawHtml;
  119634. fragment = test;
  119635. }
  119636. return fragment;
  119637. };
  119638. return AbstractViewerNavbarButton;
  119639. }());
  119640. exports.AbstractViewerNavbarButton = AbstractViewerNavbarButton;
  119641. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoidmlld2VyVGVtcGxhdGVQbHVnaW4uanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi8uLi9zcmMvdGVtcGxhdGluZy92aWV3ZXJUZW1wbGF0ZVBsdWdpbi50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiOztBQUNBLHVEQUF5RDtBQVl6RDtJQUFBO1FBRW9CLGlCQUFZLEdBQVcsUUFBUSxDQUFDO1FBQ2hDLG1CQUFjLEdBQWtCLENBQUMsYUFBYSx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XhEcUIsZ0VBQTBCIn0=
  119642. /***/ }),
  119643. /* 66 */
  119644. /***/ (function(module, exports, __webpack_require__) {
  119645. /*!
  119646. * PEP v0.4.3 | https://github.com/jquery/PEP
  119647. * Copyright jQuery Foundation and other contributors | http://jquery.org/license
  119648. */
  119649. (function (global, factory) {
  119650. true ? module.exports = factory() :
  119651. typeof define === 'function' && define.amd ? define(factory) :
  119652. (global.PointerEventsPolyfill = factory());
  119653. }(this, function () { 'use strict';
  119654. /**
  119655. * This is the constructor for new PointerEvents.
  119656. *
  119657. * New Pointer Events must be given a type, and an optional dictionary of
  119658. * initialization properties.
  119659. *
  119660. * Due to certain platform requirements, events returned from the constructor
  119661. * identify as MouseEvents.
  119662. *
  119663. * @constructor
  119664. * @param {String} inType The type of the event to create.
  119665. * @param {Object} [inDict] An optional dictionary of initial event properties.
  119666. * @return {Event} A new PointerEvent of type `inType`, initialized with properties from `inDict`.
  119667. */
  119668. var MOUSE_PROPS = [
  119669. 'bubbles',
  119670. 'cancelable',
  119671. 'view',
  119672. 'detail',
  119673. 'screenX',
  119674. 'screenY',
  119675. 'clientX',
  119676. 'clientY',
  119677. 'ctrlKey',
  119678. 'altKey',
  119679. 'shiftKey',
  119680. 'metaKey',
  119681. 'button',
  119682. 'relatedTarget',
  119683. 'pageX',
  119684. 'pageY'
  119685. ];
  119686. var MOUSE_DEFAULTS = [
  119687. false,
  119688. false,
  119689. null,
  119690. null,
  119691. 0,
  119692. 0,
  119693. 0,
  119694. 0,
  119695. false,
  119696. false,
  119697. false,
  119698. false,
  119699. 0,
  119700. null,
  119701. 0,
  119702. 0
  119703. ];
  119704. function PointerEvent(inType, inDict) {
  119705. inDict = inDict || Object.create(null);
  119706. var e = document.createEvent('Event');
  119707. e.initEvent(inType, inDict.bubbles || false, inDict.cancelable || false);
  119708. // define inherited MouseEvent properties
  119709. // skip bubbles and cancelable since they're set above in initEvent()
  119710. for (var i = 2, p; i < MOUSE_PROPS.length; i++) {
  119711. p = MOUSE_PROPS[i];
  119712. e[p] = inDict[p] || MOUSE_DEFAULTS[i];
  119713. }
  119714. e.buttons = inDict.buttons || 0;
  119715. // Spec requires that pointers without pressure specified use 0.5 for down
  119716. // state and 0 for up state.
  119717. var pressure = 0;
  119718. if (inDict.pressure && e.buttons) {
  119719. pressure = inDict.pressure;
  119720. } else {
  119721. pressure = e.buttons ? 0.5 : 0;
  119722. }
  119723. // add x/y properties aliased to clientX/Y
  119724. e.x = e.clientX;
  119725. e.y = e.clientY;
  119726. // define the properties of the PointerEvent interface
  119727. e.pointerId = inDict.pointerId || 0;
  119728. e.width = inDict.width || 0;
  119729. e.height = inDict.height || 0;
  119730. e.pressure = pressure;
  119731. e.tiltX = inDict.tiltX || 0;
  119732. e.tiltY = inDict.tiltY || 0;
  119733. e.twist = inDict.twist || 0;
  119734. e.tangentialPressure = inDict.tangentialPressure || 0;
  119735. e.pointerType = inDict.pointerType || '';
  119736. e.hwTimestamp = inDict.hwTimestamp || 0;
  119737. e.isPrimary = inDict.isPrimary || false;
  119738. return e;
  119739. }
  119740. /**
  119741. * This module implements a map of pointer states
  119742. */
  119743. var USE_MAP = window.Map && window.Map.prototype.forEach;
  119744. var PointerMap = USE_MAP ? Map : SparseArrayMap;
  119745. function SparseArrayMap() {
  119746. this.array = [];
  119747. this.size = 0;
  119748. }
  119749. SparseArrayMap.prototype = {
  119750. set: function(k, v) {
  119751. if (v === undefined) {
  119752. return this.delete(k);
  119753. }
  119754. if (!this.has(k)) {
  119755. this.size++;
  119756. }
  119757. this.array[k] = v;
  119758. },
  119759. has: function(k) {
  119760. return this.array[k] !== undefined;
  119761. },
  119762. delete: function(k) {
  119763. if (this.has(k)) {
  119764. delete this.array[k];
  119765. this.size--;
  119766. }
  119767. },
  119768. get: function(k) {
  119769. return this.array[k];
  119770. },
  119771. clear: function() {
  119772. this.array.length = 0;
  119773. this.size = 0;
  119774. },
  119775. // return value, key, map
  119776. forEach: function(callback, thisArg) {
  119777. return this.array.forEach(function(v, k) {
  119778. callback.call(thisArg, v, k, this);
  119779. }, this);
  119780. }
  119781. };
  119782. var CLONE_PROPS = [
  119783. // MouseEvent
  119784. 'bubbles',
  119785. 'cancelable',
  119786. 'view',
  119787. 'detail',
  119788. 'screenX',
  119789. 'screenY',
  119790. 'clientX',
  119791. 'clientY',
  119792. 'ctrlKey',
  119793. 'altKey',
  119794. 'shiftKey',
  119795. 'metaKey',
  119796. 'button',
  119797. 'relatedTarget',
  119798. // DOM Level 3
  119799. 'buttons',
  119800. // PointerEvent
  119801. 'pointerId',
  119802. 'width',
  119803. 'height',
  119804. 'pressure',
  119805. 'tiltX',
  119806. 'tiltY',
  119807. 'pointerType',
  119808. 'hwTimestamp',
  119809. 'isPrimary',
  119810. // event instance
  119811. 'type',
  119812. 'target',
  119813. 'currentTarget',
  119814. 'which',
  119815. 'pageX',
  119816. 'pageY',
  119817. 'timeStamp'
  119818. ];
  119819. var CLONE_DEFAULTS = [
  119820. // MouseEvent
  119821. false,
  119822. false,
  119823. null,
  119824. null,
  119825. 0,
  119826. 0,
  119827. 0,
  119828. 0,
  119829. false,
  119830. false,
  119831. false,
  119832. false,
  119833. 0,
  119834. null,
  119835. // DOM Level 3
  119836. 0,
  119837. // PointerEvent
  119838. 0,
  119839. 0,
  119840. 0,
  119841. 0,
  119842. 0,
  119843. 0,
  119844. '',
  119845. 0,
  119846. false,
  119847. // event instance
  119848. '',
  119849. null,
  119850. null,
  119851. 0,
  119852. 0,
  119853. 0,
  119854. 0
  119855. ];
  119856. var BOUNDARY_EVENTS = {
  119857. 'pointerover': 1,
  119858. 'pointerout': 1,
  119859. 'pointerenter': 1,
  119860. 'pointerleave': 1
  119861. };
  119862. var HAS_SVG_INSTANCE = (typeof SVGElementInstance !== 'undefined');
  119863. /**
  119864. * This module is for normalizing events. Mouse and Touch events will be
  119865. * collected here, and fire PointerEvents that have the same semantics, no
  119866. * matter the source.
  119867. * Events fired:
  119868. * - pointerdown: a pointing is added
  119869. * - pointerup: a pointer is removed
  119870. * - pointermove: a pointer is moved
  119871. * - pointerover: a pointer crosses into an element
  119872. * - pointerout: a pointer leaves an element
  119873. * - pointercancel: a pointer will no longer generate events
  119874. */
  119875. var dispatcher = {
  119876. pointermap: new PointerMap(),
  119877. eventMap: Object.create(null),
  119878. captureInfo: Object.create(null),
  119879. // Scope objects for native events.
  119880. // This exists for ease of testing.
  119881. eventSources: Object.create(null),
  119882. eventSourceList: [],
  119883. /**
  119884. * Add a new event source that will generate pointer events.
  119885. *
  119886. * `inSource` must contain an array of event names named `events`, and
  119887. * functions with the names specified in the `events` array.
  119888. * @param {string} name A name for the event source
  119889. * @param {Object} source A new source of platform events.
  119890. */
  119891. registerSource: function(name, source) {
  119892. var s = source;
  119893. var newEvents = s.events;
  119894. if (newEvents) {
  119895. newEvents.forEach(function(e) {
  119896. if (s[e]) {
  119897. this.eventMap[e] = s[e].bind(s);
  119898. }
  119899. }, this);
  119900. this.eventSources[name] = s;
  119901. this.eventSourceList.push(s);
  119902. }
  119903. },
  119904. register: function(element) {
  119905. var l = this.eventSourceList.length;
  119906. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  119907. // call eventsource register
  119908. es.register.call(es, element);
  119909. }
  119910. },
  119911. unregister: function(element) {
  119912. var l = this.eventSourceList.length;
  119913. for (var i = 0, es; (i < l) && (es = this.eventSourceList[i]); i++) {
  119914. // call eventsource register
  119915. es.unregister.call(es, element);
  119916. }
  119917. },
  119918. contains: /*scope.external.contains || */function(container, contained) {
  119919. try {
  119920. return container.contains(contained);
  119921. } catch (ex) {
  119922. // most likely: https://bugzilla.mozilla.org/show_bug.cgi?id=208427
  119923. return false;
  119924. }
  119925. },
  119926. // EVENTS
  119927. down: function(inEvent) {
  119928. inEvent.bubbles = true;
  119929. this.fireEvent('pointerdown', inEvent);
  119930. },
  119931. move: function(inEvent) {
  119932. inEvent.bubbles = true;
  119933. this.fireEvent('pointermove', inEvent);
  119934. },
  119935. up: function(inEvent) {
  119936. inEvent.bubbles = true;
  119937. this.fireEvent('pointerup', inEvent);
  119938. },
  119939. enter: function(inEvent) {
  119940. inEvent.bubbles = false;
  119941. this.fireEvent('pointerenter', inEvent);
  119942. },
  119943. leave: function(inEvent) {
  119944. inEvent.bubbles = false;
  119945. this.fireEvent('pointerleave', inEvent);
  119946. },
  119947. over: function(inEvent) {
  119948. inEvent.bubbles = true;
  119949. this.fireEvent('pointerover', inEvent);
  119950. },
  119951. out: function(inEvent) {
  119952. inEvent.bubbles = true;
  119953. this.fireEvent('pointerout', inEvent);
  119954. },
  119955. cancel: function(inEvent) {
  119956. inEvent.bubbles = true;
  119957. this.fireEvent('pointercancel', inEvent);
  119958. },
  119959. leaveOut: function(event) {
  119960. this.out(event);
  119961. this.propagate(event, this.leave, false);
  119962. },
  119963. enterOver: function(event) {
  119964. this.over(event);
  119965. this.propagate(event, this.enter, true);
  119966. },
  119967. // LISTENER LOGIC
  119968. eventHandler: function(inEvent) {
  119969. // This is used to prevent multiple dispatch of pointerevents from
  119970. // platform events. This can happen when two elements in different scopes
  119971. // are set up to create pointer events, which is relevant to Shadow DOM.
  119972. if (inEvent._handledByPE) {
  119973. return;
  119974. }
  119975. var type = inEvent.type;
  119976. var fn = this.eventMap && this.eventMap[type];
  119977. if (fn) {
  119978. fn(inEvent);
  119979. }
  119980. inEvent._handledByPE = true;
  119981. },
  119982. // set up event listeners
  119983. listen: function(target, events) {
  119984. events.forEach(function(e) {
  119985. this.addEvent(target, e);
  119986. }, this);
  119987. },
  119988. // remove event listeners
  119989. unlisten: function(target, events) {
  119990. events.forEach(function(e) {
  119991. this.removeEvent(target, e);
  119992. }, this);
  119993. },
  119994. addEvent: /*scope.external.addEvent || */function(target, eventName) {
  119995. target.addEventListener(eventName, this.boundHandler);
  119996. },
  119997. removeEvent: /*scope.external.removeEvent || */function(target, eventName) {
  119998. target.removeEventListener(eventName, this.boundHandler);
  119999. },
  120000. // EVENT CREATION AND TRACKING
  120001. /**
  120002. * Creates a new Event of type `inType`, based on the information in
  120003. * `inEvent`.
  120004. *
  120005. * @param {string} inType A string representing the type of event to create
  120006. * @param {Event} inEvent A platform event with a target
  120007. * @return {Event} A PointerEvent of type `inType`
  120008. */
  120009. makeEvent: function(inType, inEvent) {
  120010. // relatedTarget must be null if pointer is captured
  120011. if (this.captureInfo[inEvent.pointerId]) {
  120012. inEvent.relatedTarget = null;
  120013. }
  120014. var e = new PointerEvent(inType, inEvent);
  120015. if (inEvent.preventDefault) {
  120016. e.preventDefault = inEvent.preventDefault;
  120017. }
  120018. e._target = e._target || inEvent.target;
  120019. return e;
  120020. },
  120021. // make and dispatch an event in one call
  120022. fireEvent: function(inType, inEvent) {
  120023. var e = this.makeEvent(inType, inEvent);
  120024. return this.dispatchEvent(e);
  120025. },
  120026. /**
  120027. * Returns a snapshot of inEvent, with writable properties.
  120028. *
  120029. * @param {Event} inEvent An event that contains properties to copy.
  120030. * @return {Object} An object containing shallow copies of `inEvent`'s
  120031. * properties.
  120032. */
  120033. cloneEvent: function(inEvent) {
  120034. var eventCopy = Object.create(null);
  120035. var p;
  120036. for (var i = 0; i < CLONE_PROPS.length; i++) {
  120037. p = CLONE_PROPS[i];
  120038. eventCopy[p] = inEvent[p] || CLONE_DEFAULTS[i];
  120039. // Work around SVGInstanceElement shadow tree
  120040. // Return the <use> element that is represented by the instance for Safari, Chrome, IE.
  120041. // This is the behavior implemented by Firefox.
  120042. if (HAS_SVG_INSTANCE && (p === 'target' || p === 'relatedTarget')) {
  120043. if (eventCopy[p] instanceof SVGElementInstance) {
  120044. eventCopy[p] = eventCopy[p].correspondingUseElement;
  120045. }
  120046. }
  120047. }
  120048. // keep the semantics of preventDefault
  120049. if (inEvent.preventDefault) {
  120050. eventCopy.preventDefault = function() {
  120051. inEvent.preventDefault();
  120052. };
  120053. }
  120054. return eventCopy;
  120055. },
  120056. getTarget: function(inEvent) {
  120057. var capture = this.captureInfo[inEvent.pointerId];
  120058. if (!capture) {
  120059. return inEvent._target;
  120060. }
  120061. if (inEvent._target === capture || !(inEvent.type in BOUNDARY_EVENTS)) {
  120062. return capture;
  120063. }
  120064. },
  120065. propagate: function(event, fn, propagateDown) {
  120066. var target = event.target;
  120067. var targets = [];
  120068. // Order of conditions due to document.contains() missing in IE.
  120069. while (target !== document && !target.contains(event.relatedTarget)) {
  120070. targets.push(target);
  120071. target = target.parentNode;
  120072. // Touch: Do not propagate if node is detached.
  120073. if (!target) {
  120074. return;
  120075. }
  120076. }
  120077. if (propagateDown) {
  120078. targets.reverse();
  120079. }
  120080. targets.forEach(function(target) {
  120081. event.target = target;
  120082. fn.call(this, event);
  120083. }, this);
  120084. },
  120085. setCapture: function(inPointerId, inTarget, skipDispatch) {
  120086. if (this.captureInfo[inPointerId]) {
  120087. this.releaseCapture(inPointerId, skipDispatch);
  120088. }
  120089. this.captureInfo[inPointerId] = inTarget;
  120090. this.implicitRelease = this.releaseCapture.bind(this, inPointerId, skipDispatch);
  120091. document.addEventListener('pointerup', this.implicitRelease);
  120092. document.addEventListener('pointercancel', this.implicitRelease);
  120093. var e = new PointerEvent('gotpointercapture');
  120094. e.pointerId = inPointerId;
  120095. e._target = inTarget;
  120096. if (!skipDispatch) {
  120097. this.asyncDispatchEvent(e);
  120098. }
  120099. },
  120100. releaseCapture: function(inPointerId, skipDispatch) {
  120101. var t = this.captureInfo[inPointerId];
  120102. if (!t) {
  120103. return;
  120104. }
  120105. this.captureInfo[inPointerId] = undefined;
  120106. document.removeEventListener('pointerup', this.implicitRelease);
  120107. document.removeEventListener('pointercancel', this.implicitRelease);
  120108. var e = new PointerEvent('lostpointercapture');
  120109. e.pointerId = inPointerId;
  120110. e._target = t;
  120111. if (!skipDispatch) {
  120112. this.asyncDispatchEvent(e);
  120113. }
  120114. },
  120115. /**
  120116. * Dispatches the event to its target.
  120117. *
  120118. * @param {Event} inEvent The event to be dispatched.
  120119. * @return {Boolean} True if an event handler returns true, false otherwise.
  120120. */
  120121. dispatchEvent: /*scope.external.dispatchEvent || */function(inEvent) {
  120122. var t = this.getTarget(inEvent);
  120123. if (t) {
  120124. return t.dispatchEvent(inEvent);
  120125. }
  120126. },
  120127. asyncDispatchEvent: function(inEvent) {
  120128. requestAnimationFrame(this.dispatchEvent.bind(this, inEvent));
  120129. }
  120130. };
  120131. dispatcher.boundHandler = dispatcher.eventHandler.bind(dispatcher);
  120132. var targeting = {
  120133. shadow: function(inEl) {
  120134. if (inEl) {
  120135. return inEl.shadowRoot || inEl.webkitShadowRoot;
  120136. }
  120137. },
  120138. canTarget: function(shadow) {
  120139. return shadow && Boolean(shadow.elementFromPoint);
  120140. },
  120141. targetingShadow: function(inEl) {
  120142. var s = this.shadow(inEl);
  120143. if (this.canTarget(s)) {
  120144. return s;
  120145. }
  120146. },
  120147. olderShadow: function(shadow) {
  120148. var os = shadow.olderShadowRoot;
  120149. if (!os) {
  120150. var se = shadow.querySelector('shadow');
  120151. if (se) {
  120152. os = se.olderShadowRoot;
  120153. }
  120154. }
  120155. return os;
  120156. },
  120157. allShadows: function(element) {
  120158. var shadows = [];
  120159. var s = this.shadow(element);
  120160. while (s) {
  120161. shadows.push(s);
  120162. s = this.olderShadow(s);
  120163. }
  120164. return shadows;
  120165. },
  120166. searchRoot: function(inRoot, x, y) {
  120167. if (inRoot) {
  120168. var t = inRoot.elementFromPoint(x, y);
  120169. var st, sr;
  120170. // is element a shadow host?
  120171. sr = this.targetingShadow(t);
  120172. while (sr) {
  120173. // find the the element inside the shadow root
  120174. st = sr.elementFromPoint(x, y);
  120175. if (!st) {
  120176. // check for older shadows
  120177. sr = this.olderShadow(sr);
  120178. } else {
  120179. // shadowed element may contain a shadow root
  120180. var ssr = this.targetingShadow(st);
  120181. return this.searchRoot(ssr, x, y) || st;
  120182. }
  120183. }
  120184. // light dom element is the target
  120185. return t;
  120186. }
  120187. },
  120188. owner: function(element) {
  120189. var s = element;
  120190. // walk up until you hit the shadow root or document
  120191. while (s.parentNode) {
  120192. s = s.parentNode;
  120193. }
  120194. // the owner element is expected to be a Document or ShadowRoot
  120195. if (s.nodeType !== Node.DOCUMENT_NODE && s.nodeType !== Node.DOCUMENT_FRAGMENT_NODE) {
  120196. s = document;
  120197. }
  120198. return s;
  120199. },
  120200. findTarget: function(inEvent) {
  120201. var x = inEvent.clientX;
  120202. var y = inEvent.clientY;
  120203. // if the listener is in the shadow root, it is much faster to start there
  120204. var s = this.owner(inEvent.target);
  120205. // if x, y is not in this root, fall back to document search
  120206. if (!s.elementFromPoint(x, y)) {
  120207. s = document;
  120208. }
  120209. return this.searchRoot(s, x, y);
  120210. }
  120211. };
  120212. var forEach = Array.prototype.forEach.call.bind(Array.prototype.forEach);
  120213. var map = Array.prototype.map.call.bind(Array.prototype.map);
  120214. var toArray = Array.prototype.slice.call.bind(Array.prototype.slice);
  120215. var filter = Array.prototype.filter.call.bind(Array.prototype.filter);
  120216. var MO = window.MutationObserver || window.WebKitMutationObserver;
  120217. var SELECTOR = '[touch-action]';
  120218. var OBSERVER_INIT = {
  120219. subtree: true,
  120220. childList: true,
  120221. attributes: true,
  120222. attributeOldValue: true,
  120223. attributeFilter: ['touch-action']
  120224. };
  120225. function Installer(add, remove, changed, binder) {
  120226. this.addCallback = add.bind(binder);
  120227. this.removeCallback = remove.bind(binder);
  120228. this.changedCallback = changed.bind(binder);
  120229. if (MO) {
  120230. this.observer = new MO(this.mutationWatcher.bind(this));
  120231. }
  120232. }
  120233. Installer.prototype = {
  120234. watchSubtree: function(target) {
  120235. // Only watch scopes that can target find, as these are top-level.
  120236. // Otherwise we can see duplicate additions and removals that add noise.
  120237. //
  120238. // TODO(dfreedman): For some instances with ShadowDOMPolyfill, we can see
  120239. // a removal without an insertion when a node is redistributed among
  120240. // shadows. Since it all ends up correct in the document, watching only
  120241. // the document will yield the correct mutations to watch.
  120242. if (this.observer && targeting.canTarget(target)) {
  120243. this.observer.observe(target, OBSERVER_INIT);
  120244. }
  120245. },
  120246. enableOnSubtree: function(target) {
  120247. this.watchSubtree(target);
  120248. if (target === document && document.readyState !== 'complete') {
  120249. this.installOnLoad();
  120250. } else {
  120251. this.installNewSubtree(target);
  120252. }
  120253. },
  120254. installNewSubtree: function(target) {
  120255. forEach(this.findElements(target), this.addElement, this);
  120256. },
  120257. findElements: function(target) {
  120258. if (target.querySelectorAll) {
  120259. return target.querySelectorAll(SELECTOR);
  120260. }
  120261. return [];
  120262. },
  120263. removeElement: function(el) {
  120264. this.removeCallback(el);
  120265. },
  120266. addElement: function(el) {
  120267. this.addCallback(el);
  120268. },
  120269. elementChanged: function(el, oldValue) {
  120270. this.changedCallback(el, oldValue);
  120271. },
  120272. concatLists: function(accum, list) {
  120273. return accum.concat(toArray(list));
  120274. },
  120275. // register all touch-action = none nodes on document load
  120276. installOnLoad: function() {
  120277. document.addEventListener('readystatechange', function() {
  120278. if (document.readyState === 'complete') {
  120279. this.installNewSubtree(document);
  120280. }
  120281. }.bind(this));
  120282. },
  120283. isElement: function(n) {
  120284. return n.nodeType === Node.ELEMENT_NODE;
  120285. },
  120286. flattenMutationTree: function(inNodes) {
  120287. // find children with touch-action
  120288. var tree = map(inNodes, this.findElements, this);
  120289. // make sure the added nodes are accounted for
  120290. tree.push(filter(inNodes, this.isElement));
  120291. // flatten the list
  120292. return tree.reduce(this.concatLists, []);
  120293. },
  120294. mutationWatcher: function(mutations) {
  120295. mutations.forEach(this.mutationHandler, this);
  120296. },
  120297. mutationHandler: function(m) {
  120298. if (m.type === 'childList') {
  120299. var added = this.flattenMutationTree(m.addedNodes);
  120300. added.forEach(this.addElement, this);
  120301. var removed = this.flattenMutationTree(m.removedNodes);
  120302. removed.forEach(this.removeElement, this);
  120303. } else if (m.type === 'attributes') {
  120304. this.elementChanged(m.target, m.oldValue);
  120305. }
  120306. }
  120307. };
  120308. function shadowSelector(v) {
  120309. return 'body /shadow-deep/ ' + selector(v);
  120310. }
  120311. function selector(v) {
  120312. return '[touch-action="' + v + '"]';
  120313. }
  120314. function rule(v) {
  120315. return '{ -ms-touch-action: ' + v + '; touch-action: ' + v + '; }';
  120316. }
  120317. var attrib2css = [
  120318. 'none',
  120319. 'auto',
  120320. 'pan-x',
  120321. 'pan-y',
  120322. {
  120323. rule: 'pan-x pan-y',
  120324. selectors: [
  120325. 'pan-x pan-y',
  120326. 'pan-y pan-x'
  120327. ]
  120328. }
  120329. ];
  120330. var styles = '';
  120331. // only install stylesheet if the browser has touch action support
  120332. var hasNativePE = window.PointerEvent || window.MSPointerEvent;
  120333. // only add shadow selectors if shadowdom is supported
  120334. var hasShadowRoot = !window.ShadowDOMPolyfill && document.head.createShadowRoot;
  120335. function applyAttributeStyles() {
  120336. if (hasNativePE) {
  120337. attrib2css.forEach(function(r) {
  120338. if (String(r) === r) {
  120339. styles += selector(r) + rule(r) + '\n';
  120340. if (hasShadowRoot) {
  120341. styles += shadowSelector(r) + rule(r) + '\n';
  120342. }
  120343. } else {
  120344. styles += r.selectors.map(selector) + rule(r.rule) + '\n';
  120345. if (hasShadowRoot) {
  120346. styles += r.selectors.map(shadowSelector) + rule(r.rule) + '\n';
  120347. }
  120348. }
  120349. });
  120350. var el = document.createElement('style');
  120351. el.textContent = styles;
  120352. document.head.appendChild(el);
  120353. }
  120354. }
  120355. var pointermap = dispatcher.pointermap;
  120356. // radius around touchend that swallows mouse events
  120357. var DEDUP_DIST = 25;
  120358. // left, middle, right, back, forward
  120359. var BUTTON_TO_BUTTONS = [1, 4, 2, 8, 16];
  120360. var HAS_BUTTONS = false;
  120361. try {
  120362. HAS_BUTTONS = new MouseEvent('test', { buttons: 1 }).buttons === 1;
  120363. } catch (e) {}
  120364. // handler block for native mouse events
  120365. var mouseEvents = {
  120366. POINTER_ID: 1,
  120367. POINTER_TYPE: 'mouse',
  120368. events: [
  120369. 'mousedown',
  120370. 'mousemove',
  120371. 'mouseup',
  120372. 'mouseover',
  120373. 'mouseout'
  120374. ],
  120375. register: function(target) {
  120376. dispatcher.listen(target, this.events);
  120377. },
  120378. unregister: function(target) {
  120379. dispatcher.unlisten(target, this.events);
  120380. },
  120381. lastTouches: [],
  120382. // collide with the global mouse listener
  120383. isEventSimulatedFromTouch: function(inEvent) {
  120384. var lts = this.lastTouches;
  120385. var x = inEvent.clientX;
  120386. var y = inEvent.clientY;
  120387. for (var i = 0, l = lts.length, t; i < l && (t = lts[i]); i++) {
  120388. // simulated mouse events will be swallowed near a primary touchend
  120389. var dx = Math.abs(x - t.x);
  120390. var dy = Math.abs(y - t.y);
  120391. if (dx <= DEDUP_DIST && dy <= DEDUP_DIST) {
  120392. return true;
  120393. }
  120394. }
  120395. },
  120396. prepareEvent: function(inEvent) {
  120397. var e = dispatcher.cloneEvent(inEvent);
  120398. // forward mouse preventDefault
  120399. var pd = e.preventDefault;
  120400. e.preventDefault = function() {
  120401. inEvent.preventDefault();
  120402. pd();
  120403. };
  120404. e.pointerId = this.POINTER_ID;
  120405. e.isPrimary = true;
  120406. e.pointerType = this.POINTER_TYPE;
  120407. return e;
  120408. },
  120409. prepareButtonsForMove: function(e, inEvent) {
  120410. var p = pointermap.get(this.POINTER_ID);
  120411. // Update buttons state after possible out-of-document mouseup.
  120412. if (inEvent.which === 0 || !p) {
  120413. e.buttons = 0;
  120414. } else {
  120415. e.buttons = p.buttons;
  120416. }
  120417. inEvent.buttons = e.buttons;
  120418. },
  120419. mousedown: function(inEvent) {
  120420. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120421. var p = pointermap.get(this.POINTER_ID);
  120422. var e = this.prepareEvent(inEvent);
  120423. if (!HAS_BUTTONS) {
  120424. e.buttons = BUTTON_TO_BUTTONS[e.button];
  120425. if (p) { e.buttons |= p.buttons; }
  120426. inEvent.buttons = e.buttons;
  120427. }
  120428. pointermap.set(this.POINTER_ID, inEvent);
  120429. if (!p || p.buttons === 0) {
  120430. dispatcher.down(e);
  120431. } else {
  120432. dispatcher.move(e);
  120433. }
  120434. }
  120435. },
  120436. mousemove: function(inEvent) {
  120437. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120438. var e = this.prepareEvent(inEvent);
  120439. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  120440. e.button = -1;
  120441. pointermap.set(this.POINTER_ID, inEvent);
  120442. dispatcher.move(e);
  120443. }
  120444. },
  120445. mouseup: function(inEvent) {
  120446. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120447. var p = pointermap.get(this.POINTER_ID);
  120448. var e = this.prepareEvent(inEvent);
  120449. if (!HAS_BUTTONS) {
  120450. var up = BUTTON_TO_BUTTONS[e.button];
  120451. // Produces wrong state of buttons in Browsers without `buttons` support
  120452. // when a mouse button that was pressed outside the document is released
  120453. // inside and other buttons are still pressed down.
  120454. e.buttons = p ? p.buttons & ~up : 0;
  120455. inEvent.buttons = e.buttons;
  120456. }
  120457. pointermap.set(this.POINTER_ID, inEvent);
  120458. // Support: Firefox <=44 only
  120459. // FF Ubuntu includes the lifted button in the `buttons` property on
  120460. // mouseup.
  120461. // https://bugzilla.mozilla.org/show_bug.cgi?id=1223366
  120462. e.buttons &= ~BUTTON_TO_BUTTONS[e.button];
  120463. if (e.buttons === 0) {
  120464. dispatcher.up(e);
  120465. } else {
  120466. dispatcher.move(e);
  120467. }
  120468. }
  120469. },
  120470. mouseover: function(inEvent) {
  120471. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120472. var e = this.prepareEvent(inEvent);
  120473. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  120474. e.button = -1;
  120475. pointermap.set(this.POINTER_ID, inEvent);
  120476. dispatcher.enterOver(e);
  120477. }
  120478. },
  120479. mouseout: function(inEvent) {
  120480. if (!this.isEventSimulatedFromTouch(inEvent)) {
  120481. var e = this.prepareEvent(inEvent);
  120482. if (!HAS_BUTTONS) { this.prepareButtonsForMove(e, inEvent); }
  120483. e.button = -1;
  120484. dispatcher.leaveOut(e);
  120485. }
  120486. },
  120487. cancel: function(inEvent) {
  120488. var e = this.prepareEvent(inEvent);
  120489. dispatcher.cancel(e);
  120490. this.deactivateMouse();
  120491. },
  120492. deactivateMouse: function() {
  120493. pointermap.delete(this.POINTER_ID);
  120494. }
  120495. };
  120496. var captureInfo = dispatcher.captureInfo;
  120497. var findTarget = targeting.findTarget.bind(targeting);
  120498. var allShadows = targeting.allShadows.bind(targeting);
  120499. var pointermap$1 = dispatcher.pointermap;
  120500. // This should be long enough to ignore compat mouse events made by touch
  120501. var DEDUP_TIMEOUT = 2500;
  120502. var CLICK_COUNT_TIMEOUT = 200;
  120503. var ATTRIB = 'touch-action';
  120504. var INSTALLER;
  120505. // handler block for native touch events
  120506. var touchEvents = {
  120507. events: [
  120508. 'touchstart',
  120509. 'touchmove',
  120510. 'touchend',
  120511. 'touchcancel'
  120512. ],
  120513. register: function(target) {
  120514. INSTALLER.enableOnSubtree(target);
  120515. },
  120516. unregister: function() {
  120517. // TODO(dfreedman): is it worth it to disconnect the MO?
  120518. },
  120519. elementAdded: function(el) {
  120520. var a = el.getAttribute(ATTRIB);
  120521. var st = this.touchActionToScrollType(a);
  120522. if (st) {
  120523. el._scrollType = st;
  120524. dispatcher.listen(el, this.events);
  120525. // set touch-action on shadows as well
  120526. allShadows(el).forEach(function(s) {
  120527. s._scrollType = st;
  120528. dispatcher.listen(s, this.events);
  120529. }, this);
  120530. }
  120531. },
  120532. elementRemoved: function(el) {
  120533. el._scrollType = undefined;
  120534. dispatcher.unlisten(el, this.events);
  120535. // remove touch-action from shadow
  120536. allShadows(el).forEach(function(s) {
  120537. s._scrollType = undefined;
  120538. dispatcher.unlisten(s, this.events);
  120539. }, this);
  120540. },
  120541. elementChanged: function(el, oldValue) {
  120542. var a = el.getAttribute(ATTRIB);
  120543. var st = this.touchActionToScrollType(a);
  120544. var oldSt = this.touchActionToScrollType(oldValue);
  120545. // simply update scrollType if listeners are already established
  120546. if (st && oldSt) {
  120547. el._scrollType = st;
  120548. allShadows(el).forEach(function(s) {
  120549. s._scrollType = st;
  120550. }, this);
  120551. } else if (oldSt) {
  120552. this.elementRemoved(el);
  120553. } else if (st) {
  120554. this.elementAdded(el);
  120555. }
  120556. },
  120557. scrollTypes: {
  120558. EMITTER: 'none',
  120559. XSCROLLER: 'pan-x',
  120560. YSCROLLER: 'pan-y',
  120561. SCROLLER: /^(?:pan-x pan-y)|(?:pan-y pan-x)|auto$/
  120562. },
  120563. touchActionToScrollType: function(touchAction) {
  120564. var t = touchAction;
  120565. var st = this.scrollTypes;
  120566. if (t === 'none') {
  120567. return 'none';
  120568. } else if (t === st.XSCROLLER) {
  120569. return 'X';
  120570. } else if (t === st.YSCROLLER) {
  120571. return 'Y';
  120572. } else if (st.SCROLLER.exec(t)) {
  120573. return 'XY';
  120574. }
  120575. },
  120576. POINTER_TYPE: 'touch',
  120577. firstTouch: null,
  120578. isPrimaryTouch: function(inTouch) {
  120579. return this.firstTouch === inTouch.identifier;
  120580. },
  120581. setPrimaryTouch: function(inTouch) {
  120582. // set primary touch if there no pointers, or the only pointer is the mouse
  120583. if (pointermap$1.size === 0 || (pointermap$1.size === 1 && pointermap$1.has(1))) {
  120584. this.firstTouch = inTouch.identifier;
  120585. this.firstXY = { X: inTouch.clientX, Y: inTouch.clientY };
  120586. this.scrolling = false;
  120587. this.cancelResetClickCount();
  120588. }
  120589. },
  120590. removePrimaryPointer: function(inPointer) {
  120591. if (inPointer.isPrimary) {
  120592. this.firstTouch = null;
  120593. this.firstXY = null;
  120594. this.resetClickCount();
  120595. }
  120596. },
  120597. clickCount: 0,
  120598. resetId: null,
  120599. resetClickCount: function() {
  120600. var fn = function() {
  120601. this.clickCount = 0;
  120602. this.resetId = null;
  120603. }.bind(this);
  120604. this.resetId = setTimeout(fn, CLICK_COUNT_TIMEOUT);
  120605. },
  120606. cancelResetClickCount: function() {
  120607. if (this.resetId) {
  120608. clearTimeout(this.resetId);
  120609. }
  120610. },
  120611. typeToButtons: function(type) {
  120612. var ret = 0;
  120613. if (type === 'touchstart' || type === 'touchmove') {
  120614. ret = 1;
  120615. }
  120616. return ret;
  120617. },
  120618. touchToPointer: function(inTouch) {
  120619. var cte = this.currentTouchEvent;
  120620. var e = dispatcher.cloneEvent(inTouch);
  120621. // We reserve pointerId 1 for Mouse.
  120622. // Touch identifiers can start at 0.
  120623. // Add 2 to the touch identifier for compatibility.
  120624. var id = e.pointerId = inTouch.identifier + 2;
  120625. e.target = captureInfo[id] || findTarget(e);
  120626. e.bubbles = true;
  120627. e.cancelable = true;
  120628. e.detail = this.clickCount;
  120629. e.button = 0;
  120630. e.buttons = this.typeToButtons(cte.type);
  120631. e.width = (inTouch.radiusX || inTouch.webkitRadiusX || 0) * 2;
  120632. e.height = (inTouch.radiusY || inTouch.webkitRadiusY || 0) * 2;
  120633. e.pressure = inTouch.force || inTouch.webkitForce || 0.5;
  120634. e.isPrimary = this.isPrimaryTouch(inTouch);
  120635. e.pointerType = this.POINTER_TYPE;
  120636. // forward modifier keys
  120637. e.altKey = cte.altKey;
  120638. e.ctrlKey = cte.ctrlKey;
  120639. e.metaKey = cte.metaKey;
  120640. e.shiftKey = cte.shiftKey;
  120641. // forward touch preventDefaults
  120642. var self = this;
  120643. e.preventDefault = function() {
  120644. self.scrolling = false;
  120645. self.firstXY = null;
  120646. cte.preventDefault();
  120647. };
  120648. return e;
  120649. },
  120650. processTouches: function(inEvent, inFunction) {
  120651. var tl = inEvent.changedTouches;
  120652. this.currentTouchEvent = inEvent;
  120653. for (var i = 0, t; i < tl.length; i++) {
  120654. t = tl[i];
  120655. inFunction.call(this, this.touchToPointer(t));
  120656. }
  120657. },
  120658. // For single axis scrollers, determines whether the element should emit
  120659. // pointer events or behave as a scroller
  120660. shouldScroll: function(inEvent) {
  120661. if (this.firstXY) {
  120662. var ret;
  120663. var scrollAxis = inEvent.currentTarget._scrollType;
  120664. if (scrollAxis === 'none') {
  120665. // this element is a touch-action: none, should never scroll
  120666. ret = false;
  120667. } else if (scrollAxis === 'XY') {
  120668. // this element should always scroll
  120669. ret = true;
  120670. } else {
  120671. var t = inEvent.changedTouches[0];
  120672. // check the intended scroll axis, and other axis
  120673. var a = scrollAxis;
  120674. var oa = scrollAxis === 'Y' ? 'X' : 'Y';
  120675. var da = Math.abs(t['client' + a] - this.firstXY[a]);
  120676. var doa = Math.abs(t['client' + oa] - this.firstXY[oa]);
  120677. // if delta in the scroll axis > delta other axis, scroll instead of
  120678. // making events
  120679. ret = da >= doa;
  120680. }
  120681. this.firstXY = null;
  120682. return ret;
  120683. }
  120684. },
  120685. findTouch: function(inTL, inId) {
  120686. for (var i = 0, l = inTL.length, t; i < l && (t = inTL[i]); i++) {
  120687. if (t.identifier === inId) {
  120688. return true;
  120689. }
  120690. }
  120691. },
  120692. // In some instances, a touchstart can happen without a touchend. This
  120693. // leaves the pointermap in a broken state.
  120694. // Therefore, on every touchstart, we remove the touches that did not fire a
  120695. // touchend event.
  120696. // To keep state globally consistent, we fire a
  120697. // pointercancel for this "abandoned" touch
  120698. vacuumTouches: function(inEvent) {
  120699. var tl = inEvent.touches;
  120700. // pointermap.size should be < tl.length here, as the touchstart has not
  120701. // been processed yet.
  120702. if (pointermap$1.size >= tl.length) {
  120703. var d = [];
  120704. pointermap$1.forEach(function(value, key) {
  120705. // Never remove pointerId == 1, which is mouse.
  120706. // Touch identifiers are 2 smaller than their pointerId, which is the
  120707. // index in pointermap.
  120708. if (key !== 1 && !this.findTouch(tl, key - 2)) {
  120709. var p = value.out;
  120710. d.push(p);
  120711. }
  120712. }, this);
  120713. d.forEach(this.cancelOut, this);
  120714. }
  120715. },
  120716. touchstart: function(inEvent) {
  120717. this.vacuumTouches(inEvent);
  120718. this.setPrimaryTouch(inEvent.changedTouches[0]);
  120719. this.dedupSynthMouse(inEvent);
  120720. if (!this.scrolling) {
  120721. this.clickCount++;
  120722. this.processTouches(inEvent, this.overDown);
  120723. }
  120724. },
  120725. overDown: function(inPointer) {
  120726. pointermap$1.set(inPointer.pointerId, {
  120727. target: inPointer.target,
  120728. out: inPointer,
  120729. outTarget: inPointer.target
  120730. });
  120731. dispatcher.enterOver(inPointer);
  120732. dispatcher.down(inPointer);
  120733. },
  120734. touchmove: function(inEvent) {
  120735. if (!this.scrolling) {
  120736. if (this.shouldScroll(inEvent)) {
  120737. this.scrolling = true;
  120738. this.touchcancel(inEvent);
  120739. } else {
  120740. inEvent.preventDefault();
  120741. this.processTouches(inEvent, this.moveOverOut);
  120742. }
  120743. }
  120744. },
  120745. moveOverOut: function(inPointer) {
  120746. var event = inPointer;
  120747. var pointer = pointermap$1.get(event.pointerId);
  120748. // a finger drifted off the screen, ignore it
  120749. if (!pointer) {
  120750. return;
  120751. }
  120752. var outEvent = pointer.out;
  120753. var outTarget = pointer.outTarget;
  120754. dispatcher.move(event);
  120755. if (outEvent && outTarget !== event.target) {
  120756. outEvent.relatedTarget = event.target;
  120757. event.relatedTarget = outTarget;
  120758. // recover from retargeting by shadow
  120759. outEvent.target = outTarget;
  120760. if (event.target) {
  120761. dispatcher.leaveOut(outEvent);
  120762. dispatcher.enterOver(event);
  120763. } else {
  120764. // clean up case when finger leaves the screen
  120765. event.target = outTarget;
  120766. event.relatedTarget = null;
  120767. this.cancelOut(event);
  120768. }
  120769. }
  120770. pointer.out = event;
  120771. pointer.outTarget = event.target;
  120772. },
  120773. touchend: function(inEvent) {
  120774. this.dedupSynthMouse(inEvent);
  120775. this.processTouches(inEvent, this.upOut);
  120776. },
  120777. upOut: function(inPointer) {
  120778. if (!this.scrolling) {
  120779. dispatcher.up(inPointer);
  120780. dispatcher.leaveOut(inPointer);
  120781. }
  120782. this.cleanUpPointer(inPointer);
  120783. },
  120784. touchcancel: function(inEvent) {
  120785. this.processTouches(inEvent, this.cancelOut);
  120786. },
  120787. cancelOut: function(inPointer) {
  120788. dispatcher.cancel(inPointer);
  120789. dispatcher.leaveOut(inPointer);
  120790. this.cleanUpPointer(inPointer);
  120791. },
  120792. cleanUpPointer: function(inPointer) {
  120793. pointermap$1.delete(inPointer.pointerId);
  120794. this.removePrimaryPointer(inPointer);
  120795. },
  120796. // prevent synth mouse events from creating pointer events
  120797. dedupSynthMouse: function(inEvent) {
  120798. var lts = mouseEvents.lastTouches;
  120799. var t = inEvent.changedTouches[0];
  120800. // only the primary finger will synth mouse events
  120801. if (this.isPrimaryTouch(t)) {
  120802. // remember x/y of last touch
  120803. var lt = { x: t.clientX, y: t.clientY };
  120804. lts.push(lt);
  120805. var fn = (function(lts, lt) {
  120806. var i = lts.indexOf(lt);
  120807. if (i > -1) {
  120808. lts.splice(i, 1);
  120809. }
  120810. }).bind(null, lts, lt);
  120811. setTimeout(fn, DEDUP_TIMEOUT);
  120812. }
  120813. }
  120814. };
  120815. INSTALLER = new Installer(touchEvents.elementAdded, touchEvents.elementRemoved,
  120816. touchEvents.elementChanged, touchEvents);
  120817. var pointermap$2 = dispatcher.pointermap;
  120818. var HAS_BITMAP_TYPE = window.MSPointerEvent &&
  120819. typeof window.MSPointerEvent.MSPOINTER_TYPE_MOUSE === 'number';
  120820. var msEvents = {
  120821. events: [
  120822. 'MSPointerDown',
  120823. 'MSPointerMove',
  120824. 'MSPointerUp',
  120825. 'MSPointerOut',
  120826. 'MSPointerOver',
  120827. 'MSPointerCancel',
  120828. 'MSGotPointerCapture',
  120829. 'MSLostPointerCapture'
  120830. ],
  120831. register: function(target) {
  120832. dispatcher.listen(target, this.events);
  120833. },
  120834. unregister: function(target) {
  120835. dispatcher.unlisten(target, this.events);
  120836. },
  120837. POINTER_TYPES: [
  120838. '',
  120839. 'unavailable',
  120840. 'touch',
  120841. 'pen',
  120842. 'mouse'
  120843. ],
  120844. prepareEvent: function(inEvent) {
  120845. var e = inEvent;
  120846. if (HAS_BITMAP_TYPE) {
  120847. e = dispatcher.cloneEvent(inEvent);
  120848. e.pointerType = this.POINTER_TYPES[inEvent.pointerType];
  120849. }
  120850. return e;
  120851. },
  120852. cleanup: function(id) {
  120853. pointermap$2.delete(id);
  120854. },
  120855. MSPointerDown: function(inEvent) {
  120856. pointermap$2.set(inEvent.pointerId, inEvent);
  120857. var e = this.prepareEvent(inEvent);
  120858. dispatcher.down(e);
  120859. },
  120860. MSPointerMove: function(inEvent) {
  120861. var e = this.prepareEvent(inEvent);
  120862. dispatcher.move(e);
  120863. },
  120864. MSPointerUp: function(inEvent) {
  120865. var e = this.prepareEvent(inEvent);
  120866. dispatcher.up(e);
  120867. this.cleanup(inEvent.pointerId);
  120868. },
  120869. MSPointerOut: function(inEvent) {
  120870. var e = this.prepareEvent(inEvent);
  120871. dispatcher.leaveOut(e);
  120872. },
  120873. MSPointerOver: function(inEvent) {
  120874. var e = this.prepareEvent(inEvent);
  120875. dispatcher.enterOver(e);
  120876. },
  120877. MSPointerCancel: function(inEvent) {
  120878. var e = this.prepareEvent(inEvent);
  120879. dispatcher.cancel(e);
  120880. this.cleanup(inEvent.pointerId);
  120881. },
  120882. MSLostPointerCapture: function(inEvent) {
  120883. var e = dispatcher.makeEvent('lostpointercapture', inEvent);
  120884. dispatcher.dispatchEvent(e);
  120885. },
  120886. MSGotPointerCapture: function(inEvent) {
  120887. var e = dispatcher.makeEvent('gotpointercapture', inEvent);
  120888. dispatcher.dispatchEvent(e);
  120889. }
  120890. };
  120891. function applyPolyfill() {
  120892. // only activate if this platform does not have pointer events
  120893. if (!window.PointerEvent) {
  120894. window.PointerEvent = PointerEvent;
  120895. if (window.navigator.msPointerEnabled) {
  120896. var tp = window.navigator.msMaxTouchPoints;
  120897. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  120898. value: tp,
  120899. enumerable: true
  120900. });
  120901. dispatcher.registerSource('ms', msEvents);
  120902. } else {
  120903. Object.defineProperty(window.navigator, 'maxTouchPoints', {
  120904. value: 0,
  120905. enumerable: true
  120906. });
  120907. dispatcher.registerSource('mouse', mouseEvents);
  120908. if (window.ontouchstart !== undefined) {
  120909. dispatcher.registerSource('touch', touchEvents);
  120910. }
  120911. }
  120912. dispatcher.register(document);
  120913. }
  120914. }
  120915. var n = window.navigator;
  120916. var s;
  120917. var r;
  120918. var h;
  120919. function assertActive(id) {
  120920. if (!dispatcher.pointermap.has(id)) {
  120921. var error = new Error('InvalidPointerId');
  120922. error.name = 'InvalidPointerId';
  120923. throw error;
  120924. }
  120925. }
  120926. function assertConnected(elem) {
  120927. var parent = elem.parentNode;
  120928. while (parent && parent !== elem.ownerDocument) {
  120929. parent = parent.parentNode;
  120930. }
  120931. if (!parent) {
  120932. var error = new Error('InvalidStateError');
  120933. error.name = 'InvalidStateError';
  120934. throw error;
  120935. }
  120936. }
  120937. function inActiveButtonState(id) {
  120938. var p = dispatcher.pointermap.get(id);
  120939. return p.buttons !== 0;
  120940. }
  120941. if (n.msPointerEnabled) {
  120942. s = function(pointerId) {
  120943. assertActive(pointerId);
  120944. assertConnected(this);
  120945. if (inActiveButtonState(pointerId)) {
  120946. dispatcher.setCapture(pointerId, this, true);
  120947. this.msSetPointerCapture(pointerId);
  120948. }
  120949. };
  120950. r = function(pointerId) {
  120951. assertActive(pointerId);
  120952. dispatcher.releaseCapture(pointerId, true);
  120953. this.msReleasePointerCapture(pointerId);
  120954. };
  120955. } else {
  120956. s = function setPointerCapture(pointerId) {
  120957. assertActive(pointerId);
  120958. assertConnected(this);
  120959. if (inActiveButtonState(pointerId)) {
  120960. dispatcher.setCapture(pointerId, this);
  120961. }
  120962. };
  120963. r = function releasePointerCapture(pointerId) {
  120964. assertActive(pointerId);
  120965. dispatcher.releaseCapture(pointerId);
  120966. };
  120967. }
  120968. h = function hasPointerCapture(pointerId) {
  120969. return !!dispatcher.captureInfo[pointerId];
  120970. };
  120971. function applyPolyfill$1() {
  120972. if (window.Element && !Element.prototype.setPointerCapture) {
  120973. Object.defineProperties(Element.prototype, {
  120974. 'setPointerCapture': {
  120975. value: s
  120976. },
  120977. 'releasePointerCapture': {
  120978. value: r
  120979. },
  120980. 'hasPointerCapture': {
  120981. value: h
  120982. }
  120983. });
  120984. }
  120985. }
  120986. applyAttributeStyles();
  120987. applyPolyfill();
  120988. applyPolyfill$1();
  120989. var pointerevents = {
  120990. dispatcher: dispatcher,
  120991. Installer: Installer,
  120992. PointerEvent: PointerEvent,
  120993. PointerMap: PointerMap,
  120994. targetFinding: targeting
  120995. };
  120996. return pointerevents;
  120997. }));
  120998. /***/ }),
  120999. /* 67 */
  121000. /***/ (function(module, exports, __webpack_require__) {
  121001. "use strict";
  121002. Object.defineProperty(exports, "__esModule", { value: true });
  121003. var defaultViewer_1 = __webpack_require__(8);
  121004. var mappers_1 = __webpack_require__(3);
  121005. var globals_1 = __webpack_require__(4);
  121006. /**
  121007. * Will attach an init function the the DOMContentLoaded event.
  121008. * The init function will be removed automatically after the event was triggered.
  121009. */
  121010. function initListeners() {
  121011. document.addEventListener("DOMContentLoaded", init);
  121012. function init(event) {
  121013. document.removeEventListener("DOMContentLoaded", init);
  121014. if (globals_1.viewerGlobals.disableInit)
  121015. return;
  121016. InitTags();
  121017. }
  121018. }
  121019. exports.initListeners = initListeners;
  121020. /**
  121021. * Select all HTML tags on the page that match the selector and initialize a viewer
  121022. *
  121023. * @param selector the selector to initialize the viewer on (default is 'babylon')
  121024. */
  121025. function InitTags(selector) {
  121026. if (selector === void 0) { selector = 'babylon'; }
  121027. var elements = document.querySelectorAll(selector);
  121028. for (var i = 0; i < elements.length; ++i) {
  121029. var element = elements.item(i);
  121030. // get the html configuration
  121031. var configMapper = mappers_1.mapperManager.getMapper('dom');
  121032. var config = configMapper.map(element);
  121033. var viewer = new defaultViewer_1.DefaultViewer(element, config);
  121034. }
  121035. }
  121036. exports.InitTags = InitTags;
  121037. //# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5pdGlhbGl6ZXIuanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi8uLi9zcmMvaW5pdGlhbGl6ZXIudHMiXSwibmFtZXMiOltdLCJtYXBwaW5ncyI6Ijs7QUFBQSx3REFBdUQ7QUFDdkQsbURBQXdEO0FBQ3hELG1EQUF3RDtBQUd4RDs7O0dBR0c7QUFDSDtJQUNJLFFBQVEsQ0FBQyxnQkFBZ0IsQ0FBQyxrQkFBa0IsRUFBRSxJQUFJLENBQUMsQ0FBQztJQUNwRCxjQUFjLEtBQUs7UUFDZixRQUFRLENBQUMsbUJBQW1CLENBQUMsa0JBQW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